feat: importer IMVU accounts and settings from the console (#14)
Co-authored-by: dhkatz <[email protected]>
This commit was merged in pull request #14.
This commit is contained in:
1 parent
7ece681eef
commit
e6a97be894
16 files changed
+5538
-13
No files matched your search
@@ -0,0 +1,186 @@
|
||||
"use client";
|
||||
// Adds an IMVU account to the catalog's importer, or gives one a new password (docs/imports.md "IMVU accounts").
|
||||
// The account is looked up and shown for confirmation first; then the password is sealed here, in the browser, for
|
||||
// the importer's public key, so the hub only ever has the sealed copy.
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState, useTransition } from "react";
|
||||
import { Tag } from "@/components/status";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { shortFingerprint } from "@/lib/importer";
|
||||
import { lookupImporterAccount, saveImporterAccount, type ImvuAccountInfo } from "../../actions";
|
||||
|
||||
/** Seals {imvuId, password} for the importer's key: RSA-OAEP with SHA-256, base64. */
|
||||
async function seal(publicKey: string, imvuId: number, password: string): Promise<string> {
|
||||
if (!globalThis.crypto?.subtle) throw new Error("This browser can't encrypt here (the page needs HTTPS).");
|
||||
const spki = Uint8Array.from(atob(publicKey), (c) => c.charCodeAt(0));
|
||||
const key = await crypto.subtle.importKey("spki", spki, { name: "RSA-OAEP", hash: "SHA-256" }, false, ["encrypt"]);
|
||||
const data = new TextEncoder().encode(JSON.stringify({ imvuId, password }));
|
||||
const sealed = new Uint8Array(await crypto.subtle.encrypt({ name: "RSA-OAEP" }, key, data));
|
||||
let s = "";
|
||||
for (const b of sealed) s += String.fromCharCode(b);
|
||||
return btoa(s);
|
||||
}
|
||||
|
||||
export function ImporterAccountForm({
|
||||
catalogId,
|
||||
publicKey,
|
||||
fingerprint,
|
||||
version,
|
||||
account,
|
||||
}: {
|
||||
catalogId: string;
|
||||
publicKey: string;
|
||||
fingerprint: string;
|
||||
version: string;
|
||||
/** Set to give an existing account a new password. */
|
||||
account?: { id: string; imvuId: number; username: string };
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [username, setUsername] = useState(account?.username ?? "");
|
||||
const [password, setPassword] = useState("");
|
||||
const [found, setFound] = useState<ImvuAccountInfo | null>(null);
|
||||
const [error, setError] = useState("");
|
||||
const [notice, setNotice] = useState("");
|
||||
const [pending, start] = useTransition();
|
||||
const [saving, setSaving] = useState(false); // the confirm step, not the lookup
|
||||
|
||||
const check = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError("");
|
||||
setNotice("");
|
||||
if (!username.trim() || !password) return setError("Give the account's username and password.");
|
||||
if (password.length > 128) return setError("That password is too long.");
|
||||
start(async () => {
|
||||
const r = await lookupImporterAccount(catalogId, username);
|
||||
if ("error" in r) return setError(r.error);
|
||||
if (account && r.ok.imvuId !== account.imvuId)
|
||||
return setError(
|
||||
`${account.username} is another IMVU account now (ID ${r.ok.imvuId}). Remove it and add that one.`,
|
||||
);
|
||||
setFound(r.ok);
|
||||
});
|
||||
};
|
||||
|
||||
const confirm = () => {
|
||||
if (!found) return;
|
||||
setSaving(true);
|
||||
start(async () => {
|
||||
try {
|
||||
await save(found);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const save = async (found: ImvuAccountInfo) => {
|
||||
let sealed: string;
|
||||
try {
|
||||
sealed = await seal(publicKey, found.imvuId, password);
|
||||
} catch (e) {
|
||||
setFound(null);
|
||||
return setError(e instanceof Error ? e.message : "The password couldn't be encrypted.");
|
||||
}
|
||||
const r = await saveImporterAccount(catalogId, { imvuId: found.imvuId, account: account?.id, sealed, fingerprint });
|
||||
setFound(null);
|
||||
if ("error" in r) return setError(r.error);
|
||||
setPassword("");
|
||||
if (!account) setUsername("");
|
||||
setNotice(
|
||||
account
|
||||
? "Saved. The importer picks the new password up within a minute."
|
||||
: `${found.username} added. The importer picks it up within a minute.`,
|
||||
);
|
||||
router.refresh();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<form onSubmit={check} className="flex max-w-2xl flex-wrap items-center gap-2">
|
||||
{!account && (
|
||||
<Input
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder="IMVU username"
|
||||
aria-label="IMVU username"
|
||||
autoComplete="off"
|
||||
maxLength={64}
|
||||
className="min-w-44 flex-1"
|
||||
/>
|
||||
)}
|
||||
{/* No name: the password is never sent as a form field, only sealed. */}
|
||||
<Input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder={account ? `New password for ${account.username}` : "Password"}
|
||||
aria-label="Password"
|
||||
autoComplete="new-password"
|
||||
className="min-w-44 flex-1"
|
||||
/>
|
||||
<Button type="submit" variant={account ? "outline" : "default"} disabled={pending}>
|
||||
{pending && !saving ? "Checking…" : account ? "Save password" : "Add account"}
|
||||
</Button>
|
||||
</form>
|
||||
{error && <p className="mt-2 text-sm text-red-700 dark:text-red-400">{error}</p>}
|
||||
{notice && <p className="mt-2 text-sm text-muted-foreground">{notice}</p>}
|
||||
|
||||
<Dialog open={found !== null} onOpenChange={(open) => !open && !pending && setFound(null)}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{account ? "New Password for This Account?" : "Add This Account?"}</DialogTitle>
|
||||
<DialogDescription>The importer signs in to IMVU with it to import products.</DialogDescription>
|
||||
</DialogHeader>
|
||||
{found && (
|
||||
<div className="flex items-center gap-3 rounded-lg border p-3">
|
||||
{found.picture ? (
|
||||
<img src={found.picture} alt="" className="size-14 rounded-md bg-muted object-cover object-top" />
|
||||
) : (
|
||||
<span
|
||||
className="grid size-14 place-items-center rounded-md bg-muted text-lg font-semibold uppercase"
|
||||
aria-hidden
|
||||
>
|
||||
{found.username.slice(0, 1)}
|
||||
</span>
|
||||
)}
|
||||
<div className="min-w-0 space-y-1">
|
||||
<p className="truncate font-medium">{found.username}</p>
|
||||
<p className="text-xs text-muted-foreground">IMVU ID {found.imvuId}</p>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{found.accessPass ? <Tag tone="adult">Access Pass</Tag> : <Tag>No Access Pass</Tag>}
|
||||
{found.ageVerified ? <Tag tone="adult">Age verified</Tag> : <Tag>Not age verified</Tag>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{found && !found.accessPass && (
|
||||
<p className="text-sm text-amber-700 dark:text-amber-400">
|
||||
Without Access Pass, the importer can't see AP products, so it can't import them with this
|
||||
account.
|
||||
</p>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
The password is encrypted in this browser for your importer (key {shortFingerprint(fingerprint)}
|
||||
{version ? `, version ${version}` : ""}) and kept only there. T5DE's hub never sees it.
|
||||
</p>
|
||||
<DialogFooter>
|
||||
<DialogClose render={<Button variant="outline" disabled={pending} />}>Cancel</DialogClose>
|
||||
<Button onClick={confirm} disabled={pending}>
|
||||
{saving ? "Saving…" : account ? "Save password" : "Add account"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -9,7 +9,9 @@ import { Input } from "@/components/ui/input";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { api, unwrap, type ImportGrant } from "@/lib/api";
|
||||
import { ConsoleNav, requireConsole } from "../../../console-nav";
|
||||
import { decideGrant, retryJob, setImporter } from "../../actions";
|
||||
import { shortFingerprint } from "@/lib/importer";
|
||||
import { changeImporterAccount, decideGrant, retryJob, setImporter, setImporterSettings } from "../../actions";
|
||||
import { ImporterAccountForm } from "./importer-account-form";
|
||||
|
||||
export const metadata: Metadata = { title: "Imports" };
|
||||
|
||||
@@ -27,6 +29,13 @@ const jobTone = {
|
||||
failed: "danger",
|
||||
done: "online",
|
||||
} as const;
|
||||
const accountState = {
|
||||
waiting: { tone: "neutral", label: "waiting for the importer" },
|
||||
received: { tone: "strong", label: "not tried yet" },
|
||||
ok: { tone: "online", label: "signed in" },
|
||||
sign_in_failed: { tone: "danger", label: "sign-in failed" },
|
||||
needs_password: { tone: "danger", label: "needs its password" },
|
||||
} as const;
|
||||
const imvuPage = (id: number) => `https://www.imvu.com/shop/product.php?products_id=${id}`;
|
||||
|
||||
export default async function CatalogImports({
|
||||
@@ -73,6 +82,19 @@ export default async function CatalogImports({
|
||||
? "With imports on, creators can bring their IMVU products here, and your importer (t5de-importer, run beside the catalog) imports what they allow."
|
||||
: `The importer signs in with the catalog's ID (${id}) and its importer key. ${data.counts.queued} queued, ${data.counts.claimed} working, ${data.counts.failed} failed, ${data.counts.done} done.`}
|
||||
</CardDescription>
|
||||
{data.importer !== "off" && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{data.program.seenAt ? (
|
||||
<>
|
||||
Importer {data.program.version || "(no version)"}, last heard from{" "}
|
||||
<DateTime iso={data.program.seenAt} />
|
||||
{data.program.fingerprint && <>, key {shortFingerprint(data.program.fingerprint)}</>}.
|
||||
</>
|
||||
) : (
|
||||
"The importer hasn't connected yet."
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</CardHeader>
|
||||
{(can.run || can.pause) && (
|
||||
<CardContent>
|
||||
@@ -126,6 +148,160 @@ export default async function CatalogImports({
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{data.importer !== "off" && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>IMVU Accounts</CardTitle>
|
||||
<CardDescription>
|
||||
The importer signs in to IMVU with these, in this order, moving to the next when one fails. Without an
|
||||
account it imports only what IMVU shows signed out; AP products need one with Access Pass. Passwords are
|
||||
encrypted in your browser for the importer and kept only by it.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{data.accounts.length > 0 && (
|
||||
<ol className="divide-y">
|
||||
{data.accounts.map((a, i) => {
|
||||
const st = accountState[a.state];
|
||||
return (
|
||||
<li key={a.id} className="space-y-2 py-3 first:pt-0">
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm">
|
||||
<span className="w-5 text-muted-foreground tabular-nums">{i + 1}.</span>
|
||||
<span className="font-medium">{a.username}</span>
|
||||
<span className="text-muted-foreground">(IMVU {a.imvuId})</span>
|
||||
<Tag tone={st.tone}>{st.label}</Tag>
|
||||
{a.accessPass ? <Tag tone="adult">Access Pass</Tag> : <Tag>No Access Pass</Tag>}
|
||||
{a.stateMessage && <span className="text-xs text-muted-foreground">{a.stateMessage}</span>}
|
||||
</div>
|
||||
{can.run && (
|
||||
<div className="flex flex-wrap items-start gap-2 pl-7">
|
||||
<ActionForm action={changeImporterAccount} fields={{ id, account: a.id }}>
|
||||
<div className="flex gap-2">
|
||||
{i > 0 && (
|
||||
<SubmitButton
|
||||
name="intent"
|
||||
value="up"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
pendingLabel="Moving…"
|
||||
>
|
||||
Up
|
||||
</SubmitButton>
|
||||
)}
|
||||
{i < data.accounts.length - 1 && (
|
||||
<SubmitButton
|
||||
name="intent"
|
||||
value="down"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
pendingLabel="Moving…"
|
||||
>
|
||||
Down
|
||||
</SubmitButton>
|
||||
)}
|
||||
<SubmitButton
|
||||
name="intent"
|
||||
value="remove"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
pendingLabel="Removing…"
|
||||
confirm={`Remove ${a.username}? The importer forgets it and its password.`}
|
||||
>
|
||||
Remove
|
||||
</SubmitButton>
|
||||
</div>
|
||||
</ActionForm>
|
||||
{data.program.publicKey && data.program.fingerprint && (
|
||||
<details
|
||||
className="min-w-64 flex-1"
|
||||
open={a.state === "needs_password" || a.state === "sign_in_failed"}
|
||||
>
|
||||
<summary className="cursor-pointer text-sm text-muted-foreground hover:text-foreground">
|
||||
New password
|
||||
</summary>
|
||||
<div className="mt-2">
|
||||
<ImporterAccountForm
|
||||
catalogId={id}
|
||||
publicKey={data.program.publicKey}
|
||||
fingerprint={data.program.fingerprint}
|
||||
version={data.program.version}
|
||||
account={{ id: a.id, imvuId: a.imvuId, username: a.username }}
|
||||
/>
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
)}
|
||||
{can.run &&
|
||||
(!data.program.publicKey || !data.program.fingerprint ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Start the importer to add accounts: passwords are encrypted for its key, which it sends when it
|
||||
connects.
|
||||
</p>
|
||||
) : data.accounts.length >= data.maxAccounts ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
An importer can have at most {data.maxAccounts} accounts.
|
||||
</p>
|
||||
) : (
|
||||
<ImporterAccountForm
|
||||
catalogId={id}
|
||||
publicKey={data.program.publicKey}
|
||||
fingerprint={data.program.fingerprint}
|
||||
version={data.program.version}
|
||||
/>
|
||||
))}
|
||||
{!can.run && data.accounts.length === 0 && <p className="text-sm text-muted-foreground">None yet.</p>}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{data.importer !== "off" && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Importer Settings</CardTitle>
|
||||
<CardDescription>The importer picks changes up within a minute.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ActionForm action={setImporterSettings} fields={{ id }}>
|
||||
<div className="flex max-w-2xl flex-wrap items-end gap-4">
|
||||
<label className="grid gap-1.5 text-sm">
|
||||
Requests a second to IMVU
|
||||
<Input
|
||||
type="number"
|
||||
name="rate"
|
||||
step="0.1"
|
||||
min={data.settingsBounds.rate.min}
|
||||
max={data.settingsBounds.rate.max}
|
||||
defaultValue={data.settings.rate}
|
||||
disabled={!can.run}
|
||||
className="w-32"
|
||||
/>
|
||||
</label>
|
||||
<label className="grid gap-1.5 text-sm">
|
||||
Jobs at once
|
||||
<Input
|
||||
type="number"
|
||||
name="concurrency"
|
||||
step="1"
|
||||
min={data.settingsBounds.concurrency.min}
|
||||
max={data.settingsBounds.concurrency.max}
|
||||
defaultValue={data.settings.concurrency}
|
||||
disabled={!can.run}
|
||||
className="w-32"
|
||||
/>
|
||||
</label>
|
||||
{can.run && <SubmitButton pendingLabel="Saving…">Save</SubmitButton>}
|
||||
</div>
|
||||
</ActionForm>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{pending.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use server";
|
||||
// Managing a catalog from the console: settings, key, team, members, invitations, what it hosts, suspension.
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { api, unwrap } from "@/lib/api";
|
||||
import { api, ApiError, unwrap } from "@/lib/api";
|
||||
import { attempt, field, type ActionState } from "@/lib/actions";
|
||||
|
||||
/** Runs a change to a catalog, then shows its pages again. */
|
||||
@@ -173,3 +173,89 @@ export async function retryJob(_: ActionState, form: FormData): Promise<ActionSt
|
||||
return "Queued.";
|
||||
});
|
||||
}
|
||||
|
||||
// ---- the importer program and its IMVU accounts (docs/imports.md "IMVU accounts") ----
|
||||
|
||||
export type ImvuAccountInfo = {
|
||||
imvuId: number;
|
||||
username: string;
|
||||
picture: string | null;
|
||||
accessPass: boolean;
|
||||
ageVerified: boolean;
|
||||
};
|
||||
|
||||
/** Called from the browser: an error to show, or what was asked for. */
|
||||
async function answered<T>(fn: () => Promise<T>): Promise<{ error: string } | { ok: T }> {
|
||||
try {
|
||||
return { ok: await fn() };
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError) return { error: e.message };
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** Looks an IMVU account up for the confirmation dialog (public info only). */
|
||||
export async function lookupImporterAccount(id: string, username: string) {
|
||||
return answered<ImvuAccountInfo>(async () =>
|
||||
unwrap(await api.catalogs({ id }).importer["imvu-account"].get({ query: { username: username.trim() } })),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an account, or gives one a new password (account set). The password arrives sealed in the browser for the
|
||||
* importer's key; it never passes through here readable.
|
||||
*/
|
||||
export async function saveImporterAccount(
|
||||
id: string,
|
||||
a: { imvuId: number; account?: string; sealed: string; fingerprint: string },
|
||||
) {
|
||||
const r = await answered(async () => {
|
||||
if (a.account)
|
||||
unwrap(
|
||||
await api
|
||||
.catalogs({ id })
|
||||
.importer.accounts({ account: a.account })
|
||||
.password.put({ sealed: a.sealed, fingerprint: a.fingerprint }),
|
||||
);
|
||||
else unwrap(await api.catalogs({ id }).importer.accounts.post({ imvuId: a.imvuId, sealed: a.sealed, fingerprint: a.fingerprint }));
|
||||
return true;
|
||||
});
|
||||
revalidatePath(`/console/catalogs/${id}/imports`);
|
||||
return r;
|
||||
}
|
||||
|
||||
/** Moves an account up or down, or removes it. */
|
||||
export async function changeImporterAccount(_: ActionState, form: FormData): Promise<ActionState> {
|
||||
const id = field(form, "id");
|
||||
const account = field(form, "account");
|
||||
return attempt(async () => {
|
||||
const intent = field(form, "intent");
|
||||
if (intent === "remove") {
|
||||
unwrap(await api.catalogs({ id }).importer.accounts({ account }).delete());
|
||||
revalidatePath(`/console/catalogs/${id}/imports`);
|
||||
return "Removed. The importer forgets it within a minute.";
|
||||
}
|
||||
unwrap(
|
||||
await api
|
||||
.catalogs({ id })
|
||||
.importer.accounts({ account })
|
||||
.move.post({ direction: intent === "up" ? "up" : "down" }),
|
||||
);
|
||||
revalidatePath(`/console/catalogs/${id}/imports`);
|
||||
});
|
||||
}
|
||||
|
||||
/** The importer's settings. */
|
||||
export async function setImporterSettings(_: ActionState, form: FormData): Promise<ActionState> {
|
||||
const id = field(form, "id");
|
||||
return attempt(async () => {
|
||||
unwrap(
|
||||
await api.catalogs({ id }).importer.settings.post({
|
||||
rate: Number(field(form, "rate")),
|
||||
concurrency: Number(field(form, "concurrency")),
|
||||
}),
|
||||
);
|
||||
revalidatePath(`/console/catalogs/${id}/imports`);
|
||||
return "Saved. The importer picks it up within a minute.";
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user