From e01840e6c8fcdd6abb40fd855bc72f73e18d5857 Mon Sep 17 00:00:00 2001 From: Yevhen Boichuk Date: Thu, 22 Oct 2026 12:43:33 +0300 Subject: [PATCH] feat: moderator tools for items and users All items: - each row shows versions, waiting versions, rating, open reports and who created it (or the import); - Manage: edit every field including the author line (moderators get the import's longer limits, so imported items can be saved), publish or hide, every version with file preview and approve/reject, the item's reports with resolve, and delete for good (DELETE /mod/apps/:slug, the slug must be typed again; versions, ratings, reports and R2 files go). Users: - Details: profile, created items (today and in all), ratings given, active sessions, last sign-in, owned items (handed-over ones marked, each a jump to All items) and reports filed; - a private moderator note, and "trusted", which lifts the 3-a-day, 20-in-all and 5-waiting limits (still scanned and reviewed); - end all sessions, remove all ratings, ban and unban. Migration 0008 adds users.trusted and users.mod_note. smoke.sh: 151 checks. Co-Authored-By: Claude Opus 5.5 --- README.md | 7 +- api/README.md | 11 +- api/migrations/0008_moderation_tools.sql | 6 + api/scripts/smoke.sh | 38 +++ api/src/apps.ts | 32 ++- api/src/auth.ts | 2 +- api/src/env.ts | 2 + api/src/moderation.ts | 185 +++++++++++- site/community.js | 346 ++++++++++++++++++++++- site/styles.css | 57 ++++ 10 files changed, 652 insertions(+), 34 deletions(-) create mode 100644 api/migrations/0008_moderation_tools.sql diff --git a/README.md b/README.md index 8b211f3..d4b2029 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,12 @@ Moderators are GitHub numeric user ids in `MODERATORS` of `api/wrangler.toml`. They see a **Moderation** tab: versions waiting for review with code and image preview, checksums and the antivirus result; approve, reject with a reason, ban an author; open reports. **All items** lists every app, wallpaper and mod with -an owner selector, **Users** everyone who has signed in, with ban and unban. +an owner selector and **Manage**: edit every field including the author +line, publish or hide, review each version with its files, see and resolve +the item's reports, delete it for good. **Users** lists everyone who has +signed in; **Details** shows their activity, items and reports, and lets a +moderator mark them trusted (no item limits; still scanned and reviewed), +keep a private note, end their sessions, remove their ratings, ban or unban. New uploads are announced in a GitHub issue labelled `moderation` (see [api/README.md](api/README.md#lifecycle-of-an-upload)). diff --git a/api/README.md b/api/README.md index 9398e98..71a38cb 100644 --- a/api/README.md +++ b/api/README.md @@ -189,11 +189,16 @@ All bodies are JSON unless noted. Authenticated calls send | GET | `/users/:login/apps[?versions]` | user | Apps of a user (all of them, with versions, for the user themself or a moderator) | | GET | `/files/:slug/:version/:name` | owner, mod | File by version id, for "My apps" and moderation previews | | GET | `/mod/queue?status=` | mod | Versions by status, default `pending_review` | -| GET | `/mod/apps` | mod | Every item with its owner, drafts and hidden ones included | -| GET | `/mod/users` | mod | Everyone who has signed in, with role and item count | +| GET | `/mod/apps` | mod | Every item with owner, creator, version and pending counts, rating, open reports | +| DELETE | `/mod/apps/:slug` | mod | `{ "confirm": "" }`: deletes the item, its versions, ratings, reports and R2 files | +| GET | `/mod/users` | mod | Everyone who has signed in, with role, trusted, note flag and item count | +| GET | `/mod/users/:login` | mod | Profile, note, trusted, activity (created, ratings, sessions, last sign-in), items, reports filed | +| PATCH | `/mod/users/:login` | mod | `{ "trusted"?: bool, "note"?: string \| null }`; trusted lifts the per-account item limits | +| POST | `/mod/users/:login/sign-out` | mod | Ends every session of the user | +| DELETE | `/mod/users/:login/ratings` | mod | Removes every rating the user gave | | POST | `/mod/versions/:id/approve` | mod | `{ "note"?: "..." }` | | POST | `/mod/versions/:id/reject` | mod | `{ "note": "reason" }` | -| GET | `/mod/reports` | mod | Open reports | +| GET | `/mod/reports[?slug=]` | mod | Open reports, or every report on one item | | POST | `/mod/reports/:id/resolve` | mod | | | POST | `/mod/users/:login/ban` / `unban` | mod | Ban hides all their apps and ends sessions | | POST | `/mod/import[?replace]` | mod | One app from the old repo (`scripts/import_catalog.py`) | diff --git a/api/migrations/0008_moderation_tools.sql b/api/migrations/0008_moderation_tools.sql new file mode 100644 index 0000000..d2ca0cf --- /dev/null +++ b/api/migrations/0008_moderation_tools.sql @@ -0,0 +1,6 @@ +-- Moderator tools: a private note per user, and "trusted" for authors the +-- moderators know, which lifts the per-account item limits (3 new a day, +-- 20 in all, 5 waiting for review). Their uploads are still scanned and +-- reviewed. +ALTER TABLE users ADD COLUMN trusted INTEGER NOT NULL DEFAULT 0; +ALTER TABLE users ADD COLUMN mod_note TEXT; diff --git a/api/scripts/smoke.sh b/api/scripts/smoke.sh index 88ca9b9..f054bb7 100755 --- a/api/scripts/smoke.sh +++ b/api/scripts/smoke.sh @@ -219,6 +219,43 @@ call 409 "no hand-over to a banned user" "${mod[@]}" "${json[@]}" -X PATCH "$API call 200 "download name is encoded" -I "${user[@]}" "$API/files/smoke-hello/$version_id/hello.lua?download" grep -qi "filename\*=UTF-8''hello.lua" "$work/body" && dl=ok || dl=raw check "Content-Disposition uses filename*" ok "$dl" + +# --- moderator tools ------------------------------------------------------ +call 200 "all items with counts" "${mod[@]}" "$API/mod/apps" +jq -e '[.items[] | select(.slug == "smoke-hello")][0] | .versions >= 1 and .created_by == "smoke-dev" and (.rating | has("average")) and (.open_reports >= 1)' "$work/body" >/dev/null && ma=ok || ma=bad +check "all items: versions, creator, rating, reports" ok "$ma" +jq -e '[.items[] | select(.slug == "Smoke_Import")][0].created_by == null' "$work/body" >/dev/null && mi=ok || mi=bad +check "an import has no creator" ok "$mi" +call 403 "user details are for moderators" "${fan[@]}" "$API/mod/users/smoke-dev" +call 200 "moderator opens a user" "${mod[@]}" "$API/mod/users/smoke-fan" +jq -e '.stats.created == 20 and .stats.sessions == 1 and (.items | length) == 19 and .user.trusted == false' "$work/body" >/dev/null && ud=ok || ud=bad +check "user details: created 20, owns 19 (one handed away), sessions" ok "$ud" +call 400 "note too long" "${mod[@]}" "${json[@]}" -X PATCH "$API/mod/users/smoke-fan" -d "{\"note\":\"$(printf 'x%.0s' $(seq 1 2001))\"}" +call 403 "users cannot edit users" "${fan[@]}" "${json[@]}" -X PATCH "$API/mod/users/smoke-fan" -d '{"trusted":true}' +call 200 "moderator trusts the fan and leaves a note" "${mod[@]}" "${json[@]}" -X PATCH "$API/mod/users/smoke-fan" -d '{"trusted":true,"note":"knows the hardware"}' +check "a trusted author is past the 20-item cap" 1 "$(spam 1 fan-trusted)" +call 200 "moderator takes trust back" "${mod[@]}" "${json[@]}" -X PATCH "$API/mod/users/smoke-fan" -d '{"trusted":false}' +check "the cap is back" 0 "$(spam 1 fan-untrusted)" +check "the note is kept" "knows the hardware" "$(curl -sS "${mod[@]}" "$API/mod/users/smoke-fan" | jq -r .user.mod_note)" +npx wrangler d1 execute lilka-catalog --local --command " +INSERT INTO users (id, login, role) VALUES (6, 'smoke-temp', 'user'); +INSERT INTO sessions VALUES ('$(sha temp-token)', 6, datetime('now', '+30 days'));" >/dev/null +temp=(-H "Authorization: Bearer temp-token") +call 200 "temp user rates" "${temp[@]}" "${json[@]}" -X PUT "$API/apps/smoke-hello/rating" -d '{"stars":2}' +call 200 "moderator removes the user's ratings" "${mod[@]}" -X DELETE "$API/mod/users/smoke-temp/ratings" +check "one rating removed" 1 "$(jq -r .ratings "$work/body")" +call 200 "moderator ends the user's sessions" "${mod[@]}" -X POST "$API/mod/users/smoke-temp/sign-out" +call 401 "the ended session no longer works" "${temp[@]}" "$API/auth/me" + +call 201 "moderator makes an item to delete" "${mod[@]}" "${json[@]}" -X POST "$API/apps" \ + -d '{"slug":"smoke-delete","kind":"app","name":"d","short_description":"d","sources_url":"https://github.com/a/b"}' +call 201 "with a version" "${mod[@]}" -X POST "$API/apps/smoke-delete/versions" \ + -F version=1.0.0 -F keira_version=1.0.0 -F entry_type=lua -F "entry=@$work/hello.lua" +delete_prefix=$(npx wrangler d1 execute lilka-catalog --local --json --command "SELECT v.storage_prefix FROM versions v JOIN apps a ON a.id = v.app_id WHERE a.slug = 'smoke-delete'" 2>/dev/null | jq -r '.[0].results[0].storage_prefix') +call 400 "delete needs the slug repeated" "${mod[@]}" "${json[@]}" -X DELETE "$API/mod/apps/smoke-delete" -d '{"confirm":"smoke"}' +call 403 "users cannot delete items" "${user[@]}" "${json[@]}" -X DELETE "$API/mod/apps/smoke-delete" -d '{"confirm":"smoke-delete"}' +call 200 "moderator deletes the item" "${mod[@]}" "${json[@]}" -X DELETE "$API/mod/apps/smoke-delete" -d '{"confirm":"smoke-delete"}' +call 404 "deleted item is gone" "${mod[@]}" "$API/apps/smoke-delete" r2_list() { curl -sS "$API/cdn-cgi/local/explorer/api/r2/buckets/lilka-catalog-files/objects?limit=1000" | jq -r '.result[].key'; } # The local bucket outlives the database between runs, so look only at this run's folders prefix_of() { npx wrangler d1 execute lilka-catalog --local --json --command "SELECT storage_prefix FROM versions WHERE id = $1" 2>/dev/null | jq -r '.[0].results[0].storage_prefix'; } @@ -229,6 +266,7 @@ call 200 "processor clears it" "${scanner[@]}" -X POST "$API/scan/versions/$reje call 200 "moderator rejects it" "${mod[@]}" "${json[@]}" -X POST "$API/mod/versions/$reject_id/reject" -d '{"note":"not a case"}' sleep 1 check "rejected files are deleted" 0 "$(r2_list | grep -c "^$(prefix_of "$reject_id")/" || true)" +check "a deleted item's files are gone" 0 "$(r2_list | grep -c "^$delete_prefix/" || true)" check "approved files are kept" 1 "$(r2_list | grep -c "^$(prefix_of "$version_id")/hello.lua$" || true)" call 200 "owner hides app" "${user[@]}" "${json[@]}" -X PATCH "$API/apps/smoke-hello" -d '{"status":"hidden"}' diff --git a/api/src/apps.ts b/api/src/apps.ts index b2c35da..b578f58 100644 --- a/api/src/apps.ts +++ b/api/src/apps.ts @@ -173,6 +173,11 @@ export async function findApp(env: Env, slug: string): Promise { return env.DB.prepare(`${APP_SELECT} WHERE a.slug = ?`).bind(slug).first(); } +/** Moderators, and authors a moderator marked trusted, skip the per-account item limits. */ +function limitsLifted(user: User): boolean { + return user.role === 'moderator' || !!user.trusted; +} + function canManage(user: User | null, app: AppRow): boolean { return !!user && user.role !== 'banned' && (user.id === app.owner_id || user.role === 'moderator'); } @@ -324,7 +329,7 @@ apps.post('/', async (c) => { const exists = await c.env.DB.prepare(`SELECT 1 FROM apps WHERE slug = ?`).bind(body.slug).first(); if (exists) fail(409, 'slug is taken'); - if (user.role !== 'moderator') { + if (!limitsLifted(user)) { // Counted from the table: it holds across Worker instances and over a // whole day, which the per-minute rate limiters cannot do. Both count // what the user created, not imports handed over to them (migration 0007) @@ -380,20 +385,23 @@ apps.patch('/:slug', async (c) => { params.push(value); }; + // Imported items were checked against the import's limits, longer than a + // new submission's; a moderator editing one must be able to save it + const mod = user.role === 'moderator'; if (body.name !== undefined) { - const name = readLocalized(body.name, 'name', 64); + const name = readLocalized(body.name, 'name', mod ? 200 : 64); if (!name.uk && !name.en) fail(400, 'name cannot be empty'); set('name_uk', name.uk); set('name_en', name.en); } if (body.short_description !== undefined) { - const short = readLocalized(body.short_description, 'short_description', 200); + const short = readLocalized(body.short_description, 'short_description', mod ? 1000 : 200); if (!short.uk && !short.en) fail(400, 'short_description cannot be empty'); set('short_uk', short.uk); set('short_en', short.en); } if (body.description !== undefined) { - const description = readLocalized(body.description, 'description', 20000); + const description = readLocalized(body.description, 'description', mod ? 100000 : 20000); set('description_uk', description.uk); set('description_en', description.en); } @@ -473,13 +481,15 @@ apps.post('/:slug/versions', async (c) => { const length = Number(c.req.header('Content-Length') ?? 0); if (length > MAX_UPLOAD_BYTES + 64 * 1024) fail(413, `upload is larger than ${MAX_UPLOAD_BYTES} bytes`); - const pending = await c.env.DB.prepare( - `SELECT COUNT(*) AS n FROM versions v JOIN apps a ON a.id = v.app_id - WHERE a.owner_id = ? AND v.status IN ('pending_scan', 'pending_review')`, - ) - .bind(app.owner_id) - .first<{ n: number }>(); - if ((pending?.n ?? 0) >= MAX_PENDING_PER_USER) fail(429, 'too many versions are waiting for review'); + if (!limitsLifted(user)) { + const pending = await c.env.DB.prepare( + `SELECT COUNT(*) AS n FROM versions v JOIN apps a ON a.id = v.app_id + WHERE a.owner_id = ? AND v.status IN ('pending_scan', 'pending_review')`, + ) + .bind(app.owner_id) + .first<{ n: number }>(); + if ((pending?.n ?? 0) >= MAX_PENDING_PER_USER) fail(429, 'too many versions are waiting for review'); + } let form: FormData; try { diff --git a/api/src/auth.ts b/api/src/auth.ts index 7b728d6..f27bb90 100644 --- a/api/src/auth.ts +++ b/api/src/auth.ts @@ -21,7 +21,7 @@ export const sessionMiddleware: MiddlewareHandler = async (c, next) => { if (match) { const tokenHash = await sha256Hex(match[1]); const user = await c.env.DB.prepare( - `SELECT u.id, u.login, u.name, u.avatar_url, u.role + `SELECT u.id, u.login, u.name, u.avatar_url, u.role, u.trusted FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.token_hash = ? AND s.expires_at > datetime('now')`, ) diff --git a/api/src/env.ts b/api/src/env.ts index b3be3f4..f94defc 100644 --- a/api/src/env.ts +++ b/api/src/env.ts @@ -30,6 +30,8 @@ export interface User { name: string | null; avatar_url: string | null; role: Role; + /** Set by a moderator: no per-account item limits (migration 0008). */ + trusted: number; } export type AppEnv = { diff --git a/api/src/moderation.ts b/api/src/moderation.ts index 0e1a3a4..96decd9 100644 --- a/api/src/moderation.ts +++ b/api/src/moderation.ts @@ -3,6 +3,7 @@ import type { AppEnv } from './env'; import { APP_SELECT, displayAuthor, + ratingSummary, findApp, kindDir, readKind, @@ -113,11 +114,20 @@ moderation.post('/versions/:id/reject', async (c) => { return c.json({ ok: true }); }); +/** Open reports, or with ?slug= every report on that item, resolved ones included. */ moderation.get('/reports', async (c) => { - const { results } = await c.env.DB.prepare( - `SELECT r.id, r.reason, r.created_at, a.slug, u.login AS reporter - FROM reports r JOIN apps a ON a.id = r.app_id JOIN users u ON u.id = r.user_id - WHERE r.resolved = 0 ORDER BY r.created_at ASC LIMIT 100`, + const slug = c.req.query('slug'); + const { results } = await (slug + ? c.env.DB.prepare( + `SELECT r.id, r.reason, r.resolved, r.created_at, a.slug, u.login AS reporter + FROM reports r JOIN apps a ON a.id = r.app_id JOIN users u ON u.id = r.user_id + WHERE a.slug = ? ORDER BY r.id DESC LIMIT 100`, + ).bind(slug) + : c.env.DB.prepare( + `SELECT r.id, r.reason, r.resolved, r.created_at, a.slug, u.login AS reporter + FROM reports r JOIN apps a ON a.id = r.app_id JOIN users u ON u.id = r.user_id + WHERE r.resolved = 0 ORDER BY r.created_at ASC LIMIT 100`, + ) ).all(); return c.json({ items: results }); }); @@ -133,7 +143,7 @@ moderation.post('/reports/:id/resolve', async (c) => { */ moderation.get('/users', async (c) => { const { results } = await c.env.DB.prepare( - `SELECT u.id, u.login, u.name, u.avatar_url, u.role, u.created_at, + `SELECT u.id, u.login, u.name, u.avatar_url, u.role, u.created_at, u.trusted, u.mod_note IS NOT NULL AS has_note, (SELECT COUNT(*) FROM apps a WHERE a.owner_id = u.id) AS items FROM users u ORDER BY u.id = 0 DESC, u.login COLLATE NOCASE ASC LIMIT 1000`, ).all<{ @@ -143,23 +153,36 @@ moderation.get('/users', async (c) => { avatar_url: string | null; role: string; created_at: string; + trusted: number; + has_note: number; items: number; }>(); return c.json({ items: results.map((u) => ({ ...u, + trusted: !!u.trusted, + has_note: !!u.has_note, // The catalog account is not a person: it holds imports until handed over system: u.id === 0, })), }); }); -/** Every item with its owner, drafts and hidden ones included, for the Apps tab. */ +/** + * Every item with its owner, drafts and hidden ones included, for the All + * items tab: one query, the counts as subqueries over indexed columns. + */ moderation.get('/apps', async (c) => { const { results } = await c.env.DB.prepare( - `SELECT a.slug, a.kind, a.status, a.author, a.name_uk, a.name_en, a.owner_id, a.created_at, - u.login AS owner_login - FROM apps a JOIN users u ON u.id = a.owner_id + `SELECT a.slug, a.kind, a.status, a.author, a.name_uk, a.name_en, a.owner_id, a.created_at, a.updated_at, + u.login AS owner_login, cb.login AS creator_login, + (SELECT COUNT(*) FROM versions v WHERE v.app_id = a.id) AS versions, + (SELECT COUNT(*) FROM versions v WHERE v.app_id = a.id + AND v.status IN ('pending_scan', 'pending_review')) AS pending, + (SELECT COUNT(*) FROM ratings r WHERE r.app_id = a.id) AS rating_count, + (SELECT AVG(stars) FROM ratings r WHERE r.app_id = a.id) AS rating_avg, + (SELECT COUNT(*) FROM reports p WHERE p.app_id = a.id AND p.resolved = 0) AS open_reports + FROM apps a JOIN users u ON u.id = a.owner_id LEFT JOIN users cb ON cb.id = a.created_by ORDER BY a.kind, a.slug LIMIT 2000`, ).all<{ slug: string; @@ -170,7 +193,14 @@ moderation.get('/apps', async (c) => { name_en: string | null; owner_id: number; created_at: string; + updated_at: string; owner_login: string; + creator_login: string | null; + versions: number; + pending: number; + rating_count: number; + rating_avg: number | null; + open_reports: number; }>(); return c.json({ items: results.map((a) => ({ @@ -179,13 +209,150 @@ moderation.get('/apps', async (c) => { status: a.status, name: { uk: a.name_uk, en: a.name_en }, author: displayAuthor(a), + author_line: a.author, owner: a.owner_login, unclaimed: a.owner_id === 0, + // null: made by the import + created_by: a.creator_login, created_at: a.created_at, + updated_at: a.updated_at, + versions: a.versions, + pending: a.pending, + rating: ratingSummary(a.rating_count, a.rating_avg === null ? null : a.rating_avg * a.rating_count), + open_reports: a.open_reports, })), }); }); +/** + * Deletes an item for good: its versions, ratings and reports (cascade) and + * every file in R2. For spam and mistakes; hiding is the reversible option. + * The body must repeat the slug, so a stray request cannot delete anything. + */ +moderation.delete('/apps/:slug', async (c) => { + const slug = c.req.param('slug'); + const { confirm } = await readJson<{ confirm?: unknown }>(c).catch(() => ({ confirm: undefined })); + if (confirm !== slug) fail(400, 'confirm must repeat the slug'); + const app = await findApp(c.env, slug); + if (!app) fail(404, 'app not found'); + const { results } = await c.env.DB.prepare(`SELECT storage_prefix FROM versions WHERE app_id = ?`) + .bind(app.id) + .all<{ storage_prefix: string }>(); + await c.env.DB.batch([ + // latest_version_id points into versions; clear it before the cascade + c.env.DB.prepare(`UPDATE apps SET latest_version_id = NULL WHERE id = ?`).bind(app.id), + c.env.DB.prepare(`DELETE FROM apps WHERE id = ?`).bind(app.id), + ]); + c.executionCtx.waitUntil( + (async () => { + for (const v of results) await deleteVersionFiles(c.env, v.storage_prefix); + })(), + ); + if (app.status === 'published') c.executionCtx.waitUntil(dispatch(c.env, c.env.CATALOG_REPO, 'api-sync', {})); + return c.json({ ok: true }); +}); + +async function findUser(c: Parameters>[0]) { + const user = await c.env.DB.prepare( + `SELECT id, login, name, avatar_url, role, created_at, bio, blog, location, company, trusted, mod_note + FROM users WHERE login = ? COLLATE NOCASE`, + ) + .bind(c.req.param('login')) + .first<{ + id: number; + login: string; + name: string | null; + avatar_url: string | null; + role: string; + created_at: string; + bio: string | null; + blog: string | null; + location: string | null; + company: string | null; + trusted: number; + mod_note: string | null; + }>(); + if (!user) fail(404, 'user not found'); + return user; +} + +/** Everything about one user for the Users tab, in one batch of indexed queries. */ +moderation.get('/users/:login', async (c) => { + const user = await findUser(c); + const [items, stats, reports] = await c.env.DB.batch>([ + c.env.DB.prepare( + `SELECT a.slug, a.kind, a.status, a.name_uk, a.name_en, a.created_at, a.created_by = a.owner_id AS own + FROM apps a WHERE a.owner_id = ? ORDER BY a.created_at DESC LIMIT 500`, + ).bind(user.id), + c.env.DB.prepare( + `SELECT (SELECT COUNT(*) FROM apps WHERE created_by = ?1) AS created, + (SELECT COUNT(*) FROM apps WHERE created_by = ?1 AND created_at > datetime('now', '-1 day')) AS created_today, + (SELECT COUNT(*) FROM ratings WHERE user_id = ?1) AS ratings, + (SELECT COUNT(*) FROM sessions WHERE user_id = ?1 AND expires_at > datetime('now')) AS sessions, + -- Sessions last 30 days from sign-in + (SELECT datetime(MAX(expires_at), '-30 days') FROM sessions WHERE user_id = ?1) AS last_sign_in`, + ).bind(user.id), + c.env.DB.prepare( + `SELECT r.id, r.reason, r.resolved, r.created_at, a.slug + FROM reports r JOIN apps a ON a.id = r.app_id WHERE r.user_id = ? ORDER BY r.id DESC LIMIT 50`, + ).bind(user.id), + ]); + return c.json({ + user: { ...user, trusted: !!user.trusted, system: user.id === 0 }, + stats: stats.results[0], + items: items.results.map((a) => ({ + slug: a.slug, + kind: a.kind, + status: a.status, + name: { uk: a.name_uk, en: a.name_en }, + created_at: a.created_at, + // false: handed over to them (an import, or another user's item) + own: !!a.own, + })), + reports: reports.results, + }); +}); + +/** What moderators may change about a user; the profile itself comes from GitHub at every sign-in. */ +moderation.patch('/users/:login', async (c) => { + const user = await findUser(c); + const body = await readJson<{ trusted?: unknown; note?: unknown }>(c); + const sets: string[] = []; + const params: unknown[] = []; + if (body.trusted !== undefined) { + if (typeof body.trusted !== 'boolean') fail(400, 'trusted must be true or false'); + if (user.id === 0) fail(409, 'the catalog account is not a person'); + sets.push('trusted = ?'); + params.push(body.trusted ? 1 : 0); + } + if (body.note !== undefined) { + if (body.note !== null && (typeof body.note !== 'string' || body.note.length > 2000)) { + fail(400, 'note must be text up to 2000 characters, or null'); + } + sets.push('mod_note = ?'); + params.push(typeof body.note === 'string' && body.note.trim() ? body.note.trim() : null); + } + if (!sets.length) fail(400, 'nothing to update'); + await c.env.DB.prepare(`UPDATE users SET ${sets.join(', ')} WHERE id = ?`) + .bind(...params, user.id) + .run(); + return c.json({ ok: true }); +}); + +/** Ends every session of the user, e.g. after a leaked token. They can sign in again. */ +moderation.post('/users/:login/sign-out', async (c) => { + const user = await findUser(c); + const result = await c.env.DB.prepare(`DELETE FROM sessions WHERE user_id = ?`).bind(user.id).run(); + return c.json({ ok: true, sessions: result.meta.changes ?? 0 }); +}); + +/** Removes every rating the user gave, e.g. a brigade; the averages follow with the next mirror run. */ +moderation.delete('/users/:login/ratings', async (c) => { + const user = await findUser(c); + const result = await c.env.DB.prepare(`DELETE FROM ratings WHERE user_id = ?`).bind(user.id).run(); + return c.json({ ok: true, ratings: result.meta.changes ?? 0 }); +}); + /** A ban also hides every app of the user, drops their ratings and ends their sessions. */ moderation.post('/users/:login/ban', async (c) => { const user = await c.env.DB.prepare(`SELECT id, role FROM users WHERE login = ? COLLATE NOCASE`) diff --git a/site/community.js b/site/community.js index cbd468d..92b224d 100644 --- a/site/community.js +++ b/site/community.js @@ -127,6 +127,40 @@ const COMMUNITY_STRINGS = { 'unban': 'Розблокувати', 'confirm-unban': 'Розблокувати {login}? Приховані додатки треба буде опублікувати знову вручну.', 'filter': 'Пошук', + 'manage': 'Керувати', + 'details': 'Докладно', + 'close': 'Згорнути', + 'author-line': 'Рядок автора (порожньо — логін власника)', + 'created-by': 'Створив', + 'created-by-import': 'імпорт', + 'versions-count': 'версій: {n}', + 'pending-count': 'чекають: {n}', + 'reports-count': 'скарг: {n}', + 'publish': 'Опублікувати', + 'delete-item': 'Видалити назавжди', + 'confirm-delete': 'Це видалить «{slug}», усі версії, файли, оцінки й скарги. Щоб підтвердити, введіть назву папки:', + 'deleted': 'Видалено.', + 'saved': 'Збережено.', + 'item-reports': 'Скарги на цей елемент', + 'no-reports-item': 'Скарг немає.', + 'resolved': 'закрито', + 'trusted': 'Довірений автор', + 'trusted-hint': 'Без лімітів на кількість елементів (3 на день, 20 усього, 5 на перевірці). Перевірка антивірусом і модератором лишається.', + 'mod-note': 'Нотатка модераторів (бачать лише модератори)', + 'sign-out-all': 'Завершити всі сесії', + 'confirm-sign-out-all': 'Вийти з усіх пристроїв для {login}?', + 'signed-out': 'Завершено сесій: {n}.', + 'remove-ratings': 'Прибрати всі оцінки', + 'confirm-remove-ratings': 'Прибрати всі оцінки від {login}?', + 'ratings-removed': 'Прибрано оцінок: {n}.', + 'user-stats': 'Створив: {created} (сьогодні: {today}) · оцінок: {ratings} · активних сесій: {sessions}', + 'last-sign-in': 'Останній вхід: {date}', + 'never-signed-in': 'Ще не входив', + 'user-items': 'Елементи', + 'user-reports': 'Скарги від користувача', + 'handed-over': 'передано', + 'role-note': 'Роль модератора задається в MODERATORS (api/wrangler.toml).', + 'note-badge': 'є нотатка', 'view': 'Переглянути', 'download': 'Завантажити', 'by': 'від', @@ -260,6 +294,40 @@ const COMMUNITY_STRINGS = { 'unban': 'Unban', 'confirm-unban': 'Unban {login}? Their hidden apps have to be published again by hand.', 'filter': 'Search', + 'manage': 'Manage', + 'details': 'Details', + 'close': 'Close', + 'author-line': 'Author line (empty: the owner\'s login)', + 'created-by': 'Created by', + 'created-by-import': 'import', + 'versions-count': 'versions: {n}', + 'pending-count': 'waiting: {n}', + 'reports-count': 'reports: {n}', + 'publish': 'Publish', + 'delete-item': 'Delete for good', + 'confirm-delete': 'This deletes "{slug}" with all versions, files, ratings and reports. Type the folder name to confirm:', + 'deleted': 'Deleted.', + 'saved': 'Saved.', + 'item-reports': 'Reports on this item', + 'no-reports-item': 'No reports.', + 'resolved': 'resolved', + 'trusted': 'Trusted author', + 'trusted-hint': 'No item limits (3 a day, 20 in all, 5 waiting for review). Uploads are still scanned and reviewed.', + 'mod-note': 'Moderator note (only moderators see it)', + 'sign-out-all': 'End all sessions', + 'confirm-sign-out-all': 'Sign {login} out on every device?', + 'signed-out': 'Sessions ended: {n}.', + 'remove-ratings': 'Remove all ratings', + 'confirm-remove-ratings': 'Remove every rating {login} gave?', + 'ratings-removed': 'Ratings removed: {n}.', + 'user-stats': 'Created: {created} (today: {today}) · ratings: {ratings} · active sessions: {sessions}', + 'last-sign-in': 'Last sign-in: {date}', + 'never-signed-in': 'Never signed in', + 'user-items': 'Items', + 'user-reports': 'Reports by this user', + 'handed-over': 'handed over', + 'role-note': 'The moderator role is set in MODERATORS (api/wrangler.toml).', + 'note-badge': 'has a note', 'view': 'View', 'download': 'Download', 'by': 'by', @@ -1252,6 +1320,8 @@ class CommunityUI { const bindTabs = (box) => box.querySelectorAll('[data-status]').forEach(btn => { btn.addEventListener('click', () => { this.modStatus = btn.dataset.status; + // A search is kept only for a jump from a user to their item + this.modSearch = ''; this.show('mod'); }); }); @@ -1369,25 +1439,277 @@ class CommunityUI { } }); }); + // Panels load on demand: one or two requests when opened, none for the list + const toggle = (btn, open) => btn.addEventListener('click', async () => { + const panel = btn.closest('.community-card').querySelector('.mod-panel'); + if (!panel.hidden) { + panel.hidden = true; + btn.textContent = btn.dataset.label; + return; + } + btn.dataset.label = btn.dataset.label || btn.textContent; + btn.textContent = this.t('close'); + panel.hidden = false; + panel.innerHTML = `
${this.esc(this.t('loading'))}
`; + try { + await open(panel); + } catch (error) { + panel.innerHTML = `

${this.esc(this.t('error', {message: error.message}))}

`; + } + }); + box.querySelectorAll('[data-manage]').forEach(btn => + toggle(btn, panel => this.renderItemPanel(panel, btn.dataset.manage))); + box.querySelectorAll('[data-details]').forEach(btn => + toggle(btn, panel => this.renderUserPanel(panel, btn.dataset.details))); + if (this.modSearch) { + search.value = this.modSearch; + search.dispatchEvent(new Event('input')); + } + search.addEventListener('input', () => { this.modSearch = search.value; }); + } + + /** Everything about one item: fields, status, versions with files and review, reports, delete. */ + async renderItemPanel(panel, slug) { + const path = `/apps/${encodeURIComponent(slug)}`; + const [app, reports] = await Promise.all([ + this.request('GET', path), + this.request('GET', `/mod/reports?slug=${encodeURIComponent(slug)}`), + ]); + const n = app.name || {}, s = app.short_description || {}, d = app.description || {}; + const field = (id, label, value, tag = 'input') => ` + `; + const [catalogType] = app.catalog_path.split('/'); + // Imported items keep their historic author line; null shows the owner's login + const authorLine = app.author === `@${app.owner.login}` ? '' : app.author; + panel.innerHTML = ` +
+
${field('name_uk', 'name-uk', n.uk)}${field('name_en', 'name-en', n.en)}
+
${field('short_uk', 'short-uk', s.uk)}${field('short_en', 'short-en', s.en)}
+
${field('description_uk', 'desc-uk', d.uk, 'textarea')}${field('description_en', 'desc-en', d.en, 'textarea')}
+
${field('sources_url', 'sources', app.sources_url)}${field('license', 'license', app.license)}
+
${field('author', 'author-line', authorLine)}
+ + +
+ + ${app.status === 'published' ? + ` + ${this.esc(this.t('view-in-catalog'))}` : + ``} + +
+
+

${this.esc(this.t('versions'))}

+ ${app.versions.length ? app.versions.map(v => ` +
+ ${this.renderVersion(v)} +
+ ${v.status === 'pending_review' ? `` : ''} + ${v.status !== 'approved' && v.status !== 'rejected' && v.status !== 'infected' ? + `` : ''} +
+
`).join('') : `

${this.esc(this.t('no-versions'))}

`} +

${this.esc(this.t('item-reports'))}

+ ${reports.items.length ? reports.items.map(r => ` +
+ ${this.esc(r.reason)} +
${this.esc(this.t('by'))} ${this.esc(r.reporter)} · ${this.esc(this.formatTime(r.created_at))}${ + r.resolved ? ` · ${this.esc(this.t('resolved'))}` : + ` · `}
+
`).join('') : `

${this.esc(this.t('no-reports-item'))}

`}`; + this.bindFileButtons(panel); + + const get = (id) => panel.querySelector(`[data-field="${id}"]`).value.trim(); + const errorBox = panel.querySelector('.form-error'); + const saved = panel.querySelector('.mod-saved'); + const run = async (work, message) => { + errorBox.hidden = true; + saved.hidden = true; + try { + await work(); + if (message) { + saved.textContent = message; + saved.hidden = false; + } + return true; + } catch (error) { + errorBox.textContent = this.t('error', {message: error.message}); + errorBox.hidden = false; + return false; + } + }; + const reload = () => this.renderItemPanel(panel, slug); + + panel.querySelector('[data-item="save"]').addEventListener('click', () => run(() => + this.request('PATCH', path, { + name: {uk: get('name_uk'), en: get('name_en')}, + short_description: {uk: get('short_uk'), en: get('short_en')}, + description: {uk: get('description_uk'), en: get('description_en')}, + sources_url: get('sources_url'), + license: get('license'), + author: get('author') || null, + }), this.t('saved'))); + panel.querySelectorAll('[data-item="hide"], [data-item="publish"]').forEach(btn => btn.addEventListener('click', async () => { + if (btn.dataset.item === 'hide' && !confirm(this.t('confirm-hide'))) return; + if (await run(() => this.request('PATCH', path, {status: btn.dataset.item === 'hide' ? 'hidden' : 'published'}))) reload(); + })); + panel.querySelector('[data-item="delete"]').addEventListener('click', async () => { + const typed = prompt(this.t('confirm-delete', {slug}), ''); + if (typed === null) return; + if (await run(() => this.request('DELETE', `/mod/apps/${encodeURIComponent(slug)}`, {confirm: typed.trim()}))) { + panel.closest('.community-card').innerHTML = `

${this.esc(this.t('deleted'))} ${this.esc(slug)}

`; + } + }); + panel.querySelectorAll('[data-review]').forEach(btn => btn.addEventListener('click', async () => { + const id = btn.closest('.mod-version').dataset.version; + let body; + if (btn.dataset.review === 'approve') { + const note = prompt(this.t('approve-note'), ''); + if (note === null) return; + body = {note: note || undefined}; + } else { + const note = prompt(this.t('reject-reason'), ''); + if (!note) return; + body = {note}; + } + if (await run(() => this.request('POST', `/mod/versions/${id}/${btn.dataset.review}`, body))) reload(); + })); + panel.querySelectorAll('[data-resolve-report]').forEach(btn => btn.addEventListener('click', async () => { + if (await run(() => this.request('POST', `/mod/reports/${btn.dataset.resolveReport}/resolve`))) reload(); + })); + } + + /** One user: profile, activity, items, reports; note, trusted, sessions, ratings, ban. */ + async renderUserPanel(panel, login) { + const base = `/mod/users/${encodeURIComponent(login)}`; + const {user, stats, items, reports} = await this.request('GET', base); + const facts = [user.location, user.company].filter(Boolean).map(f => this.esc(f)); + if (user.blog && /^https?:\/\//i.test(user.blog)) { + facts.push(`${this.esc(user.blog)}`); + } + const lastSignIn = stats.last_sign_in ? + this.t('last-sign-in', {date: this.formatTime(stats.last_sign_in)}) : this.t('never-signed-in'); + const banAction = user.system || user.role === 'moderator' ? '' : user.role === 'banned' ? + `` : + ``; + panel.innerHTML = ` + ${user.bio ? `

${this.esc(user.bio)}

` : ''} + ${facts.length ? `

${facts.join(' · ')}

` : ''} +

${this.esc(this.t('user-stats', { + created: stats.created, today: stats.created_today, ratings: stats.ratings, sessions: stats.sessions}))} · ${ + this.esc(lastSignIn)}

+ ${user.role === 'moderator' ? `

${this.esc(this.t('role-note'))}

` : ''} +
+ ${user.system ? '' : ` + `} + + + +
+ + ${user.system ? '' : ` + + `} + ${banAction} +
+
+

${this.esc(this.t('user-items'))}

+ ${items.length ? `
${items.map(a => ` +
+ + ${this.statusBadge(a.status)} + ${this.esc(a.kind)} · ${this.esc(this.formatTime(a.created_at))}${a.own ? '' : ` · ${this.esc(this.t('handed-over'))}`} +
`).join('')}
` : `

${this.esc(this.t('mod-empty'))}

`} +

${this.esc(this.t('user-reports'))}

+ ${reports.length ? reports.map(r => ` +
${this.esc(r.slug)} ${this.esc(r.reason)} + · ${this.esc(this.formatTime(r.created_at))}${r.resolved ? ` · ${this.esc(this.t('resolved'))}` : ''} +
`).join('') : `

${this.esc(this.t('no-reports-item'))}

`}`; + + const errorBox = panel.querySelector('.form-error'); + const saved = panel.querySelector('.mod-saved'); + const run = async (work, message) => { + errorBox.hidden = true; + saved.hidden = true; + try { + const result = await work(); + if (message) { + saved.textContent = message(result); + saved.hidden = false; + } + return true; + } catch (error) { + errorBox.textContent = this.t('error', {message: error.message}); + errorBox.hidden = false; + return false; + } + }; + panel.querySelector('[data-user="save"]').addEventListener('click', () => { + const trusted = panel.querySelector('[data-user-field="trusted"]'); + const body = {note: panel.querySelector('[data-user-field="note"]').value.trim() || null}; + if (trusted) body.trusted = trusted.checked; + run(() => this.request('PATCH', base, body), () => this.t('saved')); + }); + panel.querySelector('[data-user="sign-out"]')?.addEventListener('click', () => { + if (!confirm(this.t('confirm-sign-out-all', {login}))) return; + run(() => this.request('POST', `${base}/sign-out`), r => this.t('signed-out', {n: r.sessions})); + }); + panel.querySelector('[data-user="ratings"]')?.addEventListener('click', () => { + if (!confirm(this.t('confirm-remove-ratings', {login}))) return; + run(() => this.request('DELETE', `${base}/ratings`), r => this.t('ratings-removed', {n: r.ratings})); + }); + panel.querySelectorAll('[data-user="ban"], [data-user="unban"]').forEach(btn => btn.addEventListener('click', async () => { + const action = btn.dataset.user; + if (!confirm(this.t(`confirm-${action}`, {login}))) return; + if (await run(() => this.request('POST', `${base}/${action}`))) this.renderUserPanel(panel, login); + })); + // An item opens in All items, found by its folder name + panel.querySelectorAll('[data-goto]').forEach(btn => btn.addEventListener('click', () => { + this.modSearch = btn.dataset.goto; + this.modStatus = 'apps'; + this.show('mod'); + })); } renderModApp(a, options) { const name = a.name[this.app.currentLang] || a.name.uk || a.name.en || a.slug; - const search = [a.slug, name, a.author, a.owner].join(' ').toLowerCase(); + const search = [a.slug, name, a.author, a.owner, a.created_by || ''].join(' ').toLowerCase(); + const facts = [ + this.t('versions-count', {n: a.versions}), + a.pending ? this.t('pending-count', {n: a.pending}) : '', + a.rating && a.rating.count ? `★ ${a.rating.average} (${a.rating.count})` : '', + a.open_reports ? this.t('reports-count', {n: a.open_reports}) : '', + `${this.t('created-by')}: ${a.created_by || this.t('created-by-import')}`, + ].filter(Boolean); return ` -
+

${this.esc(name)}

${this.esc(a.slug)} - ${this.esc(a.kind)} · ${this.esc(a.status)} · ${this.esc(this.t('by'))} ${this.esc(a.author)}${ + ${this.statusBadge(a.status)} + ${this.esc(a.kind)} · ${this.esc(this.t('by'))} ${this.esc(a.author)}${ a.unclaimed ? ` · ${this.esc(this.t('unclaimed'))}` : ''} +
${this.esc(facts.join(' · '))}
+
+
+ +
-
+
`; } @@ -1400,17 +1722,23 @@ class CommunityUI { ``; const profile = u.system ? '' : ` · GitHub`; + const flags = [u.trusted ? this.t('trusted') : '', u.has_note ? this.t('note-badge') : ''].filter(Boolean); return ` -
+

${this.esc(u.name || u.login)}

@${this.esc(u.login)} ${this.esc(role)} · ${this.esc(this.t('items-count', {n: u.items}))} · ${ this.esc(this.t('joined', {date: this.formatTime(u.created_at)}))}${profile} + ${flags.length ? `
${this.esc(flags.join(' · '))}
` : ''} +
+
+ + ${action}
-
${action}
+
`; } diff --git a/site/styles.css b/site/styles.css index 675e979..4c5ab2f 100644 --- a/site/styles.css +++ b/site/styles.css @@ -2213,3 +2213,60 @@ footer { .rating-star:disabled { cursor: wait; } + +/* Moderation: item and user panels (community.js renderItemPanel, renderUserPanel) */ +.mod-panel { + margin-top: 1rem; + padding-top: 1rem; + border-top: 1px solid var(--border-solid); + display: flex; + flex-direction: column; + gap: 0.75rem; +} + +.mod-panel h4 { + margin: 0.75rem 0 0; +} + +.mod-version { + display: flex; + flex-direction: column; + gap: 0.5rem; +} + +.mod-check { + display: flex; + gap: 0.6rem; + align-items: flex-start; + cursor: pointer; +} + +.mod-check input { + margin-top: 0.25rem; + accent-color: var(--primary-color); +} + +.mod-user-items { + display: flex; + flex-direction: column; + gap: 0.4rem; +} + +.mod-user-item { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem; +} + +.mod-alert { + color: var(--warning); +} + +.mod-saved { + color: var(--success); +} + +.community-actions:has(.mod-owner) { + align-items: flex-end; +}