From 64b9658bad7b38d09645a8468c3585cf0e981571 Mon Sep 17 00:00:00 2001 From: dhkatz Date: Sat, 7 Nov 2026 11:12:26 -0800 Subject: [PATCH] feat: recorded import grants, unclaimed creators and claiming Admins record consent for IMVU creators without an account; their products belong to a placeholder (imvu_) until they link the account and claim them. Proof by a tagline code. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/app.ts | 94 +- apps/api/src/auth.ts | 3 +- apps/api/src/imports.ts | 159 +- apps/api/test/catalogs.test.ts | 2 +- apps/api/test/imports.test.ts | 84 + apps/web/app/account/actions.ts | 10 + apps/web/app/account/page.tsx | 21 +- .../console/catalogs/[id]/imports/page.tsx | 4 +- apps/web/app/console/console-nav.tsx | 1 + apps/web/app/console/imports/actions.ts | 71 + apps/web/app/console/imports/page.tsx | 291 ++ apps/web/app/imports/actions.ts | 13 +- apps/web/lib/imvu.ts | 13 + docs/imports.md | 22 +- packages/db/drizzle/0018_recorded_grants.sql | 4 + packages/db/drizzle/meta/0018_snapshot.json | 4443 +++++++++++++++++ packages/db/drizzle/meta/_journal.json | 7 + packages/db/src/schema.ts | 6 + 18 files changed, 5222 insertions(+), 26 deletions(-) create mode 100644 apps/web/app/console/imports/actions.ts create mode 100644 apps/web/app/console/imports/page.tsx create mode 100644 apps/web/lib/imvu.ts create mode 100644 packages/db/drizzle/0018_recorded_grants.sql create mode 100644 packages/db/drizzle/meta/0018_snapshot.json diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 993f495..86eec9b 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -401,6 +401,7 @@ export function createApp({ exclude: r.grant.exclude, listed: r.grant.listed, consentKind: r.grant.consentKind as "verified" | "recorded", + consentProven: r.grant.proofCheckedAt !== null, // recorded, and the creator put the code in their tagline consentVersion: r.grant.consentVersion, status: r.grant.status as "pending" | "active" | "declined" | "suspended" | "withdrawn", statusReason: r.grant.statusReason, @@ -498,7 +499,7 @@ export function createApp({ url: `${(webURL ?? "").replace(/\/+$/, "")}/catalogs/${i.catalogId}?invite=${i.code}`, }); - type ConsoleSection = "overview" | "products" | "catalogs" | "cases" | "people" | "blocks" | "audit" | "settings"; + type ConsoleSection = "overview" | "products" | "catalogs" | "cases" | "people" | "imports" | "blocks" | "audit" | "settings"; /** Tokens as their owner sees them (never the hash), with their scopes' names. */ const tokenViews = async (rows: (typeof schema.apiToken.$inferSelect)[]) => { @@ -1026,10 +1027,21 @@ export function createApp({ canLink: links.length < me.linkCap, // Two-factor sign-in: on or off, and what needs it (sensitive permissions the person holds). twoFactor: { enabled: me.twoFactorEnabled, neededFor: await sensitiveHeld(me) }, + // Unclaimed creators for IMVU accounts they've linked: what an admin recorded for them, theirs to claim. + claims: (await imports.claimable(me.id)).map((c) => ({ imvuId: c.imvuId!, username: c.username ?? "", products: c.products, grants: c.grants })), }; }, { signedIn: true }, ) + .post( + "/account/claims/:imvu", + async ({ me, params }) => { + const r = await productCall(() => imports.claimCreator(me.id, params.imvu)); + await audited(me, "import.claim", String(params.imvu), r, { person: me.id }); + return r; + }, + { scripted: true, params: imvuIdParam }, + ) .post( "/account/links", async ({ me, body, set }) => { @@ -1984,6 +1996,79 @@ export function createApp({ }, ) + // Recorded grants (docs/imports.md): admins record consent for creators who won't make an account. + .get( + "/console/imports", + async ({ me }) => { + if (!(await perms.can(me, "import:grant-on-behalf", hubScope))) throw new Problem(403, "forbidden", "Not yours to see."); + const rows = await imports.recordedGrants(); + return { + grants: rows.map((r) => ({ + ...grantView(r), + evidence: r.grant.evidence, + recordedBy: r.recordedByName ?? "", + proofCode: r.grant.proofCode, + proofCheckedAt: r.grant.proofCheckedAt?.toISOString() ?? null, + claimed: r.claimed, + })), + creators: await imports.topRequested(), + catalogs: await imports.catalogs(), + consent, + }; + }, + { signedIn: true }, + ) + .post( + "/console/imports/grants", + async ({ me, body, set }) => { + await need(me, "import:grant-on-behalf", hubScope); + const who = body.imvu.trim(); + const found = await imvuCall(me, () => (/^\d{1,12}$/.test(who) ? imvu.byId(Number(who)) : imvu.byUsername(who))); + const g = await productCall(() => imports.recordGrant(me.id, found, body)); + await audited( + me, + "import.grant_record", + g.id, + { imvu: g.imvuId, imvuName: found.username, scope: g.scope, products: g.products.length, evidence: g.evidence }, + { catalog: g.catalogId, person: g.creatorId }, + ); + set.status = 201; + return { grant: grantView({ grant: g, imvuName: found.username }) }; + }, + { + scripted: true, + body: t.Object({ + catalog: t.String({ maxLength: 20 }), + imvu: t.String({ minLength: 1, maxLength: 64 }), + scope: t.String({ maxLength: 20 }), + products: t.Optional(t.Array(t.Integer({ minimum: 1 }), { maxItems: 1000 })), + exclude: t.Optional(t.Array(t.Integer({ minimum: 1 }), { maxItems: 1000 })), + listed: t.Optional(t.Boolean()), + evidence: t.String({ maxLength: 1000 }), + }), + }, + ) + .post( + "/console/imports/grants/:id/proof", + async ({ me, params }) => { + await need(me, "import:grant-on-behalf", hubScope); + return { code: await productCall(() => imports.proofCode(params.id, linkCode())) }; + }, + { scripted: true }, + ) + .post( + "/console/imports/grants/:id/proof/check", + async ({ me, params }) => { + await need(me, "import:grant-on-behalf", hubScope); + const g = await productCall(() => imports.grant(params.id)); + const found = await imvuCall(me, () => imvu.byId(g.imvuId)); + const checked = await productCall(() => imports.checkProof(g.id, found.tagline)); + await audited(me, "import.grant_proof", g.id, { imvu: g.imvuId }, { catalog: g.catalogId, person: g.creatorId }); + return { grant: grantView({ grant: checked, imvuName: found.username }) }; + }, + { scripted: true }, + ) + // Imports (docs/imports.md): grants, requests, and each catalog's importer. .get("/imports/catalogs", async () => ({ catalogs: await imports.catalogs(), consent })) .get("/imports/grants", async ({ me }) => ({ grants: (await imports.grantsOf(me.id)).map(grantView) }), { signedIn: true }) @@ -2012,7 +2097,11 @@ export function createApp({ "/imports/grants/:id", async ({ me, params, body }) => { const g = await productCall(() => imports.grant(params.id)); - if (g.creatorId !== me.id) throw new Problem(403, "forbidden", "Only its creator changes a grant."); + if (g.creatorId !== me.id) { + // A recorded grant's creator hasn't claimed it: admins change it for them. + if (!(await imports.unclaimed(g))) throw new Problem(403, "forbidden", "Only its creator changes a grant."); + await need(me, "import:grant-on-behalf", hubScope); + } const { grant, withdrawn } = await productCall(() => imports.updateGrant(g.id, body)); await audited( me, @@ -3122,6 +3211,7 @@ export function createApp({ if (mod || scope.catalogs.length || scope.products.length || (await cases.list(me, { limit: 1 })).length) sections.push("cases"); if (mod) sections.push("people"); + if (await perms.can(me, "import:grant-on-behalf", hubScope)) sections.push("imports"); if (await perms.can(me, "product:remove", hubScope)) sections.push("blocks"); if (sections.length > 1 || scope.rooms.length) sections.push("audit"); if (me.role === "admin") sections.push("settings"); diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts index 474c45d..3b05231 100644 --- a/apps/api/src/auth.ts +++ b/apps/api/src/auth.ts @@ -59,7 +59,8 @@ export function createAuth(db: Database, config: AuthConfig) { username({ minUsernameLength: 3, maxUsernameLength: 32, - usernameValidator: (name) => /^[A-Za-z0-9_]+$/.test(name), + // imvu_ is reserved for unclaimed creators (docs/imports.md). + usernameValidator: (name) => /^[A-Za-z0-9_]+$/.test(name) && !/^imvu_/i.test(name), }), admin({ defaultRole: "user", adminRoles: ["admin"] }), deviceAuthorization({ diff --git a/apps/api/src/imports.ts b/apps/api/src/imports.ts index 6a5f1b0..61066bd 100644 --- a/apps/api/src/imports.ts +++ b/apps/api/src/imports.ts @@ -3,11 +3,11 @@ // registers the revisions as an ordinary product owned by the creator. The routes are in app.ts. import { createHash, timingSafeEqual } from "node:crypto"; import { and, asc, desc, eq, inArray, lt, ne, sql, schema, type Database, type FileEntry } from "@t5de/db"; -import { ImvuUnavailable, type ImvuClient } from "./imvu"; +import { ImvuUnavailable, type ImvuClient, type ImvuUser } from "./imvu"; import type { Signer } from "./keys"; import { BlockedUpload, checkFiles, newProductID, ProductError, type Catalog } from "./products"; -const { catalog, catalogChange, fileBlock, hosting, imvuLink, imvuProductInfo, importGrant, importJob, importRequest, library, product, productRevision } = +const { catalog, catalogChange, fileBlock, hosting, imvuLink, imvuProductInfo, importGrant, importJob, importRequest, library, product, productRevision, user } = schema; export type Grant = typeof importGrant.$inferSelect; @@ -50,6 +50,12 @@ const productIDs = (v: unknown): number[] | undefined => { return [...out].sort((a, b) => a - b); }; +/** A grant's IMVU account's name: its link's, or its unclaimed creator's. */ +const imvuNameOf = sql`coalesce(${imvuLink.username}, (select u.display_username from "user" u where u.unclaimed_imvu_id = ${importGrant.imvuId}))`; + +/** An unclaimed creator's username: reserved (people can't sign up with the prefix). */ +export const unclaimedUsername = (imvuId: number) => `imvu_${imvuId}`; + /** Whether a grant covers an IMVU product (by its IMVU creator): active, the creator's, and in its scope. */ export function covers(g: Grant, imvuProduct: number, creatorId: number): boolean { if (g.status !== "active" || creatorId !== g.imvuId) return false; @@ -191,6 +197,141 @@ export class Imports { return g!; } + // ---- recorded grants and unclaimed creators (docs/imports.md "Unclaimed creators and claiming") ---- + + /** The unclaimed creator standing in for an IMVU account, made if there's none yet. */ + private async placeholderFor(imvu: ImvuUser): Promise { + const [known] = await this.db.select({ id: user.id }).from(user).where(eq(user.unclaimedImvuId, imvu.id)); + if (known) return known.id; + const id = crypto.randomUUID().replaceAll("-", ""); + await this.db.insert(user).values({ + id, + name: `${imvu.username}, on IMVU`, + // Never delivered (.invalid); there's no password, so nobody signs in as it. + email: `imvu-${imvu.id}@unclaimed.invalid`, + username: unclaimedUsername(imvu.id), + displayUsername: imvu.username, + unclaimedImvuId: imvu.id, + }); + return id; + } + + /** + * An admin records a creator's consent (they won't make an account): a grant for an unclaimed creator standing in + * for their IMVU account. Pending until the catalog's team accepts, like any grant. + */ + async recordGrant( + byId: string, + imvu: ImvuUser, + input: { catalog: string; scope: string; products?: unknown; exclude?: unknown; listed?: boolean; evidence: string }, + ): Promise { + const evidence = input.evidence.trim(); + if (!evidence) throw new ProductError(400, "invalid", "Say how they agreed (where and when)."); + const [link] = await this.db.select().from(imvuLink).where(eq(imvuLink.imvuId, imvu.id)); + if (link) + throw new ProductError(409, "linked", `${imvu.username} is on T5DE: they bring their products themselves, from their account.`); + const [c] = await this.db.select().from(catalog).where(eq(catalog.id, input.catalog)); + if (!c || c.status !== "approved" || c.importer === "off") throw new ProductError(404, "not_found", "That catalog doesn't take imports."); + const scope = this.checkScope(input.scope, input.products, input.exclude); + const [open] = await this.db + .select({ id: importGrant.id }) + .from(importGrant) + .where(and(eq(importGrant.catalogId, c.id), eq(importGrant.imvuId, imvu.id), inArray(importGrant.status, ["pending", "active", "suspended"]))); + if (open) throw new ProductError(409, "exists", "That IMVU account already has a grant with this catalog. Change that one instead."); + const creatorId = await this.placeholderFor(imvu); + const [g] = await this.db + .insert(importGrant) + .values({ + id: newProductID(), + catalogId: c.id, + creatorId, + imvuId: imvu.id, + ...scope, + listed: input.listed !== false, + consentVersion: consent.version, + consentKind: "recorded", + evidence: evidence.slice(0, 1000), + recordedBy: byId, + }) + .returning(); + return g!; + } + + /** Grants admins recorded, newest first: their catalog, IMVU name, who recorded them, and whether claimed. */ + async recordedGrants() { + const recorder = sql`(select u.username from "user" u where u.id = ${importGrant.recordedBy})`; + return this.db + .select({ + grant: importGrant, + catalogName: catalog.name, + imvuName: imvuNameOf, + recordedByName: recorder, + claimed: sql`not exists (select 1 from "user" u where u.id = ${importGrant.creatorId} and u.unclaimed_imvu_id is not null)`, + }) + .from(importGrant) + .innerJoin(catalog, eq(catalog.id, importGrant.catalogId)) + .leftJoin(imvuLink, eq(imvuLink.imvuId, importGrant.imvuId)) + .where(eq(importGrant.consentKind, "recorded")) + .orderBy(desc(importGrant.createdAt)); + } + + /** Whether a grant's creator is still an unclaimed placeholder. */ + async unclaimed(g: Grant): Promise { + const [u] = await this.db.select({ imvu: user.unclaimedImvuId }).from(user).where(eq(user.id, g.creatorId)); + return u?.imvu != null; + } + + /** The code for a recorded grant's proof (made once): the creator puts it in their IMVU tagline. */ + async proofCode(id: string, code: string): Promise { + const g = await this.grant(id); + if (g.consentKind !== "recorded") throw new ProductError(409, "not_recorded", "Only recorded grants need proof."); + if (g.proofCode) return g.proofCode; + await this.db.update(importGrant).set({ proofCode: code }).where(eq(importGrant.id, g.id)); + return code; + } + + /** Checks a recorded grant's proof against the IMVU account's tagline. */ + async checkProof(id: string, tagline: string): Promise { + const g = await this.grant(id); + if (!g.proofCode) throw new ProductError(409, "no_code", "Make a code first, and send it to the creator."); + if (!tagline.includes(g.proofCode)) + throw new ProductError(409, "not_found", `The code isn't in that IMVU account's tagline yet. It must say ${g.proofCode}.`); + const [updated] = await this.db.update(importGrant).set({ proofCheckedAt: new Date() }).where(eq(importGrant.id, g.id)).returning(); + return updated!; + } + + /** What a person could claim: unclaimed creators for IMVU accounts they've linked, with their products and grants. */ + async claimable(personId: string) { + return this.db + .select({ + imvuId: user.unclaimedImvuId, + username: user.displayUsername, + products: sql`(select count(*)::int from ${product} p where p.creator_id = ${user.id} and p.removed_at is null)`, + grants: sql`(select count(*)::int from ${importGrant} g where g.creator_id = ${user.id} and g.status in ('pending', 'active', 'suspended'))`, + }) + .from(user) + .innerJoin(imvuLink, eq(imvuLink.imvuId, user.unclaimedImvuId)) + .where(eq(imvuLink.userId, personId)); + } + + /** + * Someone who linked an IMVU account claims its unclaimed creator: its products and grants become theirs, and the + * placeholder is deleted. + */ + async claimCreator(personId: string, imvuId: number): Promise<{ products: number; grants: number }> { + const [link] = await this.db.select().from(imvuLink).where(eq(imvuLink.imvuId, imvuId)); + if (!link || link.userId !== personId) throw new ProductError(403, "not_linked", "Link that IMVU account first."); + const [placeholder] = await this.db.select().from(user).where(eq(user.unclaimedImvuId, imvuId)); + if (!placeholder) throw new ProductError(404, "not_found", "Nothing waits for that IMVU account."); + return this.db.transaction(async (tx) => { + const products = await tx.update(product).set({ creatorId: personId }).where(eq(product.creatorId, placeholder.id)).returning({ id: product.id }); + await tx.update(productRevision).set({ uploadedBy: personId }).where(eq(productRevision.uploadedBy, placeholder.id)); + const grants = await tx.update(importGrant).set({ creatorId: personId }).where(eq(importGrant.creatorId, placeholder.id)).returning({ id: importGrant.id }); + await tx.delete(user).where(eq(user.id, placeholder.id)); + return { products: products.length, grants: grants.length }; + }); + } + private checkScope(scope: string, products: unknown, exclude: unknown) { if (scope !== "shop" && scope !== "products") throw new ProductError(400, "invalid", "Choose the whole shop or listed products."); const p = productIDs(products); @@ -203,7 +344,7 @@ export class Imports { /** A person's grants (as the creator), newest first, with their catalogs' names. */ async grantsOf(personId: string) { return this.db - .select({ grant: importGrant, catalogName: catalog.name, imvuName: imvuLink.username }) + .select({ grant: importGrant, catalogName: catalog.name, imvuName: imvuNameOf }) .from(importGrant) .innerJoin(catalog, eq(catalog.id, importGrant.catalogId)) .leftJoin(imvuLink, eq(imvuLink.imvuId, importGrant.imvuId)) @@ -214,7 +355,7 @@ export class Imports { /** A catalog's grants, pending first. */ async grantsFor(catalogId: string) { return this.db - .select({ grant: importGrant, catalogName: catalog.name, imvuName: imvuLink.username }) + .select({ grant: importGrant, catalogName: catalog.name, imvuName: imvuNameOf }) .from(importGrant) .innerJoin(catalog, eq(catalog.id, importGrant.catalogId)) .leftJoin(imvuLink, eq(imvuLink.imvuId, importGrant.imvuId)) @@ -272,7 +413,14 @@ export class Imports { const gs = await this.db .update(importGrant) .set({ status: "suspended", statusReason: reason }) - .where(and(eq(importGrant.imvuId, imvuId), inArray(importGrant.status, ["pending", "active"]))) + .where( + and( + eq(importGrant.imvuId, imvuId), + inArray(importGrant.status, ["pending", "active"]), + // An unclaimed creator's grants stand on the consent an admin recorded, whoever links the account. + sql`not exists (select 1 from "user" u where u.id = ${importGrant.creatorId} and u.unclaimed_imvu_id is not null)`, + ), + ) .returning(); for (const g of gs) { await this.db.update(importJob).set({ status: "failed", reason }).where(and(eq(importJob.grantId, g.id), inArray(importJob.status, ["queued", "claimed"]))); @@ -407,6 +555,7 @@ export class Imports { return this.db .select({ imvuCreator: importRequest.imvuCreator, + name: sql`coalesce((select max(i.creator_name) from ${imvuProductInfo} i where i.creator_id = ${importRequest.imvuCreator}), '')`, people: sql`count(distinct ${importRequest.userId})::int`, products: sql`count(distinct ${importRequest.imvuProduct}) filter (where ${importRequest.imvuProduct} <> 0)::int`, }) diff --git a/apps/api/test/catalogs.test.ts b/apps/api/test/catalogs.test.ts index cca4738..76b0a53 100644 --- a/apps/api/test/catalogs.test.ts +++ b/apps/api/test/catalogs.test.ts @@ -302,7 +302,7 @@ test("the console is for everyone who controls something; its audit log shows on expect(ownerConsole.sections).toEqual(["overview", "catalogs", "cases", "audit"]); expect(ownerConsole.moderation).toBeNull(); expect((await call(maker, "GET", "/api/v1/console")).json.sections).toEqual(["overview", "products", "cases", "audit"]); - expect((await call(admin, "GET", "/api/v1/console")).json.sections).toEqual(["overview", "products", "catalogs", "cases", "people", "blocks", "audit", "settings"]); + expect((await call(admin, "GET", "/api/v1/console")).json.sections).toEqual(["overview", "products", "catalogs", "cases", "people", "imports", "blocks", "audit", "settings"]); // The owner sees their catalog's entries, not the other catalog's; the maker sees their product's. const ownerLog = (await call(owner, "GET", "/api/v1/console/audit")).json.entries; diff --git a/apps/api/test/imports.test.ts b/apps/api/test/imports.test.ts index 06694cf..d3c1b0f 100644 --- a/apps/api/test/imports.test.ts +++ b/apps/api/test/imports.test.ts @@ -314,3 +314,87 @@ test("the importer's key, IMVU accounts with sealed passwords, and settings", as // 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: "r@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); + 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: "squat@example.test", 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"])); +}); diff --git a/apps/web/app/account/actions.ts b/apps/web/app/account/actions.ts index 78aa0e9..62e76c6 100644 --- a/apps/web/app/account/actions.ts +++ b/apps/web/app/account/actions.ts @@ -102,3 +102,13 @@ export async function revokeToken(_: ActionState, form: FormData): Promise { + return attempt(async () => { + const r = unwrap(await api.account.claims({ imvu: field(form, "imvuId") }).post()); + done(); + revalidatePath("/imports"); + return `They're yours: ${r.products} product${r.products === 1 ? "" : "s"}. Manage them on the Imports page.`; + }); +} diff --git a/apps/web/app/account/page.tsx b/apps/web/app/account/page.tsx index d11afff..721b392 100644 --- a/apps/web/app/account/page.tsx +++ b/apps/web/app/account/page.tsx @@ -7,7 +7,7 @@ import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Input } from "@/components/ui/input"; import { api, getMe, isModerator, unwrap } from "@/lib/api"; -import { linkAccount, signOutComputers } from "./actions"; +import { claimCreator, linkAccount, signOutComputers } from "./actions"; import { AgeCard } from "./age-card"; import { ChallengeCard } from "./challenge-card"; import { LinkCard } from "./link-card"; @@ -64,6 +64,25 @@ export default async function Account({ searchParams }: { searchParams: Promise< + {account.claims.map((c) => ( + + + Your IMVU Products on T5DE + + Before you joined, you agreed with T5DE to bring {c.username}'s products here, and an admin recorded + it. They're waiting for you: {c.products} imported product{c.products === 1 ? "" : "s"} and{" "} + {c.grants} catalog{c.grants === 1 ? "" : "s"} hosting them. Claim them to manage them yourself, or to + withdraw them. + + + + + Claim them + + + + ))} + {challenges.map((c) => ( ))} diff --git a/apps/web/app/console/catalogs/[id]/imports/page.tsx b/apps/web/app/console/catalogs/[id]/imports/page.tsx index 748c0f0..f10a20e 100644 --- a/apps/web/app/console/catalogs/[id]/imports/page.tsx +++ b/apps/web/app/console/catalogs/[id]/imports/page.tsx @@ -428,7 +428,9 @@ function GrantRow({ {g.imvuName || `IMVU account ${g.imvuId}`} (IMVU {g.imvuId}) {g.status} - {g.consentKind === "recorded" && consent recorded by an admin} + {g.consentKind === "recorded" && ( + {g.consentProven ? "consent recorded by an admin, proven" : "consent recorded by an admin"} + )} diff --git a/apps/web/app/console/console-nav.tsx b/apps/web/app/console/console-nav.tsx index 85e0b48..09241d8 100644 --- a/apps/web/app/console/console-nav.tsx +++ b/apps/web/app/console/console-nav.tsx @@ -41,6 +41,7 @@ const tabs: { section: Section; href: string; label: string }[] = [ { section: "catalogs", href: "/console/catalogs", label: "Catalogs" }, { section: "cases", href: "/console/cases", label: "Cases" }, { section: "people", href: "/console/people", label: "People" }, + { section: "imports", href: "/console/imports", label: "Imports" }, { section: "blocks", href: "/console/blocks", label: "Blocks" }, { section: "audit", href: "/console/audit", label: "Audit" }, ]; diff --git a/apps/web/app/console/imports/actions.ts b/apps/web/app/console/imports/actions.ts new file mode 100644 index 0000000..a9134ea --- /dev/null +++ b/apps/web/app/console/imports/actions.ts @@ -0,0 +1,71 @@ +"use server"; +// Recorded grants from the console (docs/imports.md): admins record consent for IMVU creators who won't make an +// account, prove it with a tagline code, and change or withdraw them until the creator claims them. +import { revalidatePath } from "next/cache"; +import { api, ApiError, unwrap } from "@/lib/api"; +import { attempt, field, type ActionState } from "@/lib/actions"; +import { productIDs } from "@/lib/imvu"; + +const done = () => revalidatePath("/console/imports"); + +/** Records a creator's consent: a grant for an unclaimed creator standing in for their IMVU account. */ +export async function recordGrant(_: ActionState, form: FormData): Promise { + const scope = field(form, "scope") === "products" ? "products" : "shop"; + const list = productIDs(field(form, scope === "products" ? "products" : "exclude")); + if (!list) return { error: "Products are IMVU product IDs or shop links, separated by spaces, commas or lines." }; + return attempt(async () => { + const r = unwrap( + await api.console.imports.grants.post({ + catalog: field(form, "catalog"), + imvu: field(form, "imvu"), + scope, + ...(scope === "products" ? { products: list } : { exclude: list }), + listed: form.get("listed") === "on", + evidence: field(form, "evidence"), + }), + ); + done(); + return `Recorded for ${r.grant.imvuName}. The catalog's team accepts it before anything is imported.`; + }); +} + +/** Proof without an account: a code for the creator's tagline, then checking it. */ +export async function grantProof(_: ActionState, form: FormData): Promise { + const id = field(form, "id"); + return attempt(async () => { + if (field(form, "intent") === "check") { + unwrap(await api.console.imports.grants({ id }).proof.check.post()); + done(); + return "Proven: the code is in their tagline. They can take it out now."; + } + const { code } = unwrap(await api.console.imports.grants({ id }).proof.post()); + done(); + return `Send them this code to put in their IMVU tagline: ${code}`; + }); +} + +/** Changes what a recorded grant covers, or withdraws it. */ +export async function changeRecorded(_: ActionState, form: FormData): Promise { + const id = field(form, "id"); + return attempt(async () => { + if (field(form, "intent") === "withdraw") { + const reason = field(form, "reason") || "Withdrawn at the creator's request."; + const r = unwrap(await api.imports.grants({ id }).delete({ reason })); + done(); + return r.withdrawn.length ? `Withdrawn. ${r.withdrawn.length} imported products were taken away.` : "Withdrawn."; + } + const scope = field(form, "scope") === "products" ? "products" : "shop"; + const list = productIDs(field(form, "list")); + if (!list) throw new ApiError(400, "invalid", "Products are IMVU product IDs or shop links."); + const r = unwrap( + await api.imports.grants({ id }).patch({ + ...(scope === "products" ? { products: list } : { exclude: list }), + listed: form.get("listed") === "on", + }), + ); + done(); + return r.withdrawn.length + ? `Saved. ${r.withdrawn.length} imported products it no longer covers were taken away.` + : "Saved."; + }); +} diff --git a/apps/web/app/console/imports/page.tsx b/apps/web/app/console/imports/page.tsx new file mode 100644 index 0000000..c1261b5 --- /dev/null +++ b/apps/web/app/console/imports/page.tsx @@ -0,0 +1,291 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { ActionForm, SubmitButton } from "@/components/forms"; +import { PageHeader, Tag } from "@/components/status"; +import { DateTime } from "@/components/time"; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; +import { Field, FieldDescription, FieldLabel } from "@/components/ui/field"; +import { Input } from "@/components/ui/input"; +import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select"; +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; +import { Textarea } from "@/components/ui/textarea"; +import { api, unwrap } from "@/lib/api"; +import { ConsoleNav, requireConsole } from "../console-nav"; +import { changeRecorded, grantProof, recordGrant } from "./actions"; + +export const metadata: Metadata = { title: "Imports" }; + +type Recorded = Awaited>["grants"][number]; +const load = async () => unwrap(await api.console.imports.get()); + +const statusTone = { + pending: "strong", + active: "online", + declined: "neutral", + suspended: "danger", + withdrawn: "neutral", +} as const; +const imvuShop = (id: number) => `https://www.imvu.com/shop/web_search.php?manufacturers_id=${id}`; + +export default async function ConsoleImports() { + const { console: c } = await requireConsole("/console/imports"); + if (!c.sections.includes("imports")) notFound(); + const data = await load(); + const open = data.grants.filter((g) => g.status !== "withdrawn" && g.status !== "declined"); + const ended = data.grants.filter((g) => g.status === "withdrawn" || g.status === "declined"); + + return ( + <> + + Consent recorded for IMVU creators who won't make an account, and the creators people ask for most. + + +
+ + + Record a Creator's Consent + + For creators who agreed to have their IMVU products on T5DE but won't make an account. Their products + belong to a placeholder until they join and link that IMVU account, when they can claim them. The + catalog's team still accepts it. + + + + {data.catalogs.length === 0 ? ( +

No catalog takes imports yet.

+ ) : ( + +
+ + IMVU creator + + + + Catalog + + {data.catalogs.map((k) => ( + + {k.name} + + ))} + + +
+
+ What they agreed to + + +
+
+ + Leave out (whole shop) +