Files
t5de-hub/apps/api/test/imports.test.ts
T
dhkatzandClaude Opus 5.5 7d708aebdb
Pull request / title (pull_request) Successful in 1s
CI / test (pull_request) Successful in 1m15s
CI / image (apps/api/Dockerfile, t5de-hub-api) (pull_request) Skipped
CI / image (apps/web/Dockerfile, t5de-hub-web) (pull_request) Skipped
feat: IMVU imports on the hub: grants, requests and the importer's job queue
Creators grant a catalog leave to import their IMVU products (whole shop less
exclusions, or listed products) from a linked IMVU account, agreeing to a versioned
consent text; the catalog's team accepts or declines. Requests queue covered
products (or add them to the library when imported already), suggest, or count.
Importers claim jobs with the catalog's importer key, get t5de-import tokens, and
the catalog registers imported revisions as published products owned by the creator.
Narrowing or withdrawing a grant withdraws products; unlinking suspends grants;
an hourly batch rechecks imported products with IMVU daily. Website: /imports and
the console's catalog imports page.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 19:46:10 -08:00

203 lines
13 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 { openDatabase, type Database } from "@t5de/db";
import { createApp } from "../src/app";
import { createAuth } from "../src/auth";
import { ImvuClient, type ImvuUser } from "../src/imvu";
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 fakeIMVU = (async (input: RequestInfo | URL) => {
const url = new URL(String(input));
const pm = url.pathname.match(/^\/product\/product-(\d+)$/);
if (pm) {
const p = imvuProducts.get(Number(pm[1]));
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 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 });
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 };
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");
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 });
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 }]);
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" });
});