{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "security-05",
  "description": "Setting up two-factor sign-in with an authenticator app, security keys and passkeys, and recovery codes shown once.",
  "registryDependencies": [
    "button",
    "input",
    "https://www.dashboardblocks.com/r/radix/block-state.json",
    "https://www.dashboardblocks.com/r/radix/settings.json",
    "https://www.dashboardblocks.com/r/radix/status-label.json",
    "https://www.dashboardblocks.com/r/radix/format.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/security/security-05.tsx",
      "content": "'use client'\n\nimport {\n  BlockStateProvider,\n  BlockStateRows,\n  type BlockStateProps,\n  getBlockState,\n  useBlockState,\n} from '@/registry/components/dashboardblocks/block-state'\nimport {\n  CopyButton,\n  useCopyToClipboard,\n} from '@/registry/components/dashboardblocks/settings'\nimport { StatusLabel } from '@/registry/components/dashboardblocks/status-label'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport { formatDate } from '@/registry/lib/dashboardblocks/format'\nimport { type FormEvent, type ReactNode, startTransition, useId, useState } from 'react'\n\nimport { Button } from '@/components/ui/button'\nimport { Input } from '@/components/ui/input'\n\nimport { cn } from '@/lib/utils'\n\ninterface SecurityKey {\n  addedAt: Date\n  id: string\n  name: string\n}\n\ninterface AuthenticatorSetup {\n  /** The QR code for the authenticator app, rendered by your server or a QR library. */\n  qrCode: ReactNode\n  secret: string\n}\n\ninterface Security5Props extends BlockStateProps {\n  authenticatorAddedAt?: Date\n  description: string\n  onAddSecurityKey?: () => void\n  onRemoveAuthenticator?: () => void\n  onRemoveSecurityKey?: (id: string) => void\n  /** Called when new recovery codes are shown, so the old ones can be revoked. */\n  onRegenerateRecoveryCodes?: () => void\n  onVerify?: (code: string) => boolean | Promise<boolean>\n  recoveryCodes: string[]\n  /** @default 0 */\n  recoveryCodesLeft?: number\n  /** Stops the last method being removed, when the workspace requires two-factor. */\n  required?: boolean\n  /** Leave out to show the empty state. */\n  securityKeys?: SecurityKey[]\n  setup: AuthenticatorSetup\n  title: string\n}\n\nfunction ExampleQrCode() {\n  const size = 21\n  const finder = (x: number, y: number) => {\n    const inside = (ox: number, oy: number) => {\n      const dx = x - ox\n      const dy = y - oy\n      if (dx < 0 || dy < 0 || dx > 6 || dy > 6) return null\n      return (\n        dx === 0 ||\n        dy === 0 ||\n        dx === 6 ||\n        dy === 6 ||\n        (dx > 1 && dx < 5 && dy > 1 && dy < 5)\n      )\n    }\n    return inside(0, 0) ?? inside(size - 7, 0) ?? inside(0, size - 7)\n  }\n  const cells: [number, number][] = []\n  for (let y = 0; y < size; y++) {\n    for (let x = 0; x < size; x++) {\n      const fixed = finder(x, y)\n      const on = fixed ?? (x * 7 + y * 13 + x * y) % 5 < 2\n      if (on) cells.push([x, y])\n    }\n  }\n  return (\n    <svg viewBox={`-2 -2 ${size + 4} ${size + 4}`} role='img' aria-label='QR code'>\n      <rect x={-2} y={-2} width={size + 4} height={size + 4} fill='white' />\n      {cells.map(([x, y]) => (\n        <rect key={`${x}-${y}`} x={x} y={y} width={1} height={1} fill='black' />\n      ))}\n    </svg>\n  )\n}\n\nconst exampleProps: Security5Props = {\n  description:\n    'A second step at sign-in, so a password alone can’t get into your account.',\n  recoveryCodes: [\n    'k7p2-9xqm',\n    'hd4w-ja8e',\n    'r3tn-vb6c',\n    'm9fz-2ksl',\n    'q5ye-ut7g',\n    'w8cd-n4rp',\n    'b2xh-6jwa',\n    'z6le-p3mt',\n  ],\n  recoveryCodesLeft: 8,\n  securityKeys: [\n    { addedAt: new Date(Date.UTC(2026, 2, 4)), id: 'k1', name: 'YubiKey 5C' },\n    { addedAt: new Date(Date.UTC(2026, 6, 19)), id: 'k2', name: 'MacBook Touch ID' },\n  ],\n  setup: { qrCode: <ExampleQrCode />, secret: 'JBSW Y3DP EHPK 3PXP' },\n  title: 'Two-factor authentication',\n}\n\ntype Step = 'idle' | 'setup' | 'codes'\n\nfunction TwoFactorSettings(props: Security5Props) {\n  const {\n    description,\n    onAddSecurityKey,\n    onRegenerateRecoveryCodes,\n    onRemoveAuthenticator,\n    onRemoveSecurityKey,\n    onVerify,\n    recoveryCodes,\n    required = false,\n    setup,\n    title,\n  } = props\n  const id = useId()\n  const [authenticator, setAuthenticator] = useState(props.authenticatorAddedAt)\n  const state = useBlockState()\n  const [keys, setKeys] = useState(props.securityKeys ?? [])\n  const [codesLeft, setCodesLeft] = useState(props.recoveryCodesLeft ?? 0)\n  const [step, setStep] = useState<Step>('idle')\n  const [code, setCode] = useState('')\n  const [error, setError] = useState<string | null>(null)\n  const [verifying, setVerifying] = useState(false)\n  const { copied, copy } = useCopyToClipboard()\n\n  const methods = (authenticator ? 1 : 0) + keys.length\n  const enabled = methods > 0\n  const locked = required && methods === 1\n\n  const verify = async (event: FormEvent<HTMLFormElement>) => {\n    event.preventDefault()\n    const digits = code.replace(/\\s/g, '')\n    if (!/^\\d{6}$/.test(digits)) return setError('Enter the 6-digit code from the app.')\n    setVerifying(true)\n    const ok = onVerify ? await onVerify(digits) : true\n    startTransition(() => {\n      setVerifying(false)\n      if (!ok) {\n        setError(\n          'That code didn’t work. Codes change every 30 seconds, so try the newest one.',\n        )\n        return\n      }\n      setAuthenticator(new Date())\n      setCodesLeft(recoveryCodes.length)\n      setCode('')\n      setError(null)\n      setStep('codes')\n    })\n  }\n\n  const download = () => {\n    const blob = new Blob([`${recoveryCodes.join('\\n')}\\n`], { type: 'text/plain' })\n    const link = document.createElement('a')\n    link.href = URL.createObjectURL(blob)\n    link.download = 'recovery-codes.txt'\n    link.click()\n    URL.revokeObjectURL(link.href)\n  }\n\n  if (state) {\n    return (\n      <section className='@container flex flex-col gap-3'>\n        <header className='flex flex-col gap-0.5'>\n          <h2 className='font-semibold tracking-tight'>{title}</h2>\n          <p className='text-muted-foreground text-sm'>{description}</p>\n        </header>\n        <BlockStateRows className='border-t' rows={3} />\n      </section>\n    )\n  }\n\n  return (\n    <section className='@container flex flex-col gap-3'>\n      <header className='flex items-start justify-between gap-3'>\n        <div className='flex min-w-0 flex-col gap-0.5'>\n          <h2 className='font-semibold tracking-tight'>{title}</h2>\n          <p className='text-muted-foreground text-sm'>{description}</p>\n        </div>\n        <StatusLabel className='mt-0.5' tone={enabled ? 'good' : 'warning'}>\n          {enabled ? 'On' : 'Off'}\n        </StatusLabel>\n      </header>\n      <ul className='flex flex-col divide-y border-t'>\n        <li className='flex flex-col gap-4 py-3'>\n          <div className='flex items-start gap-3'>\n            <div className='flex min-w-0 flex-1 flex-col gap-0.5'>\n              <span id={`${id}-app`} className='text-sm font-medium'>\n                Authenticator app\n              </span>\n              <span className='text-muted-foreground text-sm'>\n                {authenticator ? (\n                  <>\n                    Added{' '}\n                    <time dateTime={authenticator.toISOString()}>\n                      {formatDate(authenticator, 'date')}\n                    </time>\n                  </>\n                ) : (\n                  'Codes from an app like 1Password, Authy or Google Authenticator.'\n                )}\n              </span>\n            </div>\n            {authenticator ? (\n              <Button\n                variant='ghost'\n                size='sm'\n                disabled={locked}\n                aria-describedby={locked ? `${id}-required` : undefined}\n                onClick={() => {\n                  setAuthenticator(undefined)\n                  onRemoveAuthenticator?.()\n                }}\n              >\n                <IconPlaceholder\n                  lucide='Trash2Icon'\n                  tabler='IconTrash'\n                  hugeicons='Delete02Icon'\n                  phosphor='TrashIcon'\n                  remixicon='RiDeleteBinLine'\n                  data-icon='inline-start'\n                />\n                Remove\n              </Button>\n            ) : (\n              step === 'idle' && (\n                <Button variant='outline' size='sm' onClick={() => setStep('setup')}>\n                  Set up\n                </Button>\n              )\n            )}\n          </div>\n\n          {step === 'setup' && (\n            <form\n              method='post'\n              onSubmit={(event) => void verify(event)}\n              noValidate\n              aria-labelledby={`${id}-app`}\n              className='flex flex-col gap-4 rounded-xl border p-4 @md:flex-row'\n            >\n              <div className='size-36 shrink-0 self-center overflow-hidden rounded-md border bg-white p-1 @md:self-start [&_svg]:size-full'>\n                {setup.qrCode}\n              </div>\n              <div className='flex min-w-0 flex-1 flex-col gap-3'>\n                <p className='text-sm'>\n                  Scan the code with your authenticator app, or enter this key:\n                </p>\n                <div className='bg-background flex items-center gap-1 rounded-md border py-1 pr-1 pl-3'>\n                  <code className='min-w-0 flex-1 truncate font-mono text-sm'>\n                    {setup.secret}\n                  </code>\n                  <CopyButton\n                    label='Copy setup key'\n                    value={setup.secret.replace(/\\s/g, '')}\n                  />\n                </div>\n                <div className='flex flex-col gap-2'>\n                  <label htmlFor={`${id}-code`} className='text-sm font-medium'>\n                    Code from the app\n                  </label>\n                  <div className='flex gap-2'>\n                    <Input\n                      id={`${id}-code`}\n                      inputMode='numeric'\n                      autoComplete='one-time-code'\n                      maxLength={7}\n                      placeholder='123 456'\n                      value={code}\n                      onChange={(event) => setCode(event.target.value)}\n                      aria-invalid={error ? true : undefined}\n                      aria-describedby={error ? `${id}-code-error` : undefined}\n                      className='w-32 font-mono tracking-widest tabular-nums'\n                    />\n                    <Button type='submit' disabled={verifying}>\n                      {verifying ? 'Checking' : 'Verify'}\n                    </Button>\n                    <Button\n                      type='button'\n                      variant='ghost'\n                      onClick={() => {\n                        setStep('idle')\n                        setCode('')\n                        setError(null)\n                      }}\n                    >\n                      Cancel\n                    </Button>\n                  </div>\n                  {error && (\n                    <p id={`${id}-code-error`} className='text-destructive text-sm'>\n                      {error}\n                    </p>\n                  )}\n                </div>\n              </div>\n            </form>\n          )}\n        </li>\n\n        <li className='flex flex-col gap-3 py-3'>\n          <div className='flex items-start gap-3'>\n            <div className='flex min-w-0 flex-1 flex-col gap-0.5'>\n              <span className='text-sm font-medium'>Security keys and passkeys</span>\n              <span className='text-muted-foreground text-sm'>\n                A hardware key, or your device’s fingerprint or face unlock.\n              </span>\n            </div>\n            <Button variant='outline' size='sm' onClick={onAddSecurityKey}>\n              <IconPlaceholder\n                lucide='PlusIcon'\n                tabler='IconPlus'\n                hugeicons='PlusSignIcon'\n                phosphor='PlusIcon'\n                remixicon='RiAddLine'\n                data-icon='inline-start'\n              />\n              Add\n            </Button>\n          </div>\n          {keys.length > 0 && (\n            <ul className='flex flex-col gap-2'>\n              {keys.map((key) => (\n                <li key={key.id} className='flex items-center gap-3'>\n                  <div className='flex min-w-0 flex-1 flex-col'>\n                    <span className='truncate text-sm'>{key.name}</span>\n                    <span className='text-muted-foreground text-xs'>\n                      Added{' '}\n                      <time dateTime={key.addedAt.toISOString()}>\n                        {formatDate(key.addedAt, 'date')}\n                      </time>\n                    </span>\n                  </div>\n                  <Button\n                    variant='ghost'\n                    size='sm'\n                    disabled={locked}\n                    aria-label={`Remove ${key.name}`}\n                    aria-describedby={locked ? `${id}-required` : undefined}\n                    onClick={() => {\n                      setKeys((current) => current.filter((item) => item.id !== key.id))\n                      onRemoveSecurityKey?.(key.id)\n                    }}\n                  >\n                    <IconPlaceholder\n                      lucide='Trash2Icon'\n                      tabler='IconTrash'\n                      hugeicons='Delete02Icon'\n                      phosphor='TrashIcon'\n                      remixicon='RiDeleteBinLine'\n                      data-icon='inline-start'\n                    />\n                    Remove\n                  </Button>\n                </li>\n              ))}\n            </ul>\n          )}\n        </li>\n\n        {enabled && (\n          <li className='flex flex-col gap-4 py-3'>\n            <div className='flex items-start gap-3'>\n              <div className='flex min-w-0 flex-1 flex-col gap-0.5'>\n                <span id={`${id}-codes`} className='text-sm font-medium'>\n                  Recovery codes\n                </span>\n                <span\n                  className={cn(\n                    'text-sm',\n                    codesLeft <= 2\n                      ? 'text-orange-700 dark:text-orange-400'\n                      : 'text-muted-foreground',\n                  )}\n                >\n                  {codesLeft} left. Each works once, if you lose your other methods.\n                </span>\n              </div>\n              {step !== 'codes' && (\n                <Button\n                  variant='outline'\n                  size='sm'\n                  onClick={() => {\n                    setCodesLeft(recoveryCodes.length)\n                    setStep('codes')\n                    onRegenerateRecoveryCodes?.()\n                  }}\n                >\n                  <IconPlaceholder\n                    lucide='RefreshCwIcon'\n                    tabler='IconRefresh'\n                    hugeicons='RefreshIcon'\n                    phosphor='ArrowClockwiseIcon'\n                    remixicon='RiRefreshLine'\n                    data-icon='inline-start'\n                  />\n                  New codes\n                </Button>\n              )}\n            </div>\n            {step === 'codes' && (\n              <section\n                aria-labelledby={`${id}-codes`}\n                className='bg-muted/50 flex flex-col gap-3 rounded-xl p-4'\n              >\n                <p className='text-sm'>\n                  Save these somewhere safe. They won’t be shown again, and any older\n                  codes no longer work.\n                </p>\n                <ol className='bg-background grid grid-cols-2 gap-x-6 gap-y-1 rounded-md border p-3 font-mono text-sm @md:grid-cols-4'>\n                  {recoveryCodes.map((item) => (\n                    <li key={item}>{item}</li>\n                  ))}\n                </ol>\n                <div className='flex flex-wrap gap-2'>\n                  <Button\n                    variant='outline'\n                    size='sm'\n                    onClick={() => void copy(recoveryCodes.join('\\n'))}\n                  >\n                    {copied ? (\n                      <IconPlaceholder\n                        lucide='CheckIcon'\n                        tabler='IconCheck'\n                        hugeicons='Tick02Icon'\n                        phosphor='CheckIcon'\n                        remixicon='RiCheckLine'\n                        data-icon='inline-start'\n                      />\n                    ) : (\n                      <IconPlaceholder\n                        lucide='CopyIcon'\n                        tabler='IconCopy'\n                        hugeicons='Copy01Icon'\n                        phosphor='CopyIcon'\n                        remixicon='RiFileCopyLine'\n                        data-icon='inline-start'\n                      />\n                    )}\n                    {copied ? 'Copied' : 'Copy'}\n                  </Button>\n                  <Button variant='outline' size='sm' onClick={download}>\n                    <IconPlaceholder\n                      lucide='DownloadIcon'\n                      tabler='IconDownload'\n                      hugeicons='Download01Icon'\n                      phosphor='DownloadIcon'\n                      remixicon='RiDownloadLine'\n                      data-icon='inline-start'\n                    />\n                    Download\n                  </Button>\n                  <Button size='sm' className='ml-auto' onClick={() => setStep('idle')}>\n                    I’ve saved them\n                  </Button>\n                </div>\n              </section>\n            )}\n          </li>\n        )}\n      </ul>\n      {locked && (\n        <p id={`${id}-required`} className='text-muted-foreground text-sm'>\n          Your workspace requires two-factor, so add another method before removing this\n          one.\n        </p>\n      )}\n    </section>\n  )\n}\n\nconst Security5 = (props: Security5Props) => {\n  const { securityKeys, errorMessage, status } = props\n  const state = getBlockState(status, securityKeys)\n\n  return (\n    <BlockStateProvider errorMessage={errorMessage} state={state}>\n      <TwoFactorSettings key={state ?? 'ready'} {...props} />\n    </BlockStateProvider>\n  )\n}\n\nexport {\n  Security5,\n  exampleProps as security5ExampleProps,\n  type AuthenticatorSetup,\n  type Security5Props,\n  type SecurityKey,\n}\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/security/security-05.tsx"
    }
  ],
  "meta": {
    "shows": "Setting up two-factor sign-in with an authenticator app, security keys and passkeys, and recovery codes shown once.",
    "size": "half",
    "usedWith": [
      "security-03",
      "security-04"
    ],
    "component": "Security5",
    "props": "{ authenticatorAddedAt?: Date; description: string; onAddSecurityKey?: () => void; onRemoveAuthenticator?: () => void; onRemoveSecurityKey?: (id: string) => void; onRegenerateRecoveryCodes?: () => void; onVerify?: (code: string) => boolean | Promise<boolean>; recoveryCodes: string[]; recoveryCodesLeft?: number; required?: boolean; securityKeys?: { addedAt: Date; id: string; name: string }[]; setup: { qrCode: ReactNode; secret: string }; title: string; errorMessage?: string; status?: \"loading\" | \"error\" }"
  },
  "type": "registry:component"
}
