feat: importer IMVU accounts and settings from the console
Pull request / title (pull_request) Successful in 2s
CI / test (pull_request) Successful in 1m18s
CI / image (apps/api/Dockerfile, t5de-hub-api) (pull_request) Skipped
CI / image (apps/web/Dockerfile, t5de-hub-web) (pull_request) Skipped

The importer sends its RSA public key (POST /importer/hello); the console
looks IMVU accounts up, confirms them in a dialog, and seals each password
in the browser for that key. The hub keeps only the sealed copy, until the
importer confirms it has it. Accounts are tried in order; settings (rate,
jobs at once) come from the console too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
dhkatzandClaude Opus 5.5 committed 2026-11-07 10:01:11 -08:00
1 parent d716aabbd2
commit dcc39d82ab
16 files changed
+5505 -9

No files matched your search

+143 -2
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 { fingerprint as keyFingerprint, Importers, maxAccounts, settingsBounds, type ImporterAccount } from "./importer";
import { consent, Imports, type Grant } from "./imports";
import { availableTo, BlockedUpload, ProductError, Products, type EditRights, type ProductViewer } from "./products";
import {
@@ -199,6 +200,7 @@ export function createApp({
const cases = new Cases(db, perms);
const blocks = new Blocks(db);
const imports = new Imports(db, signer, imvu);
const importers = new Importers(db);
const notifications = new Notifications(db, (userId, message) => realtime.notify(userId, message));
/** Tells a product's creator that someone else changed it. */
@@ -376,6 +378,18 @@ export function createApp({
}
};
const importerAccountView = (a: ImporterAccount) => ({
id: a.id,
imvuId: a.imvuId,
username: a.username,
state: a.state as "waiting" | "received" | "ok" | "sign_in_failed" | "needs_password",
stateMessage: a.stateMessage,
stateAt: a.stateAt.toISOString(),
accessPass: a.accessPass,
ageVerified: a.ageVerified,
createdAt: a.createdAt.toISOString(),
});
const grantView = (r: { grant: Grant; catalogName?: string | null; imvuName?: string | null }) => ({
id: r.grant.id,
catalog: r.grant.catalogId,
@@ -1933,6 +1947,43 @@ export function createApp({
},
)
// The importer program's setup (docs/imports.md "IMVU accounts"): its key, its config, its accounts' states.
.post(
"/importer/hello",
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.");
const r = await productCall(() => importers.hello(c, body.version, body.publicKey));
if (r.changed) await audited(null, "catalog.importer_hello", c.id, { version: body.version, fingerprint: keyFingerprint(body.publicKey) });
const [fresh] = await db.select().from(catalog).where(eq(catalog.id, c.id));
return importers.config(fresh!);
},
{ body: t.Object({ version: t.String({ maxLength: 40 }), publicKey: t.String({ maxLength: 1200 }) }) },
)
.get("/importer/config", async ({ request }) => {
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 importers.config(c);
})
.post(
"/importer/accounts/: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 a = await productCall(() => importers.report(c, params.id, body));
return { account: importerAccountView(a) };
},
{
params: t.Object({ id: t.String({ maxLength: 20 }) }),
body: t.Object({
received: t.Optional(t.Boolean()),
state: t.Optional(t.Union([t.Literal("ok"), t.Literal("sign_in_failed"), t.Literal("needs_password")])),
accessPass: t.Optional(t.Boolean()),
message: t.Optional(t.String({ maxLength: 300 })),
}),
},
)
// 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 })
@@ -2080,13 +2131,25 @@ export function createApp({
})
.from(schema.importJob)
.where(eq(schema.importJob.catalogId, c.id));
const run = await perms.can(me, "import:run", scope);
return {
importer: c.importer as "off" | "on" | "paused",
program: {
version: c.importerVersion,
seenAt: c.importerSeenAt?.toISOString() ?? null,
fingerprint: c.importerFingerprint,
// Passwords are sealed for this key in the browser; only those who may add accounts get it.
publicKey: run ? c.importerPublicKey : null,
},
settings: c.importerSettings,
settingsBounds,
maxAccounts,
accounts: (await importers.accounts(c.id)).map(importerAccountView),
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),
run,
pause: await perms.can(me, "import:pause", scope),
accept: await perms.can(me, "import:accept", scope),
withdraw: await perms.can(me, "import:withdraw", scope),
@@ -2132,6 +2195,84 @@ export function createApp({
},
{ scripted: true, params: catalogParam },
)
.get(
"/catalogs/:id/importer/imvu-account",
async ({ me, params, query }) => {
await need(me, "import:run", catalogScope(params.id));
const u = await imvuCall(me, () => imvu.byUsername(query.username));
return { imvuId: u.id, username: u.username, picture: u.picture, accessPass: u.accessPass, ageVerified: u.ageVerified };
},
{ signedIn: true, params: catalogParam, query: t.Object({ username: t.String({ minLength: 1, maxLength: 64 }) }) },
)
.post(
"/catalogs/:id/importer/accounts",
async ({ me, params, body, set }) => {
await need(me, "import:run", catalogScope(params.id));
const u = await imvuCall(me, () => imvu.byId(body.imvuId));
const a = await productCall(() =>
importers.addAccount(
params.id,
{ imvuId: u.id, username: u.username, accessPass: u.accessPass, ageVerified: u.ageVerified, sealed: body.sealed, fingerprint: body.fingerprint },
me.id,
),
);
await audited(me, "catalog.importer_account", params.id, { change: "add", imvuId: a.imvuId, username: a.username });
set.status = 201;
return { account: importerAccountView(a) };
},
{
scripted: true,
params: catalogParam,
body: t.Object({ imvuId: t.Integer({ minimum: 1 }), sealed: t.String({ maxLength: 1000 }), fingerprint: t.String({ maxLength: 64 }) }),
},
)
.put(
"/catalogs/:id/importer/accounts/:account/password",
async ({ me, params, body }) => {
await need(me, "import:run", catalogScope(params.id));
const a = await productCall(() => importers.setPassword(params.id, params.account, body.sealed, body.fingerprint));
await audited(me, "catalog.importer_account", params.id, { change: "password", imvuId: a.imvuId, username: a.username });
return { account: importerAccountView(a) };
},
{
scripted: true,
params: t.Object({ id: t.String({ pattern: "^[a-z2-7]{10}$" }), account: t.String({ maxLength: 20 }) }),
body: t.Object({ sealed: t.String({ maxLength: 1000 }), fingerprint: t.String({ maxLength: 64 }) }),
},
)
.post(
"/catalogs/:id/importer/accounts/:account/move",
async ({ me, params, body }) => {
await need(me, "import:run", catalogScope(params.id));
await productCall(() => importers.moveAccount(params.id, params.account, body.direction));
return { accounts: (await importers.accounts(params.id)).map(importerAccountView) };
},
{
scripted: true,
params: t.Object({ id: t.String({ pattern: "^[a-z2-7]{10}$" }), account: t.String({ maxLength: 20 }) }),
body: t.Object({ direction: t.Union([t.Literal("up"), t.Literal("down")]) }),
},
)
.delete(
"/catalogs/:id/importer/accounts/:account",
async ({ me, params, set }) => {
await need(me, "import:run", catalogScope(params.id));
const a = await productCall(() => importers.removeAccount(params.id, params.account));
await audited(me, "catalog.importer_account", params.id, { change: "remove", imvuId: a.imvuId, username: a.username });
set.status = 204;
},
{ scripted: true, params: t.Object({ id: t.String({ pattern: "^[a-z2-7]{10}$" }), account: t.String({ maxLength: 20 }) }) },
)
.post(
"/catalogs/:id/importer/settings",
async ({ me, params, body }) => {
await need(me, "import:run", catalogScope(params.id));
const settings = await productCall(() => importers.setSettings(params.id, body));
await audited(me, "catalog.importer_settings", params.id, settings);
return { settings };
},
{ scripted: true, params: catalogParam, body: t.Object({ rate: t.Number(), concurrency: t.Integer() }) },
)
.post(
"/catalogs/:id/importer/jobs/:job/retry",
async ({ me, params }) => {
@@ -3260,7 +3401,7 @@ export function createApp({
.get("/health", () => ({ ok: true }))
.use(api);
return { app, realtime, age, rooms, products, signer, hosted, decorations, imports };
return { app, realtime, age, rooms, products, signer, hosted, decorations, imports, importers };
}
export type App = ReturnType<typeof createApp>["app"];
+215
View File
@@ -0,0 +1,215 @@
// A catalog's importer program and the IMVU accounts it signs in with (docs/imports.md "IMVU accounts"). The importer
// sends its RSA public key; the console seals each account's password in the browser for that key; the hub keeps the
// sealed copy only until the importer has it. Everything but what the importer needs to reach the hub is set here,
// from the console. The routes are in app.ts.
import { createHash, createPublicKey } from "node:crypto";
import { and, asc, eq, lt, sql, schema, type Database, type ImporterSettings } from "@t5de/db";
import { newProductID, ProductError, type Catalog } from "./products";
const { catalog, importerAccount } = schema;
export type ImporterAccount = typeof importerAccount.$inferSelect;
export type AccountState = "waiting" | "received" | "ok" | "sign_in_failed" | "needs_password";
/** A sealed password the importer hasn't fetched within this long is dropped. */
export const sealedFor = 7 * 24 * 60 * 60 * 1000;
/** Accounts a catalog's importer may have. */
export const maxAccounts = 10;
/** Settings' bounds. */
export const settingsBounds = { rate: { min: 0.2, max: 10 }, concurrency: { min: 1, max: 8 } } as const;
/** sha256 of the key's SPKI, hex: what the console shows (shortened) and seals are checked against. */
export const fingerprint = (spkiBase64: string) => createHash("sha256").update(Buffer.from(spkiBase64, "base64")).digest("hex");
/** Checks an importer's public key: base64 SPKI of an RSA key of 3072 to 4096 bits. */
function checkPublicKey(spki: string) {
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(spki)) throw new ProductError(400, "invalid", "The public key isn't base64.");
let bits: number | undefined;
try {
const key = createPublicKey({ key: Buffer.from(spki, "base64"), format: "der", type: "spki" });
if (key.asymmetricKeyType !== "rsa") throw new Error("not RSA");
bits = key.asymmetricKeyDetails?.modulusLength;
} catch {
throw new ProductError(400, "invalid", "The public key isn't an RSA key (SPKI).");
}
if (!bits || bits < 3072 || bits > 4096) throw new ProductError(400, "invalid", "The public key must be RSA with 3072 to 4096 bits.");
}
/** Checks a sealed password: base64 of one RSA-OAEP block (384 or 512 bytes). */
function checkSealed(sealed: string) {
const bytes = /^[A-Za-z0-9+/]+={0,2}$/.test(sealed) ? Buffer.from(sealed, "base64").length : 0;
if (bytes !== 384 && bytes !== 512) throw new ProductError(400, "invalid", "That isn't a sealed password.");
}
export class Importers {
constructor(private readonly db: Database) {}
private async catalogOf(catalogId: string): Promise<Catalog> {
const [c] = await this.db.select().from(catalog).where(eq(catalog.id, catalogId));
if (!c) throw new ProductError(404, "not_found", "No such catalog.");
return c;
}
// ---- the importer program ----
/**
* The importer says hello: its version and public key. A new key (a new install) can't read passwords sealed for
* the old one, so those accounts need their passwords again.
*/
async hello(c: Catalog, version: string, publicKey: string): Promise<{ changed: boolean }> {
checkPublicKey(publicKey);
const print = fingerprint(publicKey);
const changed = c.importerFingerprint !== print;
await this.db.transaction(async (tx) => {
await tx
.update(catalog)
.set({ importerPublicKey: publicKey, importerFingerprint: print, importerVersion: version, importerSeenAt: new Date() })
.where(eq(catalog.id, c.id));
if (changed && c.importerFingerprint)
await tx
.update(importerAccount)
.set({ sealed: null, sealedFor: null, sealedAt: null, state: "needs_password", stateMessage: "The importer's key changed.", stateAt: new Date() })
.where(eq(importerAccount.catalogId, c.id));
});
return { changed };
}
/** What the importer runs with: paused or not, its settings, and its accounts in order (sealed passwords too). */
async config(c: Catalog) {
await this.db.update(catalog).set({ importerSeenAt: new Date() }).where(eq(catalog.id, c.id));
const accounts = await this.accounts(c.id);
return {
paused: c.importer === "paused",
settings: c.importerSettings,
fingerprint: c.importerFingerprint,
accounts: accounts.map((a) => ({
id: a.id,
imvuId: a.imvuId,
username: a.username,
// Only a password sealed for the key the importer has now.
sealed: a.sealed && a.sealedFor === c.importerFingerprint ? a.sealed : null,
})),
};
}
/** The importer reports on an account: it has the sealed password, and how signing in went. */
async report(c: Catalog, id: string, r: { received?: boolean; state?: "ok" | "sign_in_failed" | "needs_password"; accessPass?: boolean; message?: string }) {
const [a] = await this.db
.select()
.from(importerAccount)
.where(and(eq(importerAccount.id, id), eq(importerAccount.catalogId, c.id)));
if (!a) throw new ProductError(404, "not_found", "No such account.");
const set: Partial<ImporterAccount> = {};
if (r.received && a.sealed) Object.assign(set, { sealed: null, sealedFor: null, sealedAt: null, state: "received", stateMessage: "", stateAt: new Date() });
if (r.state) Object.assign(set, { state: r.state, stateMessage: (r.message ?? "").slice(0, 300), stateAt: new Date() });
if (r.accessPass !== undefined) set.accessPass = r.accessPass;
if (Object.keys(set).length === 0) return a;
const [updated] = await this.db.update(importerAccount).set(set).where(eq(importerAccount.id, a.id)).returning();
return updated!;
}
// ---- the console ----
async accounts(catalogId: string): Promise<ImporterAccount[]> {
return this.db
.select()
.from(importerAccount)
.where(eq(importerAccount.catalogId, catalogId))
.orderBy(asc(importerAccount.position), asc(importerAccount.createdAt));
}
/** Adds an account, its password sealed for the importer's key (which must be the one the console showed). */
async addAccount(
catalogId: string,
a: { imvuId: number; username: string; accessPass: boolean; ageVerified: boolean; sealed: string; fingerprint: string },
byId: string,
): Promise<ImporterAccount> {
const c = await this.catalogOf(catalogId);
this.checkSeal(c, a.sealed, a.fingerprint);
const existing = await this.accounts(c.id);
if (existing.some((x) => x.imvuId === a.imvuId))
throw new ProductError(409, "exists", "The importer has that account already: enter its password again instead.");
if (existing.length >= maxAccounts) throw new ProductError(409, "too_many", `An importer can have at most ${maxAccounts} accounts.`);
const [row] = await this.db
.insert(importerAccount)
.values({
id: newProductID(),
catalogId: c.id,
imvuId: a.imvuId,
username: a.username,
position: existing.length ? Math.max(...existing.map((x) => x.position)) + 1 : 0,
sealed: a.sealed,
sealedFor: a.fingerprint,
sealedAt: new Date(),
accessPass: a.accessPass,
ageVerified: a.ageVerified,
addedBy: byId,
})
.returning();
return row!;
}
/** A new password for an account. */
async setPassword(catalogId: string, id: string, sealed: string, print: string): Promise<ImporterAccount> {
const c = await this.catalogOf(catalogId);
this.checkSeal(c, sealed, print);
const [row] = await this.db
.update(importerAccount)
.set({ sealed, sealedFor: print, sealedAt: new Date(), state: "waiting", stateMessage: "", stateAt: new Date() })
.where(and(eq(importerAccount.id, id), eq(importerAccount.catalogId, c.id)))
.returning();
if (!row) throw new ProductError(404, "not_found", "No such account.");
return row;
}
private checkSeal(c: Catalog, sealed: string, print: string) {
if (!c.importerFingerprint) throw new ProductError(409, "no_importer", "Start the importer first: passwords are sealed for its key.");
if (print !== c.importerFingerprint)
throw new ProductError(409, "importer_key_changed", "The importer's key changed since this page was loaded. Load it again and retry.");
checkSealed(sealed);
}
/** Removes an account; the importer forgets it on its next look at its config. */
async removeAccount(catalogId: string, id: string): Promise<ImporterAccount> {
const [row] = await this.db
.delete(importerAccount)
.where(and(eq(importerAccount.id, id), eq(importerAccount.catalogId, catalogId)))
.returning();
if (!row) throw new ProductError(404, "not_found", "No such account.");
return row;
}
/** Moves an account one place earlier or later in the order the importer tries them. */
async moveAccount(catalogId: string, id: string, direction: "up" | "down"): Promise<void> {
const list = await this.accounts(catalogId);
const i = list.findIndex((a) => a.id === id);
if (i < 0) throw new ProductError(404, "not_found", "No such account.");
const j = direction === "up" ? i - 1 : i + 1;
if (j < 0 || j >= list.length) return;
[list[i], list[j]] = [list[j]!, list[i]!];
await this.db.transaction(async (tx) => {
for (const [n, a] of list.entries()) await tx.update(importerAccount).set({ position: n }).where(eq(importerAccount.id, a.id));
});
}
async setSettings(catalogId: string, s: ImporterSettings): Promise<ImporterSettings> {
const { rate, concurrency } = settingsBounds;
if (!(s.rate >= rate.min && s.rate <= rate.max)) throw new ProductError(400, "invalid", `Requests a second: ${rate.min} to ${rate.max}.`);
if (!Number.isInteger(s.concurrency) || s.concurrency < concurrency.min || s.concurrency > concurrency.max)
throw new ProductError(400, "invalid", `Jobs at once: ${concurrency.min} to ${concurrency.max}.`);
const settings = { rate: Math.round(s.rate * 10) / 10, concurrency: s.concurrency };
const [c] = await this.db.update(catalog).set({ importerSettings: settings }).where(eq(catalog.id, catalogId)).returning();
if (!c) throw new ProductError(404, "not_found", "No such catalog.");
return c.importerSettings;
}
/** Drops sealed passwords no importer fetched in time; their accounts need their passwords again. */
async expireSealed(): Promise<number> {
const rows = await this.db
.update(importerAccount)
.set({ sealed: null, sealedFor: null, sealedAt: null, state: "needs_password", stateMessage: "The importer didn't fetch the password within 7 days.", stateAt: new Date() })
.where(and(sql`${importerAccount.sealed} is not null`, lt(importerAccount.sealedAt, new Date(Date.now() - sealedFor))))
.returning({ id: importerAccount.id });
return rows.length;
}
}
+8 -2
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, imports } = createApp({ db, auth, imvu, age: ageService, apiURL, webURL, settings });
const { app, age, rooms, products, imports, importers } = 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
@@ -90,5 +90,11 @@ const importRecheck = () =>
.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);
setInterval(() => {
importRecheck();
importers
.expireSealed()
.then((n) => n && console.log(`imports: ${n} sealed importer passwords expired`))
.catch((e) => console.error("importer passwords:", e));
}, 60 * 60 * 1000);
console.log(`t5de-hub API on ${apiURL} (website ${webURL})`);