Better Auth's twoFactor plugin: an authenticator app (TOTP) with 10 backup codes. Turning it on, making new backup codes and turning it off are on the account page, and signing in asks for a code once it's on. Sensitive permissions (product:remove, person:ban, person:role, settings:edit, catalog:suspend, ...) answer 403 two_factor_required without it, API tokens included; the console reminds people who need it. Better Auth's own admin endpoints are closed (404). Co-Authored-By: Claude Opus 5.5 <[email protected]>
292 lines
9.5 KiB
TypeScript
292 lines
9.5 KiB
TypeScript
"use client";
|
|
// Two-factor sign-in on the account page: turning it on (scan a code into an authenticator app, keep the backup codes,
|
|
// confirm with a code), new backup codes, and turning it off. Sensitive permissions need it on.
|
|
import { useRouter } from "next/navigation";
|
|
import { useState } from "react";
|
|
import { renderSVG } from "uqr";
|
|
import { CopyButton } from "@/components/copy-button";
|
|
import { ErrorText } from "@/components/forms";
|
|
import { Tag } from "@/components/status";
|
|
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
|
import { Button } from "@/components/ui/button";
|
|
import {
|
|
Card,
|
|
CardContent,
|
|
CardDescription,
|
|
CardHeader,
|
|
CardTitle,
|
|
} from "@/components/ui/card";
|
|
import { Input } from "@/components/ui/input";
|
|
import { authClient } from "@/lib/auth-client";
|
|
|
|
type Stage =
|
|
| { kind: "idle" }
|
|
| { kind: "password"; then: "enable" | "codes" | "disable" }
|
|
| { kind: "setup"; uri: string; codes: string[] }
|
|
| { kind: "codes"; codes: string[] };
|
|
|
|
export function TwoFactorCard({
|
|
enabled,
|
|
neededFor,
|
|
}: {
|
|
enabled: boolean;
|
|
neededFor: string[];
|
|
}) {
|
|
const router = useRouter();
|
|
const [stage, setStage] = useState<Stage>({ kind: "idle" });
|
|
const [error, setError] = useState("");
|
|
const [pending, setPending] = useState(false);
|
|
|
|
async function run(fn: () => Promise<string | void>) {
|
|
setError("");
|
|
setPending(true);
|
|
const failed = await fn();
|
|
if (failed) setError(failed);
|
|
setPending(false);
|
|
}
|
|
|
|
async function withPassword(
|
|
then: "enable" | "codes" | "disable",
|
|
password: string,
|
|
) {
|
|
if (then === "enable") {
|
|
const { data, error } = await authClient.twoFactor.enable({ password });
|
|
if (error || !data || !("totpURI" in data) || !data.totpURI)
|
|
return error?.message ?? "That didn't work. Try again.";
|
|
setStage({
|
|
kind: "setup",
|
|
uri: data.totpURI,
|
|
codes: data.backupCodes ?? [],
|
|
});
|
|
} else if (then === "codes") {
|
|
const { data, error } = await authClient.twoFactor.generateBackupCodes({
|
|
password,
|
|
});
|
|
if (error || !data)
|
|
return error?.message ?? "That didn't work. Try again.";
|
|
setStage({ kind: "codes", codes: data.backupCodes });
|
|
} else {
|
|
const { error } = await authClient.twoFactor.disable({ password });
|
|
if (error) return error.message ?? "That didn't work. Try again.";
|
|
setStage({ kind: "idle" });
|
|
router.refresh();
|
|
}
|
|
}
|
|
|
|
async function confirm(code: string) {
|
|
const { error } = await authClient.twoFactor.verifyTotp({
|
|
code: code.replace(/\s+/g, ""),
|
|
});
|
|
if (error) return error.message ?? "That code didn't work. Try again.";
|
|
setStage({ kind: "idle" });
|
|
router.refresh();
|
|
}
|
|
|
|
const submitTo =
|
|
(fn: (form: FormData) => Promise<string | void>) =>
|
|
(e: React.FormEvent<HTMLFormElement>) => {
|
|
e.preventDefault();
|
|
const form = new FormData(e.currentTarget);
|
|
void run(() => fn(form));
|
|
};
|
|
|
|
return (
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="flex items-center gap-2">
|
|
Two-Factor Sign-In {enabled && <Tag tone="strong">on</Tag>}
|
|
</CardTitle>
|
|
<CardDescription>
|
|
Signing in asks for a code from an authenticator app on your phone as
|
|
well as your password.
|
|
</CardDescription>
|
|
</CardHeader>
|
|
<CardContent className="space-y-4">
|
|
{!enabled && neededFor.length > 0 && stage.kind !== "setup" && (
|
|
<Alert>
|
|
<AlertTitle>Turn this on to use everything you can do</AlertTitle>
|
|
<AlertDescription>
|
|
<span>
|
|
These need it:{" "}
|
|
{neededFor.map((p, i) => (
|
|
<span key={p}>
|
|
{i > 0 && ", "}
|
|
<span className="font-mono text-xs">{p}</span>
|
|
</span>
|
|
))}
|
|
.
|
|
</span>
|
|
</AlertDescription>
|
|
</Alert>
|
|
)}
|
|
|
|
{stage.kind === "idle" &&
|
|
(enabled ? (
|
|
<div className="flex flex-wrap gap-2">
|
|
<Button
|
|
variant="outline"
|
|
onClick={() => setStage({ kind: "password", then: "codes" })}
|
|
>
|
|
New backup codes
|
|
</Button>
|
|
<Button
|
|
variant="outline"
|
|
onClick={() => setStage({ kind: "password", then: "disable" })}
|
|
>
|
|
Turn off
|
|
</Button>
|
|
</div>
|
|
) : (
|
|
<Button
|
|
onClick={() => setStage({ kind: "password", then: "enable" })}
|
|
>
|
|
Turn on
|
|
</Button>
|
|
))}
|
|
|
|
{stage.kind === "password" && (
|
|
<form
|
|
onSubmit={submitTo((f) =>
|
|
withPassword(stage.then, String(f.get("password"))),
|
|
)}
|
|
className="space-y-3"
|
|
>
|
|
<p className="text-sm">
|
|
{stage.then === "disable"
|
|
? neededFor.length > 0
|
|
? "Turning it off stops the things listed above working until you turn it on again. Enter your password."
|
|
: "Enter your password to turn it off."
|
|
: stage.then === "codes"
|
|
? "Your old backup codes stop working. Enter your password."
|
|
: "Enter your password to start."}
|
|
</p>
|
|
<div className="flex max-w-md flex-wrap gap-2">
|
|
<Input
|
|
name="password"
|
|
type="password"
|
|
autoComplete="current-password"
|
|
required
|
|
autoFocus
|
|
aria-label="Password"
|
|
className="max-w-xs"
|
|
/>
|
|
<Button
|
|
type="submit"
|
|
variant={stage.then === "disable" ? "destructive" : "default"}
|
|
disabled={pending}
|
|
>
|
|
{pending
|
|
? "Checking…"
|
|
: stage.then === "disable"
|
|
? "Turn off"
|
|
: "Continue"}
|
|
</Button>
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
onClick={() => setStage({ kind: "idle" })}
|
|
>
|
|
Cancel
|
|
</Button>
|
|
</div>
|
|
</form>
|
|
)}
|
|
|
|
{stage.kind === "setup" && (
|
|
<div className="space-y-4">
|
|
<ol className="list-decimal space-y-4 pl-5 text-sm">
|
|
<li className="space-y-2">
|
|
<p>
|
|
Scan this with an authenticator app (such as Google
|
|
Authenticator, Microsoft Authenticator or 1Password).
|
|
</p>
|
|
<div
|
|
className="w-44 rounded-md bg-white p-2 [&>svg]:h-auto [&>svg]:w-full"
|
|
role="img"
|
|
aria-label="QR code for your authenticator app"
|
|
dangerouslySetInnerHTML={{
|
|
__html: renderSVG(stage.uri, { border: 1 }),
|
|
}}
|
|
/>
|
|
<p className="text-muted-foreground">
|
|
Or enter this key:{" "}
|
|
<code className="font-mono text-xs break-all text-foreground">
|
|
{new URL(stage.uri).searchParams.get("secret")}
|
|
</code>
|
|
</p>
|
|
</li>
|
|
<li className="space-y-2">
|
|
<p>
|
|
Keep these backup codes somewhere safe. Each signs you in once
|
|
if you lose your phone.
|
|
</p>
|
|
<BackupCodes codes={stage.codes} />
|
|
</li>
|
|
<li className="space-y-2">
|
|
<p>Enter the code the app shows.</p>
|
|
<form
|
|
onSubmit={submitTo((f) => confirm(String(f.get("code"))))}
|
|
className="flex max-w-md flex-wrap gap-2"
|
|
>
|
|
<Input
|
|
name="code"
|
|
required
|
|
inputMode="numeric"
|
|
pattern="\s*[0-9]{6}\s*"
|
|
maxLength={8}
|
|
autoComplete="one-time-code"
|
|
aria-label="Code"
|
|
placeholder="123456"
|
|
className="w-32 font-mono"
|
|
/>
|
|
<Button type="submit" disabled={pending}>
|
|
{pending ? "Checking…" : "Turn on"}
|
|
</Button>
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
onClick={() => setStage({ kind: "idle" })}
|
|
>
|
|
Cancel
|
|
</Button>
|
|
</form>
|
|
</li>
|
|
</ol>
|
|
</div>
|
|
)}
|
|
|
|
{stage.kind === "codes" && (
|
|
<div className="space-y-2 text-sm">
|
|
<p>
|
|
Your new backup codes. Keep them somewhere safe: they won't
|
|
be shown again.
|
|
</p>
|
|
<BackupCodes codes={stage.codes} />
|
|
<Button
|
|
variant="outline"
|
|
onClick={() => setStage({ kind: "idle" })}
|
|
>
|
|
Done
|
|
</Button>
|
|
</div>
|
|
)}
|
|
|
|
{error && <ErrorText>{error}</ErrorText>}
|
|
</CardContent>
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
function BackupCodes({ codes }: { codes: string[] }) {
|
|
return (
|
|
<div className="flex flex-wrap items-start gap-3">
|
|
<ul className="grid grid-cols-2 gap-x-6 gap-y-1 rounded-md bg-muted px-3 py-2 font-mono text-xs">
|
|
{codes.map((c) => (
|
|
<li key={c}>{c}</li>
|
|
))}
|
|
</ul>
|
|
<CopyButton text={codes.join("\n")} />
|
|
</div>
|
|
);
|
|
}
|