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"];