Files
t5de-hub/apps/api/src/app.ts
T
dhkatzandClaude Opus 5.5 dcc39d82ab
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
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]>
2026-11-07 10:01:11 -08:00

3408 lines
147 KiB
TypeScript

// The hub's API: Better Auth at /api/auth, the hub's own routes at /api/v1. The website calls it through its own
// origin (Next.js rewrites /api to here), so session cookies are first-party; T5DE's proxy calls it with a bearer
// token.
import { Elysia, t } from "elysia";
import {
and,
asc,
desc,
eq,
ilike,
isNull,
inArray,
ne,
or,
sql,
count,
schema,
type Database,
type AuditTags,
type ParentInfo,
type RoomModerator,
} from "@t5de/db";
import type { Auth } from "./auth";
import { AgeError, AgeRefused, AgeService } from "./age";
import { imvuAgeProvider, imvuResult } from "./age/imvu";
import { ImvuClient, ImvuUnavailable, NoSuchImvuUser } from "./imvu";
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 {
chatId,
HostedError,
HostedRooms,
instanceId,
maxImageBytes,
maxModerators,
maxPlacement,
maxSceneItems,
roomInfo,
type RoomChanges,
type Viewer,
} from "./hosted";
import { DecorationError, Decorations, maxBatch, maxDecorationPlacement, maxDecorations } from "./decorations";
import { Settings } from "./settings";
import { Catalogs } from "./catalogs";
import { appealable, caseKinds, Cases, type Case, type CaseKind } from "./cases";
import { Notifications } from "./notifications";
import { maxGrants, maxTokenDays, tokenPrefix, Tokens } from "./tokens";
import {
assignableCatalogRoles,
Forbidden,
hubScope,
Permissions,
roles as roleBundles,
sensitive,
TwoFactorRequired,
type Permission,
type Scope,
} from "./permissions";
const { user, session, imvuLink, linkChallenge, audit, hostedRoom, catalog, product, hosting } = schema;
export type Deps = {
db: Database;
auth: Auth;
imvu: ImvuClient;
realtime?: Realtime;
age?: AgeService;
rooms?: Rooms;
/** The hub's API URL, the issuer of its tokens. */
apiURL?: string;
/** The website's address: providers send people back only to it. */
webURL?: string;
/** Whether a catalog answers at an address (its /health), checked when a catalog's address changes. */
catalogHealthy?: (url: string) => Promise<boolean>;
/** The hub's settings (default: kept in the database, with no environment defaults). */
settings?: Settings;
};
/** An error shown to the person: the website displays message as is. */
export class Problem extends Error {
constructor(
readonly status: number,
readonly slug: string,
message: string,
/** More for the website, e.g. the permission that was missing. */
readonly extra: Record<string, unknown> = {},
) {
super(message);
}
}
/** A missing permission as the API answers it: 403 forbidden, naming the permission and its scope. */
const forbiddenProblem = (e: Forbidden) =>
new Problem(403, "forbidden", e.message, {
missing: { permission: e.permission, scope: e.scope.type === "hub" ? { hub: true } : { [e.scope.type]: e.scope.id } },
});
type Person = typeof user.$inferSelect;
type Link = typeof imvuLink.$inferSelect;
const roles = ["user", "moderator", "admin"] as const;
const isModerator = (p: Person) => p.role === "moderator" || p.role === "admin";
// Link codes: "t5de-" and eight letters and digits without look-alikes.
function linkCode(): string {
const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
const bytes = crypto.getRandomValues(new Uint8Array(8));
const s = [...bytes].map((b) => alphabet[b % alphabet.length]).join("");
return `t5de-${s.slice(0, 4)}-${s.slice(4)}`;
}
function randomID(bytes = 16): string {
return Buffer.from(crypto.getRandomValues(new Uint8Array(bytes))).toString("base64url");
}
const challengeLifetime = 24 * 60 * 60 * 1000;
/** Allows n attempts per key in a window (IMVU lookups, which cost IMVU a request each). */
class Limiter {
private hits = new Map<string, number[]>();
allow(key: string, n: number, windowMs: number): boolean {
const now = Date.now();
const recent = (this.hits.get(key) ?? []).filter((t) => now - t < windowMs);
if (recent.length >= n) {
this.hits.set(key, recent);
return false;
}
recent.push(now);
this.hits.set(key, recent);
if (this.hits.size > 100_000) this.hits.clear();
return true;
}
}
export function createApp({
db,
auth,
imvu,
realtime: rt,
age: ageService,
rooms: roomsService,
apiURL,
webURL,
settings: hubSettings,
catalogHealthy,
}: Deps) {
const age = ageService ?? new AgeService(db, [imvuAgeProvider(imvu)]);
const settings = hubSettings ?? new Settings(db);
const signer = new Signer(db, apiURL ?? "http://localhost:4101");
const products = new Products(db, signer, imvu);
const perms = new Permissions(db);
const tokens = new Tokens(db, perms);
const catalogs = new Catalogs(db, catalogHealthy);
const rooms = roomsService ?? new Rooms(db, imvu);
const hosted = new HostedRooms(db);
const decorations = new Decorations(db);
const apiBase = (apiURL ?? "http://localhost:4101").replace(/\/+$/, "");
const realtime =
rt ??
new Realtime({
owner: async (imvuId) => {
const [l] = await db.select({ userId: imvuLink.userId }).from(imvuLink).where(eq(imvuLink.imvuId, imvuId));
return l?.userId;
},
adult: async (userId, imvuId) => (await age.adultAccounts(userId, [imvuId])).has(imvuId),
room: (instanceId) => {
rooms.seen(instanceId).catch((e) => console.error("rooms:", e));
},
hostedRoom: (n) => hosted.info(n),
hostedBanned: (n, imvuId) => hosted.banned(n, imvuId),
hostedBoot: async (b) => {
if (b.ban) await hosted.ban(b.room, b.imvuId, b.by, b.minutes);
await audited(b.byUserId, b.ban ? "hosted_room.ban" : "hosted_room.boot", String(b.room), {
imvu: b.imvuId,
by: b.by,
...(b.ban ? { minutes: b.minutes } : {}),
});
},
accountName: async (imvuId) => {
const [l] = await db.select({ username: imvuLink.username }).from(imvuLink).where(eq(imvuLink.imvuId, imvuId));
return l?.username ?? "";
},
hostedVisit: (userId, n, imvuId) => {
hosted.visit(userId, n, imvuId).catch((e) => console.error("hosted visit:", e));
},
wearable: async (userId, ids) => {
const rows = await db
.select({ id: product.id })
.from(product)
.where(and(inArray(product.id, ids), availableTo(userId)));
return new Set(rows.map((r) => r.id));
},
});
const limiter = new Limiter();
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. */
const productEdited = async (me: Person, id: string, creatorId: string, kind: string, fields: string[], reason: string) => {
const [p] = await db.select({ name: product.name }).from(product).where(eq(product.id, id));
await notifications.add(
creatorId,
"product_edited",
{ product: id, name: p?.name ?? "", kind, fields, reason, by: me.displayUsername ?? me.username ?? "" },
{ product: id },
me.id,
);
};
const personView = (p: Person) => ({
id: p.id,
username: p.displayUsername ?? p.username ?? p.name,
email: p.email,
role: (roles as readonly string[]).includes(p.role) ? (p.role as (typeof roles)[number]) : "user",
linkCap: p.linkCap,
createdAt: p.createdAt.toISOString(),
banned: p.banned === true,
banReason: p.banReason ?? "",
approved: p.approved,
twoFactor: p.twoFactorEnabled,
});
/** A person's picture, for the website's header: their first linked IMVU account's avatar picture (null if none,
* or IMVU can't say). Kept an hour per account, so pages don't each ask IMVU. */
const pictures = new Map<number, { url: string | null; at: number }>();
const picture = async (userId: string): Promise<string | null> => {
const [first] = await db
.select({ imvuId: imvuLink.imvuId })
.from(imvuLink)
.where(eq(imvuLink.userId, userId))
.orderBy(asc(imvuLink.linkedAt))
.limit(1);
if (!first) return null;
const kept = pictures.get(first.imvuId);
if (kept && Date.now() - kept.at < 60 * 60 * 1000) return kept.url;
let url: string | null = kept?.url ?? null;
try {
url = (await imvu.byId(first.imvuId)).picture;
} catch {
// IMVU unavailable: the last known one (or none), asked again next time.
return url;
}
pictures.set(first.imvuId, { url, at: Date.now() });
return url;
};
/** Links as the website shows them: with live presence, and age by the one rule. */
const linkViews = async (userId: string, links: Link[]) => {
const ids = links.map((l) => l.imvuId);
const adult = await age.adultAccounts(userId, ids);
const imvuChecks = await age.accountChecks("imvu", ids);
const online = realtime.online();
return links.map((l) => {
const live = online.find((o) => o.imvuId === l.imvuId);
const check = imvuChecks.get(l.imvuId);
return {
imvuId: l.imvuId,
username: l.username,
linkedAt: l.linkedAt.toISOString(),
ageVerified: check?.method === "imvu_age_verified",
accessPass: check?.method === "imvu_access_pass",
adult: adult.has(l.imvuId),
checkedAt: (check?.checkedAt ?? l.linkedAt).toISOString(),
showBadge: l.showBadge,
showPresence: l.showPresence,
listRooms: l.listRooms,
online: live !== undefined,
outfit: live?.outfit ?? [],
};
});
};
const linkView = async (l: Link) => (await linkViews(l.userId, [l]))[0]!;
/** Writes an audit entry. Tags (who may see it, docs/console.md) default from the action: catalog.*, product.*
* and hosted_room.* entries are about their target. */
const audited = (
actor: string | null | { id: string; token?: { name: string } },
action: string,
target: string,
detail: Record<string, unknown> = {},
tags?: AuditTags,
) => {
const t: AuditTags = tags ?? {};
if (!tags && target) {
if (action.startsWith("catalog.")) t.catalog = target;
else if (action.startsWith("product.")) t.product = target;
else if (action.startsWith("hosted_room.")) t.room = target;
}
// Actions by API token are the person's, marked with the token's name.
const actorId = typeof actor === "object" && actor ? actor.id : actor;
const token = typeof actor === "object" && actor?.token ? actor.token.name : undefined;
return db.insert(audit).values({ actorId, action, target, detail: token ? { ...detail, token } : detail, tags: t });
};
/** Runs a check, turning a missing permission into a Problem. */
const need = async (who: Person, permission: Parameters<Permissions["require"]>[1], scope: Scope) => {
try {
await perms.require(who, permission, scope);
} catch (e) {
if (e instanceof Forbidden) throw forbiddenProblem(e);
if (e instanceof TwoFactorRequired)
throw new Problem(403, "two_factor_required", e.message, { permission: e.permission });
throw e;
}
};
/** The sensitive permissions a person holds anywhere (hub-wide, or on a catalog's team): they need two-factor
* sign-in for those. */
const sensitiveHeld = async (me: Person): Promise<Permission[]> => {
const held = new Set([...perms.hub(me)].filter((p) => sensitive.includes(p)));
for (const c of await perms.teamCatalogs(me.id))
for (const p of await perms.at(me, catalogScope(c))) if (sensitive.includes(p)) held.add(p);
return sensitive.filter((p) => held.has(p));
};
/** Who's online that viewer may see: accounts showing their presence (moderators see all). */
const visibleOnline = async (viewer: Person | undefined) => {
const online = realtime.online();
if (online.length === 0) return [];
const links = await db.select().from(imvuLink).where(inArray(imvuLink.imvuId, online.map((o) => o.imvuId)));
const mod = viewer !== undefined && isModerator(viewer);
const adult = new Set<number>();
if (mod) {
for (const l of links) if ((await age.adultAccounts(l.userId, [l.imvuId])).has(l.imvuId)) adult.add(l.imvuId);
}
return online.flatMap((o) => {
const l = links.find((l) => l.imvuId === o.imvuId);
if (!l || (!l.showPresence && !mod)) return [];
return [
{
imvuId: o.imvuId,
username: l.username,
badge: l.showBadge,
since: o.since.toISOString(),
outfit: o.outfit,
...(mod ? { hidden: !l.showPresence, personId: o.userId, adult: adult.has(o.imvuId) } : {}),
},
];
});
};
const imvuIdParam = t.Object({ imvu: t.Numeric({ minimum: 1 }) });
/** Whether any of a person's IMVU accounts counts as adult (for seeing adult products and rooms). */
const personAdult = async (p: Person | undefined) => {
if (!p) return false;
const ids = (await db.select({ id: imvuLink.imvuId }).from(imvuLink).where(eq(imvuLink.userId, p.id))).map((l) => l.id);
return ids.length > 0 && (await age.adultAccounts(p.id, ids)).size > 0;
};
/** Runs a product operation, turning its errors into Problems. */
const productCall = async <T>(f: () => Promise<T>): Promise<T> => {
try {
return await f();
} catch (e) {
if (e instanceof ProductError) throw new Problem(e.status, e.slug, e.message);
throw e;
}
};
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 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,
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,
creator?: string | null,
creatorUsername?: string | null,
latest?: { parent: number | null; parentInfo: ParentInfo | null } | null,
) => ({
id: p.id,
name: p.name,
description: p.description,
rating: p.rating as "general" | "adult",
latest: p.latest,
creator: creator ?? creatorUsername ?? "",
creatorUsername: creatorUsername ?? "",
parent: latest?.parent ?? 0,
image: latest?.parentInfo?.image ?? null,
// Its own category if one was chosen, else its parent's.
categories: p.category ?? latest?.parentInfo?.categories ?? [],
category: p.category,
status: p.status as "draft" | "published",
listed: p.listed,
tags: p.tags,
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(),
});
const productViewer = (p: Person | undefined): ProductViewer | undefined =>
p ? { id: p.id, moderator: isModerator(p) } : undefined;
const productScope = (id: string): Scope => ({ type: "product", id });
/** What someone editing a product may do beyond product:edit. */
const editRights = async (me: Person, id: string, creatorId: string): Promise<EditRights> => ({
creator: me.id === creatorId,
editLocked: await perms.can(me, "product:edit-locked", productScope(id)),
rateLower: await perms.can(me, "product:rate-lower", productScope(id)),
});
/** A product's creator (for its audit tags and the person's rights), or 404. */
const creatorOf = async (id: string) => {
const [p] = await db.select({ creatorId: product.creatorId }).from(product).where(eq(product.id, id));
if (!p) throw new Problem(404, "not_found", "No such product.");
return p.creatorId;
};
const catalogView = (c: typeof schema.catalog.$inferSelect) => ({
id: c.id,
name: c.name,
url: c.url,
contact: c.contact,
visibility: c.visibility,
membership: c.membership,
status: c.status,
statusReason: c.statusReason,
maxRating: c.maxRating,
uploads: c.uploads,
mirrors: c.mirrors,
importer: c.importer as "off" | "on" | "paused",
createdAt: c.createdAt.toISOString(),
});
const catalogParam = t.Object({ id: t.String({ pattern: "^[a-z2-7]{10}$" }) });
const catalogScope = (id: string): Scope => ({ type: "catalog", id });
const inviteView = (i: typeof schema.catalogInvite.$inferSelect) => ({
code: i.code,
maxUses: i.maxUses,
uses: i.uses,
expiresAt: i.expiresAt?.toISOString() ?? null,
createdAt: i.createdAt.toISOString(),
url: `${(webURL ?? "").replace(/\/+$/, "")}/catalogs/${i.catalogId}?invite=${i.code}`,
});
type ConsoleSection = "overview" | "products" | "catalogs" | "cases" | "people" | "blocks" | "audit" | "settings";
/** Tokens as their owner sees them (never the hash), with their scopes' names. */
const tokenViews = async (rows: (typeof schema.apiToken.$inferSelect)[]) => {
const ids = (type: string) => [
...new Set(rows.flatMap((r) => r.grants.flatMap((g) => (g.scope.type === type && "id" in g.scope ? [g.scope.id] : [])))),
];
const names: Record<string, string> = {};
const cs = ids("catalog");
const ps = ids("product");
if (cs.length) for (const c of await db.select({ id: catalog.id, name: catalog.name }).from(catalog).where(inArray(catalog.id, cs))) names[c.id] = c.name;
if (ps.length)
for (const p of await db.select({ id: schema.product.id, name: schema.product.name }).from(schema.product).where(inArray(schema.product.id, ps)))
names[p.id] = p.name;
const now = Date.now();
return rows.map((r) => ({
id: r.id,
name: r.name,
grants: r.grants.map((g) => ({ ...g, name: "id" in g.scope ? (names[g.scope.id] ?? g.scope.id) : "T5DE" })),
status: r.revokedAt ? ("revoked" as const) : r.expiresAt.getTime() <= now ? ("expired" as const) : ("active" as const),
createdAt: r.createdAt.toISOString(),
expiresAt: r.expiresAt.toISOString(),
lastUsedAt: r.lastUsedAt?.toISOString() ?? null,
revokedAt: r.revokedAt?.toISOString() ?? null,
}));
};
const blockParam = t.Object({ sha256: t.String({ pattern: "^[0-9a-f]{64}$" }) });
const blockView = (b: { block: typeof schema.fileBlock.$inferSelect; by: string | null }) => ({
sha256: b.block.sha256,
reason: b.block.reason,
by: b.by,
at: b.block.createdAt.toISOString(),
});
const caseParam = t.Object({ id: t.Numeric({ minimum: 1, multipleOf: 1 }) });
/** Whether the person may know who opened a case: anyone, but for reports only the reporter and moderators. */
const seesOpener = (me: Person, c: Case) => c.kind !== "report" || c.openedBy === me.id || isModerator(me);
/** A case as a person sees it (reports keep who reported private: seesOpener). */
const caseView = (c: Case, names: Record<string, string>, me: Person) => ({
id: c.id,
kind: c.kind as CaseKind,
status: c.status as "open" | "resolved" | "declined",
tags: c.tags,
tagNames: Object.fromEntries(Object.values(c.tags).filter((v): v is string => !!v).map((v) => [v, names[v] ?? v])),
openedBy: c.openedBy && seesOpener(me, c) ? (names[c.openedBy] ?? "") : "",
assignee: c.assignee ? (names[c.assignee] ?? "") : null,
reason: c.reason,
data: c.kind === "appeal" ? { audit: c.data.audit, action: c.data.action, detail: c.data.detail } : {},
resolution: c.resolution,
decidedBy: c.decidedBy ? (names[c.decidedBy] ?? "") : null,
decidedAt: c.decidedAt?.toISOString() ?? null,
createdAt: c.createdAt.toISOString(),
updatedAt: c.updatedAt.toISOString(),
});
/** A case the person may see, else 404. */
const visibleCase = async (me: Person, id: number) => {
const c = await productCall(() => cases.get(id));
if (!(await cases.canSee(me, c))) throw new Problem(404, "not_found", "No such case.");
return c;
};
/** Whether an audit entry is an action the person may appeal: it affected them (their product, their catalog, or
* them), and someone else did it. */
const affectedBy = async (me: Person, e: { action: string; actorId: string | null; tags: AuditTags }) => {
const who = appealable[e.action];
if (!who || !e.actorId || e.actorId === me.id) return false;
if (who === "person") return e.tags.person === me.id;
if (who === "creator" && e.tags.product) {
const [p] = await db.select({ creatorId: product.creatorId }).from(product).where(eq(product.id, e.tags.product));
return p?.creatorId === me.id;
}
if (who === "owner" && e.tags.catalog) {
const [c] = await db.select({ ownerId: catalog.ownerId }).from(catalog).where(eq(catalog.id, e.tags.catalog));
return c?.ownerId === me.id;
}
return false;
};
/** What resolving a case does: lowers the rating, removes the product, deletes the catalog. Reports and appeals
* record the decision; the moderator acts on them as they would anywhere. */
const caseEffect = async (me: Person, c: Case, resolution: string) => {
if (c.kind === "rating-review" && c.tags.product) {
const id = c.tags.product;
const creatorId = await creatorOf(id);
const reason = resolution || "Rating review accepted.";
const done = await productCall(() =>
products.updateInfo(me.id, id, { rating: "general" }, reason, { creator: false, editLocked: true, rateLower: true }),
);
if (done.entry) {
await audited(me, "product.edit", id, { fields: done.fields, reason, case: c.id }, { product: id, person: creatorId });
await productEdited(me, id, creatorId, "edit", done.fields, reason);
}
} else if (c.kind === "removal-request" && c.tags.product) {
const reason = resolution || c.reason;
const removed = await productCall(() => products.removeByModeration(c.tags.product!, reason));
await audited(me, "product.remove", removed.id, { reason, case: c.id }, { product: removed.id, person: removed.creatorId });
await notifications.add(removed.creatorId, "product_removed", { product: removed.id, name: removed.name, reason }, { product: removed.id }, me.id);
} else if (c.kind === "catalog-deletion" && c.tags.catalog) {
const deleted = await productCall(() => catalogs.markDeleted(c.tags.catalog!, resolution || c.reason));
await audited(me, "catalog.delete", deleted.id, { name: deleted.name, case: c.id });
}
};
/** What a person controls: the catalogs they're on the team of, their products, their hosted rooms. */
const consoleScope = async (me: Person) => ({
catalogs: await perms.teamCatalogs(me.id),
products: await perms.ownProducts(me.id),
rooms: (await db.select({ n: hostedRoom.n }).from(hostedRoom).where(eq(hostedRoom.ownerId, me.id))).map((r) => String(r.n)),
});
type AuditQuery = {
catalog?: string;
product?: string;
room?: string;
person?: string;
actor?: string;
action?: string;
q?: string;
from?: string;
to?: string;
before?: number;
limit?: number;
};
/**
* Audit entries a person may see (docs/console.md): moderators all; others those they made, and those tagged
* with a catalog they're on the team of, a product of theirs or a hosted room of theirs. Newest first.
*/
const auditFor = async (me: Person, scope: Awaited<ReturnType<typeof consoleScope>>, f: AuditQuery) => {
const conds = [];
if (!isModerator(me)) {
const visible = [eq(audit.actorId, me.id)];
if (scope.catalogs.length) visible.push(inArray(sql`${audit.tags}->>'catalog'`, scope.catalogs));
if (scope.products.length) visible.push(inArray(sql`${audit.tags}->>'product'`, scope.products));
if (scope.rooms.length) visible.push(inArray(sql`${audit.tags}->>'room'`, scope.rooms));
conds.push(or(...visible)!);
}
for (const k of ["catalog", "product", "room"] as const) if (f[k]) conds.push(sql`${audit.tags}->>${k} = ${f[k]}`);
if (f.person) {
const [p] = await db.select({ id: user.id }).from(user).where(sql`lower(${user.username}) = lower(${f.person})`);
conds.push(p ? or(sql`${audit.tags}->>'person' = ${p.id}`, eq(audit.actorId, p.id))! : sql`false`);
}
if (f.actor) {
const [p] = await db.select({ id: user.id }).from(user).where(sql`lower(${user.username}) = lower(${f.actor})`);
conds.push(p ? eq(audit.actorId, p.id) : sql`false`);
}
const esc = (v: string) => v.replace(/[%_\\]/g, (c) => "\\" + c);
if (f.action) conds.push(ilike(audit.action, `${esc(f.action)}%`));
if (f.q) {
const like = `%${esc(f.q)}%`;
conds.push(or(ilike(audit.action, like), ilike(audit.target, like), sql`${audit.detail}::text ilike ${like}`)!);
}
const day = (v: string | undefined) => (v && /^\d{4}-\d{2}-\d{2}$/.test(v) ? v : undefined);
if (day(f.from)) conds.push(sql`${audit.at} >= ${day(f.from)}::date`);
if (day(f.to)) conds.push(sql`${audit.at} < ${day(f.to)}::date + 1`);
if (f.before) conds.push(sql`${audit.id} < ${f.before}`);
const rows = await db
.select({
id: audit.id,
at: audit.at,
actor: user.username,
actorId: audit.actorId,
action: audit.action,
target: audit.target,
tags: audit.tags,
detail: audit.detail,
})
.from(audit)
.leftJoin(user, eq(user.id, audit.actorId))
.where(conds.length ? and(...conds) : undefined)
.orderBy(desc(audit.id))
.limit(Math.min(f.limit ?? 100, 200));
// Names for the tags, so the console can show and link them.
const ids = (k: keyof AuditTags) => [...new Set(rows.map((r) => r.tags[k]).filter((v): v is string => !!v))];
const [cs, ps, people] = await Promise.all([
ids("catalog").length ? db.select({ id: catalog.id, name: catalog.name }).from(catalog).where(inArray(catalog.id, ids("catalog"))) : [],
ids("product").length ? db.select({ id: product.id, name: product.name }).from(product).where(inArray(product.id, ids("product"))) : [],
ids("person").length
? db.select({ id: user.id, name: user.username }).from(user).where(inArray(user.id, ids("person")))
: [],
]);
const names: Record<string, string> = {};
for (const x of [...cs, ...ps, ...people]) names[x.id] = x.name ?? "";
const rowsAppealable = await Promise.all(rows.map((r) => affectedBy(me, { ...r, actorId: r.actorId })));
return rows.map((r, i) => ({
appealable: rowsAppealable[i]!,
id: r.id,
at: r.at.toISOString(),
actor: r.actor ?? "",
action: r.action,
target: r.target,
tags: r.tags,
tagNames: Object.fromEntries(Object.values(r.tags).filter((v): v is string => !!v && names[v] !== undefined).map((v) => [v, names[v]!])),
detail: r.detail,
}));
};
const personByUsername = async (username: string) => {
const [p] = await db.select().from(user).where(sql`lower(${user.username}) = lower(${username.trim()})`);
if (!p) throw new Problem(404, "not_found", `Nobody on T5DE is called ${username.trim()}.`);
return p;
};
/** Runs a hosted-room operation, turning its errors into Problems. */
const hostedCall = async <T>(f: () => Promise<T>): Promise<T> => {
try {
return await f();
} catch (e) {
if (e instanceof HostedError) throw new Problem(e.status, e.slug, e.message);
throw e;
}
};
type HostedRow = { room: typeof schema.hostedRoom.$inferSelect; ownerName: string };
type Extras = { favorite: boolean; score: number; ratings: number };
const hostedView = ({ room: r, ownerName }: HostedRow, extras: Extras = { favorite: false, score: 0, ratings: 0 }) => ({
n: r.n,
instanceId: instanceId(r.ownerImvuId, r.n),
chatId: chatId(r.n),
name: r.name,
description: r.description,
roomPid: r.roomPid,
rating: r.rating as "general" | "adult",
maxUsers: r.maxUsers,
ownerImvuId: r.ownerImvuId,
ownerName,
occupancy: realtime.occupancy(r.n),
privacy: (r.privacy === "private" ? "private" : "public") as "public" | "private",
moderators: r.moderators.map((m) => m.imvuId),
moderatorNames: r.moderators.map((m) => m.username),
image: r.imageHash ? `${apiBase}/api/v1/hosted-rooms/${r.n}/image?v=${r.imageHash.slice(0, 16)}` : null,
favorite: extras.favorite,
score: extras.score,
ratings: extras.ratings,
createdAt: r.createdAt.toISOString(),
});
/** Rooms as a viewer sees them: with their ratings, and (signed in) whether each is a favorite. */
const hostedViews = async (rows: HostedRow[], person: Person | undefined) => {
const ns = rows.map((r) => r.room.n);
const [scores, favorites] = await Promise.all([
hosted.scores(ns),
person ? hosted.favoriteSet(person.id, ns) : Promise.resolve(new Set<number>()),
]);
return rows.map((r) =>
hostedView(r, { favorite: favorites.has(r.room.n), ...(scores.get(r.room.n) ?? { score: 0, ratings: 0 }) }),
);
};
const hostedViewFor = async (r: HostedRow, person: Person | undefined) => (await hostedViews([r], person))[0]!;
/** The person and their linked IMVU accounts. */
const viewerOf = async (p: Person): Promise<Viewer> => ({
id: p.id,
imvuIds: (await db.select({ id: imvuLink.imvuId }).from(imvuLink).where(eq(imvuLink.userId, p.id))).map((l) => l.id),
});
/** Moderators as the owner gave them (IMVU IDs, or names, which are looked up: linked accounts first, then IMVU). */
const resolveModerators = async (me: Person, entries: (number | string)[], known: RoomModerator[]) => {
if (entries.length > maxModerators) throw new Problem(400, "invalid", `A room has up to ${maxModerators} moderators.`);
const out: RoomModerator[] = [];
for (const e of entries) {
const text = typeof e === "string" ? e.trim() : "";
const id = typeof e === "number" ? e : /^[0-9]{1,15}$/.test(text) ? Number(text) : 0;
if (id > 0) {
const name = known.find((m) => m.imvuId === id)?.username;
const [l] = name ? [] : await db.select({ username: imvuLink.username }).from(imvuLink).where(eq(imvuLink.imvuId, id));
out.push({ imvuId: id, username: name ?? l?.username ?? "" });
continue;
}
if (!text || text.length > 64) throw new Problem(400, "invalid", "Moderators are IMVU names or account IDs.");
const k = known.find((m) => m.username.toLowerCase() === text.toLowerCase());
if (k) {
out.push(k);
continue;
}
const [l] = await db
.select({ imvuId: imvuLink.imvuId, username: imvuLink.username })
.from(imvuLink)
.where(sql`lower(${imvuLink.username}) = lower(${text})`);
if (l) {
out.push(l);
continue;
}
try {
const found = await imvuCall(me, () => imvu.byUsername(text));
out.push({ imvuId: found.id, username: found.username });
} catch (err) {
if (err instanceof Problem && err.slug === "no_such_imvu_account")
throw new Problem(404, "no_such_imvu_account", `IMVU has no account named ${text}.`);
throw err;
}
}
return out;
};
const hostedParam = t.Object({ n: t.Numeric({ minimum: 1, maximum: 47_483_647, multipleOf: 1 }) });
const rating = t.Union([t.Literal("general"), t.Literal("adult")]);
const privacy = t.Union([t.Literal("public"), t.Literal("private")]);
const roomPid = t.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER });
const maxUsers = t.Integer({ minimum: 2, maximum: 30 });
const sceneItem = t.Tuple([
t.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER }),
t.Union([t.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }), t.String({ pattern: "^[a-z2-7]{10}$" })]),
t.String({ maxLength: maxPlacement }),
]);
/** Runs a decorations operation, turning its errors into Problems. */
const decorationCall = async <T>(f: () => Promise<T>): Promise<T> => {
try {
return await f();
} catch (e) {
if (e instanceof DecorationError) throw new Problem(e.status, e.slug, e.message);
throw e;
}
};
const decorationItem = t.Tuple([
t.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER }),
t.String({ pattern: "^[a-z2-7]{10}$" }),
t.String({ maxLength: maxDecorationPlacement }),
]);
const productParam = t.Object({ id: t.String({ pattern: "^[a-z2-7]{10}$" }) });
const ownLink = async (p: Person, imvuId: number) => {
const [l] = await db.select().from(imvuLink).where(and(eq(imvuLink.imvuId, imvuId), eq(imvuLink.userId, p.id)));
if (!l) throw new Problem(404, "not_found", "That account isn't linked to you.");
return l;
};
const imvuCall = async <T>(p: Person, call: () => Promise<T>): Promise<T> => {
if (!limiter.allow(`imvu:${p.id}`, 20, 60 * 60 * 1000))
throw new Problem(429, "rate_limited", "Too many lookups. Try again in a while.");
try {
return await call();
} catch (e) {
if (e instanceof NoSuchImvuUser) throw new Problem(404, "no_such_imvu_account", "IMVU has no account by that name.");
if (e instanceof ImvuUnavailable) throw new Problem(502, "imvu_unavailable", "IMVU didn't answer. Try again in a moment.");
throw e;
}
};
const personById = async (id: string) => {
const [p] = await db.select().from(user).where(eq(user.id, id));
if (!p) throw new Problem(404, "not_found", "No such person.");
return p;
};
const api = new Elysia({ prefix: "/api/v1" })
.error({ Problem })
.onError(({ code, error, set }) => {
if (code === "Problem") {
set.status = error.status;
return { error: error.slug, message: error.message, ...error.extra };
}
if (code === "VALIDATION") {
set.status = 400;
return { error: "invalid", message: "Some of that isn't right. Check it and try again." };
}
if (code === "NOT_FOUND") {
set.status = 404;
return { error: "not_found", message: "Not found." };
}
})
.derive(async ({ request }) => {
// An API token: only routes open to scripts (`scripted`) take it; everywhere else it's signed out.
const bearer = request.headers.get("authorization")?.match(/^Bearer (\S+)$/)?.[1];
if (bearer?.startsWith(tokenPrefix)) {
const tok = await tokens.verify(bearer);
const owner = tok ? (await db.select().from(user).where(eq(user.id, tok.userId)))[0] : undefined;
const ok = owner && !owner.banned && owner.approved ? owner : undefined;
return {
person: undefined,
waiting: undefined,
sessionId: undefined,
tokenPerson: tok && ok ? Object.assign(ok, { token: { id: tok.id, name: tok.name, grants: tok.grants } }) : undefined,
badToken: !(tok && ok),
};
}
const s = await auth.api.getSession({ headers: request.headers });
const person = s?.user ? ((await db.select().from(user).where(eq(user.id, s.user.id)))[0] ?? undefined) : undefined;
// A person waiting for approval counts as signed out everywhere but their own account (/me).
const usable = person && !person.banned ? person : undefined;
return {
person: usable?.approved ? usable : undefined,
waiting: usable && !usable.approved ? usable : undefined,
sessionId: s?.session.id,
tokenPerson: undefined,
badToken: false,
};
})
.macro({
/** Signed in, approved or still waiting. */
account: {
resolve: ({ person, waiting, tokenPerson, badToken }) => {
if (tokenPerson || badToken) throw new Problem(403, "token_not_allowed", "API tokens can't do this. Sign in on the website.");
const me = person ?? waiting;
if (!me) throw new Problem(401, "signed_out", "Sign in first.");
return { me };
},
},
signedIn: {
resolve: ({ person, waiting, tokenPerson, badToken }) => {
if (tokenPerson || badToken) throw new Problem(403, "token_not_allowed", "API tokens can't do this. Sign in on the website.");
if (waiting) throw new Problem(403, "awaiting_approval", "Your account is waiting for a moderator's approval.");
if (!person) throw new Problem(401, "signed_out", "Sign in first.");
return { me: person };
},
},
moderator: {
resolve: ({ person, waiting, tokenPerson, badToken }) => {
if (tokenPerson || badToken) throw new Problem(403, "token_not_allowed", "API tokens can't do this. Sign in on the website.");
if (waiting) throw new Problem(403, "awaiting_approval", "Your account is waiting for a moderator's approval.");
if (!person) throw new Problem(401, "signed_out", "Sign in first.");
if (!isModerator(person)) throw new Problem(403, "forbidden", "Only moderators can do this.");
return { me: person };
},
},
/** Signed in, or an API token (whose grants then limit every permission check). */
scripted: {
resolve: ({ person, waiting, tokenPerson, badToken }) => {
if (badToken) throw new Problem(401, "bad_token", "That token isn't valid: wrong, revoked or expired.");
if (tokenPerson) return { me: tokenPerson };
if (waiting) throw new Problem(403, "awaiting_approval", "Your account is waiting for a moderator's approval.");
if (!person) throw new Problem(401, "signed_out", "Sign in first.");
return { me: person };
},
},
})
// Who's signed in, and the home page.
.get(
"/me",
async ({ me, person }) => {
// Whether the console is for them: moderators, and anyone controlling a catalog, product or room.
let console = false;
if (person) {
const scope = await consoleScope(person);
console = isModerator(person) || scope.catalogs.length + scope.products.length + scope.rooms.length > 0;
}
return {
person: { ...personView(me), picture: await picture(me.id), console, unread: await notifications.unread(me.id) },
};
},
{ account: true },
)
// The hub's public settings: whether new accounts wait for approval.
.get("/hub", async () => ({ registration: await settings.registration() }))
.get("/home", async ({ person }) => {
const online = (await visibleOnline(person)).length;
if (!person) return { onlineCount: online };
const [row] = await db.select({ n: count() }).from(imvuLink).where(eq(imvuLink.userId, person.id));
return { onlineCount: online, links: row?.n ?? 0 };
})
// Who's online.
.get("/online", async ({ person }) => ({ online: await visibleOnline(person) }))
.get("/online/events", ({ person, request }) => {
const encoder = new TextEncoder();
let stop = () => {};
const stream = new ReadableStream({
start(controller) {
const send = async () => {
const online = await visibleOnline(person);
try {
controller.enqueue(encoder.encode(`event: online\ndata: ${JSON.stringify({ online })}\n\n`));
} catch {}
};
const unsubscribe = realtime.subscribe(() => void send());
const keepAlive = setInterval(() => {
try {
controller.enqueue(encoder.encode(": keep-alive\n\n"));
} catch {}
}, 25_000);
stop = () => {
unsubscribe();
clearInterval(keepAlive);
};
request.signal.addEventListener("abort", () => {
stop();
try {
controller.close();
} catch {}
});
void send();
},
cancel() {
stop();
},
});
return new Response(stream, {
headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-store", Connection: "keep-alive" },
});
})
// Your account.
.get(
"/account",
async ({ me }) => {
const links = await db.select().from(imvuLink).where(eq(imvuLink.userId, me.id)).orderBy(imvuLink.linkedAt);
const challenges = await db
.select()
.from(linkChallenge)
.where(and(eq(linkChallenge.userId, me.id), sql`${linkChallenge.createdAt} > now() - interval '1 day'`))
.orderBy(linkChallenge.createdAt);
const [computers] = await db
.select({ n: count() })
.from(session)
.where(and(eq(session.userId, me.id), ilike(session.userAgent, "t5de-proxy%"), sql`${session.expiresAt} > now()`));
return {
person: personView(me),
links: await linkViews(me.id, links),
challenges: challenges.map((c) => ({
imvuId: c.imvuId,
username: c.username,
code: c.code,
createdAt: c.createdAt.toISOString(),
expiresAt: new Date(c.createdAt.getTime() + challengeLifetime).toISOString(),
})),
computers: computers?.n ?? 0,
canLink: links.length < me.linkCap,
// Two-factor sign-in: on or off, and what needs it (sensitive permissions the person holds).
twoFactor: { enabled: me.twoFactorEnabled, neededFor: await sensitiveHeld(me) },
};
},
{ signedIn: true },
)
.post(
"/account/links",
async ({ me, body, set }) => {
const found = await imvuCall(me, () => imvu.byUsername(body.username));
const [existing] = await db.select().from(imvuLink).where(eq(imvuLink.imvuId, found.id));
if (existing?.userId === me.id)
throw new Problem(409, "already_linked", `${found.username} is already linked.`);
const code = linkCode();
const [c] = await db
.insert(linkChallenge)
.values({ userId: me.id, imvuId: found.id, username: found.username, code })
.onConflictDoUpdate({
target: [linkChallenge.userId, linkChallenge.imvuId],
set: { code, username: found.username, createdAt: new Date() },
})
.returning();
set.status = 201;
return {
challenge: {
imvuId: c!.imvuId,
username: c!.username,
code: c!.code,
createdAt: c!.createdAt.toISOString(),
expiresAt: new Date(c!.createdAt.getTime() + challengeLifetime).toISOString(),
},
};
},
{ signedIn: true, body: t.Object({ username: t.String({ minLength: 1, maxLength: 64 }) }) },
)
.post(
"/account/links/:imvu/check",
async ({ me, params }) => {
const [c] = await db
.select()
.from(linkChallenge)
.where(
and(
eq(linkChallenge.userId, me.id),
eq(linkChallenge.imvuId, params.imvu),
sql`${linkChallenge.createdAt} > now() - interval '1 day'`,
),
);
if (!c) throw new Problem(410, "expired", "That code expired. Start again.");
const found = await imvuCall(me, () => imvu.byId(params.imvu));
if (!found.tagline.toLowerCase().includes(c.code.toLowerCase()))
throw new Problem(
409,
"code_missing",
`${found.username}'s tagline doesn't have the code yet. IMVU can take a minute to show a new tagline.`,
);
const result = await db.transaction(async (tx) => {
const [{ n } = { n: 0 }] = await tx
.select({ n: count() })
.from(imvuLink)
.where(and(eq(imvuLink.userId, me.id), ne(imvuLink.imvuId, found.id)));
if (n >= me.linkCap)
throw new Problem(403, "link_cap", `You can link up to ${me.linkCap} IMVU accounts. Ask a moderator if you need more.`);
const [prev] = await tx.select().from(imvuLink).where(eq(imvuLink.imvuId, found.id));
const moved = prev !== undefined && prev.userId !== me.id;
const values = { userId: me.id, username: found.username };
let link: Link;
if (!prev) {
[link] = (await tx.insert(imvuLink).values({ imvuId: found.id, pairwiseId: randomID(), ...values }).returning()) as [Link];
} else if (moved) {
// A moved account gets a new pairwise ID and starts with nothing shown: nothing connects the new owner
// to the old one.
[link] = (await tx
.update(imvuLink)
.set({ ...values, pairwiseId: randomID(), linkedAt: new Date(), showBadge: false, showPresence: false })
.where(eq(imvuLink.imvuId, found.id))
.returning()) as [Link];
} else {
[link] = (await tx.update(imvuLink).set(values).where(eq(imvuLink.imvuId, found.id)).returning()) as [Link];
}
await tx.delete(linkChallenge).where(eq(linkChallenge.imvuId, found.id));
await tx.insert(audit).values({
actorId: me.id,
action: "link.add",
target: String(found.id),
detail: moved ? { imvu: found.username, movedFrom: prev!.userId } : { imvu: found.username },
});
return { link, moved, previousOwner: prev?.userId };
});
// Age from IMVU, for this account; a moved account's earlier checks belonged to its previous owner.
if (result.moved) await age.forgetAccount(found.id);
await age.record({ userId: me.id, imvuId: found.id }, "imvu", imvuResult(found));
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 };
},
{ signedIn: true, params: imvuIdParam },
)
.delete(
"/account/challenges/:imvu",
async ({ me, params, set }) => {
await db.delete(linkChallenge).where(and(eq(linkChallenge.userId, me.id), eq(linkChallenge.imvuId, params.imvu)));
set.status = 204;
},
{ signedIn: true, params: imvuIdParam },
)
.patch(
"/account/links/:imvu",
async ({ me, params, body }) => {
await ownLink(me, params.imvu);
const [l] = await db
.update(imvuLink)
.set({
...(body.showBadge !== undefined ? { showBadge: body.showBadge } : {}),
...(body.showPresence !== undefined ? { showPresence: body.showPresence } : {}),
...(body.listRooms !== undefined ? { listRooms: body.listRooms } : {}),
})
.where(eq(imvuLink.imvuId, params.imvu))
.returning();
return { link: await linkView(l!) };
},
{
signedIn: true,
params: imvuIdParam,
body: t.Object({
showBadge: t.Optional(t.Boolean()),
showPresence: t.Optional(t.Boolean()),
listRooms: t.Optional(t.Boolean()),
}),
},
)
.post(
"/account/links/:imvu/recheck",
async ({ me, params }) => {
await ownLink(me, params.imvu);
const found = await imvuCall(me, () => imvu.byId(params.imvu));
await age.record({ userId: me.id, imvuId: params.imvu }, "imvu", imvuResult(found));
const [l] = await db.update(imvuLink).set({ username: found.username }).where(eq(imvuLink.imvuId, params.imvu)).returning();
return { link: await linkView(l!) };
},
{ signedIn: true, params: imvuIdParam },
)
.delete(
"/account/links/:imvu",
async ({ me, params, set }) => {
const l = await ownLink(me, params.imvu);
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;
},
{ signedIn: true, params: imvuIdParam },
)
.post(
"/account/signout-computers",
async ({ me, set }) => {
await db.delete(session).where(and(eq(session.userId, me.id), ilike(session.userAgent, "t5de-proxy%")));
realtime.disconnect(me.id);
set.status = 204;
},
{ signedIn: true },
)
// A proxy's sign-in code, approved by the person on the website.
.post(
"/device/approve",
async ({ me, body, request, set }) => {
const raw = body.code.toUpperCase().replace(/[\s-]/g, "");
try {
// Viewing the code claims it for this person; then they approve it.
await auth.api.deviceVerify({ query: { user_code: raw }, headers: request.headers });
await auth.api.deviceApprove({ body: { userCode: raw }, headers: request.headers });
} catch {
throw new Problem(404, "not_found", "That code isn't right, or it expired. Check the code T5DE shows.");
}
await audited(me, "proxy.signin", "");
set.status = 204;
},
{ signedIn: true, body: t.Object({ code: t.String({ minLength: 4, maxLength: 32 }) }) },
)
// IMVU rooms whose owners list them, with the T5DE users in each now (those showing they're online).
.get("/rooms", async ({ person: me }) => {
const viewerAdult = await personAdult(me);
const listed = (await rooms.listed()).filter((r) => viewerAdult || !isAdultRoom(r.room));
const here = new Map<string, number[]>();
for (const o of realtime.online()) for (const r of o.rooms) here.set(r, [...(here.get(r) ?? []), o.imvuId]);
const ids = [...new Set([...here.values()].flat())];
const shown = ids.length
? await db
.select({ imvuId: imvuLink.imvuId, username: imvuLink.username, badge: imvuLink.showBadge })
.from(imvuLink)
.where(and(inArray(imvuLink.imvuId, ids), eq(imvuLink.showPresence, true)))
: [];
const out = listed.map(({ room: r, owner }) => {
const t5de = shown.filter((u) => here.get(r.instanceId)?.includes(u.imvuId));
return {
instanceId: r.instanceId,
name: r.name,
description: r.description,
imageURL: r.imageURL,
owner: { imvuId: r.ownerImvuId, username: owner },
adult: isAdultRoom(r),
occupancy: r.occupancy,
capacity: r.capacity,
url: `https://go.imvu.com/chat/room-${r.instanceId}`,
t5de,
seenAt: r.seenAt.toISOString(),
};
});
out.sort((a, b) => b.t5de.length - a.t5de.length);
return { rooms: out };
})
// T5DE-hosted rooms (docs/hosted-rooms.md).
.post(
"/hosted-rooms",
async ({ me, body, set }) => {
if (!limiter.allow(`hosted:${me.id}`, 20, 60 * 60 * 1000))
throw new Problem(429, "rate_limited", "Too many new rooms. Try again in a while.");
const r = await hostedCall(async () => hosted.create(me.id, await personAdult(me), body));
await audited(me, "hosted_room.create", String(r.room.n), {
name: r.room.name,
rating: r.room.rating,
privacy: r.room.privacy,
});
set.status = 201;
return { room: hostedView(r) };
},
{
signedIn: true,
body: t.Object({
name: t.String({ maxLength: 64 }),
description: t.Optional(t.String({ maxLength: 512 })),
roomPid,
rating,
maxUsers: t.Optional(maxUsers),
imvuId: t.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }),
privacy: t.Optional(privacy),
}),
},
)
.get(
"/hosted-rooms",
async ({ person, query }) => {
const on = (v?: string) => v === "1" || v === "true";
const mine = on(query.mine);
const favorites = on(query.favorites);
const recent = on(query.recent);
if ((mine || favorites || recent) && !person) throw new Problem(401, "signed_out", "Sign in first.");
const rows = await hosted.list({
adult: await personAdult(person),
viewer: person ? await viewerOf(person) : undefined,
mine,
favorites,
recent,
});
return { rooms: await hostedViews(rows, person) };
},
{
query: t.Object({
mine: t.Optional(t.String({ maxLength: 8 })),
favorites: t.Optional(t.String({ maxLength: 8 })),
recent: t.Optional(t.String({ maxLength: 8 })),
}),
},
)
.get(
"/hosted-rooms/:n",
async ({ person, params }) => {
const r = await hostedCall(async () => hosted.get(params.n, await personAdult(person), person?.id));
return {
room: await hostedViewFor(r, person),
scene: { contents: r.room.scene, hash: r.room.sceneHash },
myRating: person ? await hosted.myRating(person.id, r.room.n) : 0,
};
},
{ params: hostedParam },
)
.patch(
"/hosted-rooms/:n",
async ({ me, params, body }) => {
const { moderators: given, ...rest } = body;
const changes: RoomChanges = given
? {
...rest,
moderators: await resolveModerators(me, given, (await hostedCall(() => hosted.own(me.id, params.n))).room.moderators),
}
: rest;
const r = await hostedCall(async () => hosted.update(me.id, await personAdult(me), params.n, changes));
realtime.hostedChanged(r.room.n, roomInfo(r));
await audited(me, "hosted_room.edit", String(r.room.n), {
fields: Object.keys(body),
...(changes.moderators ? { moderators: changes.moderators.map((m) => m.imvuId) } : {}),
});
return { room: await hostedViewFor(r, me) };
},
{
signedIn: true,
params: hostedParam,
body: t.Object({
name: t.Optional(t.String({ maxLength: 64 })),
description: t.Optional(t.String({ maxLength: 512 })),
rating: t.Optional(rating),
maxUsers: t.Optional(maxUsers),
roomPid: t.Optional(roomPid),
privacy: t.Optional(privacy),
moderators: t.Optional(
t.Array(t.Union([t.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }), t.String({ maxLength: 64 })]), {
maxItems: maxModerators,
}),
),
}),
},
)
.put(
"/hosted-rooms/:n/scene",
async ({ me, params, body }) => {
if (!limiter.allow(`scene:${me.id}`, 60, 60 * 1000))
throw new Problem(429, "rate_limited", "Too many changes. Try again in a moment.");
const r = await hostedCall(() => hosted.setScene(me.id, params.n, body.contents, body.roomPid));
return { room: hostedView(r), scene: { contents: r.room.scene, hash: r.room.sceneHash } };
},
{
signedIn: true,
params: hostedParam,
body: t.Object({ contents: t.Array(sceneItem, { maxItems: maxSceneItems }), roomPid: t.Optional(roomPid) }),
},
)
.delete(
"/hosted-rooms/:n",
async ({ me, params, set }) => {
const r = await hostedCall(() => hosted.close(me.id, isModerator(me), params.n));
realtime.hostedClosed(r.n);
await audited(me, "hosted_room.close", String(r.n), { name: r.name, ...(r.ownerId !== me.id ? { owner: r.ownerId } : {}) });
set.status = 204;
},
{ signedIn: true, params: hostedParam },
)
// Phase 2: bans, images, favorites, ratings.
.get(
"/hosted-rooms/:n/participants",
async ({ person, params }) => {
const r = await hostedCall(async () => hosted.get(params.n, await personAdult(person), person?.id));
return { participants: realtime.participants(r.room.n) };
},
{ params: hostedParam },
)
.get(
"/hosted-rooms/:n/bans",
async ({ me, params }) => {
await hostedCall(async () => hosted.managed(await viewerOf(me), params.n));
const bans = await hosted.bans(params.n);
return {
bans: bans.map((b) => ({
imvuId: b.imvuId,
byImvuId: b.byImvuId,
until: b.until?.toISOString() ?? null,
createdAt: b.createdAt.toISOString(),
})),
};
},
{ signedIn: true, params: hostedParam },
)
.delete(
"/hosted-rooms/:n/bans/:imvu",
async ({ me, params, set }) => {
if (!(await hostedCall(() => hosted.unban(me.id, params.n, params.imvu))))
throw new Problem(404, "not_found", "That account isn't banned here.");
await audited(me, "hosted_room.unban", String(params.n), { imvu: params.imvu });
set.status = 204;
},
{
signedIn: true,
params: t.Object({
n: t.Numeric({ minimum: 1, maximum: 47_483_647, multipleOf: 1 }),
imvu: t.Numeric({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, multipleOf: 1 }),
}),
},
)
.get(
"/hosted-rooms/:n/image",
async ({ person, params, request }) => {
const r = await hostedCall(async () => hosted.get(params.n, await personAdult(person), person?.id));
const img = r.room.imageHash ? await hosted.image(params.n) : undefined;
if (!img) throw new Problem(404, "not_found", "This room has no image.");
const etag = `"${img.hash}"`;
const headers = {
"Cache-Control": `${r.room.rating === "adult" ? "private" : "public"}, max-age=3600`,
ETag: etag,
"X-Content-Type-Options": "nosniff",
"Content-Security-Policy": "default-src 'none'; sandbox",
};
if (request.headers.get("if-none-match") === etag) return new Response(null, { status: 304, headers });
return new Response(new Uint8Array(img.data), { headers: { ...headers, "Content-Type": img.contentType } });
},
{ params: hostedParam },
)
.put(
"/hosted-rooms/:n/image",
async ({ me, params, body }) => {
if (!limiter.allow(`image:${me.id}`, 30, 60 * 60 * 1000))
throw new Problem(429, "rate_limited", "Too many uploads. Try again in a while.");
if (body.image.size > maxImageBytes) throw new Problem(400, "invalid", "An image is up to 512 KB.");
const data = Buffer.from(await body.image.arrayBuffer());
const r = await hostedCall(() => hosted.setImage(me.id, params.n, data));
await audited(me, "hosted_room.image", String(params.n), { bytes: data.length });
return { room: await hostedViewFor(r, me) };
},
{
signedIn: true,
params: hostedParam,
body: t.Object({ image: t.File() }),
beforeHandle({ request }) {
// Refuse big uploads before reading them (with room for the multipart framing).
if (Number(request.headers.get("content-length") ?? 0) > maxImageBytes + 16 * 1024)
throw new Problem(400, "invalid", "An image is up to 512 KB.");
},
},
)
.delete(
"/hosted-rooms/:n/image",
async ({ me, params }) => {
const r = await hostedCall(() => hosted.removeImage(me.id, params.n));
await audited(me, "hosted_room.image", String(params.n), { removed: true });
return { room: await hostedViewFor(r, me) };
},
{ signedIn: true, params: hostedParam },
)
.put(
"/hosted-rooms/:n/favorite",
async ({ me, params, set }) => {
if (!limiter.allow(`fav:${me.id}`, 120, 60 * 1000)) throw new Problem(429, "rate_limited", "Slow down a little.");
await hostedCall(async () => hosted.get(params.n, await personAdult(me), me.id));
await hosted.favorite(me.id, params.n, true);
set.status = 204;
},
{ signedIn: true, params: hostedParam },
)
.delete(
"/hosted-rooms/:n/favorite",
async ({ me, params, set }) => {
await hosted.favorite(me.id, params.n, false);
set.status = 204;
},
{ signedIn: true, params: hostedParam },
)
.put(
"/hosted-rooms/:n/rating",
async ({ me, params, body }) => {
if (!limiter.allow(`rate:${me.id}`, 120, 60 * 1000)) throw new Problem(429, "rate_limited", "Slow down a little.");
const r = await hostedCall(async () => hosted.get(params.n, await personAdult(me), me.id));
if (r.room.ownerId === me.id) throw new Problem(403, "forbidden", "You can't rate your own room.");
await hosted.rate(me.id, params.n, body.score);
return { room: await hostedViewFor(r, me), myRating: body.score };
},
{ signedIn: true, params: hostedParam, body: t.Object({ score: t.Integer({ minimum: 1, maximum: 5 }) }) },
)
.delete(
"/hosted-rooms/:n/rating",
async ({ me, params, set }) => {
await hosted.rate(me.id, params.n, null);
set.status = 204;
},
{ signedIn: true, params: hostedParam },
)
// Decorations over IMVU rooms (docs/products.md, "Decorations").
.get(
"/decorations",
async ({ person, query }) => {
const instances = [...new Set((query.instances ?? "").split(",").filter(Boolean))];
if (instances.length > maxBatch) throw new Problem(400, "invalid", `Up to ${maxBatch} rooms at a time.`);
return { rooms: await decorationCall(async () => decorations.get(instances, await personAdult(person))) };
},
{ query: t.Object({ instances: t.Optional(t.String({ maxLength: 1024 })) }) },
)
.get(
"/decorations/:instance",
async ({ person, params }) =>
(await decorationCall(async () => decorations.get([params.instance], await personAdult(person))))[0]!,
{ params: t.Object({ instance: t.String({ maxLength: 32 }) }) },
)
.put(
"/decorations/:instance",
async ({ me, params, body }) => {
if (!limiter.allow(`decor:${me.id}`, 60, 60 * 1000))
throw new Problem(429, "rate_limited", "Too many changes. Try again in a moment.");
await decorationCall(() => decorations.set(me.id, params.instance, body.contents));
realtime.decorated(params.instance);
return (await decorations.get([params.instance], await personAdult(me)))[0]!;
},
{
signedIn: true,
params: t.Object({ instance: t.String({ maxLength: 32 }) }),
body: t.Object({ contents: t.Array(decorationItem, { maxItems: maxDecorations }) }),
},
)
// Catalogs: registering one, and the directory.
.post(
"/catalogs",
async ({ me, body, set }) => {
const r = await productCall(() => products.registerCatalog(me.id, body));
await audited(me, "catalog.register", r.catalog.id, { name: r.catalog.name, url: r.catalog.url });
set.status = 201;
return { catalog: catalogView(r.catalog), key: r.key };
},
{
signedIn: true,
body: t.Object({
name: t.String({ maxLength: 64 }),
url: t.String({ maxLength: 300 }),
contact: t.String({ maxLength: 200 }),
visibility: t.String(),
membership: t.String(),
}),
},
)
.get("/catalogs", async ({ person }) => ({
catalogs: (await products.catalogs(person?.id)).map((c) => ({ ...catalogView(c), mine: c.ownerId === person?.id })),
}))
// Managing a catalog (docs/products.md; permissions in docs/console.md).
.get(
"/catalogs/:id",
async ({ person, params }) => {
const c = await productCall(() => catalogs.get(params.id));
const held = [...(await perms.at(person, catalogScope(c.id)))];
const team = held.includes("audit:read");
if (c.status !== "approved" && !team) throw new Problem(404, "not_found", "No such catalog.");
return {
catalog: { ...catalogView(c), mine: c.ownerId === person?.id },
membership: person ? ((await catalogs.membership(c.id, person.id)) ?? null) : null,
permissions: held,
roles: await perms.rolesAt(person, catalogScope(c.id)),
hosted: await catalogs.hostedCounts(c.id),
members: team ? await catalogs.memberCounts(c.id) : null,
};
},
{ params: catalogParam },
)
.patch(
"/catalogs/:id",
async ({ me, params, body }) => {
await need(me, "catalog:edit", catalogScope(params.id));
const r = await productCall(() => catalogs.update(params.id, body));
if (Object.keys(r.changed).length) await audited(me, "catalog.edit", params.id, { changed: r.changed });
return { catalog: catalogView(r.catalog) };
},
{
scripted: true,
params: catalogParam,
body: t.Object({
name: t.Optional(t.String({ maxLength: 64 })),
url: t.Optional(t.String({ maxLength: 300 })),
contact: t.Optional(t.String({ maxLength: 200 })),
visibility: t.Optional(t.Union([t.Literal("public"), t.Literal("private")])),
membership: t.Optional(t.Union([t.Literal("open"), t.Literal("approval"), t.Literal("invite")])),
maxRating: t.Optional(t.Union([t.Literal("general"), t.Literal("adult")])),
uploads: t.Optional(t.Union([t.Literal("anyone"), t.Literal("members"), t.Literal("team")])),
mirrors: t.Optional(t.Union([t.Literal("auto"), t.Literal("approve"), t.Literal("off")])),
}),
},
)
.post(
"/catalogs/:id/key",
async ({ me, params }) => {
await need(me, "catalog:rotate-key", catalogScope(params.id));
const key = await productCall(() => catalogs.rotateKey(params.id));
await audited(me, "catalog.rotate_key", params.id);
return { key };
},
{ scripted: true, params: catalogParam },
)
.post(
"/catalogs/:id/suspend",
async ({ me, params, body }) => {
await need(me, "catalog:suspend", catalogScope(params.id));
const c = await productCall(() => catalogs.setSuspended(params.id, true, body.reason.trim()));
await audited(me, "catalog.suspend", c.id, { name: c.name, reason: body.reason.trim() });
return { catalog: catalogView(c) };
},
{ scripted: true, params: catalogParam, body: t.Object({ reason: t.String({ minLength: 1, maxLength: 500 }) }) },
)
// Deleting a catalog goes to moderators for now (docs/console.md): its owner opens a catalog-deletion case.
.post(
"/catalogs/:id/delete",
async ({ me, params, body }) => {
await need(me, "catalog:delete-request", catalogScope(params.id));
const c = await productCall(() => catalogs.get(params.id));
if (c.status === "deleted") throw new Problem(409, "deleted", "That catalog is deleted already.");
const open = await cases.findOpen("catalog-deletion", { catalog: c.id });
if (open) throw new Problem(409, "requested", "Its deletion was requested already.", { case: open.id });
const kase = await cases.open("catalog-deletion", me.id, { catalog: c.id }, body.reason);
await audited(me, "case.open", String(kase.id), { kind: kase.kind }, kase.tags);
return { case: kase.id };
},
{ scripted: true, params: catalogParam, body: t.Object({ reason: t.String({ minLength: 1, maxLength: 2000 }) }) },
)
.post(
"/catalogs/:id/reinstate",
async ({ me, params }) => {
await need(me, "catalog:suspend", catalogScope(params.id));
const c = await productCall(() => catalogs.setSuspended(params.id, false, ""));
await audited(me, "catalog.reinstate", c.id, { name: c.name });
return { catalog: catalogView(c) };
},
{ scripted: true, params: catalogParam },
)
// A catalog's team: the owner, and the roles it gave.
.get(
"/catalogs/:id/team",
async ({ me, params }) => {
await need(me, "audit:read", catalogScope(params.id));
const team = await perms.team(params.id);
return {
...team,
assignable: assignableCatalogRoles.map((r) => ({
id: r,
name: roleBundles[r].name,
permissions: [...roleBundles[r].permissions],
})),
};
},
{ scripted: true, params: catalogParam },
)
.put(
"/catalogs/:id/team/:username",
async ({ me, params, body }) => {
const scope = catalogScope(params.id);
await need(me, "team:manage", scope);
if (!(await perms.mayGive(me, body.role, scope)))
throw new Problem(403, "forbidden", "You can only give roles whose permissions you have.");
const p = await personByUsername(params.username);
await productCall(() => catalogs.addRole(params.id, p.id, body.role, me.id));
await audited(me, "catalog.team_add", params.id, { person: p.username, role: body.role }, { catalog: params.id, person: p.id });
return { team: await perms.team(params.id) };
},
{
scripted: true,
params: t.Object({ id: t.String({ pattern: "^[a-z2-7]{10}$" }), username: t.String({ maxLength: 64 }) }),
body: t.Object({ role: t.Literal("catalog-operator") }),
},
)
.delete(
"/catalogs/:id/team/:username",
async ({ me, params, query }) => {
const scope = catalogScope(params.id);
const p = await personByUsername(params.username);
// Anyone may leave a team; taking others off needs team:manage.
if (p.id !== me.id) await need(me, "team:manage", scope);
await productCall(() => catalogs.removeRole(params.id, p.id, query.role));
await audited(me, "catalog.team_remove", params.id, { person: p.username, role: query.role }, { catalog: params.id, person: p.id });
return { team: await perms.team(params.id) };
},
{
scripted: true,
params: t.Object({ id: t.String({ pattern: "^[a-z2-7]{10}$" }), username: t.String({ maxLength: 64 }) }),
query: t.Object({ role: t.Literal("catalog-operator") }),
},
)
// Membership: joining and leaving; the team's view and decisions; invitations.
.post(
"/catalogs/:id/join",
async ({ me, params, body }) => {
const invite = body?.invite || undefined;
const status = await productCall(() => catalogs.join(params.id, me.id, invite));
await audited(me, status === "member" ? "catalog.join" : "catalog.request", params.id, invite ? { invite: true } : {}, {
catalog: params.id,
person: me.id,
});
if (status === "member") realtime.notify(me.id, { type: "library" });
return { membership: status };
},
{
signedIn: true,
params: catalogParam,
body: t.Optional(t.Object({ invite: t.Optional(t.String({ maxLength: 32 })) })),
},
)
.delete(
"/catalogs/:id/join",
async ({ me, params, set }) => {
await catalogs.leave(params.id, me.id);
await audited(me, "catalog.leave", params.id, {}, { catalog: params.id, person: me.id });
realtime.notify(me.id, { type: "library" });
set.status = 204;
},
{ signedIn: true, params: catalogParam },
)
.get(
"/catalogs/:id/members",
async ({ me, params, query }) => {
await need(me, "member:approve", catalogScope(params.id));
return { members: await catalogs.members(params.id, query.status), counts: await catalogs.memberCounts(params.id) };
},
{
scripted: true,
params: catalogParam,
query: t.Object({
status: t.Optional(t.Union([t.Literal("requested"), t.Literal("member"), t.Literal("banned")])),
}),
},
)
.put(
"/catalogs/:id/members/:username",
async ({ me, params, body }) => {
await need(me, body.status === "banned" ? "member:ban" : "member:approve", catalogScope(params.id));
const p = await personByUsername(params.username);
const before = await catalogs.membership(params.id, p.id);
await productCall(() => catalogs.setMember(params.id, p.id, body.status, me.id));
const action =
body.status === "banned" ? "catalog.member_ban" : before === "requested" ? "catalog.member_approve" : "catalog.member_add";
await audited(me, action, params.id, { person: p.username, ...(before ? { from: before } : {}) }, {
catalog: params.id,
person: p.id,
});
realtime.notify(p.id, { type: "library" });
if (before !== body.status) {
const c = await catalogs.get(params.id);
await notifications.add(p.id, "membership_decided", { catalog: c.id, name: c.name, status: body.status }, { catalog: c.id }, me.id);
}
return { membership: body.status };
},
{
scripted: true,
params: t.Object({ id: t.String({ pattern: "^[a-z2-7]{10}$" }), username: t.String({ maxLength: 64 }) }),
body: t.Object({ status: t.Union([t.Literal("member"), t.Literal("banned")]) }),
},
)
.delete(
"/catalogs/:id/members/:username",
async ({ me, params, set }) => {
await need(me, "member:remove", catalogScope(params.id));
const p = await personByUsername(params.username);
const before = await catalogs.membership(params.id, p.id);
await productCall(() => catalogs.removeMember(params.id, p.id));
const action =
before === "requested" ? "catalog.member_decline" : before === "banned" ? "catalog.member_unban" : "catalog.member_remove";
await audited(me, action, params.id, { person: p.username }, { catalog: params.id, person: p.id });
realtime.notify(p.id, { type: "library" });
if (before === "requested") {
const c = await catalogs.get(params.id);
await notifications.add(p.id, "membership_decided", { catalog: c.id, name: c.name, status: "declined" }, { catalog: c.id }, me.id);
}
set.status = 204;
},
{
scripted: true,
params: t.Object({ id: t.String({ pattern: "^[a-z2-7]{10}$" }), username: t.String({ maxLength: 64 }) }),
},
)
.get(
"/catalogs/:id/invites",
async ({ me, params }) => {
await need(me, "member:invite", catalogScope(params.id));
return { invites: (await catalogs.invites(params.id)).map(inviteView) };
},
{ scripted: true, params: catalogParam },
)
.post(
"/catalogs/:id/invites",
async ({ me, params, body, set }) => {
await need(me, "member:invite", catalogScope(params.id));
const inv = await productCall(() => catalogs.createInvite(params.id, me.id, body));
await audited(me, "catalog.invite_create", params.id, {
maxUses: inv.maxUses,
expiresAt: inv.expiresAt?.toISOString() ?? null,
});
set.status = 201;
return { invite: inviteView(inv) };
},
{
scripted: true,
params: catalogParam,
body: t.Object({
maxUses: t.Optional(t.Integer({ minimum: 1, maximum: 10_000 })),
expiresInDays: t.Optional(t.Integer({ minimum: 1, maximum: 365 })),
}),
},
)
.delete(
"/catalogs/:id/invites/:code",
async ({ me, params, set }) => {
await need(me, "member:invite", catalogScope(params.id));
await productCall(() => catalogs.revokeInvite(params.id, params.code));
await audited(me, "catalog.invite_revoke", params.id, { code: params.code.slice(0, 3) + "…" });
set.status = 204;
},
{
scripted: true,
params: t.Object({ id: t.String({ pattern: "^[a-z2-7]{10}$" }), code: t.String({ maxLength: 32 }) }),
},
)
// What a catalog hosts, and delisting.
.get(
"/catalogs/:id/products",
async ({ me, params }) => {
await need(me, "audit:read", catalogScope(params.id));
return { products: await catalogs.hosted(params.id) };
},
{ scripted: true, params: catalogParam },
)
.delete(
"/catalogs/:id/products/:product",
async ({ me, params, query }) => {
await need(me, "hosting:delist", catalogScope(params.id));
const reason = query.reason.trim();
const revisions = await productCall(() => catalogs.delist(params.id, params.product));
await audited(me, "catalog.delist", params.id, { product: params.product, revisions, reason }, {
catalog: params.id,
product: params.product,
});
return { revisions };
},
{
scripted: true,
params: t.Object({ id: t.String({ pattern: "^[a-z2-7]{10}$" }), product: t.String({ pattern: "^[a-z2-7]{10}$" }) }),
query: t.Object({ reason: t.String({ minLength: 1, maxLength: 500 }) }),
},
)
// For catalogs: what to act on (files to delete, revisions to mirror, its status). A suspended catalog still
// reads it, to learn that it's suspended.
.get(
"/catalog/changes",
async ({ request, query }) => {
const c = await products.catalogFor(request.headers.get("authorization"), true);
if (!c) throw new Problem(401, "forbidden", "Not an approved catalog.");
return catalogs.changes(c.id, query.after ?? 0);
},
{ query: t.Object({ after: t.Optional(t.Numeric({ minimum: 0, multipleOf: 1 })) }) },
)
// For catalogs: registering an uploaded revision.
.post(
"/catalog/revisions",
async ({ request, body, set }) => {
const c = await products.catalogFor(request.headers.get("authorization"));
if (!c) throw new Problem(401, "forbidden", "Not an approved catalog.");
const r = await productCall(async () => {
try {
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)
await audited(e.personId, "file.blocked_upload", c.id, { files: e.files }, { catalog: c.id, person: e.personId });
throw e;
}
});
set.status = 201;
return r;
},
{
body: t.Object({
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.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 })),
}),
},
)
// 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 })
.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));
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,
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 },
)
.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 }) => {
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",
async ({ me, body }) => {
// A token uploads revisions of products it's granted; new products take the website (they start as drafts).
if (body.product) await need(me, "revision:upload", productScope(body.product));
else if ("token" in me) throw new Problem(403, "token_not_allowed", "API tokens upload new revisions of existing products only.");
return productCall(() => products.uploadToken(me.id, body.catalog, body.product));
},
{ scripted: true, body: t.Object({ catalog: t.String(), product: t.Optional(t.String()) }) },
)
.get(
"/products",
async ({ person, query }) => {
const adult = await personAdult(person);
const rows = await products.list({ ...query, adult, viewerId: person?.id });
return { products: rows.map((r) => productView(r.product, r.creator, r.creatorUsername, r)) };
},
{
query: t.Object({
q: t.Optional(t.String({ maxLength: 100 })),
creator: t.Optional(t.String({ maxLength: 64 })),
category: t.Optional(t.Numeric({ minimum: 1, maximum: 2_147_483_647, multipleOf: 1 })),
tag: t.Optional(t.String({ maxLength: 24 })),
catalog: t.Optional(t.String({ pattern: "^[a-z2-7]{10}$" })),
limit: t.Optional(t.Numeric({ minimum: 1, maximum: 200, multipleOf: 1 })),
}),
},
)
.get(
"/products/:id",
async ({ person, params }) => {
const adult = await personAdult(person);
const p = await productCall(() => products.get(params.id, adult, productViewer(person)));
const lib = person ? await products.inLibrary(person.id, params.id) : undefined;
const latest = p.revisions.find((r) => r.number === p.product.latest);
return {
product: productView(p.product, p.creator, p.creatorUsername, latest),
revisions: p.revisions.map((r) => ({
number: r.number,
rating: r.rating,
notes: r.notes,
retracted: r.retracted,
files: r.files,
size: r.files.reduce((n, f) => n + f.size, 0),
createdAt: r.createdAt.toISOString(),
catalogs: p.hosts.filter((h) => h.number === r.number).map((h) => h.name),
})),
inLibrary: lib !== undefined,
stayOn: lib?.stayOn ?? null,
mine: person?.id === p.product.creatorId,
permissions: person ? [...(await perms.at(person, productScope(p.product.id)))] : [],
available: person ? await products.available(person.id, p.product.id) : false,
catalogs: await Promise.all(
(await products.hostingCatalogs(p.product.id)).map(async (c) => ({
...c,
membership: c.membership as "open" | "approval" | "invite",
joined: person ? ((await catalogs.membership(c.id, person.id)) ?? null) : null,
})),
),
};
},
{ params: productParam },
)
.patch(
"/products/:id",
async ({ me, params, body }) => {
const creatorId = await creatorOf(params.id);
await need(me, "product:edit", productScope(params.id));
const { reason = "", ...input } = body;
const rights = await editRights(me, params.id, creatorId);
// Lowering a rating without product:rate-lower asks moderators: a rating-review case (one at a time).
let review: number | null = null;
if (input.rating === "general" && !rights.rateLower) {
const [cur] = await db.select({ rating: product.rating }).from(product).where(eq(product.id, params.id));
if (cur?.rating === "adult") {
await productCall(() => products.checkFilesGeneral(params.id));
delete input.rating;
const open = await cases.findOpen("rating-review", { product: params.id });
if (open) review = open.id;
else {
const c = await cases.open("rating-review", me.id, { product: params.id, person: creatorId }, reason || "Lower the rating to general.");
await audited(me, "case.open", String(c.id), { kind: c.kind }, c.tags);
review = c.id;
}
}
}
const done = await productCall(async () => products.updateInfo(me.id, params.id, input, reason, rights));
if (done.entry) {
await audited(me, "product.edit", params.id, { fields: done.fields, ...(reason ? { reason } : {}) }, {
product: params.id,
person: creatorId,
});
await productEdited(me, params.id, creatorId, "edit", done.fields, reason);
}
return {
product: productView(done.product, undefined, undefined, await products.latestParent(done.product)),
fields: done.fields,
review,
};
},
{
scripted: true,
params: productParam,
body: t.Object({
name: t.Optional(t.String({ maxLength: 64 })),
description: t.Optional(t.String({ maxLength: 20000 })),
rating: t.Optional(t.Union([t.Literal("general"), t.Literal("adult")])),
tags: t.Optional(t.Array(t.String({ maxLength: 64 }), { maxItems: 20 })),
listed: t.Optional(t.Boolean()),
category: t.Optional(t.Union([t.Integer({ minimum: 1 }), t.Null()])),
reason: t.Optional(t.String({ maxLength: 500 })),
}),
},
)
// The categories a product may be filed under.
.get(
"/products/:id/categories",
async ({ me, params }) => {
await creatorOf(params.id);
await need(me, "product:edit", productScope(params.id));
const [p] = await db.select().from(product).where(eq(product.id, params.id));
const parent = (await products.latestParent(p!))?.parentInfo?.categories ?? [];
return { choices: await products.categoryChoices(p!), parent };
},
{ scripted: true, params: productParam },
)
// A draft becomes published.
.post(
"/products/:id/publish",
async ({ me, params }) => {
const creatorId = await creatorOf(params.id);
await need(me, "product:publish", productScope(params.id));
const p = await productCall(() => products.publish(me.id, params.id));
await audited(me, "product.publish", p.id, { name: p.name }, { product: p.id, person: creatorId });
return { product: productView(p, undefined, undefined, await products.latestParent(p)) };
},
{ scripted: true, params: productParam },
)
// The info history: who changed what, and why.
.get(
"/products/:id/history",
async ({ me, params }) => {
const creatorId = await creatorOf(params.id);
await need(me, "audit:read", productScope(params.id));
const entries = await products.history(params.id);
return {
entries: entries.map((e) => ({
id: e.id,
at: e.at.toISOString(),
kind: e.kind as "edit" | "revert" | "lock" | "publish",
by: e.by ?? "",
byCreator: e.byId === creatorId,
changes: e.changes,
reason: e.reason,
revertOf: e.revertOf,
})),
};
},
{ scripted: true, params: productParam },
)
.post(
"/products/:id/history/:entry/revert",
async ({ me, params, body }) => {
const creatorId = await creatorOf(params.id);
await need(me, "product:edit", productScope(params.id));
const reason = body.reason ?? "";
const done = await productCall(async () =>
products.revert(me.id, params.id, params.entry, reason, await editRights(me, params.id, creatorId)),
);
await audited(
me.id,
"product.revert",
params.id,
{ entry: params.entry, fields: done.fields, ...(reason ? { reason } : {}) },
{ product: params.id, person: creatorId },
);
await productEdited(me, params.id, creatorId, "revert", done.fields, reason);
return {
product: productView(done.product, undefined, undefined, await products.latestParent(done.product)),
fields: done.fields,
};
},
{
scripted: true,
params: t.Object({ id: t.String({ pattern: "^[a-z2-7]{10}$" }), entry: t.Numeric({ minimum: 1, multipleOf: 1 }) }),
body: t.Object({ reason: t.Optional(t.String({ maxLength: 500 })) }),
},
)
// Moderators lock info fields, so only people with product:edit-locked change them.
.put(
"/products/:id/locks",
async ({ me, params, body }) => {
const creatorId = await creatorOf(params.id);
await need(me, "product:lock", productScope(params.id));
const p = await productCall(() => products.setLocks(me.id, params.id, body.fields, body.reason));
await audited(me, "product.lock", p.id, { fields: p.locked, reason: body.reason.trim() }, {
product: p.id,
person: creatorId,
});
await productEdited(me, p.id, creatorId, "lock", p.locked, body.reason.trim());
return { product: productView(p, undefined, undefined, await products.latestParent(p)) };
},
{
scripted: true,
params: productParam,
body: t.Object({
fields: t.Array(
t.Union([
t.Literal("name"),
t.Literal("description"),
t.Literal("rating"),
t.Literal("tags"),
t.Literal("listed"),
t.Literal("category"),
]),
{ maxItems: 6 },
),
reason: t.String({ maxLength: 500 }),
}),
},
)
// Its creator deletes a product (no longer listed or added; those who have it keep it).
.delete(
"/products/:id",
async ({ me, params, set }) => {
await productCall(() => products.delete(me.id, params.id));
await audited(me, "product.delete", params.id);
set.status = 204;
},
{ signedIn: true, params: productParam },
)
// Moderation removes a product: gone everywhere.
.post(
"/products/:id/remove",
async ({ me, params, body }) => {
await need(me, "product:remove", hubScope);
const removed = await productCall(() => products.removeByModeration(params.id, body.reason.trim()));
await audited(me, "product.remove", params.id, { reason: body.reason.trim() }, {
product: params.id,
person: removed.creatorId,
});
await notifications.add(removed.creatorId, "product_removed", { product: removed.id, name: removed.name, reason: body.reason.trim() }, { product: removed.id }, me.id);
return { ok: true };
},
{ moderator: true, params: productParam, body: t.Object({ reason: t.String({ minLength: 1, maxLength: 500 }) }) },
)
// API tokens (docs/console.md): made, listed and revoked from a website session only.
.get(
"/account/tokens",
async ({ me }) => {
// What a token could be given: the person's permissions hub-wide, on their catalogs' teams and products.
const scopes: { scope: Scope; name: string; permissions: string[] }[] = [];
const hubHeld = [...perms.hub(me)];
if (hubHeld.length) scopes.push({ scope: hubScope, name: "T5DE", permissions: hubHeld });
const team = await perms.teamCatalogs(me.id);
if (team.length)
for (const c of await db.select({ id: catalog.id, name: catalog.name }).from(catalog).where(inArray(catalog.id, team)).orderBy(catalog.name))
scopes.push({ scope: catalogScope(c.id), name: c.name, permissions: [...(await perms.at({ id: me.id, role: "user" }, catalogScope(c.id)))] });
const own = await db
.select({ id: schema.product.id, name: schema.product.name })
.from(schema.product)
.where(and(eq(schema.product.creatorId, me.id), isNull(schema.product.deletedAt), isNull(schema.product.removedAt)))
.orderBy(schema.product.name)
.limit(200);
for (const p of own)
scopes.push({ scope: productScope(p.id), name: p.name, permissions: [...(await perms.at({ id: me.id, role: "user" }, productScope(p.id)))] });
return { tokens: await tokenViews(await tokens.list(me.id)), scopes, maxDays: maxTokenDays };
},
{ signedIn: true },
)
.post(
"/account/tokens",
async ({ me, body, set }) => {
const made = await productCall(() => tokens.create(me, body.name, body.days, body.grants));
await audited(me, "token.create", made.row.id, { name: made.row.name, grants: made.row.grants }, { person: me.id });
set.status = 201;
return { token: made.token, info: (await tokenViews([made.row]))[0]! };
},
{
signedIn: true,
body: t.Object({
name: t.String({ maxLength: 200 }),
days: t.Integer({ minimum: 1, maximum: maxTokenDays }),
grants: t.Array(
t.Object({
permission: t.String({ maxLength: 64 }),
scope: t.Union([
t.Object({ type: t.Literal("hub") }),
t.Object({ type: t.Literal("catalog"), id: t.String({ maxLength: 32 }) }),
t.Object({ type: t.Literal("product"), id: t.String({ maxLength: 32 }) }),
]),
}),
{ maxItems: maxGrants },
),
}),
},
)
.delete(
"/account/tokens/:id",
async ({ me, params, set }) => {
const t = await productCall(() => tokens.revoke(me.id, params.id));
await audited(me, "token.revoke", t.id, { name: t.name }, { person: me.id });
set.status = 204;
},
{ signedIn: true, params: t.Object({ id: t.String({ maxLength: 32 }) }) },
)
// File blocks: moderation blocks a file network-wide (docs/products.md).
.get(
"/blocks",
async ({ me, query }) => {
await need(me, "product:remove", hubScope);
const limit = 50;
const rows = await blocks.list({ before: query.before ? new Date(query.before) : undefined, limit });
return { blocks: rows.map(blockView), before: rows.length === limit ? rows.at(-1)!.block.createdAt.toISOString() : null };
},
{ scripted: true, query: t.Object({ before: t.Optional(t.String({ format: "date-time" })) }) },
)
// A file's block, if any, and the products using it (what blocking it removes).
.get(
"/blocks/:sha256",
async ({ me, params }) => {
await need(me, "product:remove", hubScope);
const b = await blocks.get(params.sha256);
return { block: b ? blockView(b) : null, products: await blocks.usedBy(params.sha256) };
},
{ scripted: true, params: blockParam },
)
.put(
"/blocks/:sha256",
async ({ me, params, body }) => {
await need(me, "product:remove", hubScope);
const reason = body.reason.trim();
if (!reason || !isSha256(params.sha256)) throw new Problem(400, "invalid", "Give a reason.");
const removed = await productCall(() => blocks.block(params.sha256, reason, me.id));
await audited(me, "file.block", params.sha256, { reason, removed: removed.map((p) => p.id) });
for (const p of removed) {
await audited(me, "product.remove", p.id, { reason, file: params.sha256 }, { product: p.id, person: p.creatorId });
await notifications.add(p.creatorId, "product_removed", { product: p.id, name: p.name, reason }, { product: p.id }, me.id);
}
return { removed: removed.map((p) => ({ id: p.id, name: p.name })) };
},
{ scripted: true, params: blockParam, body: t.Object({ reason: t.String({ maxLength: 500 }) }) },
)
.delete(
"/blocks/:sha256",
async ({ me, params, body, set }) => {
await need(me, "product:remove", hubScope);
await productCall(() => blocks.unblock(params.sha256));
const reason = body?.reason?.trim() ?? "";
await audited(me, "file.unblock", params.sha256, reason ? { reason } : {});
set.status = 204;
},
{ scripted: true, params: blockParam, body: t.Optional(t.Object({ reason: t.Optional(t.String({ maxLength: 500 })) })) },
)
// Moderation restores a removed product (an upheld appeal, a mistake).
.post(
"/products/:id/unremove",
async ({ me, params, body }) => {
await need(me, "product:unremove", productScope(params.id));
const p = await productCall(() => products.unremove(params.id));
const reason = body.reason?.trim() ?? "";
await audited(me, "product.unremove", p.id, reason ? { reason } : {}, { product: p.id, person: p.creatorId });
await notifications.add(p.creatorId, "product_restored", { product: p.id, name: p.name, reason }, { product: p.id }, me.id);
return { ok: true };
},
{ scripted: true, params: productParam, body: t.Object({ reason: t.Optional(t.String({ maxLength: 500 })) }) },
)
.post(
"/products/:id/revisions/:n/retract",
async ({ me, params }) => {
await need(me, "revision:retract", productScope(params.id));
await productCall(() => products.retract(me.id, params.id, params.n));
await audited(me, "product.retract", params.id, { revision: params.n });
return { ok: true };
},
{ scripted: true, params: t.Object({ id: t.String({ pattern: "^[a-z2-7]{10}$" }), n: t.Numeric({ minimum: 1 }) }) },
)
// What the proxy loads: the revision this person uses, where to get it, and the hub's word on its files.
.get(
"/products/:id/files",
async ({ person, params }) => {
const r = await productCall(async () =>
products.revisionFor(person?.id, params.id, await personAdult(person), productViewer(person)),
);
return {
product: r.product.id,
revision: r.revision.number,
rating: r.revision.rating,
parent: r.revision.parent,
name: r.product.name,
creator: r.creator ?? "",
files: r.revision.files,
catalogs: r.catalogs,
token: r.revision.token,
};
},
{ params: productParam },
)
.post(
"/access",
async ({ me }) => ({
token: await signer.sign("t5de-access", { sub: me.id, adult: await personAdult(me) }, 60 * 60),
}),
{ signedIn: true },
)
// Libraries.
.get(
"/library",
async ({ me }) => ({
library: (await products.library(me.id)).map((l) => ({
product: productView(l.product, l.creator, undefined, l),
stayOn: l.stayOn,
addedAt: l.addedAt.toISOString(),
})),
}),
{ signedIn: true },
)
.put(
"/library/:id",
async ({ me, params }) => {
try {
await products.add(me.id, params.id, await personAdult(me), productViewer(me));
} catch (e) {
if (e instanceof ProductError && e.slug === "members_only")
throw new Problem(e.status, e.slug, e.message, { catalogs: await products.hostingCatalogs(params.id) });
if (e instanceof ProductError) throw new Problem(e.status, e.slug, e.message);
throw e;
}
realtime.notify(me.id, { type: "library" });
return { ok: true };
},
{ signedIn: true, params: productParam },
)
.delete(
"/library/:id",
async ({ me, params, set }) => {
await products.remove(me.id, params.id);
realtime.notify(me.id, { type: "library" });
set.status = 204;
},
{ signedIn: true, params: productParam },
)
.patch(
"/library/:id",
async ({ me, params, body }) => {
await productCall(() => products.stayOn(me.id, params.id, body.stayOn));
realtime.notify(me.id, { type: "library" });
return { ok: true };
},
{
signedIn: true,
params: productParam,
body: t.Object({ stayOn: t.Union([t.Integer({ minimum: 1 }), t.Null()]) }),
},
)
// Age verification beyond IMVU's: the providers in use, and the person's own checks.
.get(
"/age",
async ({ me }) => ({
providers: age.list(),
checks: (await age.personChecks(me.id)).map((c) => ({
provider: c.provider,
method: c.method,
status: c.status,
overEighteen: c.overEighteen,
createdAt: c.createdAt.toISOString(),
checkedAt: c.checkedAt?.toISOString() ?? null,
expiresAt: c.expiresAt?.toISOString() ?? null,
})),
}),
{ signedIn: true },
)
.post(
"/age/:provider/start",
async ({ me, params, body }) => {
let p;
try {
p = age.provider(params.provider);
} catch {
throw new Problem(404, "not_found", "That way of verifying age isn't available.");
}
if (p.scope !== "person") throw new Problem(400, "invalid", "That one checks an IMVU account: link it instead.");
// A path on the website, or an address on it.
const web = new URL(webURL ?? "http://localhost:4100");
let back: URL | undefined;
try {
back = new URL(body.returnURL, web);
} catch {}
if (!back || back.origin !== web.origin)
throw new Problem(400, "invalid", "The return address must be on the hub's website.");
let started;
try {
started = await age.start({ userId: me.id }, p.id, back.href);
} catch (e) {
if (e instanceof AgeRefused) throw new Problem(409, "refused", e.message);
console.error(`age ${p.id}:`, e);
throw new Problem(502, "provider_unavailable", "The age check didn't start. Try again in a moment.");
}
await audited(me, "age.start", p.id, { ref: started.kind === "done" ? null : started.ref });
return started.kind === "done" ? { kind: "done" as const } : started;
},
{ signedIn: true, params: t.Object({ provider: t.String() }), body: t.Object({ returnURL: t.String({ maxLength: 500 }) }) },
)
.post(
"/age/:provider/complete",
async ({ params, body }) => {
const p = age.provider(params.provider);
if (!p.complete) throw new Problem(404, "not_found", "Not found.");
try {
const c = await age.finish(p.id, body.ref, await p.complete(body.ref, body.response));
return { status: c.status, overEighteen: c.overEighteen };
} catch (e) {
if (e instanceof AgeError) throw new Problem(404, "not_found", "That check isn't waiting for an answer.");
throw e;
}
},
{ signedIn: true, params: t.Object({ provider: t.String() }), body: t.Object({ ref: t.String(), response: t.Unknown() }) },
)
// Providers' webhooks: each checks the request is really from it.
.post(
"/age/webhook/:provider",
async ({ params, request, set }) => {
let p;
try {
p = age.provider(params.provider);
} catch {
throw new Problem(404, "not_found", "Not found.");
}
if (!p.webhook) throw new Problem(404, "not_found", "Not found.");
let answer;
try {
answer = await p.webhook(request);
} catch (e) {
// Not from the provider, or its answer couldn't be read: either way the provider tries again later.
console.error(`age webhook ${p.id}:`, e instanceof Error ? e.message : e);
throw new Problem(401, "forbidden", "Not from the provider.");
}
if (answer) {
try {
await age.finish(p.id, answer.ref, answer.result, { anyStatus: true });
} catch (e) {
if (!(e instanceof AgeError)) throw e; // a check that isn't the hub's (another environment's)
}
}
set.status = 204;
},
{ params: t.Object({ provider: t.String() }), parse: "none" },
)
// Cases: reports, reviews, requests and appeals (docs/console.md).
.get(
"/cases",
async ({ me, query }) => {
const rows = await cases.list(me, { ...query, mine: query.mine === "1" });
const names = await cases.names(rows);
return {
cases: rows.map((c) => caseView(c, names, me)),
before: rows.length ? rows[rows.length - 1]!.id : null,
moderator: isModerator(me),
};
},
{
signedIn: true,
query: t.Object({
status: t.Optional(t.Union([t.Literal("open"), t.Literal("resolved"), t.Literal("declined")])),
kind: t.Optional(t.Union(caseKinds.map((k) => t.Literal(k)))),
mine: t.Optional(t.Literal("1")),
before: t.Optional(t.Numeric({ minimum: 1, multipleOf: 1 })),
limit: t.Optional(t.Numeric({ minimum: 1, maximum: 200, multipleOf: 1 })),
}),
},
)
.post(
"/cases",
async ({ me, body, set }) => {
const reason = body.reason.trim();
let c: Case;
if (body.kind === "report") {
const about = body.about ?? {};
const tags: AuditTags = {};
if (about.product) tags.product = (await productCall(() => products.get(about.product!, true, productViewer(me)))).product.id;
else if (about.catalog) tags.catalog = (await productCall(() => catalogs.get(about.catalog!))).id;
else if (about.room) {
const [r] = await db.select({ n: hostedRoom.n }).from(hostedRoom).where(eq(hostedRoom.n, Number(about.room)));
if (!r) throw new Problem(404, "not_found", "No such room.");
tags.room = String(r.n);
} else if (about.person) tags.person = (await personByUsername(about.person)).id;
else throw new Problem(400, "invalid", "Say what you're reporting: a product, catalog, room or person.");
if (tags.person === me.id) throw new Problem(400, "invalid", "You can't report yourself.");
c = await productCall(() => cases.report(me.id, tags, reason));
} else if (body.kind === "removal-request") {
// A catalog's team asks moderators to remove a product it hosts everywhere.
if (!body.about?.product || !body.catalog) throw new Problem(400, "invalid", "Name the product and your catalog.");
await need(me, "hosting:delist", catalogScope(body.catalog));
const [h] = await db
.select({ id: hosting.productId })
.from(hosting)
.where(and(eq(hosting.catalogId, body.catalog), eq(hosting.productId, body.about.product)))
.limit(1);
if (!h) throw new Problem(404, "not_found", "Your catalog doesn't host that product.");
if (!reason) throw new Problem(400, "reason_needed", "Say why it should be removed.");
const tags = { product: body.about.product, catalog: body.catalog };
const open = await cases.findOpen("removal-request", { product: body.about.product });
if (open) throw new Problem(409, "requested", "Its removal was requested already.", { case: open.id });
c = await cases.open("removal-request", me.id, tags, reason);
} else {
// An appeal of an action that affected the person (one per action).
if (!body.audit) throw new Problem(400, "invalid", "Say which action you're appealing.");
const [entry] = await db.select().from(audit).where(eq(audit.id, body.audit));
if (!entry || !(await affectedBy(me, entry))) throw new Problem(404, "not_found", "No such action of yours to appeal.");
if (!reason) throw new Problem(400, "reason_needed", "Say why it should be undone.");
const [already] = await db
.select({ id: schema.moderationCase.id })
.from(schema.moderationCase)
.where(and(eq(schema.moderationCase.kind, "appeal"), sql`${schema.moderationCase.data}->>'audit' = ${String(entry.id)}`));
if (already) throw new Problem(409, "appealed", "You appealed that already.", { case: already.id });
c = await cases.open("appeal", me.id, entry.tags, reason, {
audit: String(entry.id),
action: entry.action,
actorId: entry.actorId,
detail: entry.detail,
});
}
// A report's entry isn't tagged with what it's about: who reported stays private (the reporter still sees it).
await audited(me, "case.open", String(c.id), { kind: c.kind }, c.kind === "report" ? {} : c.tags);
set.status = 201;
return { case: caseView(c, await cases.names([c]), me) };
},
{
signedIn: true,
body: t.Object({
kind: t.Union([t.Literal("report"), t.Literal("removal-request"), t.Literal("appeal")]),
about: t.Optional(
t.Object({
product: t.Optional(t.String({ pattern: "^[a-z2-7]{10}$" })),
catalog: t.Optional(t.String({ pattern: "^[a-z2-7]{10}$" })),
room: t.Optional(t.String({ pattern: "^[0-9]{1,12}$" })),
person: t.Optional(t.String({ maxLength: 64 })),
}),
),
catalog: t.Optional(t.String({ pattern: "^[a-z2-7]{10}$" })),
audit: t.Optional(t.Integer({ minimum: 1 })),
reason: t.String({ maxLength: 2000 }),
}),
},
)
.get(
"/cases/:id",
async ({ me, params }) => {
const c = await visibleCase(me, params.id);
const decide = await cases.canDecide(me, c);
return {
case: caseView(c, await cases.names([c]), me),
notes: (await cases.notes(c, decide || isModerator(me))).map((n) => ({
id: n.id,
by: n.byId === c.openedBy && !seesOpener(me, c) ? "Reporter" : (n.by ?? ""),
byOpener: n.byId === c.openedBy,
body: n.body,
internal: n.internal,
at: n.at.toISOString(),
})),
canDecide: decide && c.status === "open",
canAssign: perms.hub(me).has("case:assign"),
};
},
{ signedIn: true, params: caseParam },
)
.post(
"/cases/:id/notes",
async ({ me, params, body }) => {
const c = await visibleCase(me, params.id);
const decide = await cases.canDecide(me, c);
const internal = body.internal === true && (decide || isModerator(me));
await productCall(() => cases.addNote(c, me.id, body.body, internal));
if (!internal) {
// The opener hears from those deciding; the assignee hears from the opener.
const to = me.id === c.openedBy ? c.assignee : c.openedBy;
await notifications.add(to, "case_note", { case: c.id, kind: c.kind, by: me.displayUsername ?? me.username ?? "" }, c.tags, me.id);
}
return { ok: true };
},
{
signedIn: true,
params: caseParam,
body: t.Object({ body: t.String({ maxLength: 4000 }), internal: t.Optional(t.Boolean()) }),
},
)
.post(
"/cases/:id/assign",
async ({ me, params, body }) => {
await need(me, "case:assign", hubScope);
const c = await visibleCase(me, params.id);
const to = body.to ? await personByUsername(body.to) : null;
if (to && !perms.hub(to).has("case:resolve")) throw new Problem(400, "invalid", "Assign cases to moderators.");
const updated = await cases.assign(c, to?.id ?? null);
await audited(me, "case.assign", String(c.id), { to: to?.username ?? null }, c.kind === "report" ? {} : c.tags);
return { case: caseView(updated, await cases.names([updated]), me) };
},
{ scripted: true, params: caseParam, body: t.Object({ to: t.Union([t.String({ maxLength: 64 }), t.Null()]) }) },
)
.post(
"/cases/:id/decide",
async ({ me, params, body }) => {
const c = await visibleCase(me, params.id);
if (c.status !== "open") throw new Problem(409, "decided", "That case is decided already.");
if (!(await cases.canDecide(me, c)))
throw new Problem(
403,
"forbidden",
c.kind === "appeal" && c.data.actorId === me.id
? "Another moderator decides appeals of what you did."
: "You can't decide this case.",
);
const resolution = body.resolution.trim();
if (body.decision === "resolve") await caseEffect(me, c, resolution);
const decided = await productCall(() => cases.decide(c, me.id, body.decision === "resolve" ? "resolved" : "declined", resolution));
await audited(
me.id,
"case.decide",
String(c.id),
{
kind: c.kind,
status: decided.status,
...(resolution ? { resolution } : {}),
...(c.kind === "appeal" && c.data.actorId === me.id ? { ownAction: true } : {}),
},
c.kind === "report" ? {} : c.tags,
);
await notifications.add(c.openedBy, "case_decided", { case: c.id, kind: c.kind, status: decided.status, resolution }, c.tags, me.id);
return { case: caseView(decided, await cases.names([decided]), me) };
},
{
signedIn: true,
params: caseParam,
body: t.Object({
decision: t.Union([t.Literal("resolve"), t.Literal("decline")]),
resolution: t.String({ maxLength: 2000 }),
}),
},
)
// Notifications.
.get(
"/notifications",
async ({ me, query }) => {
const rows = await notifications.list(me.id, query.before);
return {
notifications: rows.map((n) => ({
id: n.id,
type: n.type,
tags: n.tags,
data: n.data,
at: n.createdAt.toISOString(),
read: n.readAt !== null,
})),
unread: await notifications.unread(me.id),
before: rows.length === 50 ? rows[rows.length - 1]!.id : null,
};
},
{ signedIn: true, query: t.Object({ before: t.Optional(t.Numeric({ minimum: 1, multipleOf: 1 })) }) },
)
.post(
"/notifications/read",
async ({ me, body }) => {
await notifications.markRead(me.id, body.ids);
return { unread: await notifications.unread(me.id) };
},
{ signedIn: true, body: t.Object({ ids: t.Optional(t.Array(t.Integer({ minimum: 1 }), { maxItems: 200 })) }) },
)
// The console.
.get(
"/console/products",
async ({ me, query }) => {
const mod = isModerator(me);
const all = mod && query.all === "1";
const rows = await products.manage({ creatorId: all ? undefined : me.id, q: query.q?.trim(), status: query.status });
if (!mod && rows.length === 0 && !query.q && !query.status && (await perms.ownProducts(me.id)).length === 0)
throw new Problem(403, "forbidden", "You haven't made any products.");
return {
products: rows.map((r) => ({
...productView(r.product, r.creator, r.creatorUsername, r),
libraries: r.libraries,
})),
moderator: mod,
all,
};
},
{
signedIn: true,
query: t.Object({
q: t.Optional(t.String({ maxLength: 100 })),
status: t.Optional(
t.Union(["draft", "published", "unlisted", "deleted", "removed", "locked"].map((s) => t.Literal(s))),
),
all: t.Optional(t.Literal("1")),
}),
},
)
.get(
"/console/catalogs",
async ({ me }) => {
const mod = isModerator(me);
const mine = await perms.teamCatalogs(me.id);
if (!mod && mine.length === 0) throw new Problem(403, "forbidden", "You're not on any catalog's team.");
const rows = mod ? await products.allCatalogs() : await db.select().from(catalog).where(inArray(catalog.id, mine));
return {
catalogs: rows.map((c) => ({ ...catalogView(c), mine: c.ownerId === me.id, team: mine.includes(c.id) })),
moderator: mod,
};
},
{ signedIn: true },
)
.post(
"/console/catalogs/:id/:decision",
async ({ me, params }) => {
const c = await productCall(() =>
products.setCatalogStatus(params.id, params.decision === "approve" ? "approved" : "rejected"),
);
await audited(me, `catalog.${params.decision}`, c.id, { name: c.name });
return { catalog: catalogView(c) };
},
{ moderator: true, params: t.Object({ id: t.String(), decision: t.Union([t.Literal("approve"), t.Literal("reject")]) }) },
)
.get(
"/console",
async ({ me }) => {
const mod = isModerator(me);
const scope = await consoleScope(me);
const sections: ConsoleSection[] = ["overview"];
if (mod || scope.products.length) sections.push("products");
if (mod || scope.catalogs.length) sections.push("catalogs");
if (mod || scope.catalogs.length || scope.products.length || (await cases.list(me, { limit: 1 })).length)
sections.push("cases");
if (mod) sections.push("people");
if (await perms.can(me, "product:remove", hubScope)) sections.push("blocks");
if (sections.length > 1 || scope.rooms.length) sections.push("audit");
if (me.role === "admin") sections.push("settings");
if (sections.length === 1)
throw new Problem(403, "forbidden", "The console is for people who manage something on T5DE: a product, a catalog or a room.");
const [requests] = scope.catalogs.length
? await db
.select({ n: count() })
.from(schema.catalogMember)
.where(and(inArray(schema.catalogMember.catalogId, scope.catalogs), eq(schema.catalogMember.status, "requested")))
: [{ n: 0 }];
let moderation = null;
if (mod) {
const [counts] = await db
.select({
people: sql<number>`(select count(*) from ${user})::int`,
waiting: sql<number>`(select count(*) from ${user} where not ${user.approved} and coalesce(${user.banned}, false) = false)::int`,
links: sql<number>`(select count(*) from ${imvuLink})::int`,
computers: sql<number>`(select count(*) from ${session} where ${session.userAgent} ilike 't5de-proxy%' and ${session.expiresAt} > now())::int`,
pendingCatalogs: sql<number>`(select count(*) from ${catalog} where ${catalog.status} = 'pending')::int`,
})
.from(sql`(select 1) as one`);
moderation = { counts: counts!, connections: realtime.connections(), online: await visibleOnline(me) };
}
return {
sections,
mine: { products: scope.products.length, catalogs: scope.catalogs.length, rooms: scope.rooms.length },
// Sensitive permissions held without two-factor sign-in: the console asks them to turn it on.
twoFactorNeededFor: me.twoFactorEnabled ? [] : await sensitiveHeld(me),
todo: {
drafts: scope.products.length ? await products.draftCount(me.id) : 0,
cases: await cases.openToDecide(me),
memberRequests: requests?.n ?? 0,
pendingCatalogs: moderation?.counts.pendingCatalogs ?? 0,
waitingPeople: moderation?.counts.waiting ?? 0,
},
moderation,
audit: await auditFor(me, scope, { limit: 20 }),
};
},
{ signedIn: true },
)
.get(
"/console/audit",
async ({ me, query }) => {
const scope = await consoleScope(me);
if (!isModerator(me) && !scope.catalogs.length && !scope.products.length && !scope.rooms.length)
throw new Problem(403, "forbidden", "The console is for people who manage something on T5DE.");
const entries = await auditFor(me, scope, query);
return { entries, before: entries.length ? entries[entries.length - 1]!.id : null };
},
{
signedIn: true,
query: t.Object({
catalog: t.Optional(t.String({ maxLength: 32 })),
product: t.Optional(t.String({ maxLength: 32 })),
room: t.Optional(t.String({ maxLength: 32 })),
person: t.Optional(t.String({ maxLength: 64 })),
actor: t.Optional(t.String({ maxLength: 64 })),
action: t.Optional(t.String({ maxLength: 64 })),
q: t.Optional(t.String({ maxLength: 100 })),
from: t.Optional(t.String({ maxLength: 32 })),
to: t.Optional(t.String({ maxLength: 32 })),
before: t.Optional(t.Numeric({ minimum: 1, multipleOf: 1 })),
limit: t.Optional(t.Numeric({ minimum: 1, maximum: 200, multipleOf: 1 })),
}),
},
)
.get(
"/console/permissions",
async ({ me, query }) => {
const scope: Scope =
query.catalog ? { type: "catalog", id: query.catalog } : query.product ? { type: "product", id: query.product } : hubScope;
return { roles: await perms.rolesAt(me, scope), permissions: [...(await perms.at(me, scope))] };
},
{
signedIn: true,
query: t.Object({
catalog: t.Optional(t.String({ pattern: "^[a-z2-7]{10}$" })),
product: t.Optional(t.String({ pattern: "^[a-z2-7]{10}$" })),
}),
},
)
.get(
"/console/people",
async ({ query }) => {
const q = (query.q ?? "").trim();
const like = `%${q.replace(/[%_\\]/g, (c) => "\\" + c)}%`;
const rows = await db
.select()
.from(user)
.where(
and(
q
? or(
ilike(user.username, like),
inArray(user.id, db.select({ id: imvuLink.userId }).from(imvuLink).where(ilike(imvuLink.username, like))),
)
: undefined,
query.waiting ? and(eq(user.approved, false), sql`coalesce(${user.banned}, false) = false`) : undefined,
),
)
.orderBy(desc(user.createdAt))
.limit(100);
return { people: rows.map(personView) };
},
{
moderator: true,
query: t.Object({ q: t.Optional(t.String({ maxLength: 64 })), waiting: t.Optional(t.BooleanString()) }),
},
)
// Accounts waiting for approval (registration closed): approve, or decline (the account is deleted).
.post(
"/console/people/:id/approve",
async ({ me, params }) => {
const p = await personById(params.id);
const [updated] = await db.update(user).set({ approved: true }).where(eq(user.id, p.id)).returning();
if (!p.approved) await audited(me, "person.approve", p.username ?? p.id);
return { person: personView(updated!) };
},
{ moderator: true },
)
.post(
"/console/people/:id/decline",
async ({ me, params }) => {
const p = await personById(params.id);
if (p.approved) throw new Problem(400, "invalid", "Only accounts waiting for approval can be declined.");
await db.delete(user).where(eq(user.id, p.id));
await audited(me, "person.decline", p.username ?? p.id);
return { declined: true };
},
{ moderator: true },
)
.get("/console/settings", async () => ({ registration: await settings.registration() }), { moderator: true })
.put(
"/console/settings",
async ({ me, body }) => {
if (me.role !== "admin") throw new Problem(403, "forbidden", "Only admins can change the hub's settings.");
await need(me, "settings:edit", hubScope);
const from = await settings.registration();
await settings.setRegistration(body.registration);
if (from !== body.registration) await audited(me, "hub.registration", body.registration, { from });
return { registration: body.registration };
},
{
moderator: true,
body: t.Object({ registration: t.Union([t.Literal("open"), t.Literal("closed")]) }),
},
)
.get(
"/console/people/:id",
async ({ params }) => {
const p = await personById(params.id);
const links = await db.select().from(imvuLink).where(eq(imvuLink.userId, p.id)).orderBy(imvuLink.linkedAt);
const [computers] = await db
.select({ n: count() })
.from(session)
.where(and(eq(session.userId, p.id), ilike(session.userAgent, "t5de-proxy%"), sql`${session.expiresAt} > now()`));
return { person: personView(p), links: await linkViews(p.id, links), computers: computers?.n ?? 0 };
},
{ moderator: true },
)
.post(
"/console/people/:id/link-cap",
async ({ me, params, body }) => {
const p = await personById(params.id);
const [updated] = await db.update(user).set({ linkCap: body.linkCap }).where(eq(user.id, p.id)).returning();
await audited(me, "person.link_cap", p.username ?? p.id, { from: p.linkCap, to: body.linkCap });
return { person: personView(updated!) };
},
{ moderator: true, body: t.Object({ linkCap: t.Integer({ minimum: 0, maximum: 1000 }) }) },
)
.post(
"/console/people/:id/ban",
async ({ me, params, body }) => {
await need(me, "person:ban", hubScope);
const p = await personById(params.id);
if (p.id === me.id) throw new Problem(400, "invalid", "You can't ban yourself.");
if (isModerator(p) && me.role !== "admin") throw new Problem(403, "forbidden", "Only admins can ban moderators.");
const [updated] = await db.update(user).set({ banned: true, banReason: body.reason }).where(eq(user.id, p.id)).returning();
await db.delete(session).where(eq(session.userId, p.id));
realtime.disconnect(p.id);
await audited(me, "person.ban", p.username ?? p.id, { reason: body.reason });
return { person: personView(updated!) };
},
{ moderator: true, body: t.Object({ reason: t.String({ minLength: 1, maxLength: 500 }) }) },
)
.post(
"/console/people/:id/unban",
async ({ me, params }) => {
await need(me, "person:ban", hubScope);
const p = await personById(params.id);
const [updated] = await db.update(user).set({ banned: false, banReason: null }).where(eq(user.id, p.id)).returning();
await audited(me, "person.unban", p.username ?? p.id);
return { person: personView(updated!) };
},
{ moderator: true },
)
.post(
"/console/people/:id/role",
async ({ me, params, body }) => {
if (me.role !== "admin") throw new Problem(403, "forbidden", "Only admins can change roles.");
await need(me, "person:role", hubScope);
const p = await personById(params.id);
if (p.id === me.id) throw new Problem(400, "invalid", "Another admin has to change your role.");
const [updated] = await db.update(user).set({ role: body.role }).where(eq(user.id, p.id)).returning();
await audited(me, "person.role", p.username ?? p.id, { from: p.role, to: body.role });
return { person: personView(updated!) };
},
{
moderator: true,
body: t.Object({ role: t.Union([t.Literal("user"), t.Literal("moderator"), t.Literal("admin")]) }),
},
)
// T5DE's proxy: which of the IMVU accounts it's showing get the T5 badge (linked, the badge turned on, the
// person not banned). Nothing else about them.
.post(
"/badges",
async ({ me, body }) => {
if (!limiter.allow(`badges:${me.id}`, 120, 60 * 1000))
throw new Problem(429, "rate_limited", "Too many lookups. Try again in a while.");
const ids = [...new Set(body.imvuIds)];
if (ids.length === 0) return { badges: [] };
const rows = await db
.select({ imvuId: imvuLink.imvuId })
.from(imvuLink)
.innerJoin(user, eq(user.id, imvuLink.userId))
.where(and(inArray(imvuLink.imvuId, ids), eq(imvuLink.showBadge, true), sql`coalesce(${user.banned}, false) = false`));
return { badges: rows.map((r) => r.imvuId) };
},
{
signedIn: true,
body: t.Object({
imvuIds: t.Array(t.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }), { maxItems: 200 }),
}),
},
)
// T5DE's proxy: the live connection.
.ws("/realtime", {
async beforeHandle({ person, set }) {
if (!person) {
set.status = 401;
return { error: "signed_out", message: "Sign in first." };
}
},
open(ws) {
const { person } = ws.data as unknown as { person: Person };
realtime.open(
ws.id,
person.id,
() => ws.close(4001, "signed out"),
(m) => ws.send(JSON.stringify(m)),
);
ws.send(JSON.stringify({ type: "welcome" }));
},
async message(ws, message) {
const reply = await realtime.message(ws.id, message);
if (reply) ws.send(JSON.stringify(reply));
},
close(ws) {
realtime.close(ws.id);
},
});
const app = new Elysia()
// Better Auth's admin endpoints (bans, roles, impersonation) aren't used: the hub's own routes do those, with
// permission and two-factor checks and the audit log.
.all("/api/auth/admin/*", ({ set }) => {
set.status = 404;
return { error: "not_found", message: "Not found." };
})
.all("/api/auth/*", ({ request }) => auth.handler(request))
.get("/.well-known/jwks.json", async () => auth.api.getJwks())
.get("/.well-known/t5de-keys.json", async () => signer.jwks())
.get("/health", () => ({ ok: true }))
.use(api);
return { app, realtime, age, rooms, products, signer, hosted, decorations, imports, importers };
}
export type App = ReturnType<typeof createApp>["app"];