# Sudo gate

> Wrap any dangerous button. A padlock on its corner shows how long you stay verified; when it’s locked, the button grows right where it stands into the “Confirm it’s you” card.

Apps ask you to sign in again before deleting an account, showing a key or changing an email, and the usual way is a modal that comes out of nowhere, every time. Sudo gate makes that window visible. A small padlock sits on the button’s corner: open, inside a ring of the time you have left (“8 min”, then “42s” in amber), or shut once it runs out. Click a locked button and it grows where it stands: the button itself widens and deepens into the card that asks (a passkey, a code or a password), pushing what’s around it aside, its label giving way to the question. Verify, and the big padlock swings open; the card folds back down into the button with the small padlock riding its corner, its ring filling, and your click goes through to the app’s own handler. Every gate on the page shares one trust window, so one verification unlocks them all.

## Install

```bash
npx shadcn@latest add https://hairlineui.com/r/sudo-gate.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): `code-input`, `number-roll`, `status-button`, `text-morph`
- Docs and live preview: https://hairlineui.com/ui/sudo-gate
- Registry item (source): https://hairlineui.com/r/sudo-gate.json

## Usage

```tsx
import { SudoGate } from "@/components/sudo-gate";

<SudoGate
  verify={async (proof) => { /* check it with your auth, throw if it fails */ }}
  reason="Deleting your account needs a recent sign-in."
>
  <Button variant="destructive" onClick={deleteAccount}>Delete account</Button>
</SudoGate>
```

## With Better Auth or Clerk

Better Auth’s deleteUser() needs a fresh session (its createdAt within session.freshAge) when no password is sent, so the gate signs you in again (passkey or email code) right before the delete runs. Clerk lets a sensitive action through for 10 minutes after a verification and runs it from session.startVerification. Either way, your server still checks before it acts.

```tsx
"use client";
import { SudoGate } from "@/components/sudo-gate";
import { authClient } from "@/lib/auth-client"; // Better Auth with the passkey and emailOTP client plugins

const FRESH_AGE = 60 * 10; // the same as session.freshAge in your betterAuth() config

export function DeleteAccount() {
  const { data } = authClient.useSession();
  if (!data) return null;
  const email = data.user.email;

  return (
    <SudoGate
      freshUntil={new Date(data.session.createdAt).getTime() + FRESH_AGE * 1000}
      trustFor={FRESH_AGE}
      methods={["passkey", "code"]}
      codeHint={email}
      reason="Deleting your account needs a recent sign-in."
      sendCode={async () => {
        const { error } = await authClient.emailOtp.sendVerificationOtp({ email, type: "sign-in" });
        if (error) throw new Error(error.message);
      }}
      verify={async (proof) => {
        const { error } =
          proof.method === "passkey"
            ? await authClient.signIn.passkey()
            : proof.method === "code"
              ? await authClient.signIn.emailOtp({ email, otp: proof.code })
              : await authClient.signIn.email({ email, password: proof.password });
        if (error) throw new Error(error.message);
      }}
    >
      {/* Runs once you're verified: the session is fresh, so Better Auth lets the delete through. */}
      <button
        onClick={async () => {
          const { error } = await authClient.deleteUser();
          if (error) alert(error.message);
        }}
      >
        Delete account
      </button>
    </SudoGate>
  );
}

// Clerk: verify with a code through the session's own verification.
//   const { session } = useSession();
//   sendCode={async () => {
//     const v = await session!.startVerification({ level: "first_factor" });
//     const factor = v.supportedFirstFactors?.find((f) => f.strategy === "email_code");
//     await session!.prepareFirstFactorVerification({ strategy: "email_code", emailAddressId: factor!.emailAddressId });
//   }}
//   verify={async (proof) => {
//     if (proof.method !== "code") throw new Error("Use the code we sent you.");
//     await session!.attemptFirstFactorVerification({ strategy: "email_code", code: proof.code });
//   }}
//   methods={["code"]} trustFor={600}
// On the server: if (!has({ reverification: "strict" })) return reverificationErrorResponse("strict");
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` | `ReactElement` | – | The app’s own button or link. Its click is held until you’re verified, then the gate clicks it for you. |
| `verify` | `(proof: SudoProof) => Promise<unknown>` | – | Checks { method: "passkey" }, { method: "code", code } or { method: "password", password }. Resolve to unlock, optionally with a Date or ms for when the trust ends; throw an Error to show its message. |
| `freshUntil` | `Date \| number \| null` | – | When the current trust ends, from your session. Leave out to start locked. |
| `trustFor` | `number` | `600` | Seconds a verification lasts when verify doesn’t say, and the full length of the ring. |
| `methods` | `("passkey" \| "code" \| "password")[]` | `["passkey", "code"]` | The ways in, first one shown first; the rest are links under it. |
| `sendCode` | `() => Promise<unknown>` | – | Sends the one-time code. Runs as the code view opens and on resend; throw to show why it failed. |
| `codeHint` | `string` | – | Where the code went, shown in its label. |
| `reason` | `string` | `"This action needs a recent sign-in."` | Why this button asks, under “Confirm it’s you”. |
| `scope` | `string` | `"session"` | Gates with the same scope share one trust window. |
| `badge` | `boolean` | `true` | Shows the padlock on the button’s corner. |
| `expireSudo(scope?)` | `function` | – | Exported: locks every gate in a scope, e.g. when your server answers that the session isn’t fresh, or on sign-out. |

## States

- **locked**: The badge is a round padlock with its shackle down and no ring. A click on the button is held and the button goes to ask.
- **asking**: The button grows in place from its own size, colour and radius to a 360px card (the screen less 16px a side on phones) over 520ms, its height measured from the content, so the layout around it makes room. Its label fades within 140ms and the question rises out of a 6px blur from 150ms. Escape, the cross, a press elsewhere or focus leaving folds it back.
- **verifying**: The method’s button turns into a spinner (“Waiting for your passkey”, “Checking”); a code row sweeps with light. A thrown error says why under it, and a wrong code shakes and clears.
- **unlocked**: The big padlock swings open on its right leg as its ring fills green. 760ms later the card folds back into the button over 440ms, the label returning as it lands, while the small padlock rides its corner with its ring filling; the click goes through once the button is back.
- **trusted**: The badge shows the time left: whole minutes rolling down, then seconds in the last minute with the ring turning amber. The ring drains in one long animation; the clock re-renders once a second only while trusted.
- **expired**: The text folds away, the ring empties and the shackle drops shut. Other gates in the scope fill up over 600ms when any one of them is verified.

## What it handles

Step-up auth usually arrives as a modal out of nowhere, and nobody can tell when it will ask again. The gate shows the trust window on the button, and the question grows out of the button you pressed, right where it is.

- **You can see the window**: An open padlock and a draining ring say you’re verified and for how long; a shut one says the next click will ask.
- **The button becomes the question**: The locked button grows in place into the card that asks, and folds back into the same button; nothing pops up over the page and you never lose track of what asked.
- **Your click still happens**: Once you’re verified, the gate clicks the app’s own button for you, so its handler, form or link runs as if nothing stopped it.
- **Three ways in**: Passkey, a one-time code (sent as the view opens, with autofill, paste and a resend clock) or a password, in the order you list.
- **One window per session**: Gates in the same scope share the trust: verify once and every badge on the page fills. expireSudo() locks them all.
- **Your auth, your server**: It only calls verify and sendCode. Errors you throw show in the card; the server stays the judge of freshness.

## Replaces

a reauthentication modal, fresh-session checks in the client, a countdown timer, passkey, code and password forms, retrying the original click

## Where it fits

- **Danger zones**: Delete an account, transfer ownership or close a workspace.
- **Secrets**: Reveal or roll an API key, a webhook secret or recovery codes.
- **Account security**: Change the email or password, turn off two-factor, remove a passkey.
- **Money**: Change the payout account, raise a spending limit or issue a refund.

## Notes

- The gate holds the click in the capture phase (preventDefault and stopPropagation), so a form doesn’t submit and a link doesn’t navigate until you’re verified. Enter and Space on the button work the same way.
- The button gets an aria-describedby saying whether it will ask. The card is a group labelled by its title; focus moves into it as it opens and back to the button on Escape or the cross.
- “Verified. Unlocked for N minutes.” is announced once from a status region outside the button; the ticking time on the badge is hidden from screen readers.
- The card takes the button’s place in the layout, so whatever sits beside or under the button moves to make room and moves back when it folds. Give the button a parent that can grow.
- Reduced motion: the card appears and goes at once without growing, and the shackle changes in place. The ring still drains, since it carries the information.
- This is the client half. The server must still refuse the action when the session isn’t fresh; call expireSudo() when it does, and the next click asks.

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