feat: IMVU imports on the hub: grants, requests and the importer's job queue (#13)
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

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]>
This commit was merged in pull request #13.
This commit is contained in:
dhkatz authored and dhkatz committed 2026-11-07 16:29:03 +00:00
1 parent eca1884918
commit 7ece681eef
24 files changed
+6565 -158

No files matched your search

+309 -4
View File
@@ -28,6 +28,7 @@ import { Realtime } from "./realtime";
import { isAdultRoom, Rooms } from "./rooms";
import { Signer } from "./keys";
import { Blocks, isSha256 } from "./blocks";
import { consent, Imports, type Grant } from "./imports";
import { availableTo, BlockedUpload, ProductError, Products, type EditRights, type ProductViewer } from "./products";
import {
chatId,
@@ -197,6 +198,7 @@ export function createApp({
const limiter = new Limiter();
const cases = new Cases(db, perms);
const blocks = new Blocks(db);
const imports = new Imports(db, signer, imvu);
const notifications = new Notifications(db, (userId, message) => realtime.notify(userId, message));
/** Tells a product's creator that someone else changed it. */
@@ -362,6 +364,49 @@ export function createApp({
}
};
const catalogName = async (id: string) => (await db.select({ name: catalog.name }).from(catalog).where(eq(catalog.id, id)))[0]?.name ?? "";
/** IMVU being unreachable, as a Problem. */
const imvuSafe = async <T>(f: () => Promise<T>): Promise<T> => {
try {
return await f();
} catch (e) {
if (e instanceof ImvuUnavailable) throw new Problem(502, "imvu_unavailable", "IMVU didn't answer. Try again in a moment.");
throw e;
}
};
const grantView = (r: { grant: Grant; catalogName?: string | null; imvuName?: string | null }) => ({
id: r.grant.id,
catalog: r.grant.catalogId,
catalogName: r.catalogName ?? "",
imvuId: r.grant.imvuId,
imvuName: r.imvuName ?? "",
scope: r.grant.scope as "shop" | "products",
products: r.grant.products,
exclude: r.grant.exclude,
listed: r.grant.listed,
consentKind: r.grant.consentKind as "verified" | "recorded",
consentVersion: r.grant.consentVersion,
status: r.grant.status as "pending" | "active" | "declined" | "suspended" | "withdrawn",
statusReason: r.grant.statusReason,
createdAt: r.grant.createdAt.toISOString(),
decidedAt: r.grant.decidedAt?.toISOString() ?? null,
});
const jobView = (j: typeof schema.importJob.$inferSelect) => ({
id: j.id,
grant: j.grantId,
imvuProduct: j.imvuProduct,
kind: j.kind as "import" | "recheck",
status: j.status as "queued" | "claimed" | "done" | "failed",
imvuRevision: j.imvuRevision,
reason: j.reason,
attempts: j.attempts,
nextAt: j.nextAt.toISOString(),
updatedAt: j.updatedAt.toISOString(),
});
/** `latest`: the latest revision's parent and its info (the image and categories are the parent's). */
const productView = (
p: typeof schema.product.$inferSelect,
@@ -387,6 +432,7 @@ export function createApp({
locked: p.locked,
deleted: p.deletedAt !== null,
removed: p.removedAt !== null,
imvuProduct: p.imvuProduct,
publishedAt: p.publishedAt?.toISOString() ?? null,
createdAt: p.createdAt.toISOString(),
updatedAt: p.updatedAt.toISOString(),
@@ -422,6 +468,7 @@ export function createApp({
maxRating: c.maxRating,
uploads: c.uploads,
mirrors: c.mirrors,
importer: c.importer as "off" | "on" | "paused",
createdAt: c.createdAt.toISOString(),
});
@@ -1058,6 +1105,8 @@ export function createApp({
if (result.moved) {
await rooms.forgetOwner(found.id);
realtime.unlinked(result.previousOwner!, found.id);
// The previous owner's import grants for it end until the new owner grants again.
await imports.suspendFor(found.id, "The IMVU account was linked to another T5DE account.");
}
await realtime.linked(me.id, found.id);
return { link: await linkView(result.link), moved: result.moved };
@@ -1115,6 +1164,7 @@ export function createApp({
await db.delete(imvuLink).where(eq(imvuLink.imvuId, l.imvuId));
await age.forgetAccount(l.imvuId);
await rooms.forgetOwner(l.imvuId);
await imports.suspendFor(l.imvuId, "The IMVU account was unlinked.");
realtime.unlinked(me.id, l.imvuId);
await audited(me, "link.remove", String(l.imvuId), { imvu: l.username });
set.status = 204;
@@ -1815,7 +1865,13 @@ export function createApp({
if (!c) throw new Problem(401, "forbidden", "Not an approved catalog.");
const r = await productCall(async () => {
try {
return await products.registerRevision(c, body);
if (body.importToken) {
const made = await imports.register(c, { ...body, importToken: body.importToken });
await audited(null, "import.revision", made.product, { catalog: c.id, revision: made.revision }, { catalog: c.id, product: made.product, person: made.creatorId });
return { product: made.product, revision: made.revision, draft: made.draft };
}
if (!body.uploadToken) throw new ProductError(400, "invalid", "An upload or import token is needed.");
return await products.registerRevision(c, { ...body, uploadToken: body.uploadToken, notes: body.notes ?? "" });
} catch (e) {
// Someone tried a blocked file again: moderators see who, and from which catalog.
if (e instanceof BlockedUpload)
@@ -1828,16 +1884,265 @@ export function createApp({
},
{
body: t.Object({
uploadToken: t.String({ maxLength: 4000 }),
uploadToken: t.Optional(t.String({ maxLength: 4000 })),
importToken: t.Optional(t.String({ maxLength: 4000 })),
files: t.Array(t.Object({ name: t.String(), sha256: t.String(), size: t.Number() }), { maxItems: 512 }),
rating: t.String(),
parent: t.Number(),
name: t.String({ maxLength: 200 }),
notes: t.String({ maxLength: 4000 }),
notes: t.Optional(t.String({ maxLength: 4000 })),
}),
},
)
// For importers (docs/products.md): `Authorization: Importer <catalog ID>:<key>`.
.post(
"/importer/jobs/claim",
async ({ request, body }) => {
const c = await imports.importerFor(request.headers.get("authorization"));
if (!c) throw new Problem(401, "forbidden", "Not an importer of an approved catalog with imports on.");
return { jobs: await imports.claim(c, body.limit ?? 5) };
},
{ body: t.Object({ limit: t.Optional(t.Integer({ minimum: 1, maximum: 20 })) }) },
)
.post(
"/importer/jobs/:id/token",
async ({ request, params, body }) => {
const c = await imports.importerFor(request.headers.get("authorization"));
if (!c) throw new Problem(401, "forbidden", "Not an importer of an approved catalog with imports on.");
return productCall(() => imvuSafe(() => imports.jobToken(c, params.id, body.imvuRevision)));
},
{ body: t.Object({ imvuRevision: t.Integer({ minimum: 1 }) }) },
)
.post(
"/importer/jobs/:id",
async ({ request, params, body }) => {
const c = await imports.importerFor(request.headers.get("authorization"));
if (!c) throw new Problem(401, "forbidden", "Not an importer of an approved catalog with imports on.");
const job = await productCall(() => imports.report(c, params.id, body));
if (job.status === "failed")
await audited(null, "import.failed", String(job.imvuProduct), { reason: job.reason, job: job.id }, { catalog: c.id });
return { job: jobView(job) };
},
{
body: t.Object({
status: t.Union([t.Literal("done"), t.Literal("unchanged"), t.Literal("failed")]),
imvuRevision: t.Optional(t.Integer({ minimum: 1 })),
reason: t.Optional(t.String({ maxLength: 2000 })),
}),
},
)
// 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 })
.post(
"/imports/grants",
async ({ me, body, set }) => {
const g = await productCall(() => imports.createGrant(me.id, body));
await audited(me, "import.grant", g.id, { imvu: g.imvuId, scope: g.scope, products: g.products.length }, { catalog: g.catalogId, person: me.id });
set.status = 201;
return { grant: grantView({ grant: g }) };
},
{
signedIn: true,
body: t.Object({
catalog: t.String({ maxLength: 20 }),
imvuId: t.Integer({ minimum: 1 }),
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()),
consentVersion: t.Integer(),
}),
},
)
.patch(
"/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.");
const { grant, withdrawn } = await productCall(() => imports.updateGrant(g.id, body));
await audited(
me,
"import.grant_change",
g.id,
{ scope: grant.scope, products: grant.products.length, exclude: grant.exclude.length, withdrawn },
{ catalog: g.catalogId, person: me.id },
);
return { grant: grantView({ grant }), withdrawn };
},
{
signedIn: true,
body: t.Object({
scope: t.Optional(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()),
}),
},
)
.post(
"/imports/grants/:id/:decision",
async ({ me, params, body }) => {
const g = await productCall(() => imports.grant(params.id));
await need(me, "import:accept", catalogScope(g.catalogId));
const decision = params.decision;
const reason = body?.reason?.trim() ?? "";
const done = await productCall(() => imports.decide(g.id, decision, me.id, reason));
await audited(
me,
`import.grant_${decision}`,
g.id,
{ imvu: g.imvuId, queued: done.queued, ...(reason ? { reason } : {}) },
{ catalog: g.catalogId, person: g.creatorId },
);
await notifications.add(
g.creatorId,
"import_grant_decided",
{ grant: g.id, catalog: g.catalogId, name: await catalogName(g.catalogId), decision, reason },
{ catalog: g.catalogId },
me.id,
);
return { grant: grantView({ grant: done.grant }), queued: done.queued };
},
{
signedIn: true,
params: t.Object({ id: t.String(), decision: t.Union([t.Literal("accept"), t.Literal("decline")]) }),
body: t.Optional(t.Object({ reason: t.Optional(t.String({ maxLength: 500 })) })),
},
)
.delete(
"/imports/grants/:id",
async ({ me, params, body }) => {
const g = await productCall(() => imports.grant(params.id));
const own = g.creatorId === me.id;
if (!own) await need(me, "import:withdraw", catalogScope(g.catalogId));
const reason = body?.reason?.trim() || (own ? "Its creator withdrew it." : "The catalog's team ended it.");
const done = await productCall(() => imports.withdraw(g.id, reason));
await audited(me, "import.grant_withdraw", g.id, { imvu: g.imvuId, reason, withdrawn: done.withdrawn }, { catalog: g.catalogId, person: g.creatorId });
if (!own)
await notifications.add(
g.creatorId,
"import_grant_ended",
{ grant: g.id, catalog: g.catalogId, name: await catalogName(g.catalogId), reason },
{ catalog: g.catalogId },
me.id,
);
return { grant: grantView({ grant: done.grant }), withdrawn: done.withdrawn };
},
{ signedIn: true, body: t.Optional(t.Object({ reason: t.Optional(t.String({ maxLength: 500 })) })) },
)
.post(
"/imports/requests",
async ({ me, body }) => {
if (body.imvuProduct === undefined && body.imvuCreator === undefined)
throw new Problem(400, "invalid", "Ask for an IMVU product or a creator's shop.");
// Each new product costs IMVU a lookup.
if (body.imvuProduct !== undefined && !limiter.allow(`import-request:${me.id}`, 60, 60 * 60 * 1000))
throw new Problem(429, "rate_limited", "Too many requests. Try again in a while.");
return productCall(() => imvuSafe(() => imports.request(me.id, body)));
},
{
signedIn: true,
body: t.Object({ imvuProduct: t.Optional(t.Integer({ minimum: 1 })), imvuCreator: t.Optional(t.Integer({ minimum: 1 })) }),
},
)
.get(
"/imports/requests",
async ({ me, query }) => {
if (query.imvuCreator === undefined) {
if (!isModerator(me)) throw new Problem(403, "forbidden", "Only moderators see every creator's requests.");
return { creators: await imports.topRequested(), requests: [] };
}
const [l] = await db.select({ userId: imvuLink.userId }).from(imvuLink).where(eq(imvuLink.imvuId, query.imvuCreator));
if (l?.userId !== me.id && !isModerator(me)) throw new Problem(403, "forbidden", "Link that IMVU account first.");
return { creators: [], requests: await imports.requestCounts(query.imvuCreator) };
},
{ signedIn: true, query: t.Object({ imvuCreator: t.Optional(t.Numeric({ minimum: 1, multipleOf: 1 })) }) },
)
// A catalog's importer: its state, grants and queue (the team; moderators), turning it on and off, pausing.
.get(
"/catalogs/:id/importer",
async ({ me, params, query }) => {
const scope = catalogScope(params.id);
if (!(await perms.can(me, "import:pause", scope))) await need(me, "import:accept", scope);
const [c] = await db.select().from(catalog).where(eq(catalog.id, params.id));
if (!c) throw new Problem(404, "not_found", "No such catalog.");
const grants = await imports.grantsFor(c.id);
const jobs = await imports.jobs(c.id, query.status);
const [counts] = await db
.select({
queued: sql<number>`(count(*) filter (where ${schema.importJob.status} = 'queued'))::int`,
claimed: sql<number>`(count(*) filter (where ${schema.importJob.status} = 'claimed'))::int`,
failed: sql<number>`(count(*) filter (where ${schema.importJob.status} = 'failed'))::int`,
done: sql<number>`(count(*) filter (where ${schema.importJob.status} = 'done'))::int`,
})
.from(schema.importJob)
.where(eq(schema.importJob.catalogId, c.id));
return {
importer: c.importer as "off" | "on" | "paused",
grants: grants.map(grantView),
jobs: jobs.map((j) => ({ ...jobView(j.job), name: j.name ?? "" })),
counts: counts ?? { queued: 0, claimed: 0, failed: 0, done: 0 },
permissions: {
run: await perms.can(me, "import:run", scope),
pause: await perms.can(me, "import:pause", scope),
accept: await perms.can(me, "import:accept", scope),
withdraw: await perms.can(me, "import:withdraw", scope),
},
};
},
{
signedIn: true,
params: catalogParam,
query: t.Object({ status: t.Optional(t.Union([t.Literal("queued"), t.Literal("claimed"), t.Literal("done"), t.Literal("failed")])) }),
},
)
.post(
"/catalogs/:id/importer",
async ({ me, params, body }) => {
const scope = catalogScope(params.id);
const [c] = await db.select().from(catalog).where(eq(catalog.id, params.id));
if (!c) throw new Problem(404, "not_found", "No such catalog.");
const from = c.importer as "on" | "off" | "paused";
let to = from;
if (body.enabled !== undefined) {
await need(me, "import:run", scope);
to = body.enabled ? (from === "off" ? "on" : from) : "off";
}
if (body.paused !== undefined) {
await need(me, "import:pause", scope);
if (to === "off") throw new Problem(409, "imports_off", "Imports are off.");
to = body.paused ? "paused" : "on";
}
const r = await productCall(() => imports.setImporter(c.id, to));
if (to !== from) await audited(me, "catalog.importer", c.id, { from, to });
return { catalog: catalogView(r.catalog), ...(r.key ? { key: r.key } : {}) };
},
{ scripted: true, params: catalogParam, body: t.Object({ enabled: t.Optional(t.Boolean()), paused: t.Optional(t.Boolean()) }) },
)
.post(
"/catalogs/:id/importer/key",
async ({ me, params }) => {
await need(me, "import:run", catalogScope(params.id));
const key = await productCall(() => imports.rotateImporterKey(params.id));
await audited(me, "catalog.importer_key", params.id);
return { key };
},
{ scripted: true, params: catalogParam },
)
.post(
"/catalogs/:id/importer/jobs/:job/retry",
async ({ me, params }) => {
await need(me, "import:run", catalogScope(params.id));
const job = await productCall(() => imports.retry(params.id, params.job));
await audited(me, "import.retry", String(job.imvuProduct), { job: job.id }, { catalog: params.id });
return { job: jobView(job) };
},
{ scripted: true, params: t.Object({ id: t.String({ pattern: "^[a-z2-7]{10}$" }), job: t.String({ maxLength: 20 }) }) },
)
// Products.
.post(
"/products/upload",
@@ -2955,7 +3260,7 @@ export function createApp({
.get("/health", () => ({ ok: true }))
.use(api);
return { app, realtime, age, rooms, products, signer, hosted, decorations };
return { app, realtime, age, rooms, products, signer, hosted, decorations, imports };
}
export type App = ReturnType<typeof createApp>["app"];
+697
View File
@@ -0,0 +1,697 @@
// Imports (docs/imports.md): creators grant a catalog leave to import their IMVU products; the catalog's team accepts;
// requests and grants queue jobs; the catalog's importer claims them, uploads the files to its catalog, and the hub
// 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 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 } =
schema;
export type Grant = typeof importGrant.$inferSelect;
export type Job = typeof importJob.$inferSelect;
export type ImvuInfo = typeof imvuProductInfo.$inferSelect;
/** The consent a creator agrees to; its version is stored with each grant. A new text means a new version. */
export const consent = {
version: 1,
text:
"I made these products on IMVU and I let this catalog copy them from IMVU and give them to T5DE users for free, " +
"to wear in IMVU Classic with T5DE. They stay mine: I can change what's included or withdraw at any time, and " +
"withdrawn products are taken away from everyone who has them. Products that derive from someone else's keep " +
"using that product from IMVU.",
};
/** Requests a person may make a day. */
export const requestsPerDay = 50;
/** Products a grant by products may list (and a shop grant may exclude). */
export const maxGrantProducts = 1000;
/** Claimed jobs not reported within this long go back to the queue. */
const claimTimeout = 30 * 60 * 1000;
/** Retries after a failure: 1 min, 10 min, 1 h, then daily; failed for good after 5 attempts. */
const backoff = [60_000, 600_000, 3_600_000, 86_400_000];
const maxAttempts = 5;
/** IMVU product info is looked up again after this long. */
const infoFresh = 24 * 60 * 60 * 1000;
const sha256 = (s: string) => createHash("sha256").update(s).digest("hex");
const randomKey = () => Buffer.from(crypto.getRandomValues(new Uint8Array(24))).toString("base64url");
const productIDs = (v: unknown): number[] | undefined => {
if (v === undefined) return [];
if (!Array.isArray(v) || v.length > maxGrantProducts) return undefined;
const out = new Set<number>();
for (const x of v) {
const n = Number(x);
if (!Number.isSafeInteger(n) || n <= 0) return undefined;
out.add(n);
}
return [...out].sort((a, b) => a - b);
};
/** 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;
return g.scope === "shop" ? !g.exclude.includes(imvuProduct) : g.products.includes(imvuProduct);
}
export class Imports {
constructor(
private readonly db: Database,
private readonly signer: Signer,
private readonly imvu?: ImvuClient,
) {}
// ---- IMVU product info ----
/** An IMVU product's info (from the cache when it's fresh). Undefined if IMVU doesn't show it publicly. Throws
* ImvuUnavailable if IMVU can't be reached and nothing is cached. */
async info(id: number, fresh = false): Promise<ImvuInfo | undefined> {
if (!Number.isSafeInteger(id) || id <= 0) return undefined;
const [known] = await this.db.select().from(imvuProductInfo).where(eq(imvuProductInfo.id, id));
if (known && !fresh && Date.now() - known.checkedAt.getTime() < infoFresh) return known.found ? known : undefined;
if (!this.imvu) {
if (known) return known.found ? known : undefined;
throw new ImvuUnavailable("no IMVU client");
}
let answer;
try {
answer = await this.imvu.lookup(id);
} catch (e) {
if (known && e instanceof ImvuUnavailable) return known.found ? known : undefined;
throw e;
}
// IMVU hides Access Pass products from anonymous callers (401, as for deleted and made-up IDs): keep what was
// last seen rather than treat a product that became AP as gone.
if (answer === "hidden" && known?.found) return known;
const p = typeof answer === "string" ? null : answer;
const row = {
id,
found: p !== null,
name: p?.name ?? "",
creatorId: p?.creatorId ?? 0,
creatorName: p?.creatorName ?? "",
rating: p?.adult ? "adult" : "general",
purchasable: p?.purchasable ?? false,
checkedAt: new Date(),
};
const [saved] = await this.db
.insert(imvuProductInfo)
.values(row)
.onConflictDoUpdate({ target: imvuProductInfo.id, set: row })
.returning();
return saved!.found ? saved : undefined;
}
// ---- catalogs and their importers ----
/** Approved catalogs with imports on (accepting grants). */
async catalogs() {
return this.db
.select({ id: catalog.id, name: catalog.name, url: catalog.url, contact: catalog.contact, maxRating: catalog.maxRating })
.from(catalog)
.where(and(eq(catalog.status, "approved"), ne(catalog.importer, "off")))
.orderBy(catalog.name);
}
/** Turns a catalog's importer on (a new key, returned once), off, or pauses and resumes it. */
async setImporter(catalogId: string, state: "on" | "off" | "paused"): Promise<{ catalog: Catalog; key?: string }> {
const [c] = await this.db.select().from(catalog).where(eq(catalog.id, catalogId));
if (!c) throw new ProductError(404, "not_found", "No such catalog.");
if (state !== "off" && c.status !== "approved")
throw new ProductError(409, "not_approved", "Imports need the catalog to be approved first.");
const key = c.importer === "off" && state !== "off" ? randomKey() : undefined;
const [updated] = await this.db
.update(catalog)
.set({ importer: state, ...(key ? { importerKeyHash: sha256(key) } : {}), ...(state === "off" ? { importerKeyHash: null } : {}) })
.where(eq(catalog.id, catalogId))
.returning();
return { catalog: updated!, key };
}
/** A new importer key; the old one stops working at once. */
async rotateImporterKey(catalogId: string): Promise<string> {
const key = randomKey();
const [c] = await this.db
.update(catalog)
.set({ importerKeyHash: sha256(key) })
.where(and(eq(catalog.id, catalogId), ne(catalog.importer, "off")))
.returning();
if (!c) throw new ProductError(409, "imports_off", "Turn imports on first.");
return key;
}
/** The catalog an `Authorization: Importer <catalog ID>:<key>` header names: approved, imports on (or paused). */
async importerFor(header: string | null): Promise<Catalog | undefined> {
const m = header?.match(/^Importer ([a-z2-7]{10}):(\S+)$/);
if (!m) return undefined;
const [c] = await this.db.select().from(catalog).where(eq(catalog.id, m[1]!));
if (!c || c.status !== "approved" || c.importer === "off" || !c.importerKeyHash) return undefined;
return timingSafeEqual(Buffer.from(sha256(m[2]!)), Buffer.from(c.importerKeyHash)) ? c : undefined;
}
// ---- grants ----
async grant(id: string): Promise<Grant> {
const [g] = await this.db.select().from(importGrant).where(eq(importGrant.id, id));
if (!g) throw new ProductError(404, "not_found", "No such grant.");
return g;
}
/** A creator grants a catalog leave to import their products from one of their linked IMVU accounts. */
async createGrant(
personId: string,
input: { catalog: string; imvuId: number; scope: string; products?: unknown; exclude?: unknown; listed?: boolean; consentVersion: number },
): Promise<Grant> {
const [link] = await this.db.select().from(imvuLink).where(eq(imvuLink.imvuId, input.imvuId));
if (!link || link.userId !== personId) throw new ProductError(403, "not_linked", "Link that IMVU account to your T5DE account first.");
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.");
if (input.consentVersion !== consent.version)
throw new ProductError(409, "consent_changed", "The consent text changed. Read it again and agree to the new one.");
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, input.imvuId), 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 [g] = await this.db
.insert(importGrant)
.values({
id: newProductID(),
catalogId: c.id,
creatorId: personId,
imvuId: input.imvuId,
...scope,
listed: input.listed !== false,
consentVersion: consent.version,
})
.returning();
return g!;
}
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);
const x = productIDs(exclude);
if (!p || !x) throw new ProductError(400, "invalid", `Products are IMVU product IDs, at most ${maxGrantProducts}.`);
if (scope === "products" && p.length === 0) throw new ProductError(400, "invalid", "List at least one product.");
return scope === "shop" ? { scope, products: [], exclude: x } : { scope, products: p, exclude: [] };
}
/** 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 })
.from(importGrant)
.innerJoin(catalog, eq(catalog.id, importGrant.catalogId))
.leftJoin(imvuLink, eq(imvuLink.imvuId, importGrant.imvuId))
.where(eq(importGrant.creatorId, personId))
.orderBy(desc(importGrant.createdAt));
}
/** A catalog's grants, pending first. */
async grantsFor(catalogId: string) {
return this.db
.select({ grant: importGrant, catalogName: catalog.name, imvuName: imvuLink.username })
.from(importGrant)
.innerJoin(catalog, eq(catalog.id, importGrant.catalogId))
.leftJoin(imvuLink, eq(imvuLink.imvuId, importGrant.imvuId))
.where(eq(importGrant.catalogId, catalogId))
.orderBy(sql`${importGrant.status} <> 'pending'`, desc(importGrant.createdAt));
}
/** The creator changes a grant's scope or listing. Products it no longer covers are withdrawn; newly covered ones
* people asked for are queued. */
async updateGrant(id: string, patch: { scope?: string; products?: unknown; exclude?: unknown; listed?: boolean }) {
const g = await this.grant(id);
if (g.status === "withdrawn" || g.status === "declined") throw new ProductError(409, "ended", "This grant has ended.");
const scope = this.checkScope(patch.scope ?? g.scope, patch.products ?? g.products, patch.exclude ?? g.exclude);
const [updated] = await this.db
.update(importGrant)
.set({ ...scope, ...(patch.listed !== undefined ? { listed: patch.listed } : {}) })
.where(eq(importGrant.id, id))
.returning();
const withdrawn = await this.withdrawUncovered(updated!, "Its creator took it out of the import.");
if (updated!.status === "active") await this.queueCovered(updated!);
return { grant: updated!, withdrawn };
}
/** The catalog's team accepts or declines a pending grant. Accepting queues what it covers that people asked for
* (and the products a grant lists). */
async decide(id: string, decision: "accept" | "decline", byId: string, reason = ""): Promise<{ grant: Grant; queued: number }> {
const g = await this.grant(id);
if (g.status !== "pending") throw new ProductError(409, "decided", "This grant isn't waiting for a decision.");
const [updated] = await this.db
.update(importGrant)
.set({ status: decision === "accept" ? "active" : "declined", statusReason: reason, decidedAt: new Date(), decidedBy: byId })
.where(eq(importGrant.id, id))
.returning();
const queued = decision === "accept" ? await this.queueCovered(updated!) : 0;
return { grant: updated!, queued };
}
/** Ends a grant (its creator, the catalog's team or a moderator): its products are withdrawn (from this catalog
* only, if another active grant still covers them). */
async withdraw(id: string, reason: string): Promise<{ grant: Grant; withdrawn: string[] }> {
const g = await this.grant(id);
if (g.status === "withdrawn" || g.status === "declined") throw new ProductError(409, "ended", "This grant has ended already.");
const [updated] = await this.db
.update(importGrant)
.set({ status: "withdrawn", statusReason: reason })
.where(eq(importGrant.id, id))
.returning();
await this.db.update(importJob).set({ status: "failed", reason: "The grant was withdrawn." }).where(and(eq(importJob.grantId, id), inArray(importJob.status, ["queued", "claimed"])));
return { grant: updated!, withdrawn: await this.withdrawUncovered(updated!, reason) };
}
/** Suspends the active and pending grants of an IMVU account (unlinked, or linked to someone else): until its
* owner grants again, nothing is imported, and the products are withdrawn. */
async suspendFor(imvuId: number, reason: string): Promise<number> {
const gs = await this.db
.update(importGrant)
.set({ status: "suspended", statusReason: reason })
.where(and(eq(importGrant.imvuId, imvuId), inArray(importGrant.status, ["pending", "active"])))
.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"])));
await this.withdrawUncovered(g, reason);
}
return gs.length;
}
/** The imported products a catalog hosts for a grant's IMVU account that no active grant covers any more (in that
* catalog: delisted; anywhere: withdrawn as moderation removes, its files deleted). Returns the products withdrawn
* everywhere. */
private async withdrawUncovered(g: Grant, reason: string): Promise<string[]> {
const hosted = await this.db
.selectDistinct({ id: product.id, imvuProduct: product.imvuProduct })
.from(product)
.innerJoin(hosting, and(eq(hosting.productId, product.id), eq(hosting.catalogId, g.catalogId)))
// The grant's IMVU account's products (a creator may have several accounts).
.innerJoin(imvuProductInfo, and(eq(imvuProductInfo.id, product.imvuProduct), eq(imvuProductInfo.creatorId, g.imvuId)))
.where(and(eq(product.creatorId, g.creatorId), sql`${product.removedAt} is null`));
if (hosted.length === 0) return [];
const active = await this.db.select().from(importGrant).where(and(eq(importGrant.imvuId, g.imvuId), eq(importGrant.status, "active")));
const gone: string[] = [];
for (const p of hosted) {
const imvuProduct = p.imvuProduct!;
if (active.some((a) => a.catalogId === g.catalogId && covers(a, imvuProduct, g.imvuId))) continue;
const elsewhere = active.some((a) => covers(a, imvuProduct, g.imvuId));
await this.unhost(p.id, elsewhere ? g.catalogId : undefined);
if (!elsewhere) {
await this.db
.update(product)
.set({ removedAt: new Date(), removedReason: `Withdrawn: ${reason}` })
.where(eq(product.id, p.id));
gone.push(p.id);
}
}
return gone;
}
/** Stops hosting a product (in one catalog, or all): its catalogs are told to delete the files. */
private async unhost(productId: string, catalogId?: string) {
await this.db.transaction(async (tx) => {
const where = catalogId ? and(eq(hosting.productId, productId), eq(hosting.catalogId, catalogId)) : eq(hosting.productId, productId);
const rows = await tx
.select({ catalogId: hosting.catalogId, number: hosting.number, files: productRevision.files })
.from(hosting)
.innerJoin(productRevision, and(eq(productRevision.productId, hosting.productId), eq(productRevision.number, hosting.number)))
.where(where);
for (const h of rows)
await tx.insert(catalogChange).values({ catalogId: h.catalogId, data: { type: "delete", product: productId, revision: h.number, files: h.files } });
await tx.delete(hosting).where(where);
});
}
/** Queues imports for what an active grant covers and isn't imported in its catalog yet: a grant's listed products,
* and the creator's products people asked for. */
private async queueCovered(g: Grant): Promise<number> {
const asked = await this.db
.selectDistinct({ id: importRequest.imvuProduct })
.from(importRequest)
.where(and(eq(importRequest.imvuCreator, g.imvuId), ne(importRequest.imvuProduct, 0)));
const wanted = new Set<number>(g.scope === "products" ? g.products : asked.map((a) => a.id).filter((id) => !g.exclude.includes(id)));
if (g.scope === "products") for (const a of asked) if (g.products.includes(a.id)) wanted.add(a.id);
if (wanted.size === 0) return 0;
const done = await this.db
.select({ imvuProduct: product.imvuProduct })
.from(product)
.innerJoin(hosting, and(eq(hosting.productId, product.id), eq(hosting.catalogId, g.catalogId)))
.where(inArray(product.imvuProduct, [...wanted]));
for (const d of done) wanted.delete(d.imvuProduct!);
let n = 0;
for (const id of wanted) if (await this.queue(g, id, "import")) n++;
return n;
}
// ---- requests ----
/**
* Someone asks for an IMVU product (or a creator's whole shop). Covered by an active grant: queued, or added to
* their library if it's imported already. Otherwise: a suggestion to a creator who grants by products, or counted.
*/
async request(
personId: string,
target: { imvuProduct?: number; imvuCreator?: number },
): Promise<{ status: "added" | "queued" | "suggested" | "counted"; product?: string }> {
const [today] = await this.db
.select({ n: sql<number>`count(*)::int` })
.from(importRequest)
.where(and(eq(importRequest.userId, personId), sql`${importRequest.createdAt} > now() - interval '1 day'`));
if ((today?.n ?? 0) >= requestsPerDay) throw new ProductError(429, "rate_limited", `You can ask for ${requestsPerDay} a day. Try again tomorrow.`);
if (target.imvuCreator !== undefined) {
if (!Number.isSafeInteger(target.imvuCreator) || target.imvuCreator <= 0) throw new ProductError(400, "invalid", "That isn't an IMVU account ID.");
await this.db.insert(importRequest).values({ userId: personId, imvuCreator: target.imvuCreator, imvuProduct: 0 }).onConflictDoNothing();
return { status: "counted" };
}
const id = target.imvuProduct ?? 0;
const info = await this.info(id);
if (!info) throw new ProductError(404, "not_found", "IMVU doesn't show that product publicly.");
if (!info.creatorId) throw new ProductError(502, "imvu_unclear", "IMVU didn't say who made that product. Try again later.");
await this.db.insert(importRequest).values({ userId: personId, imvuCreator: info.creatorId, imvuProduct: id }).onConflictDoNothing();
const grants = await this.db.select().from(importGrant).where(eq(importGrant.imvuId, info.creatorId));
const covering = grants.filter((g) => covers(g, id, info.creatorId));
if (covering.length) {
const [imported] = await this.db.select().from(product).where(eq(product.imvuProduct, id));
if (imported && !imported.removedAt && imported.latest > 0) {
await this.fulfil(id, imported.id);
return { status: "added", product: imported.id };
}
for (const g of covering) await this.queue(g, id, "import");
return { status: "queued" };
}
if (grants.some((g) => g.status === "active" && g.scope === "products")) return { status: "suggested" };
return { status: "counted" };
}
/** How many people asked for an IMVU creator's products: per product (0: the whole shop), most asked first. */
async requestCounts(imvuCreator: number) {
const rows = await this.db
.select({ imvuProduct: importRequest.imvuProduct, n: sql<number>`count(*)::int`, name: imvuProductInfo.name })
.from(importRequest)
.leftJoin(imvuProductInfo, eq(imvuProductInfo.id, importRequest.imvuProduct))
.where(eq(importRequest.imvuCreator, imvuCreator))
.groupBy(importRequest.imvuProduct, imvuProductInfo.name)
.orderBy(desc(sql`count(*)`), asc(importRequest.imvuProduct))
.limit(200);
return rows.map((r) => ({ imvuProduct: r.imvuProduct, name: r.name ?? "", requests: r.n }));
}
/** IMVU creators people asked for most (for admins: whom it's worth asking). */
async topRequested(limit = 50) {
return this.db
.select({
imvuCreator: importRequest.imvuCreator,
people: sql<number>`count(distinct ${importRequest.userId})::int`,
products: sql<number>`count(distinct ${importRequest.imvuProduct}) filter (where ${importRequest.imvuProduct} <> 0)::int`,
})
.from(importRequest)
.groupBy(importRequest.imvuCreator)
.orderBy(desc(sql`count(distinct ${importRequest.userId})`))
.limit(limit);
}
/** Puts an imported product in the libraries of those who asked for it. */
private async fulfil(imvuProduct: number, productId: string) {
const waiting = await this.db
.update(importRequest)
.set({ fulfilledAt: new Date() })
.where(and(eq(importRequest.imvuProduct, imvuProduct), sql`${importRequest.fulfilledAt} is null`))
.returning({ userId: importRequest.userId });
if (waiting.length)
await this.db
.insert(library)
.values(waiting.map((w) => ({ userId: w.userId, productId })))
.onConflictDoNothing();
}
// ---- jobs ----
/** Queues a job (unless one is open for that product in that catalog). Returns whether it was queued. */
async queue(g: Grant, imvuProduct: number, kind: "import" | "recheck"): Promise<boolean> {
const [j] = await this.db
.insert(importJob)
.values({ id: newProductID(), catalogId: g.catalogId, grantId: g.id, imvuProduct, kind })
.onConflictDoNothing()
.returning();
return j !== undefined;
}
/** An importer claims queued jobs (none while its catalog's importer is paused). Claims older than the timeout go
* back to the queue first. */
async claim(c: Catalog, limit: number) {
if (c.importer !== "on") return [];
await this.db
.update(importJob)
.set({ status: "queued", claimedAt: null })
.where(and(eq(importJob.catalogId, c.id), eq(importJob.status, "claimed"), lt(importJob.claimedAt, new Date(Date.now() - claimTimeout))));
const n = Math.min(Math.max(Math.trunc(limit) || 1, 1), 20);
const jobs = await this.db.transaction(async (tx) => {
const due = await tx
.select({ id: importJob.id })
.from(importJob)
.where(and(eq(importJob.catalogId, c.id), eq(importJob.status, "queued"), sql`${importJob.nextAt} <= now()`))
.orderBy(asc(importJob.nextAt))
.limit(n)
.for("update", { skipLocked: true });
if (due.length === 0) return [];
return tx
.update(importJob)
.set({ status: "claimed", claimedAt: new Date() })
.where(inArray(importJob.id, due.map((d) => d.id)))
.returning();
});
const last = jobs.length
? await this.db
.select({ imvuProduct: product.imvuProduct, imvuRevision: sql<number | null>`max(${productRevision.imvuRevision})` })
.from(product)
.innerJoin(productRevision, eq(productRevision.productId, product.id))
.where(inArray(product.imvuProduct, jobs.map((j) => j.imvuProduct)))
.groupBy(product.imvuProduct)
: [];
return jobs.map((j) => ({
id: j.id,
kind: j.kind,
imvuProduct: j.imvuProduct,
lastRevision: last.find((l) => l.imvuProduct === j.imvuProduct)?.imvuRevision ?? 0,
}));
}
/** A claimed job of this catalog's, whose grant still covers its product. */
private async liveJob(c: Catalog, jobId: string): Promise<{ job: Job; grant: Grant; info: ImvuInfo }> {
const [job] = await this.db.select().from(importJob).where(and(eq(importJob.id, jobId), eq(importJob.catalogId, c.id)));
if (!job) throw new ProductError(404, "not_found", "No such job.");
if (job.status !== "claimed") throw new ProductError(409, "not_claimed", "That job isn't claimed.");
const g = await this.grant(job.grantId);
const info = await this.info(job.imvuProduct);
if (!info || !covers(g, job.imvuProduct, info.creatorId)) throw new ProductError(409, "not_covered", "The grant no longer covers this product.");
return { job, grant: g, info };
}
/** A `t5de-import` token for a claimed job's revision, and where to upload it. */
async jobToken(c: Catalog, jobId: string, imvuRevision: number) {
if (!Number.isSafeInteger(imvuRevision) || imvuRevision <= 0) throw new ProductError(400, "invalid", "imvuRevision must be a revision number.");
const { job } = await this.liveJob(c, jobId);
const token = await this.signer.sign(
"t5de-import",
{ sub: job.id, catalog: c.id, imvuProduct: job.imvuProduct, imvuRevision },
30 * 60,
);
return { token, url: `${c.url}/api/v1/uploads` };
}
/** The importer reports a job's outcome. Failures retry with backoff, then fail for good. */
async report(c: Catalog, jobId: string, body: { status: string; imvuRevision?: number; reason?: string }): Promise<Job> {
const [job] = await this.db.select().from(importJob).where(and(eq(importJob.id, jobId), eq(importJob.catalogId, c.id)));
if (!job) throw new ProductError(404, "not_found", "No such job.");
if (job.status !== "claimed") throw new ProductError(409, "not_claimed", "That job isn't claimed.");
const reason = (body.reason ?? "").trim().slice(0, 500);
let set: Partial<Job>;
if (body.status === "done" || body.status === "unchanged") {
set = { status: "done", imvuRevision: body.imvuRevision ?? job.imvuRevision, reason: body.status === "unchanged" ? "unchanged" : "", claimedAt: null };
} else if (body.status === "failed") {
const attempts = job.attempts + 1;
set =
attempts >= maxAttempts
? { status: "failed", attempts, reason: reason || "failed", claimedAt: null }
: { status: "queued", attempts, reason: reason || "failed", claimedAt: null, nextAt: new Date(Date.now() + backoff[attempts - 1]!) };
} else throw new ProductError(400, "invalid", "status is done, unchanged or failed.");
const [updated] = await this.db.update(importJob).set(set).where(eq(importJob.id, job.id)).returning();
return updated!;
}
/** A catalog's jobs, newest first (optionally by status). */
async jobs(catalogId: string, status?: string, limit = 100) {
return this.db
.select({ job: importJob, name: imvuProductInfo.name })
.from(importJob)
.leftJoin(imvuProductInfo, eq(imvuProductInfo.id, importJob.imvuProduct))
.where(and(eq(importJob.catalogId, catalogId), status ? eq(importJob.status, status) : undefined))
.orderBy(desc(importJob.updatedAt))
.limit(limit);
}
/** The catalog's team retries a failed job (or re-imports a product): queued now, attempts reset. */
async retry(catalogId: string, jobId: string): Promise<Job> {
const [job] = await this.db
.update(importJob)
.set({ status: "queued", attempts: 0, reason: "", nextAt: new Date(), claimedAt: null })
.where(and(eq(importJob.id, jobId), eq(importJob.catalogId, catalogId), inArray(importJob.status, ["failed", "done"])))
.returning();
if (!job) throw new ProductError(404, "not_found", "No such finished job.");
const g = await this.grant(job.grantId);
if (g.status !== "active") throw new ProductError(409, "not_covered", "Its grant isn't active.");
return job;
}
// ---- registering imported revisions (from the catalog, after the importer's upload) ----
/**
* A catalog registers an imported revision (`importToken` instead of `uploadToken`): the job must be claimed and
* its grant still cover the product. A new product is published at once, owned by the grant's creator; a revision
* another catalog imported already is hosted here too (same files only). The job is done, and those who asked get
* the product.
*/
async register(c: Catalog, body: { importToken: string; files: unknown; rating: string; parent: number; name: string; notes?: string }) {
const claims = await this.signer.verify(body.importToken, "t5de-import");
if (!claims || claims.catalog !== c.id || typeof claims.sub !== "string")
throw new ProductError(401, "bad_token", "The import token isn't valid for this catalog.");
const imvuRevision = Number(claims.imvuRevision);
const { job, grant: g, info } = await this.liveJob(c, claims.sub);
if (Number(claims.imvuProduct) !== job.imvuProduct) throw new ProductError(401, "bad_token", "The import token isn't for this job.");
const files = checkFiles(body.files);
if (!files) throw new ProductError(400, "invalid", "The file list isn't valid.");
if (body.rating !== "general" && body.rating !== "adult") throw new ProductError(400, "invalid", "The rating must be general or adult.");
// The higher of IMVU's rating and the files'.
const rating = body.rating === "adult" || info.rating === "adult" ? "adult" : "general";
if (rating === "adult" && c.maxRating === "general")
throw new ProductError(400, "rating_ceiling", "This catalog hosts general-audience products only.");
const parent = Number.isSafeInteger(body.parent) && body.parent > 0 ? body.parent : 0;
const blocked = await this.db
.select({ sha256: fileBlock.sha256 })
.from(fileBlock)
.where(inArray(fileBlock.sha256, [...new Set(files.map((f) => f.sha256))]));
if (blocked.length) {
const hit = new Set(blocked.map((b) => b.sha256));
throw new BlockedUpload(g.creatorId, c.id, files.filter((f) => hit.has(f.sha256)));
}
const made = await this.db.transaction(async (tx) => {
let [p] = await tx.select().from(product).where(eq(product.imvuProduct, job.imvuProduct)).for("update");
if (p?.removedAt) throw new ProductError(410, "removed", "This product was removed or withdrawn on T5DE.");
if (!p) {
const name = (info.name || body.name || "Untitled").trim().slice(0, 64);
const description =
`<p>Imported from IMVU with its creator's permission. ` +
`<a href="https://www.imvu.com/shop/product.php?products_id=${job.imvuProduct}">Its IMVU page</a>.</p>`;
[p] = await tx
.insert(product)
.values({
id: newProductID(),
creatorId: g.creatorId,
name,
description,
rating,
status: "published",
publishedAt: new Date(),
listed: g.listed,
imvuProduct: job.imvuProduct,
})
.returning();
}
const [same] = await tx
.select()
.from(productRevision)
.where(and(eq(productRevision.productId, p!.id), eq(productRevision.imvuRevision, imvuRevision)));
if (same) {
if (!sameFiles(same.files, files)) throw new ProductError(409, "different_files", "That IMVU revision was imported with other files.");
await tx.insert(hosting).values({ catalogId: c.id, productId: p!.id, number: same.number }).onConflictDoNothing();
return { product: p!.id, revision: same.number, draft: false };
}
const number = p!.latest + 1;
const token = await this.signer.sign("t5de-revision", { product: p!.id, revision: number, rating, files, parent });
await tx.insert(productRevision).values({
productId: p!.id,
number,
files,
rating,
parent,
notes: `Imported from IMVU revision ${imvuRevision}.`,
token,
uploadedBy: g.creatorId,
imvuRevision,
});
await tx
.update(product)
.set({ latest: number, rating: p!.rating === "adult" || rating === "adult" ? "adult" : "general" })
.where(eq(product.id, p!.id));
await tx.insert(hosting).values({ catalogId: c.id, productId: p!.id, number });
return { product: p!.id, revision: number, draft: false };
});
await this.db.update(importJob).set({ status: "done", imvuRevision, reason: "", claimedAt: null }).where(eq(importJob.id, job.id));
await this.fulfil(job.imvuProduct, made.product);
return { ...made, creatorId: g.creatorId };
}
// ---- upkeep ----
/**
* Daily: re-checks imported products with IMVU (gone, or another creator's: withdrawn; rated AP: adult) and queues
* a recheck job (new revisions) for each active grant's imported products not checked in a day.
*/
async recheck(limit = 200): Promise<{ queued: number; withdrawn: string[] }> {
const rows = await this.db
.select({ grant: importGrant, productId: product.id, imvuProduct: product.imvuProduct, rating: product.rating })
.from(importGrant)
.innerJoin(hosting, eq(hosting.catalogId, importGrant.catalogId))
.innerJoin(product, and(eq(product.id, hosting.productId), eq(product.creatorId, importGrant.creatorId)))
// As last seen: the grant's IMVU account's products.
.innerJoin(imvuProductInfo, and(eq(imvuProductInfo.id, product.imvuProduct), eq(imvuProductInfo.creatorId, importGrant.imvuId)))
.where(
and(
eq(importGrant.status, "active"),
sql`${product.imvuProduct} is not null`,
sql`${product.removedAt} is null`,
sql`not exists (select 1 from ${importJob} j where j.catalog_id = ${importGrant.catalogId}
and j.imvu_product = ${product.imvuProduct} and j.updated_at > now() - interval '1 day')`,
),
)
.limit(limit);
let queued = 0;
const withdrawn: string[] = [];
const seen = new Set<string>();
for (const r of rows) {
const key = `${r.grant.catalogId}:${r.imvuProduct}`;
if (seen.has(key)) continue;
seen.add(key);
let info: ImvuInfo | undefined;
try {
info = await this.info(r.imvuProduct!, true);
} catch {
continue; // IMVU unavailable: next time
}
if (!info || info.creatorId !== r.grant.imvuId) {
await this.unhost(r.productId);
await this.db
.update(product)
.set({ removedAt: new Date(), removedReason: info ? "Withdrawn: another creator's on IMVU now." : "Withdrawn: gone from IMVU." })
.where(eq(product.id, r.productId));
withdrawn.push(r.productId);
continue;
}
if (info.rating === "adult" && r.rating !== "adult") await this.db.update(product).set({ rating: "adult" }).where(eq(product.id, r.productId));
if (covers(r.grant, r.imvuProduct!, info.creatorId) && (await this.queue(r.grant, r.imvuProduct!, "recheck"))) queued++;
}
return { queued, withdrawn };
}
}
// Field by field: stored lists come back from JSONB with their keys in another order.
const sameFiles = (a: FileEntry[], b: FileEntry[]) =>
a.length === b.length && a.every((f, i) => f.name === b[i]!.name && f.sha256 === b[i]!.sha256 && f.size === b[i]!.size);
+34 -7
View File
@@ -26,15 +26,20 @@ export type ImvuRoom = {
expired: boolean;
};
/** An IMVU product's public info, as T5 products derived from it show it. */
/** An IMVU product's public info: as T5 products derived from it show it, and as imports need it. */
export type ImvuProduct = {
image: string | null; // https, on *.imvu.com
categories: { id: number; name: string }[]; // outermost first, e.g. Clothing / Clothing for Female / Tops
gender: string; // "female", "male", or "" (either)
name: string;
creatorId: number; // the creator's IMVU account (0 if IMVU didn't say)
creatorName: string;
adult: boolean; // rated AP
purchasable: boolean; // false once retired
};
export class NoSuchImvuUser extends Error {
constructor() {
constructor(readonly status = 404) {
super("no such IMVU account");
}
}
@@ -78,13 +83,24 @@ export class ImvuClient {
* Access Pass ones). Throws ImvuUnavailable if IMVU can't be reached.
*/
async product(id: number): Promise<ImvuProduct | null> {
if (!Number.isSafeInteger(id) || id <= 0) return null;
const p = await this.lookup(id);
return typeof p === "string" ? null : p;
}
/**
* Like product(), but tells "missing" (404) from "hidden": IMVU answers 401 alike for Access Pass products,
* deleted ones and IDs that never existed, so a hidden product may still exist.
*/
async lookup(id: number): Promise<ImvuProduct | "missing" | "hidden"> {
if (!Number.isSafeInteger(id) || id <= 0) return "missing";
let answer: unknown;
try {
return parseProduct(await this.get(`/product/product-${id}`, [401, 403]), id);
answer = await this.get(`/product/product-${id}`, [401, 403]);
} catch (e) {
if (e instanceof NoSuchImvuUser) return null;
if (e instanceof NoSuchImvuUser) return e.status === 404 ? "missing" : "hidden";
throw e;
}
return parseProduct(answer, id) ?? "missing";
}
private async wait() {
@@ -106,7 +122,7 @@ export class ImvuClient {
} catch (e) {
throw new ImvuUnavailable(String(e));
}
if (response.status === 404 || missing.includes(response.status)) throw new NoSuchImvuUser();
if (response.status === 404 || missing.includes(response.status)) throw new NoSuchImvuUser(response.status);
if (!response.ok) throw new ImvuUnavailable(`IMVU answered ${response.status}`);
return response.json();
}
@@ -165,7 +181,18 @@ export function parseProduct(answer: unknown, id: number): ImvuProduct | null {
return [{ id: n, name: name.trim().slice(0, 100) }];
});
const gender = d.gender === "female" || d.gender === "male" ? d.gender : "";
return { image: imvuImage(d.product_image), categories, gender };
const creatorId = Number(d.creator_cid);
const text = (v: unknown, max: number) => (typeof v === "string" ? v.trim().slice(0, max) : "");
return {
image: imvuImage(d.product_image),
categories,
gender,
name: text(d.product_name, 200),
creatorId: Number.isSafeInteger(creatorId) && creatorId > 0 ? creatorId : 0,
creatorName: text(d.creator_name, 64),
adult: d.rating === "AP" || d.is_ap === true,
purchasable: d.is_purchasable !== false,
};
}
// IMVU's "denormalized" answers: the user is the one /user/user-<id> entry.
+9 -1
View File
@@ -63,7 +63,7 @@ for (const id of providers) {
}
const ageService = new AgeService(db, providers.map((id) => ageProviders[id]!()));
const { app, age, rooms, products } = createApp({ db, auth, imvu, age: ageService, apiURL, webURL, settings });
const { app, age, rooms, products, imports } = createApp({ db, auth, imvu, age: ageService, apiURL, webURL, settings });
app.listen({ port, hostname: env.HOST ?? "0.0.0.0" });
// Age answers that can change (IMVU's) are checked again when they expire, a few at a time; revisions missing their
@@ -83,4 +83,12 @@ setInterval(() => {
parentInfo();
purgeDrafts();
}, 10 * 60 * 1000);
// Imported products are checked with IMVU again daily (gone or another creator's: withdrawn; new revisions: a recheck
// job for the catalog's importer), a batch each hour.
const importRecheck = () =>
imports
.recheck(200)
.then((r) => (r.queued || r.withdrawn.length) && console.log(`imports: ${r.queued} rechecks queued, ${r.withdrawn.length} withdrawn`))
.catch((e) => console.error("import rechecks:", e));
setInterval(importRecheck, 60 * 60 * 1000);
console.log(`t5de-hub API on ${apiURL} (website ${webURL})`);
+9 -1
View File
@@ -13,7 +13,15 @@ const { notification } = schema;
* - product_restored: moderation restored it `{product, name, reason}`
* - membership_decided: a catalog decided their membership `{catalog, name, status}` (member, declined, banned)
*/
export type NotificationType = "product_edited" | "product_removed" | "product_restored" | "case_decided" | "case_note" | "membership_decided";
export type NotificationType =
| "product_edited"
| "product_removed"
| "product_restored"
| "case_decided"
| "case_note"
| "membership_decided"
| "import_grant_decided"
| "import_grant_ended";
export class Notifications {
constructor(
+219
View File
@@ -0,0 +1,219 @@
// 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();
});
+6 -1
View File
@@ -214,7 +214,7 @@ test("IMVU product info: parsing and image addresses", () => {
const answer = {
denormalized: {
"https://api.imvu.com/product/product-9": {
data: { product_image: "https://x.imvu.com/i.png", gender: "female", category_path: [{ id: 106, name: "Clothing" }, { id: "x", name: "Bad" }, { id: 716, name: " Coats & Jackets " }] },
data: { product_image: "https://x.imvu.com/i.png", gender: "female", category_path: [{ id: 106, name: "Clothing" }, { id: "x", name: "Bad" }, { id: 716, name: " Coats & Jackets " }], product_name: " Coat ", creator_cid: 77, creator_name: "Maker", rating: "AP", is_purchasable: false },
},
},
};
@@ -222,6 +222,11 @@ test("IMVU product info: parsing and image addresses", () => {
image: "https://x.imvu.com/i.png",
categories: [{ id: 106, name: "Clothing" }, { id: 716, name: "Coats & Jackets" }],
gender: "female",
name: "Coat",
creatorId: 77,
creatorName: "Maker",
adult: true,
purchasable: false,
});
expect(parseProduct(answer, 10)).toBeNull();
});
+7
View File
@@ -89,6 +89,13 @@ export default async function Account({ searchParams }: { searchParams: Promise<
Other people can&apos;t see which IMVU accounts are yours. Adult IMVU accounts can see adult community
products: those IMVU has age verified (or with Access Pass), or all of them once you verify your age below.
</p>
<p className="text-sm text-muted-foreground">
Made products on IMVU?{" "}
<Link href="/imports" className="text-foreground underline underline-offset-4">
Bring them to T5DE
</Link>
.
</p>
</CardContent>
</Card>
+23 -82
View File
@@ -9,13 +9,7 @@ import { ErrorText } from "@/components/forms";
import { Tag } from "@/components/status";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { authClient } from "@/lib/auth-client";
@@ -25,13 +19,7 @@ type Stage =
| { kind: "setup"; uri: string; codes: string[] }
| { kind: "codes"; codes: string[] };
export function TwoFactorCard({
enabled,
neededFor,
}: {
enabled: boolean;
neededFor: string[];
}) {
export function TwoFactorCard({ enabled, neededFor }: { enabled: boolean; neededFor: string[] }) {
const router = useRouter();
const [stage, setStage] = useState<Stage>({ kind: "idle" });
const [error, setError] = useState("");
@@ -45,10 +33,7 @@ export function TwoFactorCard({
setPending(false);
}
async function withPassword(
then: "enable" | "codes" | "disable",
password: string,
) {
async function withPassword(then: "enable" | "codes" | "disable", password: string) {
if (then === "enable") {
const { data, error } = await authClient.twoFactor.enable({ password });
if (error || !data || !("totpURI" in data) || !data.totpURI)
@@ -62,8 +47,7 @@ export function TwoFactorCard({
const { data, error } = await authClient.twoFactor.generateBackupCodes({
password,
});
if (error || !data)
return error?.message ?? "That didn't work. Try again.";
if (error || !data) return error?.message ?? "That didn't work. Try again.";
setStage({ kind: "codes", codes: data.backupCodes });
} else {
const { error } = await authClient.twoFactor.disable({ password });
@@ -82,13 +66,11 @@ export function TwoFactorCard({
router.refresh();
}
const submitTo =
(fn: (form: FormData) => Promise<string | void>) =>
(e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const form = new FormData(e.currentTarget);
void run(() => fn(form));
};
const submitTo = (fn: (form: FormData) => Promise<string | void>) => (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const form = new FormData(e.currentTarget);
void run(() => fn(form));
};
return (
<Card>
@@ -97,8 +79,7 @@ export function TwoFactorCard({
Two-Factor Sign-In {enabled && <Tag tone="strong">on</Tag>}
</CardTitle>
<CardDescription>
Signing in asks for a code from an authenticator app on your phone as
well as your password.
Signing in asks for a code from an authenticator app on your phone as well as your password.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
@@ -123,34 +104,19 @@ export function TwoFactorCard({
{stage.kind === "idle" &&
(enabled ? (
<div className="flex flex-wrap gap-2">
<Button
variant="outline"
onClick={() => setStage({ kind: "password", then: "codes" })}
>
<Button variant="outline" onClick={() => setStage({ kind: "password", then: "codes" })}>
New backup codes
</Button>
<Button
variant="outline"
onClick={() => setStage({ kind: "password", then: "disable" })}
>
<Button variant="outline" onClick={() => setStage({ kind: "password", then: "disable" })}>
Turn off
</Button>
</div>
) : (
<Button
onClick={() => setStage({ kind: "password", then: "enable" })}
>
Turn on
</Button>
<Button onClick={() => setStage({ kind: "password", then: "enable" })}>Turn on</Button>
))}
{stage.kind === "password" && (
<form
onSubmit={submitTo((f) =>
withPassword(stage.then, String(f.get("password"))),
)}
className="space-y-3"
>
<form onSubmit={submitTo((f) => withPassword(stage.then, String(f.get("password"))))} className="space-y-3">
<p className="text-sm">
{stage.then === "disable"
? neededFor.length > 0
@@ -170,22 +136,10 @@ export function TwoFactorCard({
aria-label="Password"
className="max-w-xs"
/>
<Button
type="submit"
variant={stage.then === "disable" ? "destructive" : "default"}
disabled={pending}
>
{pending
? "Checking…"
: stage.then === "disable"
? "Turn off"
: "Continue"}
<Button type="submit" variant={stage.then === "disable" ? "destructive" : "default"} disabled={pending}>
{pending ? "Checking…" : stage.then === "disable" ? "Turn off" : "Continue"}
</Button>
<Button
type="button"
variant="ghost"
onClick={() => setStage({ kind: "idle" })}
>
<Button type="button" variant="ghost" onClick={() => setStage({ kind: "idle" })}>
Cancel
</Button>
</div>
@@ -197,8 +151,8 @@ export function TwoFactorCard({
<ol className="list-decimal space-y-4 pl-5 text-sm">
<li className="space-y-2">
<p>
Scan this with an authenticator app (such as Google
Authenticator, Microsoft Authenticator or 1Password).
Scan this with an authenticator app (such as Google Authenticator, Microsoft Authenticator or
1Password).
</p>
<div
className="w-44 rounded-md bg-white p-2 [&>svg]:h-auto [&>svg]:w-full"
@@ -216,10 +170,7 @@ export function TwoFactorCard({
</p>
</li>
<li className="space-y-2">
<p>
Keep these backup codes somewhere safe. Each signs you in once
if you lose your phone.
</p>
<p>Keep these backup codes somewhere safe. Each signs you in once if you lose your phone.</p>
<BackupCodes codes={stage.codes} />
</li>
<li className="space-y-2">
@@ -242,11 +193,7 @@ export function TwoFactorCard({
<Button type="submit" disabled={pending}>
{pending ? "Checking…" : "Turn on"}
</Button>
<Button
type="button"
variant="ghost"
onClick={() => setStage({ kind: "idle" })}
>
<Button type="button" variant="ghost" onClick={() => setStage({ kind: "idle" })}>
Cancel
</Button>
</form>
@@ -257,15 +204,9 @@ export function TwoFactorCard({
{stage.kind === "codes" && (
<div className="space-y-2 text-sm">
<p>
Your new backup codes. Keep them somewhere safe: they won&apos;t
be shown again.
</p>
<p>Your new backup codes. Keep them somewhere safe: they won&apos;t be shown again.</p>
<BackupCodes codes={stage.codes} />
<Button
variant="outline"
onClick={() => setStage({ kind: "idle" })}
>
<Button variant="outline" onClick={() => setStage({ kind: "idle" })}>
Done
</Button>
</div>
@@ -0,0 +1,305 @@
import type { Metadata } from "next";
import Link from "next/link";
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 { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { api, unwrap, type ImportGrant } from "@/lib/api";
import { ConsoleNav, requireConsole } from "../../../console-nav";
import { decideGrant, retryJob, setImporter } from "../../actions";
export const metadata: Metadata = { title: "Imports" };
const statuses = ["queued", "claimed", "failed", "done"] as const;
const grantTone = {
pending: "strong",
active: "online",
declined: "neutral",
suspended: "danger",
withdrawn: "neutral",
} as const;
const jobTone = {
queued: "neutral",
claimed: "strong",
failed: "danger",
done: "online",
} as const;
const imvuPage = (id: number) => `https://www.imvu.com/shop/product.php?products_id=${id}`;
export default async function CatalogImports({
params,
searchParams,
}: {
params: Promise<{ id: string }>;
searchParams: Promise<{ status?: string }>;
}) {
const { id } = await params;
await requireConsole(`/console/catalogs/${id}/imports`);
const wanted = (await searchParams).status;
const status = statuses.find((s) => s === wanted);
const [catalogAnswer, answer] = await Promise.all([
api.catalogs({ id }).get(),
api.catalogs({ id }).importer.get({ query: status ? { status } : {} }),
]);
if (catalogAnswer.error || answer.error) notFound();
const c = unwrap(catalogAnswer).catalog;
const data = unwrap(answer);
const can = data.permissions;
const pending = data.grants.filter((g) => g.status === "pending");
const others = data.grants.filter((g) => g.status !== "pending");
return (
<>
<PageHeader title={`${c.name}: Imports`}>
<Link href={`/console/catalogs/${id}`} className="underline-offset-4 hover:underline">
Back to the catalog
</Link>
</PageHeader>
<ConsoleNav />
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
Importer{" "}
<Tag tone={data.importer === "on" ? "online" : data.importer === "paused" ? "strong" : "neutral"}>
{data.importer}
</Tag>
</CardTitle>
<CardDescription>
{data.importer === "off"
? "With imports on, creators can bring their IMVU products here, and your importer (t5de-importer, run beside the catalog) imports what they allow."
: `The importer signs in with the catalog's ID (${id}) and its importer key. ${data.counts.queued} queued, ${data.counts.claimed} working, ${data.counts.failed} failed, ${data.counts.done} done.`}
</CardDescription>
</CardHeader>
{(can.run || can.pause) && (
<CardContent>
<ActionForm action={setImporter} fields={{ id }}>
<div className="flex flex-wrap gap-2">
{data.importer === "off" ? (
can.run && (
<SubmitButton name="intent" value="on" pendingLabel="Turning on…">
Turn imports on
</SubmitButton>
)
) : (
<>
{can.pause &&
(data.importer === "paused" ? (
<SubmitButton name="intent" value="resume" pendingLabel="Resuming…">
Resume
</SubmitButton>
) : (
<SubmitButton name="intent" value="pause" variant="outline" pendingLabel="Pausing…">
Pause
</SubmitButton>
))}
{can.run && (
<SubmitButton
name="intent"
value="key"
variant="outline"
pendingLabel="Making one…"
confirm="The old importer key stops working at once. Go on?"
>
New key
</SubmitButton>
)}
{can.run && (
<SubmitButton
name="intent"
value="off"
variant="outline"
pendingLabel="Turning off…"
confirm="Turn imports off? No new grants, and the importer stops. What's imported stays."
>
Turn off
</SubmitButton>
)}
</>
)}
</div>
</ActionForm>
</CardContent>
)}
</Card>
{pending.length > 0 && (
<Card>
<CardHeader>
<CardTitle>Waiting for You</CardTitle>
<CardDescription>
Creators asking this catalog to host their IMVU products. Nothing is imported until you accept.
</CardDescription>
</CardHeader>
<CardContent className="divide-y">
{pending.map((g) => (
<GrantRow key={g.id} id={id} grant={g} accept={can.accept} withdraw={can.withdraw} />
))}
</CardContent>
</Card>
)}
{others.length > 0 && (
<Card>
<CardHeader>
<CardTitle>Grants</CardTitle>
</CardHeader>
<CardContent className="divide-y">
{others.map((g) => (
<GrantRow key={g.id} id={id} grant={g} accept={can.accept} withdraw={can.withdraw} />
))}
</CardContent>
</Card>
)}
<Card>
<CardHeader>
<CardTitle>Queue</CardTitle>
<CardDescription className="flex flex-wrap gap-3">
{[undefined, ...statuses].map((s) => (
<Link
key={s ?? "all"}
href={`/console/catalogs/${id}/imports${s ? `?status=${s}` : ""}`}
className={s === status ? "font-medium text-foreground" : "underline-offset-4 hover:underline"}
>
{s ?? "all"}
</Link>
))}
</CardDescription>
</CardHeader>
<CardContent>
{data.jobs.length === 0 ? (
<p className="text-sm text-muted-foreground">Nothing here.</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>IMVU product</TableHead>
<TableHead>Job</TableHead>
<TableHead>Status</TableHead>
<TableHead>Updated</TableHead>
<TableHead />
</TableRow>
</TableHeader>
<TableBody>
{data.jobs.map((j) => (
<TableRow key={j.id}>
<TableCell>
<a
href={imvuPage(j.imvuProduct)}
target="_blank"
rel="noreferrer"
className="underline-offset-4 hover:underline"
>
{j.name || j.imvuProduct}
</a>
</TableCell>
<TableCell className="text-muted-foreground">
{j.kind}
{j.imvuRevision ? ` · revision ${j.imvuRevision}` : ""}
</TableCell>
<TableCell className="whitespace-normal">
<Tag tone={jobTone[j.status]}>{j.status}</Tag>
{j.reason && j.reason !== "unchanged" && (
<span className="ml-2 text-xs text-muted-foreground">
{j.reason}
{j.attempts > 0 && ` (attempt ${j.attempts})`}
</span>
)}
</TableCell>
<TableCell className="text-muted-foreground">
<DateTime iso={j.updatedAt} />
</TableCell>
<TableCell className="text-right">
{can.run && (j.status === "failed" || j.status === "done") && (
<ActionForm action={retryJob} fields={{ id, job: j.id }}>
<SubmitButton size="sm" variant="outline" pendingLabel="Queuing…">
{j.status === "failed" ? "Retry" : "Again"}
</SubmitButton>
</ActionForm>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
</div>
</>
);
}
function GrantRow({
id,
grant: g,
accept,
withdraw,
}: {
id: string;
grant: ImportGrant;
accept: boolean;
withdraw: boolean;
}) {
const open = g.status === "pending" || g.status === "active" || g.status === "suspended";
return (
<div className="space-y-2 py-4 first:pt-0 last:pb-0">
<div className="flex flex-wrap items-center gap-2 text-sm">
<span className="font-medium">{g.imvuName || `IMVU account ${g.imvuId}`}</span>
<span className="text-muted-foreground">(IMVU {g.imvuId})</span>
<Tag tone={grantTone[g.status]}>{g.status}</Tag>
{g.consentKind === "recorded" && <Tag>consent recorded by an admin</Tag>}
<span className="text-xs text-muted-foreground">
<DateTime iso={g.createdAt} dateOnly />
</span>
</div>
<p className="text-sm">
{g.scope === "shop"
? `The whole shop${g.exclude.length ? `, less ${g.exclude.length} left out` : ""}.`
: `${g.products.length} chosen product${g.products.length === 1 ? "" : "s"}: ${g.products.slice(0, 10).join(", ")}${g.products.length > 10 ? "…" : ""}.`}{" "}
{g.listed ? "Listed." : "Unlisted."}
</p>
{g.statusReason && <p className="text-sm text-muted-foreground">{g.statusReason}</p>}
{open && (accept || withdraw) && (
<ActionForm action={decideGrant} fields={{ id, grant: g.id }}>
<div className="flex max-w-2xl flex-wrap gap-2">
{(g.status === "pending" || withdraw) && (
<Input
name="reason"
maxLength={500}
placeholder={g.status === "pending" ? "Reason (if declining)" : "Reason (if ending)"}
aria-label="Reason"
className="min-w-56 flex-1"
/>
)}
{g.status === "pending" && accept && (
<>
<SubmitButton name="intent" value="accept" pendingLabel="Accepting…">
Accept
</SubmitButton>
<SubmitButton name="intent" value="decline" variant="outline" pendingLabel="Declining…">
Decline
</SubmitButton>
</>
)}
{g.status !== "pending" && withdraw && (
<SubmitButton
name="intent"
value="end"
variant="outline"
pendingLabel="Ending…"
confirm="End this grant? Its imported products are taken away from everyone who has them."
>
End
</SubmitButton>
)}
</div>
</ActionForm>
)}
</div>
);
}
@@ -162,6 +162,24 @@ export default async function ManageCatalog({ params }: { params: Promise<{ id:
</CardContent>
</Card>
{(has("import:accept") || has("import:pause")) && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
Imports <Tag tone={c.importer === "on" ? "online" : "neutral"}>{c.importer}</Tag>
</CardTitle>
<CardDescription>
Creators&apos; IMVU products, imported with their permission: grants, the importer and its queue.
</CardDescription>
</CardHeader>
<CardContent>
<Link href={`/console/catalogs/${id}/imports`} className="text-sm underline underline-offset-4">
Manage imports
</Link>
</CardContent>
</Card>
)}
{has("catalog:rotate-key") && (
<Card>
<CardHeader>
+53
View File
@@ -120,3 +120,56 @@ export async function membership(_: ActionState, form: FormData): Promise<Action
return membership === "member" ? "You're a member." : "Asked. The catalog's team will decide.";
});
}
// ---- imports (docs/imports.md) ----
/** Turns the importer on (its key, shown once) or off, pauses or resumes it, or makes a new key. */
export async function setImporter(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
revalidatePath(`/console/catalogs/${id}/imports`);
const intent = field(form, "intent");
if (intent === "key") {
const { key } = unwrap(await api.catalogs({ id }).importer.key.post());
return `New importer key (shown once; put it in the importer's IMPORTER_KEY and restart it): ${key}`;
}
const body =
intent === "on" ? { enabled: true } : intent === "off" ? { enabled: false } : { paused: intent === "pause" };
const r = unwrap(await api.catalogs({ id }).importer.post(body));
if (r.key) return `Imports are on. The importer's key (shown once; put it in IMPORTER_KEY): ${r.key}`;
});
}
/** The catalog's team accepts, declines or ends a creator's grant. */
export async function decideGrant(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
revalidatePath(`/console/catalogs/${id}/imports`);
const grant = field(form, "grant");
const intent = field(form, "intent");
const reason = field(form, "reason");
if (intent === "end") {
unwrap(await api.imports.grants({ id: grant }).delete(reason ? { reason } : {}));
return "Ended. Its imported products were taken away.";
}
const decision = intent === "accept" ? "accept" : "decline";
const r = unwrap(
await api.imports
.grants({ id: grant })({ decision })
.post(reason ? { reason } : {}),
);
return decision === "accept" ? `Accepted. ${r.queued} queued for the importer.` : "Declined.";
});
}
/** Retries a failed import job (or imports a product again). */
export async function retryJob(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
revalidatePath(`/console/catalogs/${id}/imports`);
unwrap(
await api
.catalogs({ id })
.importer.jobs({ job: field(form, "job") })
.retry.post(),
);
return "Queued.";
});
}
+4 -20
View File
@@ -3,14 +3,7 @@ import { notFound, redirect } from "next/navigation";
import { cache } from "react";
import { NavLink } from "@/components/header-client";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import {
api,
getMe,
isModerator,
unwrap,
type ConsoleData,
type Person,
} from "@/lib/api";
import { api, getMe, isModerator, unwrap, type ConsoleData, type Person } from "@/lib/api";
/** The signed-in moderator, or off to sign in; others get not found (these pages aren't for them). */
export async function requireModerator(path: string): Promise<Person> {
@@ -31,9 +24,7 @@ const loadConsole = cache(async (): Promise<ConsoleData | undefined> => {
* The signed-in person and their console, or off to sign in. People who manage nothing get not found: the console
* is for those controlling a product, catalog or room.
*/
export async function requireConsole(
path: string,
): Promise<{ me: Person; console: ConsoleData }> {
export async function requireConsole(path: string): Promise<{ me: Person; console: ConsoleData }> {
const me = await getMe();
if (!me) redirect(`/signin?next=${encodeURIComponent(path)}`);
const data = await loadConsole();
@@ -67,10 +58,7 @@ export async function ConsoleNav() {
<AlertDescription>
<span>
Some of what you can do here needs it ({needed.join(", ")}).{" "}
<Link
href="/account"
className="text-foreground underline underline-offset-4"
>
<Link href="/account" className="text-foreground underline underline-offset-4">
Turn it on in your account
</Link>
.
@@ -82,11 +70,7 @@ export async function ConsoleNav() {
{tabs
.filter((t) => sections.has(t.section))
.map((t) => (
<NavLink
key={t.section}
href={t.href}
exact={t.section === "overview"}
>
<NavLink key={t.section} href={t.href} exact={t.section === "overview"}>
{t.label}
</NavLink>
))}
+90
View File
@@ -0,0 +1,90 @@
"use server";
// Imports from the website: asking for an IMVU product, and creators' grants (bring, change, withdraw).
import { revalidatePath } from "next/cache";
import { api, ApiError, unwrap } from "@/lib/api";
import { attempt, field, type ActionState } from "@/lib/actions";
const done = () => {
revalidatePath("/imports");
revalidatePath("/library");
};
/** IMVU product IDs in what someone typed or pasted: numbers, or shop links (`products_id=123`, `product-123`). */
function productIDs(text: string): number[] | undefined {
const out = new Set<number>();
for (const part of text.split(/[\s,]+/).filter(Boolean)) {
const m = part.match(/(?:products_id=|product-)(\d+)/) ?? part.match(/^(\d+)$/);
const n = m ? Number(m[1]) : NaN;
if (!Number.isSafeInteger(n) || n <= 0) return undefined;
out.add(n);
}
return [...out];
}
const answers = {
added: "It's in your library.",
queued: "Its creator lets T5DE have it: it'll be in your library once the catalog imports it.",
suggested: "Its creator brings chosen products to T5DE; they'll see you asked for this one.",
counted: "Its creator hasn't brought it to T5DE. Your request is counted, and they'll see it if they do.",
} as const;
/** Someone asks for an IMVU product (an ID or a shop link). */
export async function requestProduct(_: ActionState, form: FormData): Promise<ActionState> {
const ids = productIDs(field(form, "product"));
if (!ids || ids.length !== 1) return { error: "Give one IMVU product ID or shop link." };
return attempt(async () => {
const r = unwrap(await api.imports.requests.post({ imvuProduct: ids[0]! }));
done();
return answers[r.status];
});
}
/** A creator brings their IMVU products to a catalog. */
export async function createGrant(_: ActionState, form: FormData): Promise<ActionState> {
if (form.get("agree") !== "on") return { error: "Agree to the terms to go on." };
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 () => {
unwrap(
await api.imports.grants.post({
catalog: field(form, "catalog"),
imvuId: Number(field(form, "imvuId")),
scope,
...(scope === "products" ? { products: list } : { exclude: list }),
listed: form.get("listed") === "on",
consentVersion: Number(field(form, "consentVersion")),
}),
);
done();
return "Sent. The catalog's team accepts it before anything is imported.";
});
}
/** A creator changes what a grant covers, or withdraws it. */
export async function changeGrant(_: ActionState, form: FormData): Promise<ActionState> {
const id = field(form, "id");
return attempt(async () => {
if (field(form, "intent") === "withdraw") {
const r = unwrap(await api.imports.grants({ id }).delete({}));
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.";
});
}
+317
View File
@@ -0,0 +1,317 @@
import type { Metadata } from "next";
import Link from "next/link";
import { redirect } 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, getMe, unwrap, type ImportGrant } from "@/lib/api";
import { changeGrant, createGrant, requestProduct } from "./actions";
export const metadata: Metadata = { title: "Imports" };
const statusTone = {
pending: "neutral",
active: "online",
declined: "danger",
suspended: "danger",
withdrawn: "neutral",
} as const;
const imvuPage = (id: number) => `https://www.imvu.com/shop/product.php?products_id=${id}`;
export default async function Imports() {
const me = await getMe();
if (!me) redirect("/signin?next=/imports");
const [account, offered, mine] = await Promise.all([
api.account.get().then(unwrap),
api.imports.catalogs.get().then(unwrap),
api.imports.grants.get().then(unwrap),
]);
const asked = await Promise.all(
account.links.map(async (l) => ({
link: l,
requests: unwrap(await api.imports.requests.get({ query: { imvuCreator: l.imvuId } })).requests,
})),
);
const open = mine.grants.filter((g) => g.status !== "withdrawn" && g.status !== "declined");
const ended = mine.grants.filter((g) => g.status === "withdrawn" || g.status === "declined");
return (
<div className="space-y-6">
<PageHeader title="IMVU Imports">
Creators can let T5DE users wear their IMVU products for free: a catalog imports them, with their permission.
</PageHeader>
<Card>
<CardHeader>
<CardTitle>Ask for a Product</CardTitle>
<CardDescription>
An IMVU product you&apos;d like on T5DE. If its creator lets T5DE have it, it comes to your library; if not,
they&apos;ll see that people asked.
</CardDescription>
</CardHeader>
<CardContent>
<ActionForm action={requestProduct}>
<div className="flex max-w-xl flex-wrap gap-2">
<Input
name="product"
required
placeholder="IMVU product ID or shop link"
aria-label="IMVU product"
className="min-w-64 flex-1"
/>
<SubmitButton pendingLabel="Asking…">Ask</SubmitButton>
</div>
</ActionForm>
</CardContent>
</Card>
{open.length > 0 && (
<Card>
<CardHeader>
<CardTitle>Your Products on T5DE</CardTitle>
</CardHeader>
<CardContent className="space-y-6">
{open.map((g) => (
<GrantRow key={g.id} grant={g} />
))}
</CardContent>
</Card>
)}
<Card>
<CardHeader>
<CardTitle>Bring Your IMVU Products</CardTitle>
<CardDescription>
Made products on IMVU? Choose a catalog to host them. Its team accepts first; then T5DE users can wear them
for free, and you can change what&apos;s included or stop any time.
</CardDescription>
</CardHeader>
<CardContent>
{account.links.length === 0 ? (
<p className="text-sm text-muted-foreground">
First{" "}
<Link href="/account" className="text-foreground underline underline-offset-4">
link your IMVU account
</Link>
, the one that made the products.
</p>
) : offered.catalogs.length === 0 ? (
<p className="text-sm text-muted-foreground">No catalog takes imports yet.</p>
) : (
<ActionForm
action={createGrant}
fields={{ consentVersion: offered.consent.version }}
className="max-w-2xl space-y-4"
>
<div className="grid gap-4 sm:grid-cols-2">
<Field>
<FieldLabel htmlFor="imvuId">Your IMVU account</FieldLabel>
<NativeSelect id="imvuId" name="imvuId">
{account.links.map((l) => (
<NativeSelectOption key={l.imvuId} value={l.imvuId}>
{l.username}
</NativeSelectOption>
))}
</NativeSelect>
</Field>
<Field>
<FieldLabel htmlFor="catalog">Catalog</FieldLabel>
<NativeSelect id="catalog" name="catalog">
{offered.catalogs.map((c) => (
<NativeSelectOption key={c.id} value={c.id}>
{c.name}
</NativeSelectOption>
))}
</NativeSelect>
</Field>
</div>
<fieldset className="space-y-2">
<legend className="mb-2 text-sm font-medium">What to bring</legend>
<label className="flex items-start gap-2 text-sm">
<input type="radio" name="scope" value="shop" defaultChecked className="mt-1" />
<span>
My whole shop, including new products
<span className="block text-muted-foreground">Leave some out below (optional).</span>
</span>
</label>
<label className="flex items-start gap-2 text-sm">
<input type="radio" name="scope" value="products" className="mt-1" />
<span>
Only the products I list
<span className="block text-muted-foreground">List them below; you can add more later.</span>
</span>
</label>
</fieldset>
<Field>
<FieldLabel htmlFor="exclude">Leave out (whole shop)</FieldLabel>
<Textarea
id="exclude"
name="exclude"
rows={2}
placeholder="IMVU product IDs or shop links"
className="font-mono text-xs"
/>
</Field>
<Field>
<FieldLabel htmlFor="products">Products (only these)</FieldLabel>
<Textarea
id="products"
name="products"
rows={2}
placeholder="IMVU product IDs or shop links"
className="font-mono text-xs"
/>
</Field>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" name="listed" defaultChecked />
Listed (shown in search and on your page; unlisted ones work by link)
</label>
<div className="rounded-md border bg-muted/40 p-3 text-sm">
<p>{offered.consent.text}</p>
<label className="mt-3 flex items-center gap-2 font-medium">
<input type="checkbox" name="agree" required />I agree
</label>
</div>
<SubmitButton pendingLabel="Sending…">Send to the catalog</SubmitButton>
</ActionForm>
)}
</CardContent>
</Card>
{asked.some((a) => a.requests.length > 0) && (
<Card>
<CardHeader>
<CardTitle>What People Asked For</CardTitle>
<CardDescription>Your IMVU products that T5DE users would like.</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{asked
.filter((a) => a.requests.length > 0)
.map((a) => (
<div key={a.link.imvuId}>
<p className="mb-2 text-sm font-medium">{a.link.username}</p>
<Table>
<TableHeader>
<TableRow>
<TableHead>Product</TableHead>
<TableHead className="text-right">People</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{a.requests.slice(0, 20).map((r) => (
<TableRow key={r.imvuProduct}>
<TableCell>
{r.imvuProduct === 0 ? (
"Your whole shop"
) : (
<a
href={imvuPage(r.imvuProduct)}
className="underline-offset-4 hover:underline"
target="_blank"
rel="noreferrer"
>
{r.name || r.imvuProduct}
</a>
)}
</TableCell>
<TableCell className="text-right tabular-nums">{r.requests}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
))}
</CardContent>
</Card>
)}
{ended.length > 0 && (
<details className="text-sm">
<summary className="cursor-pointer text-muted-foreground hover:text-foreground">Ended</summary>
<ul className="mt-2 divide-y">
{ended.map((g) => (
<li key={g.id} className="py-2">
{g.imvuName || g.imvuId} → {g.catalogName} <Tag tone={statusTone[g.status]}>{g.status}</Tag>{" "}
<span className="text-muted-foreground">{g.statusReason}</span>
</li>
))}
</ul>
</details>
)}
</div>
);
}
function GrantRow({ grant: g }: { grant: ImportGrant }) {
const list = g.scope === "products" ? g.products : g.exclude;
return (
<div className="space-y-3 border-b pb-6 last:border-b-0 last:pb-0">
<div className="flex flex-wrap items-center gap-2 text-sm">
<span className="font-medium">{g.imvuName || g.imvuId}</span>
<span className="text-muted-foreground">to</span>
<span className="font-medium">{g.catalogName}</span>
<Tag tone={statusTone[g.status]}>{g.status === "pending" ? "waiting for the catalog" : g.status}</Tag>
<span className="text-xs text-muted-foreground">
since <DateTime iso={g.createdAt} dateOnly />
</span>
</div>
{g.statusReason && <p className="text-sm text-muted-foreground">{g.statusReason}</p>}
<p className="text-sm">
{g.scope === "shop"
? `Your whole shop${g.exclude.length ? `, less ${g.exclude.length} left out` : ""}.`
: `${g.products.length} chosen product${g.products.length === 1 ? "" : "s"}.`}{" "}
{g.listed ? "Listed." : "Unlisted."}
</p>
{g.status === "suspended" ? (
<p className="text-sm text-muted-foreground">Withdraw it, then bring your products again to start over.</p>
) : null}
<ActionForm action={changeGrant} fields={{ id: g.id, scope: g.scope }} className="max-w-2xl space-y-2">
{g.status !== "suspended" && (
<>
<Field>
<FieldLabel htmlFor={`list-${g.id}`}>{g.scope === "shop" ? "Left out" : "Products"}</FieldLabel>
<Textarea
id={`list-${g.id}`}
name="list"
rows={2}
defaultValue={list.join("\n")}
className="font-mono text-xs"
/>
<FieldDescription>
{g.scope === "shop"
? "Products left out that were imported are taken away from everyone."
: "Products taken off the list that were imported are taken away from everyone."}
</FieldDescription>
</Field>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" name="listed" defaultChecked={g.listed} />
Listed
</label>
</>
)}
<div className="flex flex-wrap gap-2">
{g.status !== "suspended" && (
<SubmitButton name="intent" value="save" variant="outline" pendingLabel="Saving…">
Save
</SubmitButton>
)}
<SubmitButton
name="intent"
value="withdraw"
variant="outline"
pendingLabel="Withdrawing…"
confirm="Withdraw? Your imported products are taken away from everyone who has them."
>
Withdraw
</SubmitButton>
</div>
</ActionForm>
</div>
);
}
+10
View File
@@ -111,6 +111,16 @@ function describe(n: NotificationEntry): { text: string; href?: string } {
: `${s("name")} declined your request to join`;
return { text, href: `/catalogs/${s("catalog")}` };
}
case "import_grant_decided":
return {
text:
s("decision") === "accept"
? `${s("name")} accepted importing your IMVU products`
: `${s("name")} declined importing your IMVU products${why}`,
href: "/imports",
};
case "import_grant_ended":
return { text: `${s("name")} stopped importing your IMVU products${why}`, href: "/imports" };
default:
return { text: n.type };
}
+7 -30
View File
@@ -4,12 +4,7 @@ import { useRouter } from "next/navigation";
import { useState } from "react";
import { ErrorText } from "@/components/forms";
import { Button } from "@/components/ui/button";
import {
Field,
FieldDescription,
FieldGroup,
FieldLabel,
} from "@/components/ui/field";
import { Field, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { authClient } from "@/lib/auth-client";
@@ -33,8 +28,7 @@ export function SignInForm({ next }: { next: string }) {
password: String(form.get("password")),
});
if (error) return setError(error.message ?? "That didn't work. Try again.");
if (data && "twoFactorRedirect" in data && data.twoFactorRedirect)
return setStep("code");
if (data && "twoFactorRedirect" in data && data.twoFactorRedirect) return setStep("code");
done();
}
@@ -44,8 +38,7 @@ export function SignInForm({ next }: { next: string }) {
step === "code"
? await authClient.twoFactor.verifyTotp({ code })
: await authClient.twoFactor.verifyBackupCode({ code });
if (error)
return setError(error.message ?? "That code didn't work. Try again.");
if (error) return setError(error.message ?? "That code didn't work. Try again.");
done();
}
@@ -67,23 +60,11 @@ export function SignInForm({ next }: { next: string }) {
<FieldGroup>
<Field>
<FieldLabel htmlFor="username">Username</FieldLabel>
<Input
id="username"
name="username"
autoComplete="username"
required
autoFocus
/>
<Input id="username" name="username" autoComplete="username" required autoFocus />
</Field>
<Field>
<FieldLabel htmlFor="password">Password</FieldLabel>
<Input
id="password"
name="password"
type="password"
autoComplete="current-password"
required
/>
<Input id="password" name="password" type="password" autoComplete="current-password" required />
</Field>
{error && <ErrorText>{error}</ErrorText>}
<Field>
@@ -99,9 +80,7 @@ export function SignInForm({ next }: { next: string }) {
<FieldGroup key={step}>
<Field>
<FieldLabel htmlFor="code">
{step === "code"
? "Code from your authenticator app"
: "Backup code"}
{step === "code" ? "Code from your authenticator app" : "Backup code"}
</FieldLabel>
<Input
id="code"
@@ -133,9 +112,7 @@ export function SignInForm({ next }: { next: string }) {
setStep(step === "code" ? "backup" : "code");
}}
>
{step === "code"
? "Use a backup code instead"
: "Use your authenticator app instead"}
{step === "code" ? "Use a backup code instead" : "Use your authenticator app instead"}
</button>
</FieldDescription>
</Field>
+4
View File
@@ -48,6 +48,10 @@ export type TokenList = Data<V1["account"]["tokens"]["get"]>;
export type TokenEntry = TokenList["tokens"][number];
export type TokenScope = TokenList["scopes"][number];
export type CatalogPage = Data<ReturnType<V1["catalogs"]>["get"]>;
export type ImportCatalogs = Data<V1["imports"]["catalogs"]["get"]>;
export type ImportGrant = Data<V1["imports"]["grants"]["get"]>["grants"][number];
export type ImporterPage = Data<ReturnType<V1["catalogs"]>["importer"]["get"]>;
export type ImportJob = ImporterPage["jobs"][number];
export type CatalogMember = Data<ReturnType<V1["catalogs"]>["members"]["get"]>["members"][number];
export type CatalogInvite = Data<ReturnType<V1["catalogs"]>["invites"]["get"]>["invites"][number];
export type HostedProduct = Data<ReturnType<V1["catalogs"]>["products"]["get"]>["products"][number];
+2
View File
@@ -481,6 +481,8 @@ Phases for products, catalogs and imports (products.md, console.md, imports.md):
reasons, moderator notes or second approval. File blocks, API tokens and two-factor sign-in **done**
(2026-11-05); auditing turning two-factor on and off, and "trust this browser", later.
4. Imports: grants, recorded grants, requests, unclaimed creators, the job queue, `t5de-importer` (after its spike).
Grants by creators, requests, the job queue and the importer API **done** (2026-11-05, imports.md "Built");
recorded grants, unclaimed creators, t5de-catalog's import uploads, the spike and the importer next.
5. Charts and stats; mirroring between catalogs.
Later: custom roles; time-limited roles; announcements and maintenance mode; audit retention; webhooks; catalog
+35 -12
View File
@@ -135,21 +135,44 @@ A Go program (its own repository) beside a `t5de-catalog`; it stores nothing las
| | |
| --- | --- |
| `GET /api/v1/imports/catalogs` | approved catalogs with imports on, accepting grants |
| `POST /api/v1/imports/grants` | `{catalog, imvuId, scope, products?, exclude?, listed, consentVersion}` → 201 `{grant}` (pending). With `onBehalf: {imvuId, evidence, proof?}` instead of a linked `imvuId`: an admin-recorded grant. |
| `GET /api/v1/imports/grants` | the person's grants; with `catalog=`, a catalog's (its team) |
| `PATCH /api/v1/imports/grants/:id` | `{scope?, products?, exclude?, listed?}` |
| `POST /api/v1/imports/grants/:id/accept`, `.../decline` | the catalog's team |
| `DELETE /api/v1/imports/grants/:id` | withdraw |
| `POST /api/v1/imports/proofs` | (admins) `{imvuId}` → `{proof, code}`; `POST .../proofs/:id/check` |
| `POST /api/v1/imports/requests` | `{imvuProduct}` or `{imvuCreator}` → `{status: "queued" \| "suggested" \| "counted", product?}` |
| `GET /api/v1/imports/requests?imvuCreator=` | counts (the creator, admins) |
| `GET /api/v1/imports/available?imvuProducts=a,b` | for the proxy's shop button: which can the person get (and the hub product ID), already have, or request |
| `GET /api/v1/imports/jobs?catalog=&status=` | the catalog's team: the queue; `POST .../jobs/:id/retry` |
| `POST /api/v1/imports/claim` | `{imvuId}`: claim an unclaimed creator's products for a linked account |
| `GET /api/v1/imports/catalogs` | (anyone) `{catalogs: [{id, name, url, contact, maxRating}], consent: {version, text}}`: approved catalogs with imports on |
| `POST /api/v1/imports/grants` | `{catalog, imvuId, scope ("shop" \| "products"), products?, exclude?, listed?, consentVersion}` → 201 `{grant}` (pending). The IMVU account must be the person's linked one (403 `not_linked`); an older consent version is 409 `consent_changed`; one open grant per catalog and account (409 `exists`). |
| `GET /api/v1/imports/grants` | the person's grants (as their creator) |
| `PATCH /api/v1/imports/grants/:id` | (its creator) `{products?, exclude?, listed?}` → `{grant, withdrawn}`: products no longer covered are withdrawn; newly covered ones people asked for are queued |
| `POST /api/v1/imports/grants/:id/accept`, `.../decline` | (`import:accept` at the catalog) `{reason?}` → `{grant, queued}`. The creator is notified. |
| `DELETE /api/v1/imports/grants/:id` | (its creator, or `import:withdraw` at the catalog) `{reason?}` → `{grant, withdrawn}` |
| `POST /api/v1/imports/requests` | `{imvuProduct}` or `{imvuCreator}` → `{status: "added" \| "queued" \| "suggested" \| "counted", product?}` (`added`: imported already, now in their library). At most 50 a day. |
| `GET /api/v1/imports/requests?imvuCreator=` | `{requests: [{imvuProduct (0: the whole shop), name, requests}]}` for a linked account of theirs (moderators: any); without `imvuCreator`, moderators get `{creators}`: the most asked-for IMVU creators |
| `GET /api/v1/catalogs/:id/importer` | (`import:accept` or `import:pause`) `{importer, grants, jobs, counts, permissions}`; `?status=` filters jobs |
| `POST /api/v1/catalogs/:id/importer` | `{enabled?}` (`import:run`; turning on returns the importer `key`, shown once) and `{paused?}` (`import:pause`) |
| `POST /api/v1/catalogs/:id/importer/key` | (`import:run`) → `{key}`: a new importer key |
| `POST /api/v1/catalogs/:id/importer/jobs/:job/retry` | (`import:run`) a failed or done job queued again |
For importers (`Authorization: Importer <catalog ID>:<key>`) in products.md.
Built (phase 4a, 2026-11-05): grants made by creators, accepting and declining, changing and withdrawing (withdrawn
products are removed as moderation removes, their hosting dropped and their files in the catalogs' changes feed;
only delisted from one catalog if another catalog's active grant still covers them), requests with library
delivery, the job queue (claims time out after 30 minutes; failures back off 1 min, 10 min, 1 h, daily, then fail
after 5), import tokens and registering imported revisions (`product.imvu_product`, `product_revision.imvu_revision`;
a revision another catalog imported already is hosted here too, same files only), grants suspended when their IMVU
account is unlinked or linked to someone else, an hourly batch of daily rechecks (`imvu_product_info` caches IMVU's
answers a day), notifications (`import_grant_decided`, `import_grant_ended`), the website's `/imports` page (ask
for a product; bring products; change or withdraw; what people asked for) and the console's
`/console/catalogs/:id/imports` (importer on, off, paused, key; accept and decline; the queue with retries).
IMVU's product fields (`product_name`, `creator_cid`, `creator_name`, `rating`, `is_purchasable`) were checked
against the live API (2026-11-06). Anonymous callers get 401 (`AUTHENTICATION-005`) alike for Access Pass products,
deleted ones and IDs that never existed (404 only for a few very old IDs), so the hub keeps what it last saw on a
401 rather than withdraw a product that became AP, and can't import AP products it never saw. The CDN
(`userimages-akm.imvu.com/productdata/<id>/<n>/`) serves AP and even deleted products' files without signing in
(made-up IDs 404), but they carry no creator, name or rating, which a grant needs to cover a product. The shop page
(`www.imvu.com/shop/product.php?products_id=`) tells them apart: an AP product redirects to sign-in, a deleted one
says "Not Found". For AP products, the importer's IMVU account (with Access Pass) would report the product info to
the hub: decide with the spike.
Still to do: admin-recorded grants, proofs and unclaimed creators (and claiming); `GET /imports/available` for the
proxy's shop button; t5de-catalog accepting `t5de-import` tokens on uploads; the spike and `t5de-importer`.
## Spike (before building the importer)
1. Import one product by hand as a local pack (full-size textures, no `_contents.json`, parent kept). Does the
+76
View File
@@ -0,0 +1,76 @@
CREATE TABLE "import_grant" (
"id" text PRIMARY KEY NOT NULL,
"catalog_id" text NOT NULL,
"creator_id" text NOT NULL,
"imvu_id" bigint NOT NULL,
"scope" text NOT NULL,
"products" jsonb DEFAULT '[]'::jsonb NOT NULL,
"exclude" jsonb DEFAULT '[]'::jsonb NOT NULL,
"listed" boolean DEFAULT true NOT NULL,
"consent_version" integer NOT NULL,
"consented_at" timestamp with time zone DEFAULT now() NOT NULL,
"consent_kind" text DEFAULT 'verified' NOT NULL,
"evidence" text DEFAULT '' NOT NULL,
"recorded_by" text,
"status" text DEFAULT 'pending' NOT NULL,
"status_reason" text DEFAULT '' NOT NULL,
"decided_at" timestamp with time zone,
"decided_by" text,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "import_job" (
"id" text PRIMARY KEY NOT NULL,
"catalog_id" text NOT NULL,
"grant_id" text NOT NULL,
"imvu_product" bigint NOT NULL,
"kind" text NOT NULL,
"status" text DEFAULT 'queued' NOT NULL,
"imvu_revision" integer,
"reason" text DEFAULT '' NOT NULL,
"attempts" integer DEFAULT 0 NOT NULL,
"claimed_at" timestamp with time zone,
"next_at" timestamp with time zone DEFAULT now() NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "import_request" (
"user_id" text NOT NULL,
"imvu_creator" bigint NOT NULL,
"imvu_product" bigint NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"fulfilled_at" timestamp with time zone,
CONSTRAINT "import_request_user_id_imvu_creator_imvu_product_pk" PRIMARY KEY("user_id","imvu_creator","imvu_product")
);
--> statement-breakpoint
CREATE TABLE "imvu_product_info" (
"id" bigint PRIMARY KEY NOT NULL,
"found" boolean NOT NULL,
"name" text DEFAULT '' NOT NULL,
"creator_id" bigint DEFAULT 0 NOT NULL,
"creator_name" text DEFAULT '' NOT NULL,
"rating" text DEFAULT 'general' NOT NULL,
"purchasable" boolean DEFAULT true NOT NULL,
"checked_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "catalog" ADD COLUMN "importer" text DEFAULT 'off' NOT NULL;--> statement-breakpoint
ALTER TABLE "catalog" ADD COLUMN "importer_key_hash" text;--> statement-breakpoint
ALTER TABLE "product" ADD COLUMN "imvu_product" bigint;--> statement-breakpoint
ALTER TABLE "product_revision" ADD COLUMN "imvu_revision" integer;--> statement-breakpoint
ALTER TABLE "import_grant" ADD CONSTRAINT "import_grant_catalog_id_catalog_id_fk" FOREIGN KEY ("catalog_id") REFERENCES "public"."catalog"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "import_grant" ADD CONSTRAINT "import_grant_creator_id_user_id_fk" FOREIGN KEY ("creator_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "import_grant" ADD CONSTRAINT "import_grant_recorded_by_user_id_fk" FOREIGN KEY ("recorded_by") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "import_grant" ADD CONSTRAINT "import_grant_decided_by_user_id_fk" FOREIGN KEY ("decided_by") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "import_job" ADD CONSTRAINT "import_job_catalog_id_catalog_id_fk" FOREIGN KEY ("catalog_id") REFERENCES "public"."catalog"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "import_job" ADD CONSTRAINT "import_job_grant_id_import_grant_id_fk" FOREIGN KEY ("grant_id") REFERENCES "public"."import_grant"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "import_request" ADD CONSTRAINT "import_request_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "import_grant_catalog" ON "import_grant" USING btree ("catalog_id","status");--> statement-breakpoint
CREATE INDEX "import_grant_imvu" ON "import_grant" USING btree ("imvu_id","status");--> statement-breakpoint
CREATE INDEX "import_job_queue" ON "import_job" USING btree ("catalog_id","status","next_at");--> statement-breakpoint
CREATE UNIQUE INDEX "import_job_open" ON "import_job" USING btree ("catalog_id","imvu_product") WHERE "import_job"."status" in ('queued', 'claimed');--> statement-breakpoint
CREATE INDEX "import_request_creator" ON "import_request" USING btree ("imvu_creator");--> statement-breakpoint
CREATE INDEX "import_request_product" ON "import_request" USING btree ("imvu_product");--> statement-breakpoint
CREATE UNIQUE INDEX "product_imvu_product" ON "product" USING btree ("imvu_product");
File diff suppressed because it is too large. Load diff
+7
View File
@@ -113,6 +113,13 @@
"when": 1793934143730,
"tag": "0015_two_factor",
"breakpoints": true
},
{
"idx": 16,
"version": "7",
"when": 1793935614967,
"tag": "0016_imports",
"breakpoints": true
}
]
}
+103
View File
@@ -289,6 +289,9 @@ export const catalog = pgTable(
uploads: text("uploads").notNull().default("anyone"), // who may upload: "anyone", "members", "team"
mirrors: text("mirrors").notNull().default("approve"), // mirroring others' revisions: "auto", "approve", "off"
keyHash: text("key_hash").notNull(), // sha256 of its key, hex
// Imports (docs/imports.md): "off", "on" or "paused" (the hub hands its importer no jobs); the importer's key.
importer: text("importer").notNull().default("off"),
importerKeyHash: text("importer_key_hash"), // sha256, hex
createdAt: createdAt(),
updatedAt: updatedAt(),
},
@@ -393,10 +396,13 @@ export const product = pgTable(
// Removed by moderation: gone everywhere (no page, no files, out of libraries and rooms).
removedAt: timestamp("removed_at", { withTimezone: true }),
removedReason: text("removed_reason"),
// Imported from IMVU (docs/imports.md): the IMVU product, one hub product each.
imvuProduct: bigint("imvu_product", { mode: "number" }),
createdAt: createdAt(),
updatedAt: updatedAt(),
},
(t) => [
uniqueIndex("product_imvu_product").on(t.imvuProduct),
index("product_creator").on(t.creatorId),
index("product_created").on(t.createdAt),
index("product_tags").using("gin", t.tags),
@@ -440,6 +446,7 @@ export const productRevision = pgTable(
token: text("token").notNull(), // the hub's t5de-revision token
uploadedBy: text("uploaded_by").references(() => user.id, { onDelete: "set null" }),
retracted: boolean("retracted").notNull().default(false),
imvuRevision: integer("imvu_revision"), // imported: the IMVU revision it came from
createdAt: createdAt(),
},
(t) => [primaryKey({ columns: [t.productId, t.number] }), index("product_revision_files").using("gin", t.files)],
@@ -708,3 +715,99 @@ export const apiToken = pgTable(
},
(t) => [uniqueIndex("api_token_hash").on(t.hash), index("api_token_user").on(t.userId)],
);
// ---- imports (docs/imports.md) ----
// A creator's consent for one catalog to import their IMVU products: the whole shop (less exclusions) or listed ones.
export const importGrant = pgTable(
"import_grant",
{
id: text("id").primaryKey(),
catalogId: text("catalog_id")
.notNull()
.references(() => catalog.id, { onDelete: "cascade" }),
creatorId: text("creator_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
imvuId: bigint("imvu_id", { mode: "number" }).notNull(), // the IMVU account whose products these are
scope: text("scope").notNull(), // "shop", "products"
products: jsonb("products").$type<number[]>().notNull().default([]), // scope "products": the IMVU product IDs
exclude: jsonb("exclude").$type<number[]>().notNull().default([]), // scope "shop": left out
listed: boolean("listed").notNull().default(true), // imported products are listed
consentVersion: integer("consent_version").notNull(),
consentedAt: timestamp("consented_at", { withTimezone: true }).notNull().defaultNow(),
consentKind: text("consent_kind").notNull().default("verified"), // "verified" (the creator), "recorded" (an admin)
evidence: text("evidence").notNull().default(""), // recorded: how they agreed
recordedBy: text("recorded_by").references(() => user.id, { onDelete: "set null" }),
// "pending" (the catalog's team hasn't accepted), "active", "declined", "suspended", "withdrawn".
status: text("status").notNull().default("pending"),
statusReason: text("status_reason").notNull().default(""),
decidedAt: timestamp("decided_at", { withTimezone: true }),
decidedBy: text("decided_by").references(() => user.id, { onDelete: "set null" }),
createdAt: createdAt(),
updatedAt: updatedAt(),
},
(t) => [index("import_grant_catalog").on(t.catalogId, t.status), index("import_grant_imvu").on(t.imvuId, t.status)],
);
// Someone asking for an IMVU product (or, with imvuProduct 0, a creator's whole shop) on T5DE. One per person and target.
export const importRequest = pgTable(
"import_request",
{
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
imvuCreator: bigint("imvu_creator", { mode: "number" }).notNull(),
imvuProduct: bigint("imvu_product", { mode: "number" }).notNull(), // 0: the whole shop
createdAt: createdAt(),
fulfilledAt: timestamp("fulfilled_at", { withTimezone: true }), // the product reached their library
},
(t) => [
primaryKey({ columns: [t.userId, t.imvuCreator, t.imvuProduct] }),
index("import_request_creator").on(t.imvuCreator),
index("import_request_product").on(t.imvuProduct),
],
);
// One product for a catalog's importer to import or re-check.
export const importJob = pgTable(
"import_job",
{
id: text("id").primaryKey(),
catalogId: text("catalog_id")
.notNull()
.references(() => catalog.id, { onDelete: "cascade" }),
grantId: text("grant_id")
.notNull()
.references(() => importGrant.id, { onDelete: "cascade" }),
imvuProduct: bigint("imvu_product", { mode: "number" }).notNull(),
kind: text("kind").notNull(), // "import", "recheck"
status: text("status").notNull().default("queued"), // "queued", "claimed", "done", "failed"
imvuRevision: integer("imvu_revision"), // done: the revision imported (or found unchanged)
reason: text("reason").notNull().default(""), // why it failed (last attempt)
attempts: integer("attempts").notNull().default(0),
claimedAt: timestamp("claimed_at", { withTimezone: true }),
nextAt: timestamp("next_at", { withTimezone: true }).notNull().defaultNow(), // queued: not before
createdAt: createdAt(),
updatedAt: updatedAt(),
},
(t) => [
index("import_job_queue").on(t.catalogId, t.status, t.nextAt),
// One open job per product and catalog.
uniqueIndex("import_job_open")
.on(t.catalogId, t.imvuProduct)
.where(sql`${t.status} in ('queued', 'claimed')`),
],
);
// IMVU products' public info, as imports and requests need it (looked up again after a day).
export const imvuProductInfo = pgTable("imvu_product_info", {
id: bigint("id", { mode: "number" }).primaryKey(),
found: boolean("found").notNull(), // IMVU shows it publicly
name: text("name").notNull().default(""),
creatorId: bigint("creator_id", { mode: "number" }).notNull().default(0),
creatorName: text("creator_name").notNull().default(""),
rating: text("rating").notNull().default("general"), // "general", "adult" (IMVU's AP)
purchasable: boolean("purchasable").notNull().default(true),
checkedAt: timestamp("checked_at", { withTimezone: true }).notNull().defaultNow(),
});