feat: importer IMVU accounts and settings from the console
Pull request / title (pull_request) Successful in 2s
CI / test (pull_request) Successful in 1m18s
CI / image (apps/api/Dockerfile, t5de-hub-api) (pull_request) Skipped
CI / image (apps/web/Dockerfile, t5de-hub-web) (pull_request) Skipped

The importer sends its RSA public key (POST /importer/hello); the console
looks IMVU accounts up, confirms them in a dialog, and seals each password
in the browser for that key. The hub keeps only the sealed copy, until the
importer confirms it has it. Accounts are tried in order; settings (rate,
jobs at once) come from the console too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
dhkatzandClaude Opus 5.5 committed 2026-11-07 10:01:11 -08:00
1 parent d716aabbd2
commit dcc39d82ab
16 files changed
+5505 -9

No files matched your search

+143 -2
View File
@@ -28,6 +28,7 @@ import { Realtime } from "./realtime";
import { isAdultRoom, Rooms } from "./rooms";
import { Signer } from "./keys";
import { Blocks, isSha256 } from "./blocks";
import { fingerprint as keyFingerprint, Importers, maxAccounts, settingsBounds, type ImporterAccount } from "./importer";
import { consent, Imports, type Grant } from "./imports";
import { availableTo, BlockedUpload, ProductError, Products, type EditRights, type ProductViewer } from "./products";
import {
@@ -199,6 +200,7 @@ export function createApp({
const cases = new Cases(db, perms);
const blocks = new Blocks(db);
const imports = new Imports(db, signer, imvu);
const importers = new Importers(db);
const notifications = new Notifications(db, (userId, message) => realtime.notify(userId, message));
/** Tells a product's creator that someone else changed it. */
@@ -376,6 +378,18 @@ export function createApp({
}
};
const importerAccountView = (a: ImporterAccount) => ({
id: a.id,
imvuId: a.imvuId,
username: a.username,
state: a.state as "waiting" | "received" | "ok" | "sign_in_failed" | "needs_password",
stateMessage: a.stateMessage,
stateAt: a.stateAt.toISOString(),
accessPass: a.accessPass,
ageVerified: a.ageVerified,
createdAt: a.createdAt.toISOString(),
});
const grantView = (r: { grant: Grant; catalogName?: string | null; imvuName?: string | null }) => ({
id: r.grant.id,
catalog: r.grant.catalogId,
@@ -1933,6 +1947,43 @@ export function createApp({
},
)
// The importer program's setup (docs/imports.md "IMVU accounts"): its key, its config, its accounts' states.
.post(
"/importer/hello",
async ({ request, body }) => {
const c = await imports.importerFor(request.headers.get("authorization"));
if (!c) throw new Problem(401, "forbidden", "Not an importer of an approved catalog with imports on.");
const r = await productCall(() => importers.hello(c, body.version, body.publicKey));
if (r.changed) await audited(null, "catalog.importer_hello", c.id, { version: body.version, fingerprint: keyFingerprint(body.publicKey) });
const [fresh] = await db.select().from(catalog).where(eq(catalog.id, c.id));
return importers.config(fresh!);
},
{ body: t.Object({ version: t.String({ maxLength: 40 }), publicKey: t.String({ maxLength: 1200 }) }) },
)
.get("/importer/config", async ({ request }) => {
const c = await imports.importerFor(request.headers.get("authorization"));
if (!c) throw new Problem(401, "forbidden", "Not an importer of an approved catalog with imports on.");
return importers.config(c);
})
.post(
"/importer/accounts/:id",
async ({ request, params, body }) => {
const c = await imports.importerFor(request.headers.get("authorization"));
if (!c) throw new Problem(401, "forbidden", "Not an importer of an approved catalog with imports on.");
const a = await productCall(() => importers.report(c, params.id, body));
return { account: importerAccountView(a) };
},
{
params: t.Object({ id: t.String({ maxLength: 20 }) }),
body: t.Object({
received: t.Optional(t.Boolean()),
state: t.Optional(t.Union([t.Literal("ok"), t.Literal("sign_in_failed"), t.Literal("needs_password")])),
accessPass: t.Optional(t.Boolean()),
message: t.Optional(t.String({ maxLength: 300 })),
}),
},
)
// Imports (docs/imports.md): grants, requests, and each catalog's importer.
.get("/imports/catalogs", async () => ({ catalogs: await imports.catalogs(), consent }))
.get("/imports/grants", async ({ me }) => ({ grants: (await imports.grantsOf(me.id)).map(grantView) }), { signedIn: true })
@@ -2080,13 +2131,25 @@ export function createApp({
})
.from(schema.importJob)
.where(eq(schema.importJob.catalogId, c.id));
const run = await perms.can(me, "import:run", scope);
return {
importer: c.importer as "off" | "on" | "paused",
program: {
version: c.importerVersion,
seenAt: c.importerSeenAt?.toISOString() ?? null,
fingerprint: c.importerFingerprint,
// Passwords are sealed for this key in the browser; only those who may add accounts get it.
publicKey: run ? c.importerPublicKey : null,
},
settings: c.importerSettings,
settingsBounds,
maxAccounts,
accounts: (await importers.accounts(c.id)).map(importerAccountView),
grants: grants.map(grantView),
jobs: jobs.map((j) => ({ ...jobView(j.job), name: j.name ?? "" })),
counts: counts ?? { queued: 0, claimed: 0, failed: 0, done: 0 },
permissions: {
run: await perms.can(me, "import:run", scope),
run,
pause: await perms.can(me, "import:pause", scope),
accept: await perms.can(me, "import:accept", scope),
withdraw: await perms.can(me, "import:withdraw", scope),
@@ -2132,6 +2195,84 @@ export function createApp({
},
{ scripted: true, params: catalogParam },
)
.get(
"/catalogs/:id/importer/imvu-account",
async ({ me, params, query }) => {
await need(me, "import:run", catalogScope(params.id));
const u = await imvuCall(me, () => imvu.byUsername(query.username));
return { imvuId: u.id, username: u.username, picture: u.picture, accessPass: u.accessPass, ageVerified: u.ageVerified };
},
{ signedIn: true, params: catalogParam, query: t.Object({ username: t.String({ minLength: 1, maxLength: 64 }) }) },
)
.post(
"/catalogs/:id/importer/accounts",
async ({ me, params, body, set }) => {
await need(me, "import:run", catalogScope(params.id));
const u = await imvuCall(me, () => imvu.byId(body.imvuId));
const a = await productCall(() =>
importers.addAccount(
params.id,
{ imvuId: u.id, username: u.username, accessPass: u.accessPass, ageVerified: u.ageVerified, sealed: body.sealed, fingerprint: body.fingerprint },
me.id,
),
);
await audited(me, "catalog.importer_account", params.id, { change: "add", imvuId: a.imvuId, username: a.username });
set.status = 201;
return { account: importerAccountView(a) };
},
{
scripted: true,
params: catalogParam,
body: t.Object({ imvuId: t.Integer({ minimum: 1 }), sealed: t.String({ maxLength: 1000 }), fingerprint: t.String({ maxLength: 64 }) }),
},
)
.put(
"/catalogs/:id/importer/accounts/:account/password",
async ({ me, params, body }) => {
await need(me, "import:run", catalogScope(params.id));
const a = await productCall(() => importers.setPassword(params.id, params.account, body.sealed, body.fingerprint));
await audited(me, "catalog.importer_account", params.id, { change: "password", imvuId: a.imvuId, username: a.username });
return { account: importerAccountView(a) };
},
{
scripted: true,
params: t.Object({ id: t.String({ pattern: "^[a-z2-7]{10}$" }), account: t.String({ maxLength: 20 }) }),
body: t.Object({ sealed: t.String({ maxLength: 1000 }), fingerprint: t.String({ maxLength: 64 }) }),
},
)
.post(
"/catalogs/:id/importer/accounts/:account/move",
async ({ me, params, body }) => {
await need(me, "import:run", catalogScope(params.id));
await productCall(() => importers.moveAccount(params.id, params.account, body.direction));
return { accounts: (await importers.accounts(params.id)).map(importerAccountView) };
},
{
scripted: true,
params: t.Object({ id: t.String({ pattern: "^[a-z2-7]{10}$" }), account: t.String({ maxLength: 20 }) }),
body: t.Object({ direction: t.Union([t.Literal("up"), t.Literal("down")]) }),
},
)
.delete(
"/catalogs/:id/importer/accounts/:account",
async ({ me, params, set }) => {
await need(me, "import:run", catalogScope(params.id));
const a = await productCall(() => importers.removeAccount(params.id, params.account));
await audited(me, "catalog.importer_account", params.id, { change: "remove", imvuId: a.imvuId, username: a.username });
set.status = 204;
},
{ scripted: true, params: t.Object({ id: t.String({ pattern: "^[a-z2-7]{10}$" }), account: t.String({ maxLength: 20 }) }) },
)
.post(
"/catalogs/:id/importer/settings",
async ({ me, params, body }) => {
await need(me, "import:run", catalogScope(params.id));
const settings = await productCall(() => importers.setSettings(params.id, body));
await audited(me, "catalog.importer_settings", params.id, settings);
return { settings };
},
{ scripted: true, params: catalogParam, body: t.Object({ rate: t.Number(), concurrency: t.Integer() }) },
)
.post(
"/catalogs/:id/importer/jobs/:job/retry",
async ({ me, params }) => {
@@ -3260,7 +3401,7 @@ export function createApp({
.get("/health", () => ({ ok: true }))
.use(api);
return { app, realtime, age, rooms, products, signer, hosted, decorations, imports };
return { app, realtime, age, rooms, products, signer, hosted, decorations, imports, importers };
}
export type App = ReturnType<typeof createApp>["app"];
+215
View File
@@ -0,0 +1,215 @@
// A catalog's importer program and the IMVU accounts it signs in with (docs/imports.md "IMVU accounts"). The importer
// sends its RSA public key; the console seals each account's password in the browser for that key; the hub keeps the
// sealed copy only until the importer has it. Everything but what the importer needs to reach the hub is set here,
// from the console. The routes are in app.ts.
import { createHash, createPublicKey } from "node:crypto";
import { and, asc, eq, lt, sql, schema, type Database, type ImporterSettings } from "@t5de/db";
import { newProductID, ProductError, type Catalog } from "./products";
const { catalog, importerAccount } = schema;
export type ImporterAccount = typeof importerAccount.$inferSelect;
export type AccountState = "waiting" | "received" | "ok" | "sign_in_failed" | "needs_password";
/** A sealed password the importer hasn't fetched within this long is dropped. */
export const sealedFor = 7 * 24 * 60 * 60 * 1000;
/** Accounts a catalog's importer may have. */
export const maxAccounts = 10;
/** Settings' bounds. */
export const settingsBounds = { rate: { min: 0.2, max: 10 }, concurrency: { min: 1, max: 8 } } as const;
/** sha256 of the key's SPKI, hex: what the console shows (shortened) and seals are checked against. */
export const fingerprint = (spkiBase64: string) => createHash("sha256").update(Buffer.from(spkiBase64, "base64")).digest("hex");
/** Checks an importer's public key: base64 SPKI of an RSA key of 3072 to 4096 bits. */
function checkPublicKey(spki: string) {
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(spki)) throw new ProductError(400, "invalid", "The public key isn't base64.");
let bits: number | undefined;
try {
const key = createPublicKey({ key: Buffer.from(spki, "base64"), format: "der", type: "spki" });
if (key.asymmetricKeyType !== "rsa") throw new Error("not RSA");
bits = key.asymmetricKeyDetails?.modulusLength;
} catch {
throw new ProductError(400, "invalid", "The public key isn't an RSA key (SPKI).");
}
if (!bits || bits < 3072 || bits > 4096) throw new ProductError(400, "invalid", "The public key must be RSA with 3072 to 4096 bits.");
}
/** Checks a sealed password: base64 of one RSA-OAEP block (384 or 512 bytes). */
function checkSealed(sealed: string) {
const bytes = /^[A-Za-z0-9+/]+={0,2}$/.test(sealed) ? Buffer.from(sealed, "base64").length : 0;
if (bytes !== 384 && bytes !== 512) throw new ProductError(400, "invalid", "That isn't a sealed password.");
}
export class Importers {
constructor(private readonly db: Database) {}
private async catalogOf(catalogId: string): Promise<Catalog> {
const [c] = await this.db.select().from(catalog).where(eq(catalog.id, catalogId));
if (!c) throw new ProductError(404, "not_found", "No such catalog.");
return c;
}
// ---- the importer program ----
/**
* The importer says hello: its version and public key. A new key (a new install) can't read passwords sealed for
* the old one, so those accounts need their passwords again.
*/
async hello(c: Catalog, version: string, publicKey: string): Promise<{ changed: boolean }> {
checkPublicKey(publicKey);
const print = fingerprint(publicKey);
const changed = c.importerFingerprint !== print;
await this.db.transaction(async (tx) => {
await tx
.update(catalog)
.set({ importerPublicKey: publicKey, importerFingerprint: print, importerVersion: version, importerSeenAt: new Date() })
.where(eq(catalog.id, c.id));
if (changed && c.importerFingerprint)
await tx
.update(importerAccount)
.set({ sealed: null, sealedFor: null, sealedAt: null, state: "needs_password", stateMessage: "The importer's key changed.", stateAt: new Date() })
.where(eq(importerAccount.catalogId, c.id));
});
return { changed };
}
/** What the importer runs with: paused or not, its settings, and its accounts in order (sealed passwords too). */
async config(c: Catalog) {
await this.db.update(catalog).set({ importerSeenAt: new Date() }).where(eq(catalog.id, c.id));
const accounts = await this.accounts(c.id);
return {
paused: c.importer === "paused",
settings: c.importerSettings,
fingerprint: c.importerFingerprint,
accounts: accounts.map((a) => ({
id: a.id,
imvuId: a.imvuId,
username: a.username,
// Only a password sealed for the key the importer has now.
sealed: a.sealed && a.sealedFor === c.importerFingerprint ? a.sealed : null,
})),
};
}
/** The importer reports on an account: it has the sealed password, and how signing in went. */
async report(c: Catalog, id: string, r: { received?: boolean; state?: "ok" | "sign_in_failed" | "needs_password"; accessPass?: boolean; message?: string }) {
const [a] = await this.db
.select()
.from(importerAccount)
.where(and(eq(importerAccount.id, id), eq(importerAccount.catalogId, c.id)));
if (!a) throw new ProductError(404, "not_found", "No such account.");
const set: Partial<ImporterAccount> = {};
if (r.received && a.sealed) Object.assign(set, { sealed: null, sealedFor: null, sealedAt: null, state: "received", stateMessage: "", stateAt: new Date() });
if (r.state) Object.assign(set, { state: r.state, stateMessage: (r.message ?? "").slice(0, 300), stateAt: new Date() });
if (r.accessPass !== undefined) set.accessPass = r.accessPass;
if (Object.keys(set).length === 0) return a;
const [updated] = await this.db.update(importerAccount).set(set).where(eq(importerAccount.id, a.id)).returning();
return updated!;
}
// ---- the console ----
async accounts(catalogId: string): Promise<ImporterAccount[]> {
return this.db
.select()
.from(importerAccount)
.where(eq(importerAccount.catalogId, catalogId))
.orderBy(asc(importerAccount.position), asc(importerAccount.createdAt));
}
/** Adds an account, its password sealed for the importer's key (which must be the one the console showed). */
async addAccount(
catalogId: string,
a: { imvuId: number; username: string; accessPass: boolean; ageVerified: boolean; sealed: string; fingerprint: string },
byId: string,
): Promise<ImporterAccount> {
const c = await this.catalogOf(catalogId);
this.checkSeal(c, a.sealed, a.fingerprint);
const existing = await this.accounts(c.id);
if (existing.some((x) => x.imvuId === a.imvuId))
throw new ProductError(409, "exists", "The importer has that account already: enter its password again instead.");
if (existing.length >= maxAccounts) throw new ProductError(409, "too_many", `An importer can have at most ${maxAccounts} accounts.`);
const [row] = await this.db
.insert(importerAccount)
.values({
id: newProductID(),
catalogId: c.id,
imvuId: a.imvuId,
username: a.username,
position: existing.length ? Math.max(...existing.map((x) => x.position)) + 1 : 0,
sealed: a.sealed,
sealedFor: a.fingerprint,
sealedAt: new Date(),
accessPass: a.accessPass,
ageVerified: a.ageVerified,
addedBy: byId,
})
.returning();
return row!;
}
/** A new password for an account. */
async setPassword(catalogId: string, id: string, sealed: string, print: string): Promise<ImporterAccount> {
const c = await this.catalogOf(catalogId);
this.checkSeal(c, sealed, print);
const [row] = await this.db
.update(importerAccount)
.set({ sealed, sealedFor: print, sealedAt: new Date(), state: "waiting", stateMessage: "", stateAt: new Date() })
.where(and(eq(importerAccount.id, id), eq(importerAccount.catalogId, c.id)))
.returning();
if (!row) throw new ProductError(404, "not_found", "No such account.");
return row;
}
private checkSeal(c: Catalog, sealed: string, print: string) {
if (!c.importerFingerprint) throw new ProductError(409, "no_importer", "Start the importer first: passwords are sealed for its key.");
if (print !== c.importerFingerprint)
throw new ProductError(409, "importer_key_changed", "The importer's key changed since this page was loaded. Load it again and retry.");
checkSealed(sealed);
}
/** Removes an account; the importer forgets it on its next look at its config. */
async removeAccount(catalogId: string, id: string): Promise<ImporterAccount> {
const [row] = await this.db
.delete(importerAccount)
.where(and(eq(importerAccount.id, id), eq(importerAccount.catalogId, catalogId)))
.returning();
if (!row) throw new ProductError(404, "not_found", "No such account.");
return row;
}
/** Moves an account one place earlier or later in the order the importer tries them. */
async moveAccount(catalogId: string, id: string, direction: "up" | "down"): Promise<void> {
const list = await this.accounts(catalogId);
const i = list.findIndex((a) => a.id === id);
if (i < 0) throw new ProductError(404, "not_found", "No such account.");
const j = direction === "up" ? i - 1 : i + 1;
if (j < 0 || j >= list.length) return;
[list[i], list[j]] = [list[j]!, list[i]!];
await this.db.transaction(async (tx) => {
for (const [n, a] of list.entries()) await tx.update(importerAccount).set({ position: n }).where(eq(importerAccount.id, a.id));
});
}
async setSettings(catalogId: string, s: ImporterSettings): Promise<ImporterSettings> {
const { rate, concurrency } = settingsBounds;
if (!(s.rate >= rate.min && s.rate <= rate.max)) throw new ProductError(400, "invalid", `Requests a second: ${rate.min} to ${rate.max}.`);
if (!Number.isInteger(s.concurrency) || s.concurrency < concurrency.min || s.concurrency > concurrency.max)
throw new ProductError(400, "invalid", `Jobs at once: ${concurrency.min} to ${concurrency.max}.`);
const settings = { rate: Math.round(s.rate * 10) / 10, concurrency: s.concurrency };
const [c] = await this.db.update(catalog).set({ importerSettings: settings }).where(eq(catalog.id, catalogId)).returning();
if (!c) throw new ProductError(404, "not_found", "No such catalog.");
return c.importerSettings;
}
/** Drops sealed passwords no importer fetched in time; their accounts need their passwords again. */
async expireSealed(): Promise<number> {
const rows = await this.db
.update(importerAccount)
.set({ sealed: null, sealedFor: null, sealedAt: null, state: "needs_password", stateMessage: "The importer didn't fetch the password within 7 days.", stateAt: new Date() })
.where(and(sql`${importerAccount.sealed} is not null`, lt(importerAccount.sealedAt, new Date(Date.now() - sealedFor))))
.returning({ id: importerAccount.id });
return rows.length;
}
}
+8 -2
View File
@@ -63,7 +63,7 @@ for (const id of providers) {
}
const ageService = new AgeService(db, providers.map((id) => ageProviders[id]!()));
const { app, age, rooms, products, imports } = createApp({ db, auth, imvu, age: ageService, apiURL, webURL, settings });
const { app, age, rooms, products, imports, importers } = createApp({ db, auth, imvu, age: ageService, apiURL, webURL, settings });
app.listen({ port, hostname: env.HOST ?? "0.0.0.0" });
// Age answers that can change (IMVU's) are checked again when they expire, a few at a time; revisions missing their
@@ -90,5 +90,11 @@ const importRecheck = () =>
.recheck(200)
.then((r) => (r.queued || r.withdrawn.length) && console.log(`imports: ${r.queued} rechecks queued, ${r.withdrawn.length} withdrawn`))
.catch((e) => console.error("import rechecks:", e));
setInterval(importRecheck, 60 * 60 * 1000);
setInterval(() => {
importRecheck();
importers
.expireSealed()
.then((n) => n && console.log(`imports: ${n} sealed importer passwords expired`))
.catch((e) => console.error("importer passwords:", e));
}, 60 * 60 * 1000);
console.log(`t5de-hub API on ${apiURL} (website ${webURL})`);
+97
View File
@@ -56,6 +56,7 @@ afterAll(async () => {
});
type Person = { cookie: string; name: string };
let rootAdmin: Person; // the first person: an admin
async function call(p: Person | undefined, method: string, path: string, body?: unknown, headers: Record<string, string> = {}) {
const res = await fetch(base + path, {
method,
@@ -95,6 +96,7 @@ const imvuProduct = (name: string, creator: number, rating = "GA") => ({ product
test("grants, requests, the importer's jobs, and withdrawal", async () => {
const admin = await person("root");
rootAdmin = admin;
const owner = await person("shelf");
const maker = await person("maker", 501);
const fan = await person("fan");
@@ -217,3 +219,98 @@ test("IMVU's 401 keeps what was last seen; 404 is gone", async () => {
imvuProducts.delete(9500);
expect(await imports.info(9500, true)).toBeUndefined();
});
test("the importer's key, IMVU accounts with sealed passwords, and settings", async () => {
const admin = rootAdmin;
const owner = await person("keeper");
const outsider = await person("outsider");
accounts.set(601, { id: 601, username: "ImportBot", tagline: "", ageVerified: true, accessPass: true, picture: null });
accounts.set(602, { id: 602, username: "SpareBot", tagline: "", ageVerified: false, accessPass: false, picture: null });
const reg = await call(owner, "POST", "/api/v1/catalogs", { name: "Keeper Shelf", url: "https://keeper.example.test", contact: "[email protected]", visibility: "public", membership: "open" });
const catalogID = reg.json.catalog.id as string;
expect((await call(admin, "POST", `/api/v1/console/catalogs/${catalogID}/approve`)).status).toBe(200);
const on = await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer`, { enabled: true });
const importer = { Authorization: `Importer ${catalogID}:${on.json.key}` };
const page = async () => (await call(owner, "GET", `/api/v1/catalogs/${catalogID}/importer`)).json;
// Before the importer has said hello there's no key to seal for.
expect((await page()).program).toMatchObject({ version: "", seenAt: null, fingerprint: null, publicKey: null });
const keys = async () => {
const pair = (await crypto.subtle.generateKey(
{ name: "RSA-OAEP", modulusLength: 3072, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" },
true,
["encrypt", "decrypt"],
)) as CryptoKeyPair;
return { pair, spki: Buffer.from(await crypto.subtle.exportKey("spki", pair.publicKey)).toString("base64") };
};
// As the console's browser does: the account's ID and password, sealed for the importer's key.
const seal = async (spki: string, imvuId: number, password: string) => {
const key = await crypto.subtle.importKey("spki", Buffer.from(spki, "base64"), { name: "RSA-OAEP", hash: "SHA-256" }, false, ["encrypt"]);
const data = new TextEncoder().encode(JSON.stringify({ imvuId, password }));
return Buffer.from(await crypto.subtle.encrypt({ name: "RSA-OAEP" }, key, data)).toString("base64");
};
const unseal = async (pair: CryptoKeyPair, sealed: string) =>
JSON.parse(new TextDecoder().decode(await crypto.subtle.decrypt({ name: "RSA-OAEP" }, pair.privateKey, Buffer.from(sealed, "base64"))));
const k1 = await keys();
expect((await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer/accounts`, { imvuId: 601, sealed: await seal(k1.spki, 601, "x"), fingerprint: "00" })).json.error).toBe("no_importer");
expect((await call(undefined, "POST", "/api/v1/importer/hello", { version: "0.1.0", publicKey: "not a key" }, importer)).status).toBe(400);
const hello = await call(undefined, "POST", "/api/v1/importer/hello", { version: "0.1.0", publicKey: k1.spki }, importer);
expect(hello.status).toBe(200);
expect(hello.json).toMatchObject({ paused: false, settings: { rate: 2, concurrency: 2 }, accounts: [] });
const shown = (await page()).program;
expect(shown).toMatchObject({ version: "0.1.0", publicKey: k1.spki });
expect(shown.fingerprint).toBe(hello.json.fingerprint);
expect(shown.seenAt).not.toBeNull();
// The console looks the account up, then adds it with the password sealed for that key.
expect((await call(outsider, "GET", `/api/v1/catalogs/${catalogID}/importer/imvu-account?username=ImportBot`)).status).toBe(403);
const found = (await call(owner, "GET", `/api/v1/catalogs/${catalogID}/importer/imvu-account?username=ImportBot`)).json;
expect(found).toMatchObject({ imvuId: 601, username: "ImportBot", accessPass: true, ageVerified: true });
const add = (imvuId: number, sealed: string, fingerprint = shown.fingerprint) =>
call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer/accounts`, { imvuId, sealed, fingerprint });
expect((await add(601, "bm90IHNlYWxlZA==")).json.error).toBe("invalid");
expect((await add(601, await seal(k1.spki, 601, "pw1"), "ff".repeat(32))).json.error).toBe("importer_key_changed");
const added = await add(601, await seal(k1.spki, 601, "pw1"));
expect(added.status).toBe(201);
expect(added.json.account).toMatchObject({ username: "ImportBot", state: "waiting", accessPass: true });
expect((await add(601, await seal(k1.spki, 601, "pw1"))).json.error).toBe("exists");
expect((await add(602, await seal(k1.spki, 602, "pw2"))).status).toBe(201);
// The importer gets the sealed passwords, in order, and can read them; the hub drops each once it has it.
const config = (await call(undefined, "GET", "/api/v1/importer/config", undefined, importer)).json;
expect(config.accounts.map((a: any) => a.username)).toEqual(["ImportBot", "SpareBot"]);
expect(await unseal(k1.pair, config.accounts[0].sealed)).toEqual({ imvuId: 601, password: "pw1" });
const first = config.accounts[0].id as string;
expect((await call(undefined, "POST", `/api/v1/importer/accounts/${first}`, { received: true }, importer)).json.account.state).toBe("received");
expect((await call(undefined, "GET", "/api/v1/importer/config", undefined, importer)).json.accounts[0].sealed).toBeNull();
await call(undefined, "POST", `/api/v1/importer/accounts/${first}`, { state: "ok", accessPass: true }, importer);
expect((await call(undefined, "POST", `/api/v1/importer/accounts/${first}`, { state: "ok" }, { Authorization: `Importer ${catalogID}:wrong` })).status).toBe(401);
// The order can change; settings are bounded.
await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer/accounts/${first}/move`, { direction: "down" });
expect((await page()).accounts.map((a: any) => [a.username, a.state])).toEqual([["SpareBot", "waiting"], ["ImportBot", "ok"]]);
expect((await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer/settings`, { rate: 50, concurrency: 2 })).status).toBe(400);
expect((await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer/settings`, { rate: 0.5, concurrency: 4 })).json.settings).toEqual({ rate: 0.5, concurrency: 4 });
expect((await call(undefined, "GET", "/api/v1/importer/config", undefined, importer)).json.settings).toEqual({ rate: 0.5, concurrency: 4 });
// A new install (a new key) can't read the old seals: every account needs its password again.
const k2 = await keys();
expect((await call(undefined, "POST", "/api/v1/importer/hello", { version: "0.1.1", publicKey: k2.spki }, importer)).json.accounts.every((a: any) => a.sealed === null)).toBe(true);
const after = await page();
expect(after.accounts.map((a: any) => a.state)).toEqual(["needs_password", "needs_password"]);
const spare = after.accounts[0].id as string;
const again = await call(owner, "PUT", `/api/v1/catalogs/${catalogID}/importer/accounts/${spare}/password`, { sealed: await seal(k2.spki, 602, "pw3"), fingerprint: after.program.fingerprint });
expect(again.json.account.state).toBe("waiting");
const sealed = (await call(undefined, "GET", "/api/v1/importer/config", undefined, importer)).json.accounts[0].sealed;
expect(await unseal(k2.pair, sealed)).toEqual({ imvuId: 602, password: "pw3" });
// Removed accounts leave the importer's config; it's all audited.
expect((await call(owner, "DELETE", `/api/v1/catalogs/${catalogID}/importer/accounts/${spare}`)).status).toBe(204);
expect((await call(undefined, "GET", "/api/v1/importer/config", undefined, importer)).json.accounts.map((a: any) => a.username)).toEqual(["ImportBot"]);
const actions = (await call(owner, "GET", "/api/v1/console/audit")).json.entries.map((e: any) => e.action);
expect(actions).toEqual(expect.arrayContaining(["catalog.importer_hello", "catalog.importer_account", "catalog.importer_settings"]));
// Passwords never show on the console.
expect(JSON.stringify(await page())).not.toContain(sealed);
});
@@ -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&apos;t see AP products, so it can&apos;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&apos;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>
+87 -1
View File
@@ -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.";
});
}
+72
View File
@@ -0,0 +1,72 @@
"use client"
import * as React from "react"
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"
import { cn } from "cn"
function Dialog(props: DialogPrimitive.Root.Props) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogContent({
className,
children,
...props
}: DialogPrimitive.Popup.Props) {
return (
<DialogPrimitive.Portal>
<DialogPrimitive.Backdrop
data-slot="dialog-backdrop"
className="fixed inset-0 z-50 bg-black/40 transition-opacity duration-150 data-ending-style:opacity-0 data-starting-style:opacity-0 supports-backdrop-filter:backdrop-blur-xs"
/>
<DialogPrimitive.Popup
data-slot="dialog-content"
className={cn(
"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-5 text-sm text-popover-foreground ring-1 ring-foreground/10 outline-none transition-all duration-150 data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0 sm:max-w-md",
className
)}
{...props}
>
{children}
</DialogPrimitive.Popup>
</DialogPrimitive.Portal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return <div data-slot="dialog-header" className={cn("flex flex-col gap-1.5", className)} {...props} />
}
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-footer"
className={cn("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", className)}
{...props}
/>
)
}
function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-base leading-none font-medium", className)}
{...props}
/>
)
}
function DialogDescription({ className, ...props }: DialogPrimitive.Description.Props) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
}
const DialogClose = DialogPrimitive.Close
export { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle }
+6
View File
@@ -0,0 +1,6 @@
// Shared by the console's importer page and its client parts.
/** The start of a key's fingerprint, for people to compare: "1a2b 3c4d 5e6f 7a8b". */
export function shortFingerprint(hex: string): string {
return (hex.slice(0, 16).match(/.{4}/g) ?? []).join(" ");
}