Files
t5de-hub/apps/api/test/imports.test.ts
T
dhkatzandClaude Opus 5.5 56f9e29573
Pull request / title (pull_request) Successful in 2s
CI / test (pull_request) Successful in 1m31s
CI / image (apps/api/Dockerfile, t5de-hub-api) (pull_request) Skipped
CI / image (apps/web/Dockerfile, t5de-hub-web) (pull_request) Skipped
feat(imports): job claims carry IMVU's rating
The importer writes it into index.xml as ProductRating, so the files agree with the revision's rating.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 05:52:43 -08:00

503 lines
35 KiB
TypeScript

// Imports (docs/imports.md): a creator grants a catalog leave to import their IMVU products; the catalog's team
// accepts; requests queue jobs; the importer claims them, gets a token, uploads, and the catalog registers the
// revision; narrowing or withdrawing a grant withdraws products.
import { afterAll, beforeAll, expect, test } from "bun:test";
import { eq, openDatabase, schema, type Database } from "@t5de/db";
import { createApp } from "../src/app";
import { createAuth } from "../src/auth";
import { ImvuClient, type ImvuUser } from "../src/imvu";
import type { Imports } from "../src/imports";
import { twoFactorOn } from "./two-factor";
const webURL = "http://web.test";
const apiURL = "http://api.test";
const accounts = new Map<number, ImvuUser>();
const imvuProducts = new Map<number, Record<string, unknown>>();
const hiddenProducts = new Set<number>(); // answered 401, as IMVU does for Access Pass products
const shops = new Map<string, number[]>(); // IMVU username (lowercase) → the products IMVU lists for it
const fakeIMVU = (async (input: RequestInfo | URL) => {
const url = new URL(String(input));
if (url.pathname === "/product" && url.searchParams.has("creator")) {
// Pages of 2 that overlap by one, as IMVU's small pages do: the client follows `next` and drops repeats.
const creator = url.searchParams.get("creator")!;
const ids = shops.get(creator.toLowerCase()) ?? [];
const offset = Number(url.searchParams.get("offset") ?? 0);
const page = ids.slice(offset, offset + 2);
const self = `http://imvu.test/product?creator=${creator}&offset=${offset}`;
const next = offset + 2 < ids.length ? { next: `http://imvu.test/product?creator=${creator}&offset=${offset + 1}` } : [];
const den: Record<string, unknown> = {
[self]: { data: { items: page.map((id) => `https://api.imvu.com/product/product-${id}`), total_count: ids.length }, relations: next },
};
for (const id of page) den[`https://api.imvu.com/product/product-${id}`] = { data: { product_id: id, ...imvuProducts.get(id) } };
return Response.json({ status: "success", id: self, denormalized: den });
}
const pm = url.pathname.match(/^\/product\/product-(\d+)$/);
if (pm) {
const p = imvuProducts.get(Number(pm[1]));
if (hiddenProducts.has(Number(pm[1]))) return Response.json({ status: "failure", error: "AUTHENTICATION-005" }, { status: 401 });
if (!p) return Response.json({ status: "failure" }, { status: 404 });
return Response.json({ denormalized: { [`https://api.imvu.com/product/product-${pm[1]}`]: { data: p } } });
}
const u = [...accounts.values()].find(
(u) => url.pathname === `/user/user-${u.id}` || url.searchParams.get("username")?.toLowerCase() === u.username.toLowerCase(),
);
return Response.json({
denormalized: u
? { [`https://api.imvu.com/user/user-${u.id}`]: { data: { legacy_cid: u.id, username: u.username, tagline: u.tagline, is_ageverified: u.ageVerified, is_ap: u.accessPass } } }
: {},
});
}) as unknown as typeof fetch;
let imports: Imports;
let db: Database;
let close: () => Promise<void>;
let base: string;
let stop: () => void;
beforeAll(async () => {
({ db, close } = await openDatabase("memory"));
const auth = createAuth(db, { apiURL, webURL, secret: "test-secret-test-secret-test-secret-1234", rateLimit: false });
const hub = createApp({ db, auth, imvu: new ImvuClient("http://imvu.test", fakeIMVU), apiURL, webURL, catalogHealthy: async () => true });
imports = hub.imports;
hub.app.listen({ port: 0, hostname: "127.0.0.1" });
const server = hub.app.server as unknown as { port: number; stop: () => void };
stop = () => server.stop();
base = `http://127.0.0.1:${server.port}`;
});
afterAll(async () => {
stop();
await close();
});
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,
headers: { Origin: webURL, ...(body !== undefined ? { "Content-Type": "application/json" } : {}), ...(p ? { Cookie: p.cookie } : {}), ...headers },
body: body !== undefined ? JSON.stringify(body) : undefined,
});
const text = await res.text();
let json: any;
try {
json = JSON.parse(text);
} catch {
json = text;
}
return { status: res.status, json };
}
/** A person (with two-factor sign-in on), optionally with a linked IMVU account. */
async function person(name: string, imvu?: number): Promise<Person> {
const res = await fetch(base + "/api/auth/sign-up/email", {
method: "POST",
headers: { Origin: webURL, "Content-Type": "application/json" },
body: JSON.stringify({ email: `${name}@example.test`, password: "a long password", name, username: name }),
});
await twoFactorOn(db, name);
const p = { cookie: res.headers.getSetCookie().map((c) => c.split(";")[0]).join("; "), name };
if (imvu) {
accounts.set(imvu, { id: imvu, username: `${name}Av`, tagline: "", ageVerified: false, accessPass: false, picture: null });
const started = await call(p, "POST", "/api/v1/account/links", { username: `${name}Av` });
accounts.get(imvu)!.tagline = started.json.challenge.code;
expect((await call(p, "POST", `/api/v1/account/links/${imvu}/check`)).status).toBe(200);
}
return p;
}
const file = (name: string, n: number) => ({ name, sha256: n.toString(16).padStart(64, "0"), size: 100 * n });
const imvuProduct = (name: string, creator: number, rating = "GA") => ({ product_name: name, creator_cid: creator, creator_name: "x", rating, is_purchasable: true });
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");
imvuProducts.set(9001, imvuProduct("Silk Dress", 501));
imvuProducts.set(9002, imvuProduct("Silk Hat", 501));
imvuProducts.set(9003, imvuProduct("Silk Shoes", 501));
imvuProducts.set(9100, imvuProduct("Someone Else's", 777));
const reg = await call(owner, "POST", "/api/v1/catalogs", { name: "Imports Shelf", url: "https://imports.example.test", contact: "[email protected]", visibility: "public", membership: "open" });
const catalogID = reg.json.catalog.id as string;
const catalogAuth = { Authorization: `Catalog ${catalogID}:${reg.json.key}` };
expect((await call(admin, "POST", `/api/v1/console/catalogs/${catalogID}/approve`)).status).toBe(200);
// Imports on: an importer key, and the catalog takes grants.
expect((await call(undefined, "GET", "/api/v1/imports/catalogs")).json.catalogs).toEqual([]);
expect((await call(fan, "POST", `/api/v1/catalogs/${catalogID}/importer`, { enabled: true })).status).toBe(403);
const on = await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer`, { enabled: true });
expect(on.json.catalog.importer).toBe("on");
const importer = { Authorization: `Importer ${catalogID}:${on.json.key}` };
const listed = (await call(undefined, "GET", "/api/v1/imports/catalogs")).json;
expect(listed.catalogs.map((c: any) => c.id)).toEqual([catalogID]);
const version = listed.consent.version;
expect((await call(undefined, "POST", "/api/v1/importer/jobs/claim", {}, { Authorization: `Importer ${catalogID}:wrong` })).status).toBe(401);
// Before any grant, requests are counted.
expect((await call(fan, "POST", "/api/v1/imports/requests", { imvuProduct: 9001 })).json).toEqual({ status: "counted" });
expect((await call(fan, "POST", "/api/v1/imports/requests", { imvuCreator: 501 })).json).toEqual({ status: "counted" });
expect((await call(fan, "POST", "/api/v1/imports/requests", { imvuProduct: 4242 })).status).toBe(404);
// A grant: only for one's own linked account, with the current consent.
const grantBody = { catalog: catalogID, imvuId: 501, scope: "shop", exclude: [9003], consentVersion: version };
expect((await call(fan, "POST", "/api/v1/imports/grants", grantBody)).json.error).toBe("not_linked");
expect((await call(maker, "POST", "/api/v1/imports/grants", { ...grantBody, consentVersion: version + 1 })).json.error).toBe("consent_changed");
const made = await call(maker, "POST", "/api/v1/imports/grants", grantBody);
expect(made.status).toBe(201);
expect(made.json.grant).toMatchObject({ status: "pending", scope: "shop", exclude: [9003], consentKind: "verified" });
const grantID = made.json.grant.id as string;
expect((await call(maker, "POST", "/api/v1/imports/grants", grantBody)).json.error).toBe("exists");
expect((await call(undefined, "POST", "/api/v1/importer/jobs/claim", {}, importer)).json.jobs).toEqual([]);
// The catalog's team accepts: what people asked for is queued; the creator hears.
expect((await call(maker, "POST", `/api/v1/imports/grants/${grantID}/accept`)).status).toBe(403);
const accepted = await call(owner, "POST", `/api/v1/imports/grants/${grantID}/accept`);
expect(accepted.json).toMatchObject({ grant: { status: "active" }, queued: 1 });
await imports.listingsDone(); // the shop's listing (IMVU lists nothing for it here)
expect((await call(maker, "GET", "/api/v1/notifications")).json.notifications[0]).toMatchObject({ type: "import_grant_decided" });
// Paused: no jobs handed out.
expect((await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer`, { paused: true })).json.catalog.importer).toBe("paused");
expect((await call(undefined, "POST", "/api/v1/importer/jobs/claim", {}, importer)).json.jobs).toEqual([]);
await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer`, { paused: false });
// The importer claims the job, gets a token for the revision it found, and uploads; the catalog registers it.
const claimed = (await call(undefined, "POST", "/api/v1/importer/jobs/claim", { limit: 5 }, importer)).json.jobs;
expect(claimed).toEqual([{ id: expect.any(String), kind: "import", imvuProduct: 9001, lastRevision: 0, rating: "general" }]);
const tok = await call(undefined, "POST", `/api/v1/importer/jobs/${claimed[0].id}/token`, { imvuRevision: 3 }, importer);
expect(tok.json.url).toBe("https://imports.example.test/api/v1/uploads");
const files = [file("index.xml", 11), file("dress.xmf", 12)];
const regd = await call(undefined, "POST", "/api/v1/catalog/revisions", { importToken: tok.json.token, files, rating: "general", parent: 1234, name: "ignored" }, catalogAuth);
expect(regd.status).toBe(201);
const productID = regd.json.product as string;
const page = (await call(fan, "GET", `/api/v1/products/${productID}`)).json;
expect(page.product).toMatchObject({ name: "Silk Dress", creatorUsername: "maker", status: "published", imvuProduct: 9001 });
// The fan who asked has it.
expect((await call(fan, "GET", "/api/v1/library")).json.library.map((l: any) => l.product.id)).toEqual([productID]);
// The same token again: the job is done.
expect((await call(undefined, "POST", "/api/v1/catalog/revisions", { importToken: tok.json.token, files, rating: "general", parent: 1234, name: "x" }, catalogAuth)).status).toBe(409);
// Asking for an imported product adds it at once; a covered one is queued; excluded or others' are counted.
const other = await person("other");
expect((await call(other, "POST", "/api/v1/imports/requests", { imvuProduct: 9001 })).json).toEqual({ status: "added", product: productID });
expect((await call(fan, "POST", "/api/v1/imports/requests", { imvuProduct: 9002 })).json).toEqual({ status: "queued" });
expect((await call(fan, "POST", "/api/v1/imports/requests", { imvuProduct: 9003 })).json).toEqual({ status: "counted" });
expect((await call(fan, "POST", "/api/v1/imports/requests", { imvuProduct: 9100 })).json).toEqual({ status: "counted" });
// A failure goes back to the queue with backoff, the reason shown to the team.
const second = (await call(undefined, "POST", "/api/v1/importer/jobs/claim", {}, importer)).json.jobs;
expect(second.map((j: any) => j.imvuProduct)).toEqual([9002]);
const failed = await call(undefined, "POST", `/api/v1/importer/jobs/${second[0].id}`, { status: "failed", reason: "CDN said 503" }, importer);
expect(failed.json.job).toMatchObject({ status: "queued", attempts: 1, reason: "CDN said 503" });
expect((await call(undefined, "POST", "/api/v1/importer/jobs/claim", {}, importer)).json.jobs).toEqual([]);
const view = (await call(owner, "GET", `/api/v1/catalogs/${catalogID}/importer`)).json;
expect(view).toMatchObject({ importer: "on", counts: { queued: 1, done: 1 }, permissions: { run: true, accept: true } });
expect(view.grants.map((g: any) => g.imvuName)).toEqual(["makerAv"]);
expect((await call(fan, "GET", `/api/v1/catalogs/${catalogID}/importer`)).status).toBe(403);
// The creator sees what people asked for.
const asked = (await call(maker, "GET", "/api/v1/imports/requests?imvuCreator=501")).json.requests;
expect(asked.map((r: any) => [r.imvuProduct, r.requests])).toEqual([[9001, 2], [0, 1], [9002, 1], [9003, 1]]);
expect((await call(fan, "GET", "/api/v1/imports/requests?imvuCreator=501")).status).toBe(403);
// Narrowing the grant withdraws what it no longer covers: gone, and the catalog deletes its files.
const narrowed = await call(maker, "PATCH", `/api/v1/imports/grants/${grantID}`, { exclude: [9001, 9003] });
expect(narrowed.json.withdrawn).toEqual([productID]);
expect((await call(fan, "GET", `/api/v1/products/${productID}`)).status).toBe(410);
const changes = (await call(undefined, "GET", "/api/v1/catalog/changes", undefined, catalogAuth)).json.changes;
expect(changes).toContainEqual({ type: "delete", product: productID, revision: 1, files: expect.any(Array) });
// Withdrawn: its open jobs fail; the catalog's audit has it all.
const gone = await call(maker, "DELETE", `/api/v1/imports/grants/${grantID}`);
expect(gone.json.grant.status).toBe("withdrawn");
expect((await call(owner, "GET", `/api/v1/catalogs/${catalogID}/importer?status=failed`)).json.jobs.map((j: any) => j.imvuProduct)).toEqual([9002]);
const actions = (await call(owner, "GET", "/api/v1/console/audit")).json.entries.map((e: any) => e.action);
expect(actions).toEqual(expect.arrayContaining(["catalog.importer", "import.grant", "import.grant_accept", "import.revision", "import.grant_withdraw"]));
// Unlinking the IMVU account suspends its grants.
const again = await call(maker, "POST", "/api/v1/imports/grants", { ...grantBody, scope: "products", products: [9002] });
expect(again.status).toBe(201);
expect((await call(maker, "DELETE", "/api/v1/account/links/501")).status).toBe(204);
expect((await call(maker, "GET", "/api/v1/imports/grants")).json.grants[0]).toMatchObject({ id: again.json.grant.id, status: "suspended" });
});
test("IMVU's 401 keeps what was last seen; 404 is gone", async () => {
imvuProducts.set(9500, imvuProduct("Turned AP", 501));
expect(await imports.info(9500, true)).toMatchObject({ found: true, creatorId: 501 });
hiddenProducts.add(9500);
expect(await imports.info(9500, true)).toMatchObject({ found: true, creatorId: 501, name: "Turned AP" });
hiddenProducts.add(9501); // never seen: nothing to keep
expect(await imports.info(9501, true)).toBeUndefined();
hiddenProducts.delete(9500);
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);
});
test("recorded grants, unclaimed creators, proof, and claiming", async () => {
const admin = rootAdmin;
const owner = await person("shelver");
const fan = await person("fanatic");
accounts.set(701, { id: 701, username: "QuietMaker", tagline: "", ageVerified: false, accessPass: false, picture: null });
imvuProducts.set(9201, imvuProduct("Quiet Coat", 701));
imvuProducts.set(9202, imvuProduct("Quiet Hat", 701));
const reg = await call(owner, "POST", "/api/v1/catalogs", { name: "Recorded Shelf", url: "https://recorded.example.test", contact: "[email protected]", visibility: "public", membership: "open" });
const catalogID = reg.json.catalog.id as string;
const catalogAuth = { Authorization: `Catalog ${catalogID}:${reg.json.key}` };
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}` };
// Only those who may grant on behalf record; evidence is required; creators on T5DE grant themselves.
const body = { catalog: catalogID, imvu: "QuietMaker", scope: "shop", exclude: [9202], evidence: "Discord DM, 2026-11-07" };
expect((await call(owner, "POST", "/api/v1/console/imports/grants", body)).status).toBe(403);
expect((await call(owner, "GET", "/api/v1/console/imports")).status).toBe(403);
expect((await call(admin, "POST", "/api/v1/console/imports/grants", { ...body, evidence: " " })).json.error).toBe("invalid");
await person("onhub", 801); // a creator on T5DE, with their IMVU account linked
expect((await call(admin, "POST", "/api/v1/console/imports/grants", { ...body, imvu: "801" })).json.error).toBe("linked");
const recorded = await call(admin, "POST", "/api/v1/console/imports/grants", body);
expect(recorded.status).toBe(201);
expect(recorded.json.grant).toMatchObject({ status: "pending", consentKind: "recorded", consentProven: false, imvuName: "QuietMaker" });
const grantID = recorded.json.grant.id as string;
expect((await call(admin, "POST", "/api/v1/console/imports/grants", body)).json.error).toBe("exists");
// The console lists it; the catalog's team sees it named, and accepts as for any grant.
const consoleView = (await call(admin, "GET", "/api/v1/console/imports")).json;
expect(consoleView.grants).toEqual([expect.objectContaining({ id: grantID, evidence: "Discord DM, 2026-11-07", recordedBy: "root", claimed: false, proofCode: null })]);
expect((await call(owner, "GET", `/api/v1/catalogs/${catalogID}/importer`)).json.grants[0]).toMatchObject({ imvuName: "QuietMaker", consentKind: "recorded" });
expect((await call(owner, "POST", `/api/v1/imports/grants/${grantID}/accept`)).json.grant.status).toBe("active");
// Proof without an account: a code in the creator's IMVU tagline.
expect((await call(admin, "POST", `/api/v1/console/imports/grants/${grantID}/proof/check`)).json.error).toBe("no_code");
const code = (await call(admin, "POST", `/api/v1/console/imports/grants/${grantID}/proof`)).json.code as string;
expect(code).toMatch(/^t5de-/);
expect((await call(admin, "POST", `/api/v1/console/imports/grants/${grantID}/proof`)).json.code).toBe(code);
expect((await call(admin, "POST", `/api/v1/console/imports/grants/${grantID}/proof/check`)).json.error).toBe("not_found");
accounts.get(701)!.tagline = `hi ${code}`;
expect((await call(admin, "POST", `/api/v1/console/imports/grants/${grantID}/proof/check`)).json.grant.consentProven).toBe(true);
// Imported products belong to the unclaimed creator.
expect((await call(fan, "POST", "/api/v1/imports/requests", { imvuProduct: 9201 })).json).toEqual({ status: "queued" });
const [job] = (await call(undefined, "POST", "/api/v1/importer/jobs/claim", {}, importer)).json.jobs;
const tok = await call(undefined, "POST", `/api/v1/importer/jobs/${job.id}/token`, { imvuRevision: 1 }, importer);
const regd = await call(undefined, "POST", "/api/v1/catalog/revisions", { importToken: tok.json.token, files: [file("index.xml", 31)], rating: "general", parent: 0, name: "x" }, catalogAuth);
expect(regd.status).toBe(201);
const productID = regd.json.product as string;
expect((await call(fan, "GET", `/api/v1/products/${productID}`)).json.product).toMatchObject({ name: "Quiet Coat", creatorUsername: "imvu_701" });
// Admins change it for them; others can't.
expect((await call(fan, "PATCH", `/api/v1/imports/grants/${grantID}`, { exclude: [] })).status).toBe(403);
expect((await call(admin, "PATCH", `/api/v1/imports/grants/${grantID}`, { exclude: [] })).json.grant.exclude).toEqual([]);
// Nobody signs up as an unclaimed creator.
const squat = await fetch(base + "/api/auth/sign-up/email", {
method: "POST",
headers: { Origin: webURL, "Content-Type": "application/json" },
body: JSON.stringify({ email: "[email protected]", password: "a long password", name: "squat", username: "imvu_702" }),
});
expect(squat.status).toBe(400);
// The creator joins and links the account: the grant stands, and they're offered the claim.
const quiet = await person("quiet", 701);
expect((await call(quiet, "GET", "/api/v1/imports/grants")).json.grants).toEqual([]);
expect((await call(admin, "GET", "/api/v1/console/imports")).json.grants[0]).toMatchObject({ status: "active", claimed: false });
expect((await call(quiet, "GET", "/api/v1/account")).json.claims).toEqual([{ imvuId: 701, username: "QuietMaker", products: 1, grants: 1 }]);
expect((await call(fan, "POST", "/api/v1/account/claims/701")).json.error).toBe("not_linked");
expect((await call(quiet, "POST", "/api/v1/account/claims/701")).json).toEqual({ products: 1, grants: 1 });
// Now it's theirs: their product and grant; the placeholder is gone; admins no longer change it.
expect((await call(fan, "GET", `/api/v1/products/${productID}`)).json.product.creatorUsername).toBe("quiet");
expect((await call(quiet, "GET", "/api/v1/imports/grants")).json.grants.map((g: any) => g.id)).toEqual([grantID]);
expect((await call(quiet, "GET", "/api/v1/account")).json.claims).toEqual([]);
expect((await call(admin, "GET", "/api/v1/console/imports")).json.grants[0].claimed).toBe(true);
expect((await call(admin, "PATCH", `/api/v1/imports/grants/${grantID}`, { exclude: [9202] })).status).toBe(403);
expect((await call(quiet, "PATCH", `/api/v1/imports/grants/${grantID}`, { exclude: [9202] })).status).toBe(200);
expect((await call(quiet, "POST", "/api/v1/account/claims/701")).status).toBe(404);
const actions = (await call(admin, "GET", "/api/v1/console/audit")).json.entries.map((e: any) => e.action);
expect(actions).toEqual(expect.arrayContaining(["import.grant_record", "import.grant_proof", "import.claim"]));
});
test("whole shops listed on IMVU, and what's available", async () => {
const owner = await person("stall");
const keeper = await person("shopkeep", 901);
const fan = await person("browser");
const reg = await call(owner, "POST", "/api/v1/catalogs", { name: "Shop Shelf", url: "https://shops.example.test", contact: "[email protected]", visibility: "public", membership: "open" });
const catalogID = reg.json.catalog.id as string;
const catalogAuth = { Authorization: `Catalog ${catalogID}:${reg.json.key}` };
expect((await call(rootAdmin, "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 version = (await call(undefined, "GET", "/api/v1/imports/catalogs")).json.consent.version;
for (const [id, name] of [[9301, "Keeper Coat"], [9302, "Keeper Boots"], [9303, "Keeper Scarf"]] as const)
imvuProducts.set(id, { ...imvuProduct(name, 901), creator_name: "shopkeepAv" });
shops.set("shopkeepav", [9301, 9302, 9303, 9100]); // 9100 is another creator's: left out
// Nothing yet.
const none = await call(undefined, "GET", "/api/v1/imports/available?products=9301,9999&creators=901");
expect(none.json).toEqual({
products: [
{ imvuProduct: 9301, status: "none", product: null },
{ imvuProduct: 9999, status: "none", product: null },
],
shops: [{ imvuCreator: 901, shop: false, products: 0 }],
});
expect((await call(undefined, "GET", "/api/v1/imports/available?products=9301,abc")).status).toBe(400);
// Accepting a whole-shop grant lists the shop on IMVU: its products are queued, less those left out.
const made = await call(keeper, "POST", "/api/v1/imports/grants", { catalog: catalogID, imvuId: 901, scope: "shop", exclude: [9303], consentVersion: version });
expect(made.json.grant).toMatchObject({ shopListedAt: null, shopListed: 0 });
const grantID = made.json.grant.id as string;
expect((await call(owner, "POST", `/api/v1/imports/grants/${grantID}/accept`)).json.queued).toBe(0);
await imports.listingsDone();
const view = (await call(owner, "GET", `/api/v1/catalogs/${catalogID}/importer`)).json;
expect(view.grants[0]).toMatchObject({ shopListed: 3, shopListedAt: expect.any(String) });
expect(view.jobs.map((j: any) => j.imvuProduct).sort()).toEqual([9301, 9302]);
expect(await imports.info(9302)).toMatchObject({ found: true, name: "Keeper Boots", creatorId: 901 });
// Queued, covered, left out; the fan's own request shows.
expect((await call(fan, "POST", "/api/v1/imports/requests", { imvuProduct: 9302 })).json).toEqual({ status: "queued" });
const queued = await call(fan, "GET", "/api/v1/imports/available?products=9301,9302,9303&creators=901");
expect(queued.json.products).toEqual([
{ imvuProduct: 9301, status: "queued", product: null, requested: false },
{ imvuProduct: 9302, status: "queued", product: null, requested: true },
{ imvuProduct: 9303, status: "none", product: null, requested: false },
]);
expect(queued.json.shops).toEqual([{ imvuCreator: 901, shop: true, products: 0 }]);
// Imported: the hub product; an adult one only for adult accounts.
const jobs = (await call(undefined, "POST", "/api/v1/importer/jobs/claim", { limit: 5 }, importer)).json.jobs;
const imported: Record<number, string> = {};
for (const j of jobs) {
const tok = await call(undefined, "POST", `/api/v1/importer/jobs/${j.id}/token`, { imvuRevision: 1 }, importer);
const rating = j.imvuProduct === 9302 ? "adult" : "general";
const files = [file("index.xml", j.imvuProduct)];
const r = await call(undefined, "POST", "/api/v1/catalog/revisions", { importToken: tok.json.token, files, rating, parent: 0, name: "x" }, catalogAuth);
expect(r.status).toBe(201);
imported[j.imvuProduct] = r.json.product;
}
const done = await call(undefined, "GET", "/api/v1/imports/available?products=9301,9302&creators=901");
expect(done.json).toEqual({
products: [
{ imvuProduct: 9301, status: "imported", product: imported[9301] },
{ imvuProduct: 9302, status: "adult", product: null },
],
shops: [{ imvuCreator: 901, shop: true, products: 2 }],
});
// A new product on IMVU: listed again (by the team, or daily), it's queued.
imvuProducts.set(9304, { ...imvuProduct("Keeper Gloves", 901), creator_name: "shopkeepAv" });
shops.set("shopkeepav", [9301, 9302, 9303, 9304]);
expect((await call(fan, "POST", `/api/v1/imports/grants/${grantID}/list`)).status).toBe(403);
const again = await call(owner, "POST", `/api/v1/imports/grants/${grantID}/list`);
expect(again.json).toMatchObject({ listed: 4, queued: 1, grant: { shopListed: 4 } });
imvuProducts.set(9305, { ...imvuProduct("Keeper Belt", 901), creator_name: "shopkeepAv" });
shops.set("shopkeepav", [9301, 9302, 9303, 9304, 9305]);
expect(await imports.listShops()).toEqual({ shops: 0, queued: 0 }); // listed within a day
await db.update(schema.importGrant).set({ shopListedAt: new Date(Date.now() - 2 * 86_400_000) }).where(eq(schema.importGrant.id, grantID));
expect(await imports.listShops()).toEqual({ shops: 1, queued: 1 });
// Grants of chosen products aren't listed.
const chooser = await person("chooser", 902);
const g2 = await call(chooser, "POST", "/api/v1/imports/grants", { catalog: catalogID, imvuId: 902, scope: "products", products: [9401], consentVersion: version });
await call(owner, "POST", `/api/v1/imports/grants/${g2.json.grant.id}/accept`);
expect((await call(owner, "POST", `/api/v1/imports/grants/${g2.json.grant.id}/list`)).json.error).toBe("not_shop");
});