Phase 4a (docs/imports.md): the hub's side of IMVU imports. **Grants** - A creator picks one of their linked IMVU accounts and a catalog with imports on. They choose the whole shop (with exclusions) or listed products, listed or unlisted, and agree to a versioned consent text (`imports.ts` `consent`). - The catalog's team (`import:accept`) accepts or declines, and the creator is notified. Accepting queues what people already asked for, plus a grant's listed products. - The creator can change what's covered or withdraw it; the team (`import:withdraw`, which moderators also have) can end it. - Withdrawn products are removed the way moderation removes products: their hosting is dropped and their files go in the catalogs' changes feed. If another catalog's active grant still covers a product, it's only delisted from this catalog. - Unlinking an IMVU account, or someone else linking it, suspends its grants. **Requests** - Anyone signed in can ask for an IMVU product (an ID or a shop link). The answer is one of: - `added`: already imported, and now in their library - `queued`: delivered to their library once imported - `suggested`: the creator grants by listed products, and will see the request - `counted`: no grant covers it yet - Creators see request counts for their accounts, and moderators see the most-requested creators. - At most 50 requests a day per person. **Importer** - Importers sign in with `Authorization: Importer <catalog>:<key>`; turning imports on returns the key once. The catalog's importer can be paused (`import:pause`). - Importers claim jobs, get `t5de-import` tokens for a revision, and report outcomes. - Claims time out after 30 minutes. Failures retry after 1 min, 10 min, 1 h, then daily, and fail for good after 5 attempts. - `POST /catalog/revisions` takes `importToken` instead of `uploadToken`. The result is a published product owned by the creator (`product.imvu_product`, `product_revision.imvu_revision`). If another catalog already imported the same IMVU revision, this catalog hosts it too. - Every hour, the API rechecks a batch of imported products with IMVU (each at most once a day). A product gone from IMVU, or now another creator's, is withdrawn. One rated AP becomes adult. If it's still covered, a recheck job looks for new revisions. **Website** - `/imports`: ask for a product; bring your products; change or withdraw a grant; what people asked for. It's linked from the account page. - The console's catalog page has an Imports card leading to `/console/catalogs/:id/imports`: - importer on, off, pause and resume, and a new key - pending grants to accept or decline - grants to end - the queue, filtered by status, with retry - Notification text for the two new notification types. **Checks** - **Tests:** `test/imports.test.ts` covers the whole flow, from grant to withdrawal. All 58 API tests pass, and type checks pass. - **Scratch hub:** through the console forms, I turned imports on (the key was shown once), paused and resumed. I checked that importer claims accept the key and refuse a wrong one, that `/imports` renders, and that a request while IMVU is unreachable says "IMVU didn't answer." - **IMVU fields not checked live:** `api.imvu.com` times out from the dev machine. The product fields (`product_name`, `creator_cid`, `creator_name`, `rating`, `is_purchasable`) are what the design recorded; the spike will check them. **Formatting** - `two-factor-card.tsx`, `signin-form.tsx` and `console-nav.tsx` are only reformatted. I'd run Prettier on them at its default 80 columns in #12, but the repo is wrapped at about 120. **Still to do (4b and later)** - admin-recorded grants, proofs and unclaimed creators (and claiming them) - `GET /imports/available` for the proxy's shop button - t5de-catalog accepting `t5de-import` tokens on uploads - the spike, then `t5de-importer` 🤖 Generated with [Claude Code](https://claude.com/claude-code) Phase 4a (docs/imports.md): the hub's side of IMVU imports. **Grants** - A creator picks one of their linked IMVU accounts and a catalog with imports on. They choose the whole shop (with exclusions) or listed products, listed or unlisted, and agree to a versioned consent text (`imports.ts` `consent`). - The catalog's team (`import:accept`) accepts or declines, and the creator is notified. Accepting queues what people already asked for, plus a grant's listed products. - The creator can change what's covered or withdraw it; the team (`import:withdraw`, which moderators also have) can end it. - Withdrawn products are removed the way moderation removes products: their hosting is dropped and their files go in the catalogs' changes feed. If another catalog's active grant still covers a product, it's only delisted from this catalog. - Unlinking an IMVU account, or someone else linking it, suspends its grants. **Requests** - Anyone signed in can ask for an IMVU product (an ID or a shop link). The answer is one of: - `added`: already imported, and now in their library - `queued`: delivered to their library once imported - `suggested`: the creator grants by listed products, and will see the request - `counted`: no grant covers it yet - Creators see request counts for their accounts, and moderators see the most-requested creators. - At most 50 requests a day per person. **Importer** - Importers sign in with `Authorization: Importer <catalog>:<key>`; turning imports on returns the key once. The catalog's importer can be paused (`import:pause`). - Importers claim jobs, get `t5de-import` tokens for a revision, and report outcomes. - Claims time out after 30 minutes. Failures retry after 1 min, 10 min, 1 h, then daily, and fail for good after 5 attempts. - `POST /catalog/revisions` takes `importToken` instead of `uploadToken`. The result is a published product owned by the creator (`product.imvu_product`, `product_revision.imvu_revision`). If another catalog already imported the same IMVU revision, this catalog hosts it too. - Every hour, the API rechecks a batch of imported products with IMVU (each at most once a day). A product gone from IMVU, or now another creator's, is withdrawn. One rated AP becomes adult. If it's still covered, a recheck job looks for new revisions. **Website** - `/imports`: ask for a product; bring your products; change or withdraw a grant; what people asked for. It's linked from the account page. - The console's catalog page has an Imports card leading to `/console/catalogs/:id/imports`: - importer on, off, pause and resume, and a new key - pending grants to accept or decline - grants to end - the queue, filtered by status, with retry - Notification text for the two new notification types. **Checks** - **Tests:** `test/imports.test.ts` covers the whole flow, from grant to withdrawal. All 58 API tests pass, and type checks pass. - **Scratch hub:** through the console forms, I turned imports on (the key was shown once), paused and resumed. I checked that importer claims accept the key and refuse a wrong one, that `/imports` renders, and that a request while IMVU is unreachable says "IMVU didn't answer." - **IMVU fields not checked live:** `api.imvu.com` times out from the dev machine. The product fields (`product_name`, `creator_cid`, `creator_name`, `rating`, `is_purchasable`) are what the design recorded; the spike will check them. **Formatting** - `two-factor-card.tsx`, `signin-form.tsx` and `console-nav.tsx` are only reformatted. I'd run Prettier on them at its default 80 columns in #12, but the repo is wrapped at about 120. **Still to do (4b and later)** - admin-recorded grants, proofs and unclaimed creators (and claiming them) - `GET /imports/available` for the proxy's shop button - t5de-catalog accepting `t5de-import` tokens on uploads - the spike, then `t5de-importer` 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: dhkatz <[email protected]>
233 lines
8.9 KiB
TypeScript
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'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>
|
|
);
|
|
}
|