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

+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>
);
}