Add image uploads with a media library, and event card backgrounds

Uploads (migration 028, server/src/media.js, routes/media.js): editors
and up upload JPEG, PNG, GIF, WebP or SVG. Photos are resized to 2400px
and saved as WebP by default, or kept as uploaded on request. Files
live in UPLOADS_DIR, served by nginx in production and by the API in
dev. Admins and up delete, after seeing what still uses the file.

Every image field in the editor is now an image widget: preview, the
path as text, Upload and Choose from library. A new Media page lists
the library. Org lists and event cards now resolve logos through
media.ts, so uploaded paths work there.

Events get a card_image (migration 029): a photo behind the card under
a light veil so the text stays readable. The card's size is unchanged.

Setup for production is in docs/media-uploads.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-27 15:04:45 -05:00
parent cd393e4ab2
commit eaff23839f
26 changed files with 1234 additions and 22 deletions

View file

@ -345,6 +345,7 @@ const events = {
text("event_logo"),
text("color"),
text("gradient"),
text("card_image"),
bool("is_published"),
bool("is_listed"),
bool("in_timeline"),

View file

@ -8,7 +8,10 @@
there too.
═══════════════════════════════════════════════════════════════ */
import { mkdir } from "node:fs/promises";
import { serve } from "@hono/node-server";
import { serveStatic } from "@hono/node-server/serve-static";
import { Hono } from "hono";
import { logger } from "hono/logger";
@ -24,6 +27,8 @@ import auth from "./routes/auth.js";
import admin from "./routes/admin.js";
import panel from "./routes/panel.js";
import adminEntities from "./routes/admin-entities.js";
import media from "./routes/media.js";
import { UPLOADS_DIR } from "./media.js";
import { startSessionSweeper } from "./auth.js";
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
import { ENTITIES } from "./admin-schema.js";
@ -39,6 +44,8 @@ const version = migrate(db);
syncDescriptorsWithSchema(db, ENTITIES);
console.log(`db ${DB_PATH} (${db.driverName}, schema v${version})`);
await mkdir(UPLOADS_DIR, { recursive: true });
console.log(`uploads ${UPLOADS_DIR}`);
/* ── App ─────────────────────────────────────────────────────── */
@ -69,8 +76,30 @@ app.use("/api/auth/login", rateLimit({ windowMs: 15 * 60_000, max: 10 }));
app.route("/api/admin/panel", panel);
app.route("/api/auth", auth);
app.route("/api/admin", admin);
// Before the entity routes, whose /:entity would claim /media.
app.route("/api/admin", media);
app.route("/api/admin", adminEntities);
/* ── Uploads ───────────────────────────────────────────────────
In production nginx serves /uploads/ straight from disk and
never passes it here. This is for development, where Vite
proxies /uploads to the API. The headers match the nginx
block's: an uploaded SVG opened on its own can't run script.
───────────────────────────────────────────────────────────── */
app.use("/uploads/*", async (c, next) => {
await next();
c.header("X-Content-Type-Options", "nosniff");
c.header("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; sandbox");
});
app.use(
"/uploads/*",
serveStatic({
root: UPLOADS_DIR,
rewriteRequestPath: (p) => p.replace(/^\/uploads/, ""),
}),
);
startSessionSweeper(db);
app.notFound((c) => c.json({ error: "Not found" }, 404));

184
server/src/media.js Normal file
View file

@ -0,0 +1,184 @@
/* ═══════════════════════════════════════════════════════════════
MEDIA STORAGE
Where uploads go and what happens to them on the way. The routes
in routes/media.js are HTTP around this; the rules are here.
── Where ──
UPLOADS_DIR, default ./uploads (next to dev.db when run from
server/). Production sets /var/lib/ngu/uploads, beside the
database and outside /srv/ngu-api, so a deploy's rsync never
deletes anyone's photos. Every file is served at
/uploads/<filename>: by nginx in production, by the API in
development (see index.js).
── What ──
The type is read from the file's first bytes, never from its
name or the browser's Content-Type, both of which the uploader
controls. JPEG, PNG, GIF, WebP and SVG are accepted; anything
else is refused.
── Processing ──
By default a raster image is turned upright (EXIF orientation),
shrunk to fit MAX_EDGE on its longest side, and saved as WebP,
which also drops its metadata, camera location included.
`keepOriginal` stores the bytes exactly as uploaded instead,
under the tighter KEEP_MAX_BYTES. An SVG is always kept as it
is: it's already small, and rasterising it would lose the point
of it.
Names are random, so two uploads of "logo.png" can't collide
and a filename says nothing about what's in it.
═══════════════════════════════════════════════════════════════ */
import { randomBytes } from "node:crypto";
import { mkdir, rename, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
import sharp from "sharp";
export const UPLOADS_DIR = path.resolve(process.env.UPLOADS_DIR ?? "./uploads");
/* The public path an image field stores. media.ts passes anything
starting with "/" through untouched. */
export const PUBLIC_PREFIX = "/uploads/";
const MB = 1024 * 1024;
/* The largest file accepted at all, before processing: room for a
full-size phone photo. */
export const MAX_UPLOAD_BYTES = 25 * MB;
/* The largest file kept as uploaded, unprocessed. */
export const KEEP_MAX_BYTES = 10 * MB;
/* Longest side after processing, in pixels. Wide enough for a
full-bleed hero on a large screen. */
const MAX_EDGE = 2400;
const WEBP_QUALITY = 82;
export class MediaError extends Error {
constructor(status, message) {
super(message);
this.status = status;
}
}
/* ── Sniffing ──────────────────────────────────────────────── */
const TYPES = {
jpeg: { mime: "image/jpeg", ext: ".jpg" },
png: { mime: "image/png", ext: ".png" },
gif: { mime: "image/gif", ext: ".gif" },
webp: { mime: "image/webp", ext: ".webp" },
svg: { mime: "image/svg+xml", ext: ".svg" },
};
function startsWith(buf, bytes, offset = 0) {
return bytes.every((byte, i) => buf[offset + i] === byte);
}
function sniff(buf) {
if (startsWith(buf, [0xff, 0xd8, 0xff])) return "jpeg";
if (startsWith(buf, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return "png";
if (startsWith(buf, [0x47, 0x49, 0x46, 0x38])) return "gif";
if (startsWith(buf, [0x52, 0x49, 0x46, 0x46]) && startsWith(buf, [0x57, 0x45, 0x42, 0x50], 8)) {
return "webp";
}
// SVG is text: an optional BOM, XML declaration, comments or a
// doctype, then an <svg> element. Look at the head only.
const head = buf.subarray(0, 1024).toString("utf8").replace(/^/, "").trimStart();
if (/^(<\?xml[\s\S]*?\?>\s*)?(<!--[\s\S]*?-->\s*|<!DOCTYPE[^>]*>\s*)*<svg[\s>]/i.test(head)) {
return "svg";
}
return null;
}
/* ── Store ─────────────────────────────────────────────────────
Writes the file and returns what the media row needs. The row
itself is the caller's, so a failed insert can call remove()
and leave nothing behind.
───────────────────────────────────────────────────────────── */
export async function store(buf, { keepOriginal = false } = {}) {
if (buf.length === 0) throw new MediaError(400, "The file is empty.");
if (buf.length > MAX_UPLOAD_BYTES) {
throw new MediaError(413, `Files can be at most ${MAX_UPLOAD_BYTES / MB} MB.`);
}
const kind = sniff(buf);
if (!kind) {
throw new MediaError(415, "Only JPEG, PNG, GIF, WebP and SVG images can be uploaded.");
}
const convert = kind !== "svg" && !keepOriginal;
if (!convert && buf.length > KEEP_MAX_BYTES) {
throw new MediaError(
413,
`Files kept as uploaded can be at most ${KEEP_MAX_BYTES / MB} MB. ` +
"Leave the original unticked to have it shrunk instead.",
);
}
let out = buf;
let type = TYPES[kind];
let width = null;
let height = null;
try {
if (convert) {
// animated keeps every frame of a GIF or an animated WebP.
const { data, info } = await sharp(buf, { animated: true })
.rotate()
.resize({ width: MAX_EDGE, height: MAX_EDGE, fit: "inside", withoutEnlargement: true })
.webp({ quality: WEBP_QUALITY })
.toBuffer({ resolveWithObject: true });
out = data;
type = TYPES.webp;
width = info.width;
// An animated image reports the whole strip's height.
height = info.pageHeight ?? info.height;
} else if (kind !== "svg") {
const meta = await sharp(buf).metadata();
width = meta.width ?? null;
height = meta.pageHeight ?? meta.height ?? null;
}
} catch {
throw new MediaError(415, "That image couldn't be read. It may be damaged.");
}
const filename = `${randomBytes(12).toString("hex")}${type.ext}`;
await mkdir(UPLOADS_DIR, { recursive: true });
// Written under a temporary name and renamed, so a half-written
// file is never served under its real one.
const tmp = path.join(UPLOADS_DIR, `.${filename}.tmp`);
await writeFile(tmp, out);
await rename(tmp, path.join(UPLOADS_DIR, filename));
return {
filename,
content_type: type.mime,
bytes: out.length,
width,
height,
processed: convert ? 1 : 0,
};
}
/* Deletes one stored file. A file that's already gone is not an
error: the row is what's being removed. */
export async function remove(filename) {
// filename comes from our own table, but it's joined onto a
// directory, so refuse anything that isn't a bare name.
if (path.basename(filename) !== filename) return;
try {
await unlink(path.join(UPLOADS_DIR, filename));
} catch (err) {
if (err.code !== "ENOENT") throw err;
}
}

View file

@ -0,0 +1,41 @@
-- ═══════════════════════════════════════════════════════════════
-- 028 MEDIA: UPLOADED IMAGES
--
-- One row per file in UPLOADS_DIR (/var/lib/ngu/uploads in
-- production, outside the deployed app so an rsync can't touch
-- it). nginx serves the directory at /uploads/; the API only
-- writes and deletes.
--
-- An image field stores the file's public path, '/uploads/<file>',
-- not this row's id. That keeps every image column a plain TEXT
-- that also takes a filename in public/ or a full URL, as before,
-- and means media.ts needs no lookup. The cost is no foreign key:
-- deleting a file a record still names leaves that record showing
-- nothing (the <Logo> and <img> fallbacks already handle a missing
-- file), so the Media page warns before a delete.
--
-- filename the stored name: random, so it can't collide or
-- be guessed from the original. '3f9c…e1.webp'
-- original_name what the uploader's file was called, for the
-- library's search and display
-- processed 1 when resized and converted to WebP, 0 when
-- kept as uploaded
-- width, height null for an SVG, which has no pixel size
--
-- PRAGMA user_version; -- reads 27 before this file
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE media (
id INTEGER PRIMARY KEY AUTOINCREMENT,
filename TEXT NOT NULL UNIQUE,
original_name TEXT NOT NULL,
content_type TEXT NOT NULL,
bytes INTEGER NOT NULL CHECK (bytes >= 0),
width INTEGER,
height INTEGER,
processed INTEGER NOT NULL DEFAULT 1 CHECK (processed IN (0, 1)),
uploaded_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
CREATE INDEX media_created_idx ON media (created_at DESC);

View file

@ -0,0 +1,15 @@
-- ═══════════════════════════════════════════════════════════════
-- 029 EVENTS: CARD BACKGROUND IMAGE
--
-- A photo behind an event's card. The card keeps its size and its
-- layout; the image covers it, under a light veil (CARD_IMAGE_VEIL
-- in EventList-Cards.tsx) so the text on top stays readable.
--
-- Like every image column, it holds a path: '/uploads/<file>' from
-- the media library, a bare filename in public/event-backgrounds/,
-- or a full URL. Null draws the card as before.
--
-- PRAGMA user_version; -- reads 28 before this file
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE events ADD COLUMN card_image TEXT;

View file

@ -148,6 +148,7 @@ function shapeEvent(row, links, cardBlocks, hosts = []) {
event_logo: row.event_logo,
color: row.effective_color,
gradient: row.gradient,
card_image: row.card_image,
hosts: hosts.map(shapeHost),

181
server/src/routes/media.js Normal file
View file

@ -0,0 +1,181 @@
/* ═══════════════════════════════════════════════════════════════
MEDIA ROUTES: mounted under /api/admin
GET /media the library, newest first, ?q=name
POST /media upload one image (multipart: file,
keep_original)
GET /media/:id/uses which records name this file
DELETE /media/:id remove the row and the file
Reading needs a session, uploading needs editor, deleting needs
admin: the same ladder the entity routes use, so an editor can
add images to what they edit but not take one out from under
somebody else's page.
Mounted before the entity routes, whose /:entity would otherwise
claim /media and answer "Unknown entity."
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { bodyLimit } from "hono/body-limit";
import { requireAuth, requireRole } from "../auth.js";
import { MAX_UPLOAD_BYTES, MediaError, PUBLIC_PREFIX, remove, store } from "../media.js";
const media = new Hono();
media.use("*", requireAuth);
const NO_STORE = { "Cache-Control": "no-store" };
const MAX_LIST = 500;
/* Tables that can't hold an image path, or mustn't be searched. */
const NOT_CONTENT = new Set(["media", "admin_users", "sessions", "feedback", "sqlite_sequence"]);
function shape(row) {
return {
id: row.id,
url: `${PUBLIC_PREFIX}${row.filename}`,
original_name: row.original_name,
content_type: row.content_type,
bytes: row.bytes,
width: row.width,
height: row.height,
processed: row.processed === 1,
uploaded_by: row.uploaded_by_name ?? row.uploaded_by_email ?? null,
created_at: row.created_at,
};
}
const SELECT = `SELECT m.*, u.name AS uploaded_by_name, u.email AS uploaded_by_email
FROM media m
LEFT JOIN admin_users u ON u.id = m.uploaded_by`;
media.get("/media", (c) => {
const q = (c.req.query("q") ?? "").trim().slice(0, 100);
const rows = c
.get("db")
.prepare(
`${SELECT}
${q ? "WHERE m.original_name LIKE ?" : ""}
ORDER BY m.created_at DESC, m.id DESC
LIMIT ${MAX_LIST}`,
)
.all(...(q ? [`%${q}%`] : []));
return c.json({ media: rows.map(shape) }, 200, NO_STORE);
});
media.post(
"/media",
requireRole("editor"),
// A little over the file limit, for the multipart framing.
bodyLimit({
maxSize: MAX_UPLOAD_BYTES + 64 * 1024,
onError: (c) => c.json({ error: "That file is too large." }, 413),
}),
async (c) => {
const db = c.get("db");
const user = c.get("user");
let body;
try {
body = await c.req.parseBody();
} catch {
return c.json({ error: "Expected a file upload." }, 400);
}
const file = body.file;
if (!(file instanceof File)) return c.json({ error: "No file was sent." }, 400);
const stored = await store(Buffer.from(await file.arrayBuffer()), {
keepOriginal: body.keep_original === "1",
});
let row;
try {
const { lastInsertRowid } = db
.prepare(
`INSERT INTO media
(filename, original_name, content_type, bytes, width, height, processed, uploaded_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
stored.filename,
(file.name || "upload").slice(0, 200),
stored.content_type,
stored.bytes,
stored.width,
stored.height,
stored.processed,
user.id,
);
row = db.prepare(`${SELECT} WHERE m.id = ?`).get(lastInsertRowid);
} catch (err) {
await remove(stored.filename);
throw err;
}
console.log(`media ${stored.filename} uploaded by ${user.email}`);
return c.json({ media: shape(row) }, 201, NO_STORE);
},
);
/* Every TEXT column of every content table, searched for the exact
path. Read from the live schema rather than a list of image
columns, so a new image field is covered the day it's added. */
function usesOf(db, url) {
const tables = db
.prepare(`SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`)
.all()
.map((t) => t.name)
.filter((name) => !NOT_CONTENT.has(name));
const uses = [];
for (const table of tables) {
const columns = db
.prepare(`SELECT name, type FROM pragma_table_info(?)`)
.all(table)
.filter((col) => col.type.toUpperCase() === "TEXT")
.map((col) => col.name);
if (columns.length === 0) continue;
// Names come from the schema, not the request; quoted anyway.
const where = columns.map((col) => `"${col}" = ?`).join(" OR ");
const { n } = db
.prepare(`SELECT COUNT(*) AS n FROM "${table}" WHERE ${where}`)
.get(...columns.map(() => url));
if (n > 0) uses.push({ table, count: n });
}
return uses;
}
function findOr404(c) {
const id = Number(c.req.param("id"));
const row = Number.isInteger(id)
? c.get("db").prepare(`SELECT * FROM media WHERE id = ?`).get(id)
: null;
if (!row) throw new MediaError(404, "No such file.");
return row;
}
media.get("/media/:id/uses", (c) => {
const row = findOr404(c);
return c.json({ uses: usesOf(c.get("db"), `${PUBLIC_PREFIX}${row.filename}`) }, 200, NO_STORE);
});
media.delete("/media/:id", requireRole("admin"), async (c) => {
const row = findOr404(c);
c.get("db").prepare(`DELETE FROM media WHERE id = ?`).run(row.id);
await remove(row.filename);
console.log(`media ${row.filename} deleted by ${c.get("user").email}`);
return c.body(null, 204);
});
media.onError((err, c) => {
if (err instanceof MediaError) return c.json({ error: err.message }, err.status, NO_STORE);
console.error(err);
return c.json({ error: "Something went wrong." }, 500);
});
export default media;