feat: two-factor sign-in, required for sensitive permissions (#12)
Release / release (push) Successful in 4s
CI / test (push) Successful in 1m16s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 13s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 19s

Phase 3d (docs/design.md): two-factor sign-in, required for sensitive permissions.

- **Sign-in:** Better Auth's `twoFactor` plugin, using an authenticator app (TOTP) with 10 backup codes. Once it's on, signing in asks for a code from the app or a backup code, and each backup code works once.
- **Account page:** a new Two-Factor Sign-In card.
  - To turn it on: enter your password, scan the QR code (the key is also shown as text), keep the backup codes, and confirm with a code.
  - Once it's on, you can make new backup codes or turn it off; both ask for the password.
  - If you hold sensitive permissions, the card lists the ones that need it.
- **Enforcement:** the sensitive permissions are `product:remove`, `person:ban`, `person:role`, `audit:read-sensitive`, `catalog:transfer`, `catalog:suspend`, `import:grant-on-behalf` and `settings:edit` (`permissions.ts` `sensitive`). Without two-factor on, they answer 403 `two_factor_required`, and API tokens get the same check through their owner.
  - Routes guarded only by the moderator check now also check the permission: removing products, ban and unban, roles, and settings.
- **Console:** a reminder on every console page while two-factor is needed. The People list notes staff without two-factor, and each person's page shows "two-factor on".
- **Closed Better Auth admin endpoints:** `/api/auth/admin/*` now answers 404. Admins could have used these endpoints to ban people or change roles without the check or the audit log.
- **Tests:** a new end-to-end test, `test/two-factor.test.ts`. Moderation tests turn two-factor on for their accounts directly (`test/two-factor.ts`). All 57 API tests pass, and type checks pass.
- **Checked on the scratch hub through the website:**
  - turning it on with a real code
  - the console reminder appearing and disappearing
  - signing in again needing a code
  - a Ban form while two-factor is off showing "Turn on two-factor sign-in on your account page first."
- **Not checked in a browser:** the QR and sign-in code screens.
- **Dependency:** `uqr` draws the QR code; it has no dependencies of its own.

Phase 3d (docs/design.md): two-factor sign-in, required for sensitive permissions.

- **Sign-in:** Better Auth's `twoFactor` plugin, using an authenticator app (TOTP) with 10 backup codes. Once it's on, signing in asks for a code from the app or a backup code, and each backup code works once.
- **Account page:** a new Two-Factor Sign-In card.
  - To turn it on: enter your password, scan the QR code (the key is also shown as text), keep the backup codes, and confirm with a code.
  - Once it's on, you can make new backup codes or turn it off; both ask for the password.
  - If you hold sensitive permissions, the card lists the ones that need it.
- **Enforcement:** the sensitive permissions are `product:remove`, `person:ban`, `person:role`, `audit:read-sensitive`, `catalog:transfer`, `catalog:suspend`, `import:grant-on-behalf` and `settings:edit` (`permissions.ts` `sensitive`). Without two-factor on, they answer 403 `two_factor_required`, and API tokens get the same check through their owner.
  - Routes guarded only by the moderator check now also check the permission: removing products, ban and unban, roles, and settings.
- **Console:** a reminder on every console page while two-factor is needed. The People list notes staff without two-factor, and each person's page shows "two-factor on".
- **Closed Better Auth admin endpoints:** `/api/auth/admin/*` now answers 404. Admins could have used these endpoints to ban people or change roles without the check or the audit log.
- **Tests:** a new end-to-end test, `test/two-factor.test.ts`. Moderation tests turn two-factor on for their accounts directly (`test/two-factor.ts`). All 57 API tests pass, and type checks pass.
- **Checked on the scratch hub through the website:**
  - turning it on with a real code
  - the console reminder appearing and disappearing
  - signing in again needing a code
  - a Ban form while two-factor is off showing "Turn on two-factor sign-in on your account page first."
- **Not checked in a browser:** the QR and sign-in code screens.
- **Dependency:** `uqr` draws the QR code; it has no dependencies of its own.

Later: auditing when two-factor is turned on or off, and an optional "trust this browser".

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Later: auditing when two-factor is turned on or off, and an optional "trust this browser".

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: dhkatz <[email protected]>
This commit was merged in pull request #12.
This commit is contained in:
dhkatz authored and dhkatz committed 2026-11-06 03:23:02 +00:00
1 parent 69c55a72fb
commit eca1884918
28 files changed
+4365 -62

No files matched your search

+3
View File
@@ -12,6 +12,7 @@ import { AgeCard } from "./age-card";
import { ChallengeCard } from "./challenge-card";
import { LinkCard } from "./link-card";
import { TokensCard } from "./tokens-card";
import { TwoFactorCard } from "./two-factor-card";
export const metadata: Metadata = { title: "Account" };
@@ -122,6 +123,8 @@ export default async function Account({ searchParams }: { searchParams: Promise<
</CardContent>
</Card>
<TwoFactorCard enabled={account.twoFactor.enabled} neededFor={account.twoFactor.neededFor} />
<TokensCard data={tokens} />
</div>
);
+291
View File
@@ -0,0 +1,291 @@
"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&apos;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>
);
}
+49 -13
View File
@@ -1,7 +1,16 @@
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { cache } from "react";
import { NavLink } from "@/components/header-client";
import { api, getMe, isModerator, unwrap, type ConsoleData, type Person } from "@/lib/api";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import {
api,
getMe,
isModerator,
unwrap,
type ConsoleData,
type Person,
} from "@/lib/api";
/** The signed-in moderator, or off to sign in; others get not found (these pages aren't for them). */
export async function requireModerator(path: string): Promise<Person> {
@@ -22,7 +31,9 @@ const loadConsole = cache(async (): Promise<ConsoleData | undefined> => {
* The signed-in person and their console, or off to sign in. People who manage nothing get not found: the console
* is for those controlling a product, catalog or room.
*/
export async function requireConsole(path: string): Promise<{ me: Person; console: ConsoleData }> {
export async function requireConsole(
path: string,
): Promise<{ me: Person; console: ConsoleData }> {
const me = await getMe();
if (!me) redirect(`/signin?next=${encodeURIComponent(path)}`);
const data = await loadConsole();
@@ -43,18 +54,43 @@ const tabs: { section: Section; href: string; label: string }[] = [
{ section: "audit", href: "/console/audit", label: "Audit" },
];
/** The console's sections this person may see. */
/** The console's sections this person may see, and a reminder when sensitive actions need two-factor sign-in. */
export async function ConsoleNav() {
const sections = new Set<Section>((await loadConsole())?.sections ?? ["overview"]);
const data = await loadConsole();
const sections = new Set<Section>(data?.sections ?? ["overview"]);
const needed = data?.twoFactorNeededFor ?? [];
return (
<nav className="mb-8 flex gap-1 border-b pb-3 text-sm">
{tabs
.filter((t) => sections.has(t.section))
.map((t) => (
<NavLink key={t.section} href={t.href} exact={t.section === "overview"}>
{t.label}
</NavLink>
))}
</nav>
<>
{needed.length > 0 && (
<Alert className="mb-6">
<AlertTitle>Turn on two-factor sign-in</AlertTitle>
<AlertDescription>
<span>
Some of what you can do here needs it ({needed.join(", ")}).{" "}
<Link
href="/account"
className="text-foreground underline underline-offset-4"
>
Turn it on in your account
</Link>
.
</span>
</AlertDescription>
</Alert>
)}
<nav className="mb-8 flex gap-1 border-b pb-3 text-sm">
{tabs
.filter((t) => sections.has(t.section))
.map((t) => (
<NavLink
key={t.section}
href={t.href}
exact={t.section === "overview"}
>
{t.label}
</NavLink>
))}
</nav>
</>
);
}
@@ -36,6 +36,7 @@ export default async function PersonPage({ params }: { params: Promise<{ id: str
</span>
{person.banned && <Tag tone="danger">banned: {person.banReason}</Tag>}
{!person.approved && <Tag tone="strong">waiting for approval</Tag>}
{person.twoFactor && <Tag>two-factor on</Tag>}
</span>
</PageHeader>
<ConsoleNav />
+6 -1
View File
@@ -65,7 +65,12 @@ export default async function People({
{p.username}
</Link>
</TableCell>
<TableCell className="capitalize">{p.role}</TableCell>
<TableCell>
<span className="capitalize">{p.role}</span>
{p.role !== "user" && !p.twoFactor && (
<span className="ml-2 text-xs text-muted-foreground">no two-factor</span>
)}
</TableCell>
<TableCell className="tabular-nums">{p.linkCap}</TableCell>
<TableCell className="text-muted-foreground">
<DateTime iso={p.createdAt} dateOnly />
+117 -32
View File
@@ -4,30 +4,56 @@ import { useRouter } from "next/navigation";
import { useState } from "react";
import { ErrorText } from "@/components/forms";
import { Button } from "@/components/ui/button";
import { Field, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
import {
Field,
FieldDescription,
FieldGroup,
FieldLabel,
} from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { authClient } from "@/lib/auth-client";
/** Signs in with Better Auth, then goes to next (already checked to be a path on this site). */
/** Signs in with Better Auth (then a code, if two-factor sign-in is on), then goes to next (already checked to be a
* path on this site). */
export function SignInForm({ next }: { next: string }) {
const router = useRouter();
const [error, setError] = useState("");
const [pending, setPending] = useState(false);
// After the password, when two-factor sign-in is on: a code from the app, or a backup code.
const [step, setStep] = useState<"password" | "code" | "backup">("password");
const done = () => {
router.push(next);
router.refresh();
};
async function signIn(form: FormData) {
const { data, error } = await authClient.signIn.username({
username: String(form.get("username")),
password: String(form.get("password")),
});
if (error) return setError(error.message ?? "That didn't work. Try again.");
if (data && "twoFactorRedirect" in data && data.twoFactorRedirect)
return setStep("code");
done();
}
async function verify(form: FormData) {
const code = String(form.get("code")).replace(/\s+/g, "");
const { error } =
step === "code"
? await authClient.twoFactor.verifyTotp({ code })
: await authClient.twoFactor.verifyBackupCode({ code });
if (error)
return setError(error.message ?? "That code didn't work. Try again.");
done();
}
async function submit(form: FormData) {
setError("");
setPending(true);
const { error } = await authClient.signIn.username({
username: String(form.get("username")),
password: String(form.get("password")),
});
if (error) {
setError(error.message ?? "That didn't work. Try again.");
setPending(false);
return;
}
router.push(next);
router.refresh();
await (step === "password" ? signIn(form) : verify(form));
setPending(false);
}
return (
@@ -37,25 +63,84 @@ export function SignInForm({ next }: { next: string }) {
void submit(new FormData(e.currentTarget));
}}
>
<FieldGroup>
<Field>
<FieldLabel htmlFor="username">Username</FieldLabel>
<Input id="username" name="username" autoComplete="username" required autoFocus />
</Field>
<Field>
<FieldLabel htmlFor="password">Password</FieldLabel>
<Input id="password" name="password" type="password" autoComplete="current-password" required />
</Field>
{error && <ErrorText>{error}</ErrorText>}
<Field>
<Button type="submit" disabled={pending}>
{pending ? "Signing in…" : "Sign in"}
</Button>
<FieldDescription className="text-center">
No account? <Link href="/signup">Create one</Link>
</FieldDescription>
</Field>
</FieldGroup>
{step === "password" ? (
<FieldGroup>
<Field>
<FieldLabel htmlFor="username">Username</FieldLabel>
<Input
id="username"
name="username"
autoComplete="username"
required
autoFocus
/>
</Field>
<Field>
<FieldLabel htmlFor="password">Password</FieldLabel>
<Input
id="password"
name="password"
type="password"
autoComplete="current-password"
required
/>
</Field>
{error && <ErrorText>{error}</ErrorText>}
<Field>
<Button type="submit" disabled={pending}>
{pending ? "Signing in…" : "Sign in"}
</Button>
<FieldDescription className="text-center">
No account? <Link href="/signup">Create one</Link>
</FieldDescription>
</Field>
</FieldGroup>
) : (
<FieldGroup key={step}>
<Field>
<FieldLabel htmlFor="code">
{step === "code"
? "Code from your authenticator app"
: "Backup code"}
</FieldLabel>
<Input
id="code"
name="code"
required
autoFocus
autoComplete="one-time-code"
{...(step === "code"
? {
inputMode: "numeric",
pattern: "\\s*[0-9]{6}\\s*",
maxLength: 8,
}
: { maxLength: 32 })}
className="font-mono"
/>
</Field>
{error && <ErrorText>{error}</ErrorText>}
<Field>
<Button type="submit" disabled={pending}>
{pending ? "Checking…" : "Sign in"}
</Button>
<FieldDescription className="text-center">
<button
type="button"
className="underline underline-offset-4"
onClick={() => {
setError("");
setStep(step === "code" ? "backup" : "code");
}}
>
{step === "code"
? "Use a backup code instead"
: "Use your authenticator app instead"}
</button>
</FieldDescription>
</Field>
</FieldGroup>
)}
</form>
);
}