feat: personal API tokens (#11)
Phase 3, part 3 (`docs/design.md`, "Next"): personal API tokens, for scripts. Two-factor sign-in comes next as its own PR. **Making them** - On the account page, in a new API Tokens card. You give each token: - a name - how long it lasts: 7 days, 30 days, 90 days or 1 year - what it may do: permissions you hold, picked for each product of yours or catalog whose team you're on (moderators and admins can also pick everywhere) - The token is shown once, with a Copy button. Only its hash is stored. - The card lists active tokens: what each grants, when it expires, and when it was last used. Each can be revoked; revoked and expired ones are folded away below. - Tokens are made and revoked only from a website session, so a token can't make tokens. Limits: 20 active tokens, 50 grants each, 1 year at most. **Using them** - Send `Authorization: Bearer t5de_pat_...`. - A token works only on routes that check a permission: - product info, publishing, locks and history - uploading and retracting revisions of a product: these now check `revision:upload` and `revision:retract` - a catalog's settings, key, team, members, invites and hosted products - file blocks, and assigning cases - Everywhere else answers 403 `token_not_allowed`, including making a new product, reports, `/me` and the console. A wrong, revoked or expired token gets 401 `bad_token`. - Each check is the intersection of what the token grants and what the person holds now: a token never does more than its owner can, and losing a role takes it from the token at once. **Audit** - Actions taken with a token are recorded as the person, with `token: <name>` added to the details. - Making and revoking a token are audited as `token.create` and `token.revoke`. **Migration** `0014_api_tokens`: the `api_token` table. **Checks** - 56 API tests pass. The new `tokens.test.ts` covers: - only permissions held now can be granted - grants are limited to their product or catalog - session-only routes refuse tokens - uploads by token - the audit marking and last use - revoked and expired tokens - a moderator demoted while their token was active - Type checks pass. - On a local hub, through the website: - the card shows what can be granted - making a token (refused without any permission chosen); the token was shown once - using it for a granted edit and the member list; refused for what it wasn't given, and on `/me` - its last use on the account page, and the audit entry naming it - Revoke, after which the token got 401 Phase 3, part 3 (`docs/design.md`, "Next"): personal API tokens, for scripts. Two-factor sign-in comes next as its own PR. **Making them** - On the account page, in a new API Tokens card. You give each token: - a name - how long it lasts: 7 days, 30 days, 90 days or 1 year - what it may do: permissions you hold, picked for each product of yours or catalog whose team you're on (moderators and admins can also pick everywhere) - The token is shown once, with a Copy button. Only its hash is stored. - The card lists active tokens: what each grants, when it expires, and when it was last used. Each can be revoked; revoked and expired ones are folded away below. - Tokens are made and revoked only from a website session, so a token can't make tokens. Limits: 20 active tokens, 50 grants each, 1 year at most. **Using them** - Send `Authorization: Bearer t5de_pat_...`. - A token works only on routes that check a permission: - product info, publishing, locks and history - uploading and retracting revisions of a product: these now check `revision:upload` and `revision:retract` - a catalog's settings, key, team, members, invites and hosted products - file blocks, and assigning cases - Everywhere else answers 403 `token_not_allowed`, including making a new product, reports, `/me` and the console. A wrong, revoked or expired token gets 401 `bad_token`. - Each check is the intersection of what the token grants and what the person holds now: a token never does more than its owner can, and losing a role takes it from the token at once. **Audit** - Actions taken with a token are recorded as the person, with `token: <name>` added to the details. - Making and revoking a token are audited as `token.create` and `token.revoke`. **Migration** `0014_api_tokens`: the `api_token` table. **Checks** - 56 API tests pass. The new `tokens.test.ts` covers: - only permissions held now can be granted - grants are limited to their product or catalog - session-only routes refuse tokens - uploads by token - the audit marking and last use - revoked and expired tokens - a moderator demoted while their token was active - Type checks pass. - On a local hub, through the website: - the card shows what can be granted - making a token (refused without any permission chosen); the token was shown once - using it for a granted edit and the member list; refused for what it wasn't given, and on `/me` - its last use on the account page, and the audit entry naming it - Revoke, after which the token got 401 Note: the permission list also offers permissions for which no route takes tokens yet, such as `import:*` and `stats:read`. They'll work once those features have routes. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Note: the permission list also offers permissions for which no route takes tokens yet, such as `import:*` and `stats:read`. They'll work once those features have routes. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: dhkatz <[email protected]>
This commit was merged in pull request #11.
This commit is contained in:
1 parent
58a3e70a63
commit
69c55a72fb
17 files changed
+4410
-98
No files matched your search
+210
-84
@@ -8,6 +8,7 @@ import {
|
||||
desc,
|
||||
eq,
|
||||
ilike,
|
||||
isNull,
|
||||
inArray,
|
||||
ne,
|
||||
or,
|
||||
@@ -46,6 +47,7 @@ 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, type Scope } from "./permissions";
|
||||
|
||||
const { user, session, imvuLink, linkChallenge, audit, hostedRoom, catalog, product, hosting } = schema;
|
||||
@@ -140,6 +142,7 @@ export function createApp({
|
||||
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);
|
||||
@@ -264,7 +267,7 @@ export function createApp({
|
||||
/** 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,
|
||||
actor: string | null | { id: string; token?: { name: string } },
|
||||
action: string,
|
||||
target: string,
|
||||
detail: Record<string, unknown> = {},
|
||||
@@ -276,7 +279,10 @@ export function createApp({
|
||||
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 });
|
||||
// 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. */
|
||||
@@ -411,6 +417,31 @@ export function createApp({
|
||||
|
||||
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,
|
||||
@@ -477,17 +508,17 @@ export function createApp({
|
||||
products.updateInfo(me.id, id, { rating: "general" }, reason, { creator: false, editLocked: true, rateLower: true }),
|
||||
);
|
||||
if (done.entry) {
|
||||
await audited(me.id, "product.edit", id, { fields: done.fields, reason, case: c.id }, { product: id, person: creatorId });
|
||||
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.id, "product.remove", removed.id, { reason, case: c.id }, { product: removed.id, person: removed.creatorId });
|
||||
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.id, "catalog.delete", deleted.id, { name: deleted.name, case: c.id });
|
||||
await audited(me, "catalog.delete", deleted.id, { name: deleted.name, case: c.id });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -754,6 +785,20 @@ export function createApp({
|
||||
}
|
||||
})
|
||||
.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).
|
||||
@@ -762,32 +807,47 @@ export function createApp({
|
||||
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 }) => {
|
||||
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 }) => {
|
||||
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 }) => {
|
||||
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.
|
||||
@@ -1032,7 +1092,7 @@ export function createApp({
|
||||
await age.forgetAccount(l.imvuId);
|
||||
await rooms.forgetOwner(l.imvuId);
|
||||
realtime.unlinked(me.id, l.imvuId);
|
||||
await audited(me.id, "link.remove", String(l.imvuId), { imvu: l.username });
|
||||
await audited(me, "link.remove", String(l.imvuId), { imvu: l.username });
|
||||
set.status = 204;
|
||||
},
|
||||
{ signedIn: true, params: imvuIdParam },
|
||||
@@ -1059,7 +1119,7 @@ export function createApp({
|
||||
} catch {
|
||||
throw new Problem(404, "not_found", "That code isn't right, or it expired. Check the code T5DE shows.");
|
||||
}
|
||||
await audited(me.id, "proxy.signin", "");
|
||||
await audited(me, "proxy.signin", "");
|
||||
set.status = 204;
|
||||
},
|
||||
{ signedIn: true, body: t.Object({ code: t.String({ minLength: 4, maxLength: 32 }) }) },
|
||||
@@ -1105,7 +1165,7 @@ export function createApp({
|
||||
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.id, "hosted_room.create", String(r.room.n), {
|
||||
await audited(me, "hosted_room.create", String(r.room.n), {
|
||||
name: r.room.name,
|
||||
rating: r.room.rating,
|
||||
privacy: r.room.privacy,
|
||||
@@ -1175,7 +1235,7 @@ export function createApp({
|
||||
: 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.id, "hosted_room.edit", String(r.room.n), {
|
||||
await audited(me, "hosted_room.edit", String(r.room.n), {
|
||||
fields: Object.keys(body),
|
||||
...(changes.moderators ? { moderators: changes.moderators.map((m) => m.imvuId) } : {}),
|
||||
});
|
||||
@@ -1218,7 +1278,7 @@ export function createApp({
|
||||
async ({ me, params, set }) => {
|
||||
const r = await hostedCall(() => hosted.close(me.id, isModerator(me), params.n));
|
||||
realtime.hostedClosed(r.n);
|
||||
await audited(me.id, "hosted_room.close", String(r.n), { name: r.name, ...(r.ownerId !== me.id ? { owner: r.ownerId } : {}) });
|
||||
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 },
|
||||
@@ -1254,7 +1314,7 @@ export function createApp({
|
||||
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.id, "hosted_room.unban", String(params.n), { imvu: params.imvu });
|
||||
await audited(me, "hosted_room.unban", String(params.n), { imvu: params.imvu });
|
||||
set.status = 204;
|
||||
},
|
||||
{
|
||||
@@ -1291,7 +1351,7 @@ export function createApp({
|
||||
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.id, "hosted_room.image", String(params.n), { bytes: data.length });
|
||||
await audited(me, "hosted_room.image", String(params.n), { bytes: data.length });
|
||||
return { room: await hostedViewFor(r, me) };
|
||||
},
|
||||
{
|
||||
@@ -1309,7 +1369,7 @@ export function createApp({
|
||||
"/hosted-rooms/:n/image",
|
||||
async ({ me, params }) => {
|
||||
const r = await hostedCall(() => hosted.removeImage(me.id, params.n));
|
||||
await audited(me.id, "hosted_room.image", String(params.n), { removed: true });
|
||||
await audited(me, "hosted_room.image", String(params.n), { removed: true });
|
||||
return { room: await hostedViewFor(r, me) };
|
||||
},
|
||||
{ signedIn: true, params: hostedParam },
|
||||
@@ -1389,7 +1449,7 @@ export function createApp({
|
||||
"/catalogs",
|
||||
async ({ me, body, set }) => {
|
||||
const r = await productCall(() => products.registerCatalog(me.id, body));
|
||||
await audited(me.id, "catalog.register", r.catalog.id, { name: r.catalog.name, url: r.catalog.url });
|
||||
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 };
|
||||
},
|
||||
@@ -1432,11 +1492,11 @@ export function createApp({
|
||||
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 });
|
||||
if (Object.keys(r.changed).length) await audited(me, "catalog.edit", params.id, { changed: r.changed });
|
||||
return { catalog: catalogView(r.catalog) };
|
||||
},
|
||||
{
|
||||
signedIn: true,
|
||||
scripted: true,
|
||||
params: catalogParam,
|
||||
body: t.Object({
|
||||
name: t.Optional(t.String({ maxLength: 64 })),
|
||||
@@ -1455,20 +1515,20 @@ export function createApp({
|
||||
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);
|
||||
await audited(me, "catalog.rotate_key", params.id);
|
||||
return { key };
|
||||
},
|
||||
{ signedIn: true, params: catalogParam },
|
||||
{ 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.id, "catalog.suspend", c.id, { name: c.name, reason: body.reason.trim() });
|
||||
await audited(me, "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 }) }) },
|
||||
{ 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(
|
||||
@@ -1480,20 +1540,20 @@ export function createApp({
|
||||
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.id, "case.open", String(kase.id), { kind: kase.kind }, kase.tags);
|
||||
await audited(me, "case.open", String(kase.id), { kind: kase.kind }, kase.tags);
|
||||
return { case: kase.id };
|
||||
},
|
||||
{ signedIn: true, params: catalogParam, body: t.Object({ reason: t.String({ minLength: 1, maxLength: 2000 }) }) },
|
||||
{ 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.id, "catalog.reinstate", c.id, { name: c.name });
|
||||
await audited(me, "catalog.reinstate", c.id, { name: c.name });
|
||||
return { catalog: catalogView(c) };
|
||||
},
|
||||
{ signedIn: true, params: catalogParam },
|
||||
{ scripted: true, params: catalogParam },
|
||||
)
|
||||
|
||||
// A catalog's team: the owner, and the roles it gave.
|
||||
@@ -1511,7 +1571,7 @@ export function createApp({
|
||||
})),
|
||||
};
|
||||
},
|
||||
{ signedIn: true, params: catalogParam },
|
||||
{ scripted: true, params: catalogParam },
|
||||
)
|
||||
.put(
|
||||
"/catalogs/:id/team/:username",
|
||||
@@ -1522,11 +1582,11 @@ export function createApp({
|
||||
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 });
|
||||
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) };
|
||||
},
|
||||
{
|
||||
signedIn: true,
|
||||
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") }),
|
||||
},
|
||||
@@ -1539,11 +1599,11 @@ export function createApp({
|
||||
// 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 });
|
||||
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) };
|
||||
},
|
||||
{
|
||||
signedIn: true,
|
||||
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") }),
|
||||
},
|
||||
@@ -1555,7 +1615,7 @@ export function createApp({
|
||||
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 } : {}, {
|
||||
await audited(me, status === "member" ? "catalog.join" : "catalog.request", params.id, invite ? { invite: true } : {}, {
|
||||
catalog: params.id,
|
||||
person: me.id,
|
||||
});
|
||||
@@ -1572,7 +1632,7 @@ export function createApp({
|
||||
"/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 });
|
||||
await audited(me, "catalog.leave", params.id, {}, { catalog: params.id, person: me.id });
|
||||
realtime.notify(me.id, { type: "library" });
|
||||
set.status = 204;
|
||||
},
|
||||
@@ -1585,7 +1645,7 @@ export function createApp({
|
||||
return { members: await catalogs.members(params.id, query.status), counts: await catalogs.memberCounts(params.id) };
|
||||
},
|
||||
{
|
||||
signedIn: true,
|
||||
scripted: true,
|
||||
params: catalogParam,
|
||||
query: t.Object({
|
||||
status: t.Optional(t.Union([t.Literal("requested"), t.Literal("member"), t.Literal("banned")])),
|
||||
@@ -1601,7 +1661,7 @@ export function createApp({
|
||||
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 } : {}) }, {
|
||||
await audited(me, action, params.id, { person: p.username, ...(before ? { from: before } : {}) }, {
|
||||
catalog: params.id,
|
||||
person: p.id,
|
||||
});
|
||||
@@ -1613,7 +1673,7 @@ export function createApp({
|
||||
return { membership: body.status };
|
||||
},
|
||||
{
|
||||
signedIn: true,
|
||||
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")]) }),
|
||||
},
|
||||
@@ -1627,7 +1687,7 @@ export function createApp({
|
||||
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 });
|
||||
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);
|
||||
@@ -1636,7 +1696,7 @@ export function createApp({
|
||||
set.status = 204;
|
||||
},
|
||||
{
|
||||
signedIn: true,
|
||||
scripted: true,
|
||||
params: t.Object({ id: t.String({ pattern: "^[a-z2-7]{10}$" }), username: t.String({ maxLength: 64 }) }),
|
||||
},
|
||||
)
|
||||
@@ -1646,14 +1706,14 @@ export function createApp({
|
||||
await need(me, "member:invite", catalogScope(params.id));
|
||||
return { invites: (await catalogs.invites(params.id)).map(inviteView) };
|
||||
},
|
||||
{ signedIn: true, params: catalogParam },
|
||||
{ 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.id, "catalog.invite_create", params.id, {
|
||||
await audited(me, "catalog.invite_create", params.id, {
|
||||
maxUses: inv.maxUses,
|
||||
expiresAt: inv.expiresAt?.toISOString() ?? null,
|
||||
});
|
||||
@@ -1661,7 +1721,7 @@ export function createApp({
|
||||
return { invite: inviteView(inv) };
|
||||
},
|
||||
{
|
||||
signedIn: true,
|
||||
scripted: true,
|
||||
params: catalogParam,
|
||||
body: t.Object({
|
||||
maxUses: t.Optional(t.Integer({ minimum: 1, maximum: 10_000 })),
|
||||
@@ -1674,11 +1734,11 @@ export function createApp({
|
||||
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) + "…" });
|
||||
await audited(me, "catalog.invite_revoke", params.id, { code: params.code.slice(0, 3) + "…" });
|
||||
set.status = 204;
|
||||
},
|
||||
{
|
||||
signedIn: true,
|
||||
scripted: true,
|
||||
params: t.Object({ id: t.String({ pattern: "^[a-z2-7]{10}$" }), code: t.String({ maxLength: 32 }) }),
|
||||
},
|
||||
)
|
||||
@@ -1690,7 +1750,7 @@ export function createApp({
|
||||
await need(me, "audit:read", catalogScope(params.id));
|
||||
return { products: await catalogs.hosted(params.id) };
|
||||
},
|
||||
{ signedIn: true, params: catalogParam },
|
||||
{ scripted: true, params: catalogParam },
|
||||
)
|
||||
.delete(
|
||||
"/catalogs/:id/products/:product",
|
||||
@@ -1698,14 +1758,14 @@ export function createApp({
|
||||
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 }, {
|
||||
await audited(me, "catalog.delist", params.id, { product: params.product, revisions, reason }, {
|
||||
catalog: params.id,
|
||||
product: params.product,
|
||||
});
|
||||
return { revisions };
|
||||
},
|
||||
{
|
||||
signedIn: true,
|
||||
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 }) }),
|
||||
},
|
||||
@@ -1757,8 +1817,13 @@ export function createApp({
|
||||
// Products.
|
||||
.post(
|
||||
"/products/upload",
|
||||
async ({ me, body }) => productCall(() => products.uploadToken(me.id, body.catalog, body.product)),
|
||||
{ signedIn: true, body: t.Object({ catalog: t.String(), product: t.Optional(t.String()) }) },
|
||||
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",
|
||||
@@ -1831,14 +1896,14 @@ export function createApp({
|
||||
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.id, "case.open", String(c.id), { kind: c.kind }, c.tags);
|
||||
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.id, "product.edit", params.id, { fields: done.fields, ...(reason ? { reason } : {}) }, {
|
||||
await audited(me, "product.edit", params.id, { fields: done.fields, ...(reason ? { reason } : {}) }, {
|
||||
product: params.id,
|
||||
person: creatorId,
|
||||
});
|
||||
@@ -1851,7 +1916,7 @@ export function createApp({
|
||||
};
|
||||
},
|
||||
{
|
||||
signedIn: true,
|
||||
scripted: true,
|
||||
params: productParam,
|
||||
body: t.Object({
|
||||
name: t.Optional(t.String({ maxLength: 64 })),
|
||||
@@ -1874,7 +1939,7 @@ export function createApp({
|
||||
const parent = (await products.latestParent(p!))?.parentInfo?.categories ?? [];
|
||||
return { choices: await products.categoryChoices(p!), parent };
|
||||
},
|
||||
{ signedIn: true, params: productParam },
|
||||
{ scripted: true, params: productParam },
|
||||
)
|
||||
// A draft becomes published.
|
||||
.post(
|
||||
@@ -1883,10 +1948,10 @@ export function createApp({
|
||||
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.id, "product.publish", p.id, { name: p.name }, { product: p.id, person: creatorId });
|
||||
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)) };
|
||||
},
|
||||
{ signedIn: true, params: productParam },
|
||||
{ scripted: true, params: productParam },
|
||||
)
|
||||
// The info history: who changed what, and why.
|
||||
.get(
|
||||
@@ -1908,7 +1973,7 @@ export function createApp({
|
||||
})),
|
||||
};
|
||||
},
|
||||
{ signedIn: true, params: productParam },
|
||||
{ scripted: true, params: productParam },
|
||||
)
|
||||
.post(
|
||||
"/products/:id/history/:entry/revert",
|
||||
@@ -1933,7 +1998,7 @@ export function createApp({
|
||||
};
|
||||
},
|
||||
{
|
||||
signedIn: true,
|
||||
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 })) }),
|
||||
},
|
||||
@@ -1945,7 +2010,7 @@ export function createApp({
|
||||
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.id, "product.lock", p.id, { fields: p.locked, reason: body.reason.trim() }, {
|
||||
await audited(me, "product.lock", p.id, { fields: p.locked, reason: body.reason.trim() }, {
|
||||
product: p.id,
|
||||
person: creatorId,
|
||||
});
|
||||
@@ -1953,7 +2018,7 @@ export function createApp({
|
||||
return { product: productView(p, undefined, undefined, await products.latestParent(p)) };
|
||||
},
|
||||
{
|
||||
signedIn: true,
|
||||
scripted: true,
|
||||
params: productParam,
|
||||
body: t.Object({
|
||||
fields: t.Array(
|
||||
@@ -1976,7 +2041,7 @@ export function createApp({
|
||||
"/products/:id",
|
||||
async ({ me, params, set }) => {
|
||||
await productCall(() => products.delete(me.id, params.id));
|
||||
await audited(me.id, "product.delete", params.id);
|
||||
await audited(me, "product.delete", params.id);
|
||||
set.status = 204;
|
||||
},
|
||||
{ signedIn: true, params: productParam },
|
||||
@@ -1986,7 +2051,7 @@ export function createApp({
|
||||
"/products/:id/remove",
|
||||
async ({ me, params, body }) => {
|
||||
const removed = await productCall(() => products.removeByModeration(params.id, body.reason.trim()));
|
||||
await audited(me.id, "product.remove", params.id, { reason: body.reason.trim() }, {
|
||||
await audited(me, "product.remove", params.id, { reason: body.reason.trim() }, {
|
||||
product: params.id,
|
||||
person: removed.creatorId,
|
||||
});
|
||||
@@ -1995,6 +2060,66 @@ export function createApp({
|
||||
},
|
||||
{ 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",
|
||||
@@ -2004,7 +2129,7 @@ export function createApp({
|
||||
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 };
|
||||
},
|
||||
{ signedIn: true, query: t.Object({ before: t.Optional(t.String({ format: "date-time" })) }) },
|
||||
{ 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(
|
||||
@@ -2014,7 +2139,7 @@ export function createApp({
|
||||
const b = await blocks.get(params.sha256);
|
||||
return { block: b ? blockView(b) : null, products: await blocks.usedBy(params.sha256) };
|
||||
},
|
||||
{ signedIn: true, params: blockParam },
|
||||
{ scripted: true, params: blockParam },
|
||||
)
|
||||
.put(
|
||||
"/blocks/:sha256",
|
||||
@@ -2023,14 +2148,14 @@ export function createApp({
|
||||
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.id, "file.block", params.sha256, { reason, removed: removed.map((p) => p.id) });
|
||||
await audited(me, "file.block", params.sha256, { reason, removed: removed.map((p) => p.id) });
|
||||
for (const p of removed) {
|
||||
await audited(me.id, "product.remove", p.id, { reason, file: params.sha256 }, { product: p.id, person: p.creatorId });
|
||||
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 })) };
|
||||
},
|
||||
{ signedIn: true, params: blockParam, body: t.Object({ reason: t.String({ maxLength: 500 }) }) },
|
||||
{ scripted: true, params: blockParam, body: t.Object({ reason: t.String({ maxLength: 500 }) }) },
|
||||
)
|
||||
.delete(
|
||||
"/blocks/:sha256",
|
||||
@@ -2038,10 +2163,10 @@ export function createApp({
|
||||
await need(me, "product:remove", hubScope);
|
||||
await productCall(() => blocks.unblock(params.sha256));
|
||||
const reason = body?.reason?.trim() ?? "";
|
||||
await audited(me.id, "file.unblock", params.sha256, reason ? { reason } : {});
|
||||
await audited(me, "file.unblock", params.sha256, reason ? { reason } : {});
|
||||
set.status = 204;
|
||||
},
|
||||
{ signedIn: true, params: blockParam, body: t.Optional(t.Object({ reason: t.Optional(t.String({ maxLength: 500 })) })) },
|
||||
{ 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(
|
||||
@@ -2050,20 +2175,21 @@ export function createApp({
|
||||
await need(me, "product:unremove", productScope(params.id));
|
||||
const p = await productCall(() => products.unremove(params.id));
|
||||
const reason = body.reason?.trim() ?? "";
|
||||
await audited(me.id, "product.unremove", p.id, reason ? { reason } : {}, { product: p.id, person: p.creatorId });
|
||||
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 };
|
||||
},
|
||||
{ signedIn: true, params: productParam, body: t.Object({ reason: t.Optional(t.String({ maxLength: 500 })) }) },
|
||||
{ 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.id, "product.retract", params.id, { revision: params.n });
|
||||
await audited(me, "product.retract", params.id, { revision: params.n });
|
||||
return { ok: true };
|
||||
},
|
||||
{ signedIn: true, params: t.Object({ id: t.String({ pattern: "^[a-z2-7]{10}$" }), n: t.Numeric({ minimum: 1 }) }) },
|
||||
{ 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(
|
||||
@@ -2188,7 +2314,7 @@ export function createApp({
|
||||
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.id, "age.start", p.id, { ref: started.kind === "done" ? null : started.ref });
|
||||
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 }) }) },
|
||||
@@ -2314,7 +2440,7 @@ export function createApp({
|
||||
});
|
||||
}
|
||||
// A report's entry isn't tagged with what it's about: who reported stays private (the reporter still sees it).
|
||||
await audited(me.id, "case.open", String(c.id), { kind: c.kind }, c.kind === "report" ? {} : c.tags);
|
||||
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) };
|
||||
},
|
||||
@@ -2385,10 +2511,10 @@ export function createApp({
|
||||
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.id, "case.assign", String(c.id), { to: to?.username ?? null }, c.kind === "report" ? {} : c.tags);
|
||||
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) };
|
||||
},
|
||||
{ signedIn: true, params: caseParam, body: t.Object({ to: t.Union([t.String({ maxLength: 64 }), t.Null()]) }) },
|
||||
{ scripted: true, params: caseParam, body: t.Object({ to: t.Union([t.String({ maxLength: 64 }), t.Null()]) }) },
|
||||
)
|
||||
.post(
|
||||
"/cases/:id/decide",
|
||||
@@ -2509,7 +2635,7 @@ export function createApp({
|
||||
const c = await productCall(() =>
|
||||
products.setCatalogStatus(params.id, params.decision === "approve" ? "approved" : "rejected"),
|
||||
);
|
||||
await audited(me.id, `catalog.${params.decision}`, c.id, { name: c.name });
|
||||
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")]) }) },
|
||||
@@ -2640,7 +2766,7 @@ export function createApp({
|
||||
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.id, "person.approve", p.username ?? p.id);
|
||||
if (!p.approved) await audited(me, "person.approve", p.username ?? p.id);
|
||||
return { person: personView(updated!) };
|
||||
},
|
||||
{ moderator: true },
|
||||
@@ -2651,7 +2777,7 @@ export function createApp({
|
||||
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.id, "person.decline", p.username ?? p.id);
|
||||
await audited(me, "person.decline", p.username ?? p.id);
|
||||
return { declined: true };
|
||||
},
|
||||
{ moderator: true },
|
||||
@@ -2663,7 +2789,7 @@ export function createApp({
|
||||
if (me.role !== "admin") throw new Problem(403, "forbidden", "Only admins can change the hub's settings.");
|
||||
const from = await settings.registration();
|
||||
await settings.setRegistration(body.registration);
|
||||
if (from !== body.registration) await audited(me.id, "hub.registration", body.registration, { from });
|
||||
if (from !== body.registration) await audited(me, "hub.registration", body.registration, { from });
|
||||
return { registration: body.registration };
|
||||
},
|
||||
{
|
||||
@@ -2689,7 +2815,7 @@ export function createApp({
|
||||
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.id, "person.link_cap", p.username ?? p.id, { from: p.linkCap, to: body.linkCap });
|
||||
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 }) }) },
|
||||
@@ -2703,7 +2829,7 @@ export function createApp({
|
||||
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.id, "person.ban", p.username ?? p.id, { reason: body.reason });
|
||||
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 }) }) },
|
||||
@@ -2713,7 +2839,7 @@ export function createApp({
|
||||
async ({ me, params }) => {
|
||||
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.id, "person.unban", p.username ?? p.id);
|
||||
await audited(me, "person.unban", p.username ?? p.id);
|
||||
return { person: personView(updated!) };
|
||||
},
|
||||
{ moderator: true },
|
||||
@@ -2725,7 +2851,7 @@ export function createApp({
|
||||
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.id, "person.role", p.username ?? p.id, { from: p.role, to: body.role });
|
||||
await audited(me, "person.role", p.username ?? p.id, { from: p.role, to: body.role });
|
||||
return { person: personView(updated!) };
|
||||
},
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user