// 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(); const imvuProducts = new Map>(); const hiddenProducts = new Set(); // 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; 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 = {}) { 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 { 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: "t@example.test", 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(); }); 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: "k@example.test", 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); });