feat: importer IMVU accounts and settings from the console
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:
1 parent
d716aabbd2
commit
dcc39d82ab
16 files changed
+5505
-9
No files matched your search
+143
-2
@@ -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"];
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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})`);
|
||||
@@ -56,6 +56,7 @@ afterAll(async () => {
|
||||
});
|
||||
|
||||
type Person = { cookie: string; name: string };
|
||||
let rootAdmin: Person; // the first person: an admin
|
||||
async function call(p: Person | undefined, method: string, path: string, body?: unknown, headers: Record<string, string> = {}) {
|
||||
const res = await fetch(base + path, {
|
||||
method,
|
||||
@@ -95,6 +96,7 @@ const imvuProduct = (name: string, creator: number, rating = "GA") => ({ product
|
||||
|
||||
test("grants, requests, the importer's jobs, and withdrawal", async () => {
|
||||
const admin = await person("root");
|
||||
rootAdmin = admin;
|
||||
const owner = await person("shelf");
|
||||
const maker = await person("maker", 501);
|
||||
const fan = await person("fan");
|
||||
@@ -217,3 +219,98 @@ test("IMVU's 401 keeps what was last seen; 404 is gone", async () => {
|
||||
imvuProducts.delete(9500);
|
||||
expect(await imports.info(9500, true)).toBeUndefined();
|
||||
});
|
||||
|
||||
test("the importer's key, IMVU accounts with sealed passwords, and settings", async () => {
|
||||
const admin = rootAdmin;
|
||||
const owner = await person("keeper");
|
||||
const outsider = await person("outsider");
|
||||
accounts.set(601, { id: 601, username: "ImportBot", tagline: "", ageVerified: true, accessPass: true, picture: null });
|
||||
accounts.set(602, { id: 602, username: "SpareBot", tagline: "", ageVerified: false, accessPass: false, picture: null });
|
||||
|
||||
const reg = await call(owner, "POST", "/api/v1/catalogs", { name: "Keeper Shelf", url: "https://keeper.example.test", contact: "[email protected]", visibility: "public", membership: "open" });
|
||||
const catalogID = reg.json.catalog.id as string;
|
||||
expect((await call(admin, "POST", `/api/v1/console/catalogs/${catalogID}/approve`)).status).toBe(200);
|
||||
const on = await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer`, { enabled: true });
|
||||
const importer = { Authorization: `Importer ${catalogID}:${on.json.key}` };
|
||||
const page = async () => (await call(owner, "GET", `/api/v1/catalogs/${catalogID}/importer`)).json;
|
||||
|
||||
// Before the importer has said hello there's no key to seal for.
|
||||
expect((await page()).program).toMatchObject({ version: "", seenAt: null, fingerprint: null, publicKey: null });
|
||||
const keys = async () => {
|
||||
const pair = (await crypto.subtle.generateKey(
|
||||
{ name: "RSA-OAEP", modulusLength: 3072, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" },
|
||||
true,
|
||||
["encrypt", "decrypt"],
|
||||
)) as CryptoKeyPair;
|
||||
return { pair, spki: Buffer.from(await crypto.subtle.exportKey("spki", pair.publicKey)).toString("base64") };
|
||||
};
|
||||
// As the console's browser does: the account's ID and password, sealed for the importer's key.
|
||||
const seal = async (spki: string, imvuId: number, password: string) => {
|
||||
const key = await crypto.subtle.importKey("spki", Buffer.from(spki, "base64"), { name: "RSA-OAEP", hash: "SHA-256" }, false, ["encrypt"]);
|
||||
const data = new TextEncoder().encode(JSON.stringify({ imvuId, password }));
|
||||
return Buffer.from(await crypto.subtle.encrypt({ name: "RSA-OAEP" }, key, data)).toString("base64");
|
||||
};
|
||||
const unseal = async (pair: CryptoKeyPair, sealed: string) =>
|
||||
JSON.parse(new TextDecoder().decode(await crypto.subtle.decrypt({ name: "RSA-OAEP" }, pair.privateKey, Buffer.from(sealed, "base64"))));
|
||||
|
||||
const k1 = await keys();
|
||||
expect((await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer/accounts`, { imvuId: 601, sealed: await seal(k1.spki, 601, "x"), fingerprint: "00" })).json.error).toBe("no_importer");
|
||||
expect((await call(undefined, "POST", "/api/v1/importer/hello", { version: "0.1.0", publicKey: "not a key" }, importer)).status).toBe(400);
|
||||
const hello = await call(undefined, "POST", "/api/v1/importer/hello", { version: "0.1.0", publicKey: k1.spki }, importer);
|
||||
expect(hello.status).toBe(200);
|
||||
expect(hello.json).toMatchObject({ paused: false, settings: { rate: 2, concurrency: 2 }, accounts: [] });
|
||||
const shown = (await page()).program;
|
||||
expect(shown).toMatchObject({ version: "0.1.0", publicKey: k1.spki });
|
||||
expect(shown.fingerprint).toBe(hello.json.fingerprint);
|
||||
expect(shown.seenAt).not.toBeNull();
|
||||
|
||||
// The console looks the account up, then adds it with the password sealed for that key.
|
||||
expect((await call(outsider, "GET", `/api/v1/catalogs/${catalogID}/importer/imvu-account?username=ImportBot`)).status).toBe(403);
|
||||
const found = (await call(owner, "GET", `/api/v1/catalogs/${catalogID}/importer/imvu-account?username=ImportBot`)).json;
|
||||
expect(found).toMatchObject({ imvuId: 601, username: "ImportBot", accessPass: true, ageVerified: true });
|
||||
const add = (imvuId: number, sealed: string, fingerprint = shown.fingerprint) =>
|
||||
call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer/accounts`, { imvuId, sealed, fingerprint });
|
||||
expect((await add(601, "bm90IHNlYWxlZA==")).json.error).toBe("invalid");
|
||||
expect((await add(601, await seal(k1.spki, 601, "pw1"), "ff".repeat(32))).json.error).toBe("importer_key_changed");
|
||||
const added = await add(601, await seal(k1.spki, 601, "pw1"));
|
||||
expect(added.status).toBe(201);
|
||||
expect(added.json.account).toMatchObject({ username: "ImportBot", state: "waiting", accessPass: true });
|
||||
expect((await add(601, await seal(k1.spki, 601, "pw1"))).json.error).toBe("exists");
|
||||
expect((await add(602, await seal(k1.spki, 602, "pw2"))).status).toBe(201);
|
||||
|
||||
// The importer gets the sealed passwords, in order, and can read them; the hub drops each once it has it.
|
||||
const config = (await call(undefined, "GET", "/api/v1/importer/config", undefined, importer)).json;
|
||||
expect(config.accounts.map((a: any) => a.username)).toEqual(["ImportBot", "SpareBot"]);
|
||||
expect(await unseal(k1.pair, config.accounts[0].sealed)).toEqual({ imvuId: 601, password: "pw1" });
|
||||
const first = config.accounts[0].id as string;
|
||||
expect((await call(undefined, "POST", `/api/v1/importer/accounts/${first}`, { received: true }, importer)).json.account.state).toBe("received");
|
||||
expect((await call(undefined, "GET", "/api/v1/importer/config", undefined, importer)).json.accounts[0].sealed).toBeNull();
|
||||
await call(undefined, "POST", `/api/v1/importer/accounts/${first}`, { state: "ok", accessPass: true }, importer);
|
||||
expect((await call(undefined, "POST", `/api/v1/importer/accounts/${first}`, { state: "ok" }, { Authorization: `Importer ${catalogID}:wrong` })).status).toBe(401);
|
||||
|
||||
// The order can change; settings are bounded.
|
||||
await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer/accounts/${first}/move`, { direction: "down" });
|
||||
expect((await page()).accounts.map((a: any) => [a.username, a.state])).toEqual([["SpareBot", "waiting"], ["ImportBot", "ok"]]);
|
||||
expect((await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer/settings`, { rate: 50, concurrency: 2 })).status).toBe(400);
|
||||
expect((await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer/settings`, { rate: 0.5, concurrency: 4 })).json.settings).toEqual({ rate: 0.5, concurrency: 4 });
|
||||
expect((await call(undefined, "GET", "/api/v1/importer/config", undefined, importer)).json.settings).toEqual({ rate: 0.5, concurrency: 4 });
|
||||
|
||||
// A new install (a new key) can't read the old seals: every account needs its password again.
|
||||
const k2 = await keys();
|
||||
expect((await call(undefined, "POST", "/api/v1/importer/hello", { version: "0.1.1", publicKey: k2.spki }, importer)).json.accounts.every((a: any) => a.sealed === null)).toBe(true);
|
||||
const after = await page();
|
||||
expect(after.accounts.map((a: any) => a.state)).toEqual(["needs_password", "needs_password"]);
|
||||
const spare = after.accounts[0].id as string;
|
||||
const again = await call(owner, "PUT", `/api/v1/catalogs/${catalogID}/importer/accounts/${spare}/password`, { sealed: await seal(k2.spki, 602, "pw3"), fingerprint: after.program.fingerprint });
|
||||
expect(again.json.account.state).toBe("waiting");
|
||||
const sealed = (await call(undefined, "GET", "/api/v1/importer/config", undefined, importer)).json.accounts[0].sealed;
|
||||
expect(await unseal(k2.pair, sealed)).toEqual({ imvuId: 602, password: "pw3" });
|
||||
|
||||
// Removed accounts leave the importer's config; it's all audited.
|
||||
expect((await call(owner, "DELETE", `/api/v1/catalogs/${catalogID}/importer/accounts/${spare}`)).status).toBe(204);
|
||||
expect((await call(undefined, "GET", "/api/v1/importer/config", undefined, importer)).json.accounts.map((a: any) => a.username)).toEqual(["ImportBot"]);
|
||||
const actions = (await call(owner, "GET", "/api/v1/console/audit")).json.entries.map((e: any) => e.action);
|
||||
expect(actions).toEqual(expect.arrayContaining(["catalog.importer_hello", "catalog.importer_account", "catalog.importer_settings"]));
|
||||
// Passwords never show on the console.
|
||||
expect(JSON.stringify(await page())).not.toContain(sealed);
|
||||
});
|
||||
Reference in new issue
Block a user