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
+2
View File
@@ -3,3 +3,5 @@ dist/
src/generated/
.env
/backups/
# images uploaded in the admin (media/media.ts)
/uploads/
+1
View File
@@ -26,6 +26,7 @@
"express": "^5.3.0",
"nodemailer": "^10.3.0",
"pg-boss": "^11.1.2",
"sharp": "^0.35.5",
"zod": "^4.6.7"
},
"devDependencies": {
@@ -0,0 +1,22 @@
-- Church App 1.0.0: uploads (docs/APP-1.0-PLAN.md §10): images uploaded in the admin.
-- CreateTable
CREATE TABLE "MediaAsset" (
"id" TEXT NOT NULL,
"filename" TEXT NOT NULL,
"mime" TEXT NOT NULL,
"bytes" INTEGER NOT NULL,
"width" INTEGER,
"height" INTEGER,
"alt" TEXT NOT NULL DEFAULT '',
"uploadedBy" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "MediaAsset_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "MediaAsset_filename_key" ON "MediaAsset"("filename");
-- CreateIndex
CREATE INDEX "MediaAsset_createdAt_idx" ON "MediaAsset"("createdAt");
+20
View File
@@ -332,6 +332,26 @@ model NotificationSettings {
/// Messages sent per local day and channel, for the heartbeat (`messages.email30d`, `whatsapp30d`).
/// Counts only: kept when a member or their messages are deleted. `key` is `<day>:<channel>`.
// ── Uploads (§10) ────────────────────────────────────────────────────────────────────────────
/// An image uploaded in the admin (announcements, campaigns, events), kept in backend/uploads and
/// served at /api/uploads/<filename>: turned upright, stripped of its metadata (a phone photo can
/// carry where it was taken), at most 2000 px wide.
model MediaAsset {
id String @id @default(uuid())
/// YYYY/MM/<uuid>.<ext>, under the uploads folder.
filename String @unique
mime String
bytes Int
width Int?
height Int?
alt String @default("")
uploadedBy String?
createdAt DateTime @default(now())
@@index([createdAt])
}
model MessageCount {
key String @id
day String
+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;
}
+69
View File
@@ -0,0 +1,69 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import request from 'supertest';
import sharp from 'sharp';
import { cookieHeader, harness, MEMBER, PASTOR, signInAs, SITE, type Harness } from './support/harness.js';
const EDITOR = '77777777-7777-4777-8777-777777777777';
const ORIGIN = 'https://app.hope.test';
async function setup() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cca-uploads-'));
const h = await harness({ env: { UPLOAD_DIR: dir } }) as Harness;
const as = (cookies: Record<string, string>) => ({
get: (p: string) => request(h.app).get(p).set('Cookie', cookieHeader(cookies)),
upload: (body: Buffer, type = 'image/jpeg') => request(h.app).post('/api/v1/admin/media?alt=Carols').set('Cookie', cookieHeader(cookies)).set('Origin', ORIGIN).set('Content-Type', type).send(body),
del: (p: string) => request(h.app).delete(p).set('Cookie', cookieHeader(cookies)).set('Origin', ORIGIN),
post: (p: string, body: object) => request(h.app).post(p).set('Cookie', cookieHeader(cookies)).set('Origin', ORIGIN).send(body),
});
const editor = as(await signInAs(h, { sub: EDITOR, name: 'Editor', roles: ['content_admin'] }, true));
const owner = as(await signInAs(h, { sub: PASTOR, name: 'Pastor Sam', roles: ['owner'] }, true));
const member = as(await signInAs(h, { sub: MEMBER, name: 'Thandi' }));
return { h, dir, editor, owner, member };
}
/** A phone photo: a JPEG with EXIF (a copyright line standing in for GPS). */
const photo = () => sharp({ create: { width: 3000, height: 2000, channels: 3, background: '#c33' } }).jpeg().withExif({ IFD0: { Copyright: 'Where-I-live-123' } }).toBuffer();
describe('uploaded images (§10)', () => {
it('keeps a photo without its metadata, at most 2000 px wide, and serves it', async () => {
const { h, dir, editor, member } = await setup();
assert.equal((await member.upload(await photo())).status, 403);
const res = await editor.upload(await photo());
assert.equal(res.status, 201);
assert.equal(res.body.width, 2000);
assert.equal(res.body.alt, 'Carols');
assert.ok(res.body.url.startsWith(`${SITE}/api/uploads/`));
const file = path.join(dir, res.body.url.slice(`${SITE}/api/uploads/`.length));
const saved = fs.readFileSync(file);
assert.ok(!saved.includes(Buffer.from('Where-I-live-123')));
const served = await request(h.app).get(new URL(res.body.url).pathname);
assert.equal(served.status, 200);
assert.equal(served.headers['content-type'], 'image/jpeg');
assert.match(served.headers['content-security-policy'], /sandbox/);
assert.ok([403, 404].includes((await request(h.app).get('/api/uploads/../../package.json')).status));
});
it('refuses what isn\'t a photo, whatever it\'s called', async () => {
const { editor } = await setup();
const res = await editor.upload(Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>'), 'image/png');
assert.equal(res.status, 415);
assert.equal(res.body.error.code, 'NOT_AN_IMAGE');
});
it('won\'t delete an image an announcement still uses, and lists where each is used', async () => {
const { h, editor } = await setup();
const img = (await editor.upload(await photo())).body;
await h.db.announcement.create({ data: { slug: 'carols', title: 'Carols', body: 'x', imageUrl: img.url, publishAt: new Date() } });
const list = await editor.get('/api/v1/admin/media');
assert.deepEqual(list.body.media[0].usedBy, ['Announcement "Carols"']);
assert.ok(list.body.storage.usedBytes > 0);
assert.equal((await editor.del(`/api/v1/admin/media/${img.id}`)).body.error.code, 'IN_USE');
await h.db.announcement.deleteMany({});
assert.equal((await editor.del(`/api/v1/admin/media/${img.id}`)).status, 200);
assert.equal((await request(h.app).get(new URL(img.url).pathname)).status, 404);
});
});
+2 -1
View File
@@ -22,6 +22,7 @@ const DEFAULTS: Record<string, () => Row> = {
outboxMessage: () => ({ sentAt: null, sentVia: null, failedAt: null, error: null, attempts: 0 }),
notificationSettings: () => ({ requestUpdates: 'email', announcements: 'off', devotional: 'off', devotionalTime: '06:00', devotionalOfferedAt: null, lastDevotionalDate: null }),
messageCount: () => ({ count: 0 }),
mediaAsset: () => ({ width: null, height: null, alt: '', uploadedBy: null }),
prayerRequest: () => ({ visibility: 'team', showName: false, anonymous: false, moderation: 'none', redactedAt: null, redactionNote: null, removedReason: null, moderatedById: null, moderatedAt: null, escalatedAt: null, escalatedById: null, escalationNote: null, closedAt: null }),
prayerRequestUpdate: () => ({ authorId: null }),
announcement: () => ({ imageUrl: null, buttonLabel: null, buttonUrl: null, campus: null, audience: 'everyone', pinned: false, publishAt: null, endsAt: null, sendEmail: false, sendWhatsApp: false, sentAt: null, createdById: null }),
@@ -31,7 +32,7 @@ const DEFAULTS: Record<string, () => Row> = {
};
const KEYS: Record<string, string> = { appSetting: 'key', notificationSettings: 'memberId', messageCount: 'key', productLink: 'installId', linkNonce: 'nonce', feedRemoval: 'eventId' };
/** Unique fields: one field, or several together (`@@unique([a, b])`). */
const UNIQUE: Record<string, (string | string[])[]> = { session: ['tokenHash'], outboxMessage: ['dedupeKey'], prayerSkip: [['commitmentId', 'date']], prayedMark: [['commitmentId', 'date']], requestPrayer: [['requestId', 'memberId']], devotional: [['source', 'date']], announcement: ['slug'], simpleEvent: ['slug'], importedEvent: [['originProduct', 'originId']] };
const UNIQUE: Record<string, (string | string[])[]> = { mediaAsset: ['filename'], session: ['tokenHash'], outboxMessage: ['dedupeKey'], prayerSkip: [['commitmentId', 'date']], prayedMark: [['commitmentId', 'date']], requestPrayer: [['requestId', 'memberId']], devotional: [['source', 'date']], announcement: ['slug'], simpleEvent: ['slug'], importedEvent: [['originProduct', 'originId']] };
const HAS_UPDATED_AT = new Set(['notificationSettings', 'member', 'appSetting', 'productLink', 'prayerCommitment', 'prayerCampaign', 'prayerRequest', 'announcement', 'devotional', 'simpleEvent']);
/** `include` support: model → relation → [other model, foreign key on the other (many) or on this row (one)]. */
const RELATIONS: Record<string, Record<string, { model: string; many: boolean; key: string }>> = {