Files
t5de-hub/apps/api/test/imports.test.ts
T
dhkatz 7ece681eef
Release / release (push) Successful in 4s
CI / test (push) Successful in 1m25s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 7s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 15s
feat: IMVU imports on the hub: grants, requests and the importer's job queue (#13)
Phase 4a (docs/imports.md): the hub's side of IMVU imports.

**Grants**
- A creator picks one of their linked IMVU accounts and a catalog with imports on. They choose the whole shop (with exclusions) or listed products, listed or unlisted, and agree to a versioned consent text (`imports.ts` `consent`).
- The catalog's team (`import:accept`) accepts or declines, and the creator is notified. Accepting queues what people already asked for, plus a grant's listed products.
- The creator can change what's covered or withdraw it; the team (`import:withdraw`, which moderators also have) can end it.
- Withdrawn products are removed the way moderation removes products: their hosting is dropped and their files go in the catalogs' changes feed. If another catalog's active grant still covers a product, it's only delisted from this catalog.
- Unlinking an IMVU account, or someone else linking it, suspends its grants.

**Requests**
- Anyone signed in can ask for an IMVU product (an ID or a shop link). The answer is one of:
  - `added`: already imported, and now in their library
  - `queued`: delivered to their library once imported
  - `suggested`: the creator grants by listed products, and will see the request
  - `counted`: no grant covers it yet
- Creators see request counts for their accounts, and moderators see the most-requested creators.
- At most 50 requests a day per person.

**Importer**
- Importers sign in with `Authorization: Importer <catalog>:<key>`; turning imports on returns the key once. The catalog's importer can be paused (`import:pause`).
- Importers claim jobs, get `t5de-import` tokens for a revision, and report outcomes.
- Claims time out after 30 minutes. Failures retry after 1 min, 10 min, 1 h, then daily, and fail for good after 5 attempts.
- `POST /catalog/revisions` takes `importToken` instead of `uploadToken`. The result is a published product owned by the creator (`product.imvu_product`, `product_revision.imvu_revision`). If another catalog already imported the same IMVU revision, this catalog hosts it too.
- Every hour, the API rechecks a batch of imported products with IMVU (each at most once a day). A product gone from IMVU, or now another creator's, is withdrawn. One rated AP becomes adult. If it's still covered, a recheck job looks for new revisions.

**Website**
- `/imports`: ask for a product; bring your products; change or withdraw a grant; what people asked for. It's linked from the account page.
- The console's catalog page has an Imports card leading to `/console/catalogs/:id/imports`:
  - importer on, off, pause and resume, and a new key
  - pending grants to accept or decline
  - grants to end
  - the queue, filtered by status, with retry
- Notification text for the two new notification types.

**Checks**
- **Tests:** `test/imports.test.ts` covers the whole flow, from grant to withdrawal. All 58 API tests pass, and type checks pass.
- **Scratch hub:** through the console forms, I turned imports on (the key was shown once), paused and resumed. I checked that importer claims accept the key and refuse a wrong one, that `/imports` renders, and that a request while IMVU is unreachable says "IMVU didn't answer."
- **IMVU fields not checked live:** `api.imvu.com` times out from the dev machine. The product fields (`product_name`, `creator_cid`, `creator_name`, `rating`, `is_purchasable`) are what the design recorded; the spike will check them.

**Formatting**
- `two-factor-card.tsx`, `signin-form.tsx` and `console-nav.tsx` are only reformatted. I'd run Prettier on them at its default 80 columns in #12, but the repo is wrapped at about 120.

**Still to do (4b and later)**
- admin-recorded grants, proofs and unclaimed creators (and claiming them)
- `GET /imports/available` for the proxy's shop button
- t5de-catalog accepting `t5de-import` tokens on uploads
- the spike, then `t5de-importer`

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Phase 4a (docs/imports.md): the hub's side of IMVU imports.

**Grants**
- A creator picks one of their linked IMVU accounts and a catalog with imports on. They choose the whole shop (with exclusions) or listed products, listed or unlisted, and agree to a versioned consent text (`imports.ts` `consent`).
- The catalog's team (`import:accept`) accepts or declines, and the creator is notified. Accepting queues what people already asked for, plus a grant's listed products.
- The creator can change what's covered or withdraw it; the team (`import:withdraw`, which moderators also have) can end it.
- Withdrawn products are removed the way moderation removes products: their hosting is dropped and their files go in the catalogs' changes feed. If another catalog's active grant still covers a product, it's only delisted from this catalog.
- Unlinking an IMVU account, or someone else linking it, suspends its grants.

**Requests**
- Anyone signed in can ask for an IMVU product (an ID or a shop link). The answer is one of:
  - `added`: already imported, and now in their library
  - `queued`: delivered to their library once imported
  - `suggested`: the creator grants by listed products, and will see the request
  - `counted`: no grant covers it yet
- Creators see request counts for their accounts, and moderators see the most-requested creators.
- At most 50 requests a day per person.

**Importer**
- Importers sign in with `Authorization: Importer <catalog>:<key>`; turning imports on returns the key once. The catalog's importer can be paused (`import:pause`).
- Importers claim jobs, get `t5de-import` tokens for a revision, and report outcomes.
- Claims time out after 30 minutes. Failures retry after 1 min, 10 min, 1 h, then daily, and fail for good after 5 attempts.
- `POST /catalog/revisions` takes `importToken` instead of `uploadToken`. The result is a published product owned by the creator (`product.imvu_product`, `product_revision.imvu_revision`). If another catalog already imported the same IMVU revision, this catalog hosts it too.
- Every hour, the API rechecks a batch of imported products with IMVU (each at most once a day). A product gone from IMVU, or now another creator's, is withdrawn. One rated AP becomes adult. If it's still covered, a recheck job looks for new revisions.

**Website**
- `/imports`: ask for a product; bring your products; change or withdraw a grant; what people asked for. It's linked from the account page.
- The console's catalog page has an Imports card leading to `/console/catalogs/:id/imports`:
  - importer on, off, pause and resume, and a new key
  - pending grants to accept or decline
  - grants to end
  - the queue, filtered by status, with retry
- Notification text for the two new notification types.

**Checks**
- **Tests:** `test/imports.test.ts` covers the whole flow, from grant to withdrawal. All 58 API tests pass, and type checks pass.
- **Scratch hub:** through the console forms, I turned imports on (the key was shown once), paused and resumed. I checked that importer claims accept the key and refuse a wrong one, that `/imports` renders, and that a request while IMVU is unreachable says "IMVU didn't answer."
- **IMVU fields not checked live:** `api.imvu.com` times out from the dev machine. The product fields (`product_name`, `creator_cid`, `creator_name`, `rating`, `is_purchasable`) are what the design recorded; the spike will check them.

**Formatting**
- `two-factor-card.tsx`, `signin-form.tsx` and `console-nav.tsx` are only reformatted. I'd run Prettier on them at its default 80 columns in #12, but the repo is wrapped at about 120.

**Still to do (4b and later)**
- admin-recorded grants, proofs and unclaimed creators (and claiming them)
- `GET /imports/available` for the proxy's shop button
- t5de-catalog accepting `t5de-import` tokens on uploads
- the spike, then `t5de-importer`

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: dhkatz <[email protected]>
2026-11-07 16:29:03 +00:00

220 lines
14 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 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 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 (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 };
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" });
});
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();
});