Files
t5de-hub/apps/web/app/account/two-factor-card.tsx
T
dhkatzandClaude Opus 5.5 7d708aebdb
Pull request / title (pull_request) Successful in 1s
CI / test (pull_request) Successful in 1m15s
CI / image (apps/api/Dockerfile, t5de-hub-api) (pull_request) Skipped
CI / image (apps/web/Dockerfile, t5de-hub-web) (pull_request) Skipped
feat: IMVU imports on the hub: grants, requests and the importer's job queue
Creators grant a catalog leave to import their IMVU products (whole shop less
exclusions, or listed products) from a linked IMVU account, agreeing to a versioned
consent text; the catalog's team accepts or declines. Requests queue covered
products (or add them to the library when imported already), suggest, or count.
Importers claim jobs with the catalog's importer key, get t5de-import tokens, and
the catalog registers imported revisions as published products owned by the creator.
Narrowing or withdrawing a grant withdraws products; unlinking suspends grants;
an hourly batch rechecks imported products with IMVU daily. Website: /imports and
the console's catalog imports page.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 19:46:10 -08:00

233 lines
8.9 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&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>
);
}