feat: permissions, a scoped console, and catalog management (#7)
Release / release (push) Successful in 4s
CI / test (push) Successful in 1m8s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 6s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 14s

Phase 1 of `docs/console.md` (builds on #6, whose docs commit it includes; merge #6 first).

**API**
- `permissions.ts`: `resource:action` permissions, built-in roles as bundles at a scope (hub, catalog, product), `can`/`require`, "may give" checks. A missing permission answers 403 with `missing: {permission, scope}`.
- Catalog management: settings (incl. rating ceiling, upload policy, mirroring), key rotation, operators, membership (open / approval / invite links, bans), delisting, suspension by moderators, and `GET /api/v1/catalog/changes` for catalogs.
- Membership is enforced: getting a product (403 `members_only` with the catalogs to join), the library list, and outfits relayed to others. Seeing products still needs no membership.
- Console for everyone who controls a catalog, product or hosted room; `/console/audit` (tagged entries, scoped by permission, with filters), `/console/permissions`; `/me` says whether the console is for them.
- Migration 0010: `role_assignment`, `catalog_member`, `catalog_invite`, `catalog_change`, catalog settings, audit `tags` (backfilled from old entries).

**Website**
- Console overview by what you manage; audit log page with filters; catalog list scoped to your teams; a catalog management page (settings, key, team, members, invitations, products, moderation, recent changes).
- Public catalog pages with join / ask / accept invitation / leave; product pages say "members only" and link the catalogs.

**Checked**: 43 API tests pass (8 new in `catalogs.test.ts`); API, web and db type checks; every new page rendered against a local hub for owner, operator, member, outsider and admin; the Eden DELETE-with-query calls tested against the API. Server-action forms weren't clicked through in a browser.

Not in this PR (later phases): catalog deletion requests (with cases), drafts and moderator product edits, notifications, API tokens, two-factor, imports, charts.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Phase 1 of `docs/console.md` (builds on #6, whose docs commit it includes; merge #6 first).

**API**
- `permissions.ts`: `resource:action` permissions, built-in roles as bundles at a scope (hub, catalog, product), `can`/`require`, "may give" checks. A missing permission answers 403 with `missing: {permission, scope}`.
- Catalog management: settings (incl. rating ceiling, upload policy, mirroring), key rotation, operators, membership (open / approval / invite links, bans), delisting, suspension by moderators, and `GET /api/v1/catalog/changes` for catalogs.
- Membership is enforced: getting a product (403 `members_only` with the catalogs to join), the library list, and outfits relayed to others. Seeing products still needs no membership.
- Console for everyone who controls a catalog, product or hosted room; `/console/audit` (tagged entries, scoped by permission, with filters), `/console/permissions`; `/me` says whether the console is for them.
- Migration 0010: `role_assignment`, `catalog_member`, `catalog_invite`, `catalog_change`, catalog settings, audit `tags` (backfilled from old entries).

**Website**
- Console overview by what you manage; audit log page with filters; catalog list scoped to your teams; a catalog management page (settings, key, team, members, invitations, products, moderation, recent changes).
- Public catalog pages with join / ask / accept invitation / leave; product pages say "members only" and link the catalogs.

**Checked**: 43 API tests pass (8 new in `catalogs.test.ts`); API, web and db type checks; every new page rendered against a local hub for owner, operator, member, outsider and admin; the Eden DELETE-with-query calls tested against the API. Server-action forms weren't clicked through in a browser.

Not in this PR (later phases): catalog deletion requests (with cases), drafts and moderator product edits, notifications, API tokens, two-factor, imports, charts.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: dhkatz <[email protected]>
This commit was merged in pull request #7.
This commit is contained in:
dhkatz authored and dhkatz committed 2026-11-05 13:13:42 +00:00
1 parent ed3a188b82
commit 2cbedd26fc
29 files changed
+5657 -181

No files matched your search

+580 -28
View File
@@ -15,6 +15,7 @@ import {
count,
schema,
type Database,
type AuditTags,
type ParentInfo,
type RoomModerator,
} from "@t5de/db";
@@ -25,7 +26,7 @@ import { ImvuClient, ImvuUnavailable, NoSuchImvuUser } from "./imvu";
import { Realtime } from "./realtime";
import { isAdultRoom, Rooms } from "./rooms";
import { Signer } from "./keys";
import { ProductError, Products } from "./products";
import { availableTo, ProductError, Products } from "./products";
import {
chatId,
HostedError,
@@ -41,8 +42,10 @@ import {
} from "./hosted";
import { DecorationError, Decorations, maxBatch, maxDecorationPlacement, maxDecorations } from "./decorations";
import { Settings } from "./settings";
import { Catalogs } from "./catalogs";
import { assignableCatalogRoles, Forbidden, hubScope, Permissions, roles as roleBundles, type Scope } from "./permissions";
const { user, session, imvuLink, linkChallenge, audit } = schema;
const { user, session, imvuLink, linkChallenge, audit, hostedRoom, catalog, product } = schema;
export type Deps = {
db: Database;
@@ -55,6 +58,8 @@ export type Deps = {
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;
};
@@ -65,11 +70,19 @@ export class Problem extends Error {
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;
@@ -117,11 +130,14 @@ export function createApp({
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 catalogs = new Catalogs(db, catalogHealthy);
const rooms = roomsService ?? new Rooms(db, imvu);
const hosted = new HostedRooms(db);
const decorations = new Decorations(db);
@@ -154,6 +170,13 @@ export function createApp({
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();
@@ -220,8 +243,33 @@ export function createApp({
};
const linkView = async (l: Link) => (await linkViews(l.userId, [l]))[0]!;
const audited = (actorId: string | null, action: string, target: string, detail: Record<string, unknown> = {}) =>
db.insert(audit).values({ actorId, action, target, detail });
/** 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 = (
actorId: string | null,
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;
}
return db.insert(audit).values({ actorId, action, target, 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);
throw e;
}
};
/** Who's online that viewer may see: accounts showing their presence (moderators see all). */
const visibleOnline = async (viewer: Person | undefined) => {
@@ -298,9 +346,124 @@ export function createApp({
visibility: c.visibility,
membership: c.membership,
status: c.status,
statusReason: c.statusReason,
maxRating: c.maxRating,
uploads: c.uploads,
mirrors: c.mirrors,
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" | "people" | "audit" | "settings";
/** 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,
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 ?? "";
return rows.map((r) => ({
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 {
@@ -452,7 +615,7 @@ export function createApp({
.onError(({ code, error, set }) => {
if (code === "Problem") {
set.status = error.status;
return { error: error.slug, message: error.message };
return { error: error.slug, message: error.message, ...error.extra };
}
if (code === "VALIDATION") {
set.status = 400;
@@ -501,7 +664,19 @@ export function createApp({
})
// Who's signed in, and the home page.
.get("/me", async ({ me }) => ({ person: { ...personView(me), picture: await picture(me.id) } }), { account: true })
.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 } };
},
{ account: true },
)
// The hub's public settings: whether new accounts wait for approval.
.get("/hub", async () => ({ registration: await settings.registration() }))
.get("/home", async ({ person }) => {
@@ -1104,6 +1279,298 @@ export function createApp({
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.id, "catalog.edit", params.id, { changed: r.changed });
return { catalog: catalogView(r.catalog) };
},
{
signedIn: 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.id, "catalog.rotate_key", params.id);
return { key };
},
{ signedIn: 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.id, "catalog.suspend", c.id, { name: c.name, reason: body.reason.trim() });
return { catalog: catalogView(c) };
},
{ signedIn: true, params: catalogParam, body: t.Object({ reason: t.String({ minLength: 1, maxLength: 500 }) }) },
)
.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.id, "catalog.reinstate", c.id, { name: c.name });
return { catalog: catalogView(c) };
},
{ signedIn: 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],
})),
};
},
{ signedIn: 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.id, "catalog.team_add", params.id, { person: p.username, role: body.role }, { catalog: params.id, person: p.id });
return { team: await perms.team(params.id) };
},
{
signedIn: 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.id, "catalog.team_remove", params.id, { person: p.username, role: query.role }, { catalog: params.id, person: p.id });
return { team: await perms.team(params.id) };
},
{
signedIn: 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.id, 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.id, "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) };
},
{
signedIn: 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.id, action, params.id, { person: p.username, ...(before ? { from: before } : {}) }, {
catalog: params.id,
person: p.id,
});
realtime.notify(p.id, { type: "library" });
return { membership: body.status };
},
{
signedIn: 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.id, action, params.id, { person: p.username }, { catalog: params.id, person: p.id });
realtime.notify(p.id, { type: "library" });
set.status = 204;
},
{
signedIn: 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) };
},
{ signedIn: 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.id, "catalog.invite_create", params.id, {
maxUses: inv.maxUses,
expiresAt: inv.expiresAt?.toISOString() ?? null,
});
set.status = 201;
return { invite: inviteView(inv) };
},
{
signedIn: 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.id, "catalog.invite_revoke", params.id, { code: params.code.slice(0, 3) + "…" });
set.status = 204;
},
{
signedIn: 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) };
},
{ signedIn: 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.id, "catalog.delist", params.id, { product: params.product, revisions, reason }, {
catalog: params.id,
product: params.product,
});
return { revisions };
},
{
signedIn: 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",
@@ -1170,6 +1637,14 @@ export function createApp({
inLibrary: lib !== undefined,
stayOn: lib?.stayOn ?? null,
mine: person?.id === p.product.creatorId,
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 },
@@ -1262,7 +1737,14 @@ export function createApp({
.put(
"/library/:id",
async ({ me, params }) => {
await productCall(async () => products.add(me.id, params.id, await personAdult(me)));
try {
await products.add(me.id, params.id, await personAdult(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 };
},
@@ -1388,8 +1870,17 @@ export function createApp({
// The console.
.get(
"/console/catalogs",
async () => ({ catalogs: (await products.allCatalogs()).map(catalogView) }),
{ moderator: true },
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",
@@ -1405,28 +1896,89 @@ export function createApp({
.get(
"/console",
async ({ me }) => {
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`,
})
.from(sql`(select 1) as one`);
const log = await db
.select({ at: audit.at, actor: user.username, action: audit.action, target: audit.target, detail: audit.detail })
.from(audit)
.leftJoin(user, eq(user.id, audit.actorId))
.orderBy(desc(audit.id))
.limit(50);
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) sections.push("people");
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 {
counts: counts!,
connections: realtime.connections(),
online: await visibleOnline(me),
audit: log.map((e) => ({ ...e, at: e.at.toISOString(), actor: e.actor ?? "" })),
sections,
mine: { products: scope.products.length, catalogs: scope.catalogs.length, rooms: scope.rooms.length },
todo: {
memberRequests: requests?.n ?? 0,
pendingCatalogs: moderation?.counts.pendingCatalogs ?? 0,
waitingPeople: moderation?.counts.waiting ?? 0,
},
moderation,
audit: await auditFor(me, scope, { limit: 20 }),
};
},
{ moderator: true },
{ 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",