feat: importer IMVU accounts and settings from the console #14

Merged
dhkatz merged 2 commits from feat/imports-4b into main 2026-11-07 19:00:01 +00:00
16 changed files with 5538 additions and 13 deletions

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(" ");
}
+51 -6
View File
@@ -120,17 +120,48 @@ don't keep it: the consent is gone.
## `t5de-importer`
A Go program (its own repository) beside a `t5de-catalog`; it stores nothing lasting but its working files.
A Go program (its own repository) beside a `t5de-catalog`; it stores nothing lasting but its working files, its key
pair and the IMVU accounts' passwords.
- Configuration: `HUB_URL`, `CATALOG_ID`, `IMPORTER_KEY` (from enabling imports on the catalog), `IMPORTER_RATE`
(requests a second to IMVU, default 2), optionally an IMVU account for exact revisions (`IMVU_USERNAME`,
`IMVU_PASSWORD`; the operator's choice and risk; the hub never holds IMVU credentials).
- Everything is set from the console (the catalog's Imports page) except what it needs to reach the hub:
`HUB_URL`, `CATALOG_ID`, `IMPORTER_KEY` (from turning imports on), `IMPORTER_DATA` (its folder). The rest
(requests a second to IMVU, jobs at a time, the IMVU accounts and their order) comes from
`GET /api/v1/importer/config`, polled every minute.
- Revisions: without an IMVU account, the CDN is probed (`HEAD productdata/<id>/<n>`) once per product; afterwards a
recheck tries the next few numbers. With one, `authorizeProducts` gives exact revisions.
- Reads CFLs with t5de-api's `cfl` package; the conversion follows `@imvu/chkn` (dhkatz/imvu.js) as a reference.
- Validates with t5de-api's `pack` rules before uploading; a product breaking them fails with the reason. (The spike
checks whether typical IMVU products fit; imports may need their own limits.)
### IMVU accounts
Signed out, IMVU shows no info for Access Pass products (see "Built"), so an importer needs an IMVU account with
Access Pass to import them, and accounts give exact revisions. The catalog's team adds them on the console; their
passwords never reach the hub readable, and are kept only by the importer.
- On first start the importer makes an RSA key pair (3072-bit, RSA-OAEP with SHA-256) in `IMPORTER_DATA` and sends
the public key with `POST /api/v1/importer/hello {version, publicKey}`. The console shows its fingerprint and
version and when it was last heard from.
- Adding an account (`import:run`): the console looks the username up on IMVU (public info: avatar, ID, Access
Pass, age verified) and asks to confirm it in a dialog showing that, with a warning if it has no Access Pass
and the importer key's fingerprint. The password is encrypted in the browser (WebCrypto) with the importer's
public key; the hub stores only that sealed blob, hands it to the importer in its config, and deletes it once the
importer confirms it has it (or after 7 days).
- Several accounts, in an order the team sets: the importer uses the first that signs in and moves to the next when
one fails. It reports each account's state (`ok`, `sign_in_failed`, `needs_password`, plus whether IMVU shows it
Access Pass) with `POST /api/v1/importer/accounts/:id`, shown on the console. Before that an account is `waiting`
(sealed, not yet with the importer) or `received`. At most 10 accounts.
- If the importer's key pair changes (a new install), passwords sealed for the old key can't be read: those
accounts show "needs password" until re-entered.
- Removing an account tells the importer to forget it. Adding, new passwords and removing are audited
(`catalog.importer_account`), as are settings (`catalog.importer_settings`) and a new importer key pair
(`catalog.importer_hello`).
- Built (2026-11-07): all of the above on the hub and the console, except the importer's report of AP products' info
(with the importer).
- What the importer sees with an account (creator, name, rating of AP products) it reports to the hub with the job
(`POST /api/v1/importer/jobs/:id {product: {creatorId, name, rating}}`), trusted from that catalog's importer
only, for products IMVU hides from the hub.
## Hub routes
| | |
@@ -147,6 +178,17 @@ A Go program (its own repository) beside a `t5de-catalog`; it stores nothing las
| `POST /api/v1/catalogs/:id/importer` | `{enabled?}` (`import:run`; turning on returns the importer `key`, shown once) and `{paused?}` (`import:pause`) |
| `POST /api/v1/catalogs/:id/importer/key` | (`import:run`) → `{key}`: a new importer key |
| `POST /api/v1/catalogs/:id/importer/jobs/:job/retry` | (`import:run`) a failed or done job queued again |
| `GET /api/v1/catalogs/:id/importer/imvu-account?username=` | (`import:run`) `{imvuId, username, picture, accessPass, ageVerified}`: IMVU's public info, for the confirmation dialog |
| `POST /api/v1/catalogs/:id/importer/accounts` | (`import:run`) `{imvuId, sealed, fingerprint}` → 201 `{account}`. `fingerprint` must be the importer's key's (409 `importer_key_changed`; 409 `no_importer` before it has said hello); one per IMVU account (409 `exists`), at most 10. |
| `PUT /api/v1/catalogs/:id/importer/accounts/:account/password` | (`import:run`) `{sealed, fingerprint}`: a new password |
| `POST /api/v1/catalogs/:id/importer/accounts/:account/move` | (`import:run`) `{direction: "up" \| "down"}` |
| `DELETE /api/v1/catalogs/:id/importer/accounts/:account` | (`import:run`) |
| `POST /api/v1/catalogs/:id/importer/settings` | (`import:run`) `{rate (0.2-10 requests a second to IMVU), concurrency (1-8 jobs at once)}` |
`GET /api/v1/catalogs/:id/importer` also has `program: {version, seenAt, fingerprint, publicKey}` (`publicKey` only
with `import:run`), `settings`, and `accounts: [{id, imvuId, username, state, stateMessage, stateAt, accessPass,
ageVerified}]` (state: `waiting` for the importer, `received`, `ok`, `sign_in_failed`, `needs_password`). Never a
password, sealed or not.
For importers (`Authorization: Importer <catalog ID>:<key>`) in products.md.
@@ -167,8 +209,11 @@ deleted ones and IDs that never existed (404 only for a few very old IDs), so th
(`userimages-akm.imvu.com/productdata/<id>/<n>/`) serves AP and even deleted products' files without signing in
(made-up IDs 404), but they carry no creator, name or rating, which a grant needs to cover a product. The shop page
(`www.imvu.com/shop/product.php?products_id=`) tells them apart: an AP product redirects to sign-in, a deleted one
says "Not Found". For AP products, the importer's IMVU account (with Access Pass) would report the product info to
the hub: decide with the spike.
says "Not Found". For AP products, the importer's IMVU account (with Access Pass) reports the product info to the
hub ("IMVU accounts" above). Also signed out: `client-dynamic.imvu.com/api/shop/product.php` and
`api.imvu.com/creator/creator-<id>` need an account, and search refuses AP (`ap_search_denied`, with
`product_rating` other than `0,5`), but `api.imvu.com/product?creator=<username>` lists a shop's other products
(100 a page, `next` relation), which whole-shop grants use.
Still to do: admin-recorded grants, proofs and unclaimed creators (and claiming); `GET /imports/available` for the
proxy's shop button; t5de-catalog accepting `t5de-import` tokens on uploads; the spike and `t5de-importer`.
+3
View File
@@ -85,6 +85,9 @@ catalog's). Only approved catalogs with imports on and not paused.
| `POST /api/v1/importer/jobs/claim` | `{limit}` (1-20) → `{jobs: [{id, kind, imvuProduct, lastRevision}]}`; claimed jobs not reported within 30 minutes go back to the queue |
| `POST /api/v1/importer/jobs/:id/token` | `{imvuRevision}` → `{token, url}`: a `t5de-import` token and the catalog's upload URL |
| `POST /api/v1/importer/jobs/:id` | `{status: "done" \| "failed" \| "unchanged", imvuRevision?, reason?}` |
| `POST /api/v1/importer/hello` | `{version, publicKey}` (base64 SPKI, RSA 3072 to 4096 bits) → the config, as below. Sent at start. A new key means passwords sealed for the old one can't be read: the catalog's accounts then need their passwords again (imports.md "IMVU accounts"). |
| `GET /api/v1/importer/config` | `{paused, settings: {rate, concurrency}, fingerprint, accounts: [{id, imvuId, username, sealed}]}`, accounts in the order to try them. `sealed` (or null): `{imvuId, password}` as JSON, RSA-OAEP (SHA-256) for the importer's key, base64; check `imvuId`. Polled every minute; accounts no longer listed are forgotten. |
| `POST /api/v1/importer/accounts/:id` | `{received?, state? ("ok" \| "sign_in_failed" \| "needs_password"), accessPass?, message?}`: `received` once the password is stored (the hub drops its sealed copy), then how signing in went |
### For people (website, signed in; the proxy with its bearer token)
@@ -0,0 +1,27 @@
CREATE TABLE "importer_account" (
"id" text PRIMARY KEY NOT NULL,
"catalog_id" text NOT NULL,
"imvu_id" bigint NOT NULL,
"username" text NOT NULL,
"position" integer NOT NULL,
"sealed" text,
"sealed_for" text,
"sealed_at" timestamp with time zone,
"state" text DEFAULT 'waiting' NOT NULL,
"state_message" text DEFAULT '' NOT NULL,
"state_at" timestamp with time zone DEFAULT now() NOT NULL,
"access_pass" boolean DEFAULT false NOT NULL,
"age_verified" boolean DEFAULT false NOT NULL,
"added_by" text,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "catalog" ADD COLUMN "importer_public_key" text;--> statement-breakpoint
ALTER TABLE "catalog" ADD COLUMN "importer_fingerprint" text;--> statement-breakpoint
ALTER TABLE "catalog" ADD COLUMN "importer_version" text DEFAULT '' NOT NULL;--> statement-breakpoint
ALTER TABLE "catalog" ADD COLUMN "importer_seen_at" timestamp with time zone;--> statement-breakpoint
ALTER TABLE "catalog" ADD COLUMN "importer_settings" jsonb DEFAULT '{"rate":2,"concurrency":2}'::jsonb NOT NULL;--> statement-breakpoint
ALTER TABLE "importer_account" ADD CONSTRAINT "importer_account_catalog_id_catalog_id_fk" FOREIGN KEY ("catalog_id") REFERENCES "public"."catalog"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "importer_account" ADD CONSTRAINT "importer_account_added_by_user_id_fk" FOREIGN KEY ("added_by") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
CREATE UNIQUE INDEX "importer_account_imvu" ON "importer_account" USING btree ("catalog_id","imvu_id");
File diff suppressed because it is too large. Load diff
+7
View File
@@ -120,6 +120,13 @@
"when": 1793935614967,
"tag": "0016_imports",
"breakpoints": true
},
{
"idx": 17,
"version": "7",
"when": 1794073227716,
"tag": "0017_importer_accounts",
"breakpoints": true
}
]
}
+1 -1
View File
@@ -11,7 +11,7 @@ import { fileURLToPath } from "node:url";
import * as schema from "./schema";
export { schema };
export type { AuditTags, DecorationItem, FileEntry, InfoChange, ParentInfo, RoomModerator, SceneItem, TokenGrant } from "./schema";
export type { AuditTags, DecorationItem, FileEntry, ImporterSettings, InfoChange, ParentInfo, RoomModerator, SceneItem, TokenGrant } from "./schema";
export * from "drizzle-orm";
const migrationsFolder = fileURLToPath(new URL("../drizzle", import.meta.url));
+40
View File
@@ -292,6 +292,14 @@ export const catalog = pgTable(
// Imports (docs/imports.md): "off", "on" or "paused" (the hub hands its importer no jobs); the importer's key.
importer: text("importer").notNull().default("off"),
importerKeyHash: text("importer_key_hash"), // sha256, hex
// The importer program (docs/imports.md "IMVU accounts"): its RSA public key (SPKI, base64) that IMVU passwords
// are sealed for, the key's fingerprint (sha256 of the SPKI, hex), its version, when it last called, and its
// settings, set on the console.
importerPublicKey: text("importer_public_key"),
importerFingerprint: text("importer_fingerprint"),
importerVersion: text("importer_version").notNull().default(""),
importerSeenAt: timestamp("importer_seen_at", { withTimezone: true }),
importerSettings: jsonb("importer_settings").$type<ImporterSettings>().notNull().default({ rate: 2, concurrency: 2 }),
createdAt: createdAt(),
updatedAt: updatedAt(),
},
@@ -800,6 +808,38 @@ export const importJob = pgTable(
],
);
/** An importer's settings: requests a second to IMVU, and jobs worked on at once. */
export type ImporterSettings = { rate: number; concurrency: number };
// An IMVU account a catalog's importer signs in with (docs/imports.md "IMVU accounts"). Its password is never stored
// readable: the console seals it in the browser for the importer's public key, and the hub keeps that sealed copy
// only until the importer has it.
export const importerAccount = pgTable(
"importer_account",
{
id: text("id").primaryKey(),
catalogId: text("catalog_id")
.notNull()
.references(() => catalog.id, { onDelete: "cascade" }),
imvuId: bigint("imvu_id", { mode: "number" }).notNull(),
username: text("username").notNull(),
position: integer("position").notNull(), // the importer tries accounts in this order
sealed: text("sealed"), // the password sealed for the importer (RSA-OAEP, base64), until it has it
sealedFor: text("sealed_for"), // the fingerprint of the key it was sealed for
sealedAt: timestamp("sealed_at", { withTimezone: true }),
// "waiting" (sealed, not yet with the importer), "received", "ok", "sign_in_failed", "needs_password"
state: text("state").notNull().default("waiting"),
stateMessage: text("state_message").notNull().default(""),
stateAt: timestamp("state_at", { withTimezone: true }).notNull().defaultNow(),
accessPass: boolean("access_pass").notNull().default(false), // as IMVU shows it (the importer's report wins)
ageVerified: boolean("age_verified").notNull().default(false),
addedBy: text("added_by").references(() => user.id, { onDelete: "set null" }),
createdAt: createdAt(),
updatedAt: updatedAt(),
},
(t) => [uniqueIndex("importer_account_imvu").on(t.catalogId, t.imvuId)],
);
// IMVU products' public info, as imports and requests need it (looked up again after a day).
export const imvuProductInfo = pgTable("imvu_product_info", {
id: bigint("id", { mode: "number" }).primaryKey(),