app: uploaded images for announcements, campaigns and events (APP-1.0-PLAN §10)

Photos (JPEG, PNG, WebP, checked by their bytes) uploaded in the admin are
turned upright, stripped of their metadata and kept at most 2000 px wide in
backend/uploads (UPLOAD_DIR), served at /api/uploads (never a listing, a
sandboxing CSP). Content keeps the image's full address, so an upload and an
image from elsewhere work alike. 5 GB included or the licence's storage
limit; an image still in use can't be deleted. The announcement, campaign
and event forms get Upload a photo next to the address. Migration media.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 14:47:33 +02:00
co-authored by Claude Opus 5.5
parent 13eaaffb95
commit c934f47b28
15 changed files with 337 additions and 4 deletions
+18
View File
@@ -13,6 +13,8 @@
* GET /jobs, PUT /jobs/:name { enabled?, cron? }, POST /jobs/:name/run Background jobs
* GET /audit?before= the audit log; GET /access?before= the access log
* GET /share, POST /share the App's link (and the poster), and "shared" for the checklist
* GET /media, POST /media?alt= (the image's bytes), DELETE /media/:id uploaded images (anyone who
* writes content: Content admin, Devotional writer, Prayer coordinator)
*/
import express, { type Request } from 'express';
import { z } from 'zod';
@@ -31,6 +33,7 @@ import { wallDay } from '../prayer/service.js';
import { wallSettings } from '../prayer/wall.js';
import { accessLogList, auditLog } from './logs.js';
import { addMember, listMembers, setRoles } from './members.js';
import { deleteMedia, listMedia, MAX_UPLOAD_BYTES, upload } from '../media/media.js';
const modulesBody = z.object(Object.fromEntries(APP_MODULES.map((m) => [m, z.boolean().optional()]))).strict();
@@ -156,6 +159,21 @@ export function adminRouter(ctx: Ctx) {
r.get('/audit', full, handle(async (req) => ({ entries: await auditLog(ctx, { before: before(req) }) })));
r.get('/access', full, handle(async (req) => ({ entries: await accessLogList(ctx, { before: before(req) }) })));
// ─── Uploaded images ───
const writers = requireRole(ctx, ['content_admin', 'devotional_writer', 'prayer_coordinator']);
r.get('/media', writers, handle(() => listMedia(ctx)));
r.post('/media', writers, express.raw({ type: () => true, limit: MAX_UPLOAD_BYTES + 1 }), handle(async (req, res) => {
const out = await upload(ctx, Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0), typeof req.query.alt === 'string' ? req.query.alt : '', req.signed!.member.id);
await audit(ctx, { actorId: req.signed!.member.id, actorRole: req.signed!.member.roles.join(','), action: 'media_uploaded', targetType: 'media', targetId: out.id, metadata: { bytes: out.bytes }, ip: clientIp(req) });
res.status(201);
return out;
}));
r.delete('/media/:id', writers, handle(async (req) => {
const m = await deleteMedia(ctx, String(req.params.id));
await audit(ctx, { actorId: req.signed!.member.id, actorRole: req.signed!.member.roles.join(','), action: 'media_deleted', targetType: 'media', targetId: m.id, metadata: { name: m.filename }, ip: clientIp(req) });
return { ok: true };
}));
// ─── Share the App ───
r.get('/share', full, handle(async () => {
const profile = await churchProfile(ctx);
+9
View File
@@ -4,6 +4,7 @@
* rest to Next.js.
*
* /api/health version and database, for monitoring, `crosscode deploy` and the Hub
* /api/uploads/… images uploaded in the admin (media/media.ts)
* /api/v1/app the church, its colours and style, the modules on (public)
* /api/auth/… signing in through the church's Accounts
* /api/accounts/v1/events Accounts' signed calls (user.updated / export / deleted)
@@ -23,6 +24,7 @@
* /api/v1/admin/messaging Settings → Email and WhatsApp: the church's settings from Accounts, Send a test
* /api/accounts/v1/messaging-changed Accounts: the email or WhatsApp settings changed (links/routes.ts)
*/
import path from 'node:path';
import express from 'express';
import type { Ctx } from './context.js';
import { adminRouter } from './admin/routes.js';
@@ -37,6 +39,7 @@ import { prayerRouter } from './prayer/routes.js';
import { requestsAdminRouter, requestsRouter } from './requests/routes.js';
import { contentAdminRouter, contentRouter } from './content/routes.js';
import { messagingAdminRouter, notificationsRouter } from './messaging/routes.js';
import { uploadDir } from './media/media.js';
export function createApp(ctx: Ctx) {
const app = express();
@@ -62,6 +65,12 @@ export function createApp(ctx: Ctx) {
return appInfo(ctx);
}));
// Uploaded images: never a directory listing, never outside the folder (express.static checks).
app.use('/api/uploads', express.static(path.resolve(uploadDir(ctx)), {
index: false, dotfiles: 'deny', fallthrough: false, maxAge: '30d', immutable: true,
setHeaders: (res) => { res.setHeader('Content-Security-Policy', "default-src 'none'; sandbox"); },
}));
app.use('/api', authRouter(ctx));
app.use('/api', linksRouter(ctx));
app.use('/api', prayerRouter(ctx));
+9
View File
@@ -28,6 +28,12 @@ export type Config = {
sessionDays: number;
/** ... up to this many days from the sign-in (decision 7: 90). */
sessionMaxDays: number;
/** Where uploaded images are kept (UPLOAD_DIR; backend/uploads by default). */
uploadDir: string | null;
/** Where backups go (backend/backups; tests set their own). */
backupDir: string | null;
/** The database, for pg_dump (backups). */
databaseUrl: string | null;
};
const bool = (v: string | undefined, def: boolean) => (v === undefined || v === '' ? def : String(v).toLowerCase() === 'true');
@@ -64,5 +70,8 @@ export function loadConfig(env: Record<string, string | undefined> = process.env
allowPrivateLinks: bool(env.LINKS_ALLOW_PRIVATE, false),
sessionDays: Math.min(sessionMaxDays, Math.max(1, Number(env.SESSION_DAYS) || 8)),
sessionMaxDays,
uploadDir: env.UPLOAD_DIR?.trim() || null,
backupDir: null,
databaseUrl: env.DATABASE_URL?.trim() || null,
};
}
+124
View File
@@ -0,0 +1,124 @@
/**
* Uploaded images (APP-1.0-PLAN §10, as the Website's media library, smaller): photos for
* announcements, campaigns and events, as JPEG, PNG or WebP, checked by their bytes, not their
* name. Each is turned upright, **stripped of its metadata** (a phone photo can carry where it was
* taken) and kept at most 2000 px wide, in backend/uploads (UPLOAD_DIR), served at
* /api/uploads/<filename> (app.ts). Content keeps the image's full address, so an upload and an
* image from elsewhere work the same; the export (§11) and backups know an upload by its address.
*
* Storage: 5 GB included, or the licence's `limits.storageBytes`. When it's full, uploads stop;
* what's there keeps showing. An image in use can't be deleted.
*/
import crypto from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import sharp from 'sharp';
import type { Ctx } from '../context.js';
import { licenceStatus } from '../hub/licence.js';
import { ApiError } from '../http.js';
export const MAX_UPLOAD_BYTES = 15 * 1024 * 1024;
export const INCLUDED_STORAGE_BYTES = 5 * 1024 ** 3;
const MAX_WIDTH = 2000;
/** backend/uploads, from src/ and dist/ alike. */
export const defaultUploadDir = () => path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'uploads');
export const uploadDir = (ctx: Ctx) => path.resolve(ctx.config.uploadDir ?? defaultUploadDir());
/** The address an upload is shown at. */
export const mediaUrl = (ctx: Ctx, filename: string) => `${ctx.config.publicUrl}/api/uploads/${filename}`;
/** The upload's filename when `url` is one of this App's uploads, else null. */
export function uploadedFilename(ctx: Ctx, url: string | null | undefined): string | null {
const prefix = `${ctx.config.publicUrl}/api/uploads/`;
if (!url || !url.startsWith(prefix)) return null;
const name = url.slice(prefix.length);
return /^[0-9]{4}\/[0-9]{2}\/[0-9a-f-]{36}\.(jpg|png|webp)$/.test(name) ? name : null;
}
type Kind = { ext: 'jpg' | 'png' | 'webp'; mime: string };
/** What the bytes are, whatever the name says. */
export function sniff(b: Buffer): Kind | null {
if (b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return { ext: 'jpg', mime: 'image/jpeg' };
if (b.length > 8 && b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return { ext: 'png', mime: 'image/png' };
if (b.length > 12 && b.toString('ascii', 0, 4) === 'RIFF' && b.toString('ascii', 8, 12) === 'WEBP') return { ext: 'webp', mime: 'image/webp' };
return null;
}
export async function storage(ctx: Ctx): Promise<{ usedBytes: number; limitBytes: number; full: boolean; percent: number }> {
const [sum, licence] = await Promise.all([ctx.db.mediaAsset.aggregate({ _sum: { bytes: true } }), licenceStatus(ctx)]);
const fromLicence = (licence.claims as { limits?: { storageBytes?: number } } | null)?.limits?.storageBytes;
const limitBytes = typeof fromLicence === 'number' ? fromLicence : INCLUDED_STORAGE_BYTES;
const usedBytes = sum._sum.bytes ?? 0;
return { usedBytes, limitBytes, full: usedBytes >= limitBytes, percent: limitBytes ? Math.min(100, Math.round((usedBytes / limitBytes) * 100)) : 100 };
}
const view = (ctx: Ctx, m: { id: string; filename: string; mime: string; bytes: number; width: number | null; height: number | null; alt: string; createdAt: Date }) => ({
id: m.id, url: mediaUrl(ctx, m.filename), mime: m.mime, bytes: m.bytes, width: m.width, height: m.height, alt: m.alt, createdAt: m.createdAt.toISOString(),
});
export async function upload(ctx: Ctx, body: Buffer, alt: string, by: string) {
if (!body.length) throw new ApiError(400, 'EMPTY', 'Choose a photo to upload.');
if (body.length > MAX_UPLOAD_BYTES) throw new ApiError(413, 'TOO_LARGE', 'That photo is larger than 15 MB. Make it smaller and try again.');
const kind = sniff(body);
if (!kind) throw new ApiError(415, 'NOT_AN_IMAGE', 'Upload a photo as JPEG, PNG or WebP.');
const s = await storage(ctx);
if (s.full) throw new ApiError(409, 'STORAGE_FULL', 'The App\'s storage is full, so uploads have stopped. Delete images you no longer use, or ask Cross Code for more; everything uploaded keeps showing.');
let out: Buffer;
let width: number | null;
let height: number | null;
try {
// rotate() follows the EXIF orientation; sharp writes no metadata unless asked, so EXIF, GPS and XMP are gone.
const img = sharp(body, { failOn: 'error' }).rotate().resize({ width: MAX_WIDTH, withoutEnlargement: true });
const encoded = kind.ext === 'png' ? img.png({ compressionLevel: 9 }) : kind.ext === 'webp' ? img.webp({ quality: 82 }) : img.jpeg({ quality: 82, mozjpeg: true });
const { data, info } = await encoded.toBuffer({ resolveWithObject: true });
out = data;
width = info.width ?? null;
height = info.height ?? null;
} catch {
throw new ApiError(415, 'NOT_AN_IMAGE', 'That photo can\'t be read. Save it again as JPEG, PNG or WebP and try again.');
}
if (s.usedBytes + out.length > s.limitBytes) throw new ApiError(409, 'STORAGE_FULL', 'That photo doesn\'t fit in the storage that\'s left, so it wasn\'t added.');
const now = ctx.now();
const filename = `${now.getUTCFullYear()}/${String(now.getUTCMonth() + 1).padStart(2, '0')}/${crypto.randomUUID()}.${kind.ext}`;
const file = path.join(uploadDir(ctx), filename);
await fs.mkdir(path.dirname(file), { recursive: true });
await fs.writeFile(file, out);
const row = await ctx.db.mediaAsset.create({ data: { filename, mime: kind.mime, bytes: out.length, width, height, alt: alt.trim().slice(0, 300), uploadedBy: by } });
return view(ctx, row);
}
/** Where each upload is used (announcements, campaigns, events), by filename. */
export async function usage(ctx: Ctx): Promise<Map<string, string[]>> {
const [announcements, campaigns, events] = await Promise.all([
ctx.db.announcement.findMany({ where: { imageUrl: { not: null } }, select: { title: true, imageUrl: true } }),
ctx.db.prayerCampaign.findMany({ where: { imageUrl: { not: null } }, select: { title: true, imageUrl: true } }),
ctx.db.simpleEvent.findMany({ where: { imageUrl: { not: null } }, select: { title: true, imageUrl: true } }),
]);
const used = new Map<string, string[]>();
const add = (what: string, url: string | null) => {
const f = uploadedFilename(ctx, url);
if (f) used.set(f, [...(used.get(f) ?? []), what]);
};
for (const a of announcements) add(`Announcement "${a.title}"`, a.imageUrl);
for (const c of campaigns) add(`Campaign "${c.title}"`, c.imageUrl);
for (const e of events) add(`Event "${e.title}"`, e.imageUrl);
return used;
}
export async function listMedia(ctx: Ctx) {
const [rows, used, s] = await Promise.all([ctx.db.mediaAsset.findMany({ orderBy: { createdAt: 'desc' }, take: 500 }), usage(ctx), storage(ctx)]);
return { storage: s, media: rows.map((m) => ({ ...view(ctx, m), usedBy: used.get(m.filename) ?? [] })) };
}
export async function deleteMedia(ctx: Ctx, id: string) {
const m = await ctx.db.mediaAsset.findUnique({ where: { id } });
if (!m) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such image.');
const usedBy = (await usage(ctx)).get(m.filename);
if (usedBy?.length) throw new ApiError(409, 'IN_USE', `That image is still used: ${usedBy.join(', ')}. Change those first.`);
await ctx.db.mediaAsset.delete({ where: { id } });
await fs.rm(path.join(uploadDir(ctx), m.filename), { force: true });
return m;
}