# Security

> The Security section of an AI product’s settings. Handles sessions, two-factor with recovery codes and deletion behind a typed confirmation.

Canonical: https://hextaui.com/blocks/security
Last updated: 2026-10-29

## Overview

Every AI product ends up with the same security page: where you’re signed in, how you sign in, and how to leave. Security is that page, built on the Settings block’s groups and rows, with every flow wired to async callbacks you own.

Active sessions lists each device with its browser, system, location and when it was last active, in plain relative time. This device is marked and can’t be signed out from here. Signing out of one device shows progress in its button, then the row folds away and focus moves to the next row. Signing out everywhere else asks first and names the devices it will sign out.

Change password checks as you type: a four-step strength meter and a checklist of what’s still missing, without blocking anything you type. If your server says the current password is wrong, the message shows under that field and focus goes back to it, with everything you typed kept. You can sign out other sessions in the same step.

Two-factor setup draws a real, scannable QR code for the otpauth link your server returns, shows the setup key with a copy button for when scanning isn’t possible, and on a phone offers to open the link in an authenticator app. The 6-digit code checks itself as soon as it’s complete, shakes and clears on a wrong code, then shows recovery codes to copy or download as a text file. Turning it off asks first.

Passkeys calls your WebAuthn flow and handles the browser’s answers: closing the prompt adds nothing and shows no error, and a device that already has a passkey says so. Deleting the account needs the exact phrase, lists what goes with it, and keeps the dialog open with your message if the server says no.

## Installation

### Step 1: Get HextaUI Pro

One payment unlocks every block, including future ones. [See pricing](https://hextaui.com/pricing).

### Step 2: Add the Pro registry to components.json

```json title="components.json"
{
  "registries": {
    "@hextaui-pro": {
      "url": "https://hextaui.com/r/pro/{name}.json",
      "headers": {
        "Authorization": "Bearer ${HEXTAUI_PRO_TOKEN}"
      }
    }
  }
}
```

### Step 3: Add your token

Create a token on your [account page](https://hextaui.com/account) and put it in `.env.local` as `HEXTAUI_PRO_TOKEN`.

### Step 4: Add the block

```bash
npx shadcn@latest add @hextaui-pro/security
```

## Usage

### Wire it to your API

Pass what the account has now and an async callback for each action. Resolve when the server is done and refresh the data, and each part shows its own progress. Throw to show your error message in place, and the person’s input stays.

```tsx
"use client"

import * as React from "react"
import { IconShieldLock } from "@tabler/icons-react"

import { SettingsSection, SettingsShell, type SettingsSectionItem } from "../settings/settings"
import { SecuritySettings, type SecurityPasskey, type SecuritySession } from "@/components/blocks/security/security"

const sections: SettingsSectionItem[] = [
  { id: "security", label: "Security", icon: <IconShieldLock />, keywords: ["password", "2fa", "sessions"] },
]

type Account = {
  email: string
  sessions: SecuritySession[]
  passkeys: SecurityPasskey[]
  passwordChangedAt: string | null
  twoFactor: boolean
}

async function call<T = void>(path: string, init?: RequestInit): Promise<T> {
  const response = await fetch(path, { headers: { "content-type": "application/json" }, ...init })
  if (!response.ok) {
    const problem = await response.json().catch(() => null)
    throw new Error(problem?.detail ?? "Check your connection and try again.")
  }
  return response.status === 204 ? (undefined as T) : response.json()
}

export function SecurityPage({ initial }: { initial: Account }) {
  const [account, setAccount] = React.useState(initial)
  const refresh = async () => setAccount(await call<Account>("/api/account/security"))

  return (
    <SettingsShell sections={sections} className="h-svh">
      <SettingsSection id="security">
        <SecuritySettings
          email={account.email}
          sessions={account.sessions}
          onSignOutSession={async (id) => {
            await call(`/api/sessions/${id}`, { method: "DELETE" })
            await refresh()
          }}
          onSignOutOtherSessions={async () => {
            await call("/api/sessions/others", { method: "DELETE" })
            await refresh()
          }}
          passwordChangedAt={account.passwordChangedAt}
          onChangePassword={async (change) => {
            const response = await fetch("/api/password", {
              method: "PUT",
              body: JSON.stringify(change),
            })
            if (response.status === 403) return { currentPassword: "That password is incorrect." }
            if (!response.ok) throw new Error("Couldn’t change your password. Try again.")
            await refresh()
          }}
          twoFactorEnabled={account.twoFactor}
          onStartTwoFactor={() => call<{ uri: string }>("/api/2fa/setup", { method: "POST" })}
          onVerifyTwoFactor={async (code) => {
            const { recoveryCodes } = await call<{ recoveryCodes: string[] }>("/api/2fa/verify", {
              method: "POST",
              body: JSON.stringify({ code }),
            })
            await refresh()
            return recoveryCodes
          }}
          onDisableTwoFactor={async () => {
            await call("/api/2fa", { method: "DELETE" })
            await refresh()
          }}
          passkeys={account.passkeys}
          onAddPasskey={async () => {
            await registerPasskey()
            await refresh()
          }}
          onRemovePasskey={async (id) => {
            await call(`/api/passkeys/${id}`, { method: "DELETE" })
            await refresh()
          }}
          onDeleteAccount={async () => {
            await call("/api/account", { method: "DELETE" })
            window.location.assign("/")
          }}
        />
      </SettingsSection>
    </SettingsShell>
  )
}

async function registerPasskey() {
  const options = await call<PublicKeyCredentialCreationOptionsJSON>("/api/passkeys/options", {
    method: "POST",
  })
  const credential = (await navigator.credentials.create({
    publicKey: PublicKeyCredential.parseCreationOptionsFromJSON(options),
  })) as PublicKeyCredential
  await call("/api/passkeys", { method: "POST", body: JSON.stringify(credential.toJSON()) })
}
```

### Use the parts on their own

SecuritySessions, SecurityPasswordRow, SecurityTwoFactorRow, SecurityPasskeys and SecurityDeleteAccount each work alone, so you can put them in any section. Return field errors from onChangePassword to show them under the field.

```tsx
"use client"

import { SettingsGroup, SettingsSection } from "../settings/settings"
import {
  SecurityDeleteAccount,
  SecurityPasswordRow,
  SecuritySessions,
  SecurityTwoFactorRow,
  type SecuritySession,
} from "@/components/blocks/security/security"

export function AccountSection({
  email,
  sessions,
  twoFactor,
  refresh,
}: {
  email: string
  sessions: SecuritySession[]
  twoFactor: boolean
  refresh: () => Promise<void>
}) {
  return (
    <SettingsSection id="account">
      <SettingsGroup title="Sign-in">
        <SecurityPasswordRow
          email={email}
          onChangePassword={async ({ currentPassword, newPassword, signOutOthers }) => {
            const response = await fetch("/api/password", {
              method: "PUT",
              body: JSON.stringify({ currentPassword, newPassword, signOutOthers }),
            })
            if (response.status === 403) return { currentPassword: "That password is incorrect." }
            if (response.status === 422) return { newPassword: "That password showed up in a data breach." }
            if (!response.ok) throw new Error("Couldn’t change your password. Try again.")
          }}
        />
        <SecurityTwoFactorRow
          email={email}
          enabled={twoFactor}
          onStart={() => fetch("/api/2fa/setup", { method: "POST" }).then((response) => response.json())}
          onVerify={async (code) => {
            const response = await fetch("/api/2fa/verify", { method: "POST", body: JSON.stringify({ code }) })
            if (!response.ok) throw new Error("That code didn’t work. Try the newest one.")
            const { recoveryCodes } = await response.json()
            await refresh()
            return recoveryCodes
          }}
          onDisable={() => fetch("/api/2fa", { method: "DELETE" }).then(refresh)}
        />
      </SettingsGroup>
      <SecuritySessions
        title="Where you’re signed in"
        sessions={sessions}
        onSignOut={(id) => fetch(`/api/sessions/${id}`, { method: "DELETE" }).then(refresh)}
        onSignOutOthers={() => fetch("/api/sessions/others", { method: "DELETE" }).then(refresh)}
      />
      <SecurityDeleteAccount
        email={email}
        consequences={["Your workspace and its 3 projects", "Your Team plan, canceled right away"]}
        onDelete={async () => {
          const response = await fetch("/api/account", { method: "DELETE" })
          if (!response.ok) throw new Error("Couldn’t delete your account. Nothing was deleted.")
          window.location.assign("/")
        }}
      />
    </SettingsSection>
  )
}
```

## Anatomy

The parts you compose, from the outside in.

| Part | Description |
| --- | --- |
| `SecuritySettings` | Everything below in one call. Each part appears when you pass the data and callbacks it needs. |
| `SecuritySessions` | A group listing signed-in devices, with sign out per device and for all other sessions. |
| `SecurityPasswordRow` | A row that opens the change password dialog. |
| `SecurityTwoFactorRow` | A row with the two-factor status, the setup dialog and the turn-off confirmation. |
| `SecurityPasskeys` | A group listing passkeys, with add and remove. |
| `SecurityDeleteAccount` | A group with the delete account row and its typed confirmation. |
| `measurePassword` | The strength check the password dialog uses, for your own forms. |

## API reference

### SecuritySettings

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `email` | `string` | – | The account’s email. Used in the delete phrase, the password manager hint and the recovery codes file. |
| `sessions` | `SecuritySession[]` | – | { id, browser, os, device?, location?, lastActive, current? }. device is "desktop", "laptop", "phone" or "tablet". |
| `onSignOutSession` | `(id: string) => Promise<void>` | – | Sign out one session. Remove it from sessions when it resolves and the row folds away. |
| `onSignOutOtherSessions` | `() => Promise<void>` | – | Sign out every session except the current one. Runs after the person confirms. |
| `passwordChangedAt` | `Date \| string \| number \| null` | – | Shown as Last changed under Password. |
| `onChangePassword` | `({ currentPassword, newPassword, signOutOthers }) => Promise<void \| errors>` | – | Return { currentPassword } or { newPassword } to show a message under that field, or throw to show it above the buttons. |
| `twoFactorEnabled` | `boolean` | `false` | Whether two-factor is on. |
| `onStartTwoFactor` | `() => Promise<{ uri, secret?, recoveryCodes? }>` | – | Create a pending secret when the setup dialog opens. uri is the otpauth link drawn as the QR code; secret defaults to the one in uri. |
| `onVerifyTwoFactor` | `(code: string) => Promise<void \| string[]>` | – | Check the 6-digit code and turn two-factor on. Return recovery codes to show them, or throw if the code is wrong. |
| `onDisableTwoFactor` | `() => Promise<void>` | – | Turn two-factor off. Runs after the person confirms. |
| `passkeys` | `SecurityPasskey[]` | – | { id, name, createdAt, lastUsed? }. |
| `onAddPasskey` | `() => Promise<void>` | – | Run your WebAuthn registration. A NotAllowedError or AbortError counts as cancelled and shows nothing. |
| `onRemovePasskey` | `(id: string) => Promise<void>` | – | Remove a passkey. Runs after the person confirms. |
| `passkeysSupported` | `boolean` | `detected` | Override the check for WebAuthn support. |
| `onDeleteAccount` | `() => Promise<void>` | – | Delete the account. Runs after the person types the phrase. Throw to keep the dialog open with your message. |
| `deleteConsequences` | `ReactNode[]` | – | What gets deleted, listed in the confirmation. |

### SecuritySessions

Also accepts every SettingsGroup prop.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `sessions` | `SecuritySession[]` | – | The signed-in devices. |
| `onSignOut` | `(id: string) => Promise<void>` | – | Sign out one session. |
| `onSignOutOthers` | `() => Promise<void>` | – | Sign out every other session. |
| `title` | `ReactNode` | `"Active sessions"` | The group heading. |

### SecurityPasswordRow

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `email` | `string` | – | Filled into a hidden username field so password managers update the right login. |
| `changedAt` | `Date \| string \| number \| null` | – | When the password last changed. |
| `onChangePassword` | `(change) => Promise<void \| errors>` | – | Same as on SecuritySettings. |

### SecurityTwoFactorRow

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `email` | `string` | – | Named in the confirmation and the recovery codes file. |
| `enabled` | `boolean` | – | Whether two-factor is on. |
| `onStart` | `() => Promise<{ uri, secret?, recoveryCodes? }>` | – | Same as onStartTwoFactor. |
| `onVerify` | `(code: string) => Promise<void \| string[]>` | – | Same as onVerifyTwoFactor. |
| `onDisable` | `() => Promise<void>` | – | Same as onDisableTwoFactor. |

### SecurityPasskeys

Also accepts every SettingsGroup prop.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `passkeys` | `SecurityPasskey[]` | – | The saved passkeys. |
| `onAdd` | `() => Promise<void>` | – | Run your WebAuthn registration. |
| `onRemove` | `(id: string) => Promise<void>` | – | Remove a passkey. |
| `supported` | `boolean` | `detected` | Whether this browser can create passkeys. |

### SecurityDeleteAccount

Also accepts every SettingsGroup prop.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `email` | `string` | – | The confirmation phrase is delete followed by this. |
| `onDelete` | `() => Promise<void>` | – | Delete the account. |
| `consequences` | `ReactNode[]` | – | What gets deleted with it. |
| `title` | `ReactNode` | `"Danger zone"` | The group heading. |

## Keyboard

| Key | Action |
| --- | --- |
| `Tab` | Moves through the rows and their buttons, then through each dialog. |
| `Enter` | Submits the password form from any field, and deletes the account from the phrase field once it matches. |
| `Escape` | Closes a dialog, except while something is saving. |
| `0–9` | Fills the verification code. It checks itself once all six digits are in, and pasting a code works too. |

## Accessibility

- Destructive actions never get focus first. Confirmations name what they affect, like the devices being signed out or the email being deleted, and the delete phrase field gets focus instead of the button.
- When a row folds away, focus moves to the next row’s button, or the previous one, so it never drops to the page. Closing a dialog returns focus to the button that opened it, or to its replacement when that button is gone.
- Sign-outs, added and removed passkeys and the password strength are announced politely. Errors from your callbacks are announced as alerts and stay next to the field or button they belong to.
- Each password requirement says whether it’s met, the QR code has a text label, and the setup key and recovery codes are readable text you can select.
- With reduced motion, rows fade instead of folding and step changes don’t slide. In high contrast mode the QR code and strength meter keep their shapes.

## Built with

The free HextaUI components Security is made from. Each one installs on its own.

- [Alert dialog](https://hextaui.com/docs/alert-dialog) - A confirmation dialog for destructive or important actions that waits for async work, and becomes a bottom sheet on phones.
- [Badge](https://hextaui.com/docs/badge) - Status labels with colored dots, removable tags that slide closed and counts that roll to their new value.
- [Button](https://hextaui.com/docs/button) - Buttons in every variant and size, with a built-in loading, success and error flow that skips the spinner for fast requests.
- [Checkbox](https://hextaui.com/docs/checkbox) - A checkbox whose check draws in, with indeterminate parents, groups and labels that share its hover.
- [Dialog](https://hextaui.com/docs/dialog) - A window over the page for forms and focused tasks, with a pinned header and footer, nesting, and a swipeable bottom sheet on phones.
- [Field](https://hextaui.com/docs/field) - Labels, descriptions and errors wired to their control, with validation states and layouts for forms.
- [Input](https://hextaui.com/docs/input) - A text input with three sizes, invalid and read-only states, native validation styling and a 16px touch font so phones never zoom in.
- [Input group](https://hextaui.com/docs/input-group) - An input with icons, text, buttons or a keyboard hint attached, sharing one border and focus ring.
- [Input OTP](https://hextaui.com/docs/input-otp) - One-time code slots that take typing, paste and SMS autofill, with an opt-in animation that cascades codes in and a status for verifying.
- [Skeleton](https://hextaui.com/docs/skeleton) - Placeholders that wait 150ms before showing, take the exact size of the content they wrap, and fade it in without moving anything.

## Code

13 files, added to components/blocks/security.
