From 2ba755145ddd636ed39cfbaf023a2557798081b0 Mon Sep 17 00:00:00 2001 From: Joshua Oosthuizen Date: Wed, 25 Nov 2026 14:04:43 +0200 Subject: [PATCH] feat(website): photos upright, without metadata, in responsive sizes Every upload is turned upright, stripped of its metadata (EXIF, GPS), kept at most 2400 px wide and saved at 480/960/1600 px in WebP and JPEG; the pages pick the size with and srcset. Every file counts towards storage; a photo that can't be read is refused. sharp 0.35 (prebuilt, no build step on the servers). Co-Authored-By: Claude Opus 5.5 --- apps/website/CHANGELOG.md | 5 ++ apps/website/README.md | 2 +- apps/website/backend/package.json | 1 + apps/website/backend/src/admin/media.ts | 69 +++++++++++++++++-- apps/website/backend/src/site/content.ts | 4 +- apps/website/backend/src/site/snapshot.ts | 21 +++++- apps/website/backend/tests/admin.test.ts | 47 ++++++++++--- apps/website/frontend/src/site/parts.tsx | 17 ++++- .../frontend/src/site/sections/Hero.tsx | 10 +-- .../frontend/src/site/sections/index.tsx | 4 +- apps/website/frontend/src/site/types.ts | 3 +- docs/HANDOVER.md | 2 +- package-lock.json | 5 +- 13 files changed, 153 insertions(+), 37 deletions(-) diff --git a/apps/website/CHANGELOG.md b/apps/website/CHANGELOG.md index 0511731..6951aa9 100644 --- a/apps/website/CHANGELOG.md +++ b/apps/website/CHANGELOG.md @@ -65,6 +65,11 @@ added twice; one from the feed can only be hidden (deleting it would bring it back). - **Simple events** (§8): date and time or all day, place, description, photo and an optional link; publish, cancel, remove. Both publish on their own, not with the site (decision 9). +- **Photos made safe and fast** (§3): every upload is turned upright, **stripped of its metadata** + (a phone photo can carry where it was taken), kept at most 2400 px wide, and saved at 480, 960 + and 1600 px in WebP and JPEG; the pages pick the size the screen needs (``, `srcset`). + Every file counts towards storage; a photo the library can't read is refused. (sharp 0.35: + prebuilt binaries, no build step on the servers.) - The admin page signs people in and out; `/auth/problem` explains a refused sign-in. - **The church's export** (`scripts/export-church.ts`): `export.json` in `crosscode.church-export/1` with its `website` part, for `crosscode export` and uninstall. diff --git a/apps/website/README.md b/apps/website/README.md index 8ebddd2..dd9f704 100644 --- a/apps/website/README.md +++ b/apps/website/README.md @@ -10,7 +10,7 @@ presses Publish; until the first publish visitors see Coming soon. **State:** being built (2026-11-25): signing in through Accounts, the four templates and the public site, the admin (editing, preview, publish, discard, restore, shared previews, media), and the demo church, people and roles, messages (with the YouTube feed) and simple events. Still to come: -responsive image sizes, the event feed with Cross Events, the Hub's "Get more storage", Lighthouse +the event feed with Cross Events, the Hub's "Get more storage", Lighthouse and the VM test. Not released; `website@1.0.0` is tagged when the plan is built. diff --git a/apps/website/backend/package.json b/apps/website/backend/package.json index 00583b8..e0b2305 100644 --- a/apps/website/backend/package.json +++ b/apps/website/backend/package.json @@ -24,6 +24,7 @@ "@prisma/client": "^7.10.1", "dotenv": "^16.3.1", "express": "^5.3.0", + "sharp": "^0.35.5", "zod": "^4.6.7" }, "devDependencies": { diff --git a/apps/website/backend/src/admin/media.ts b/apps/website/backend/src/admin/media.ts index 0a81d7b..e63ae29 100644 --- a/apps/website/backend/src/admin/media.ts +++ b/apps/website/backend/src/admin/media.ts @@ -4,11 +4,14 @@ * `limits.storageBytes` says more once extra storage is bought. **When it's full, uploads stop** * (decision 12) until more is bought; what's already uploaded keeps showing. * - * Responsive sizes (WebP and JPEG per width) come next; for now the file is served as uploaded. + * Every photo is turned upright and **stripped of its metadata** (a phone photo can carry the place + * it was taken), kept at most 2400 px wide, and saved in responsive sizes (WebP and JPEG at 480, + * 960 and 1600 px wide, each smaller than the photo), all counted towards storage (§3). */ import crypto from 'node:crypto'; import fs from 'node:fs/promises'; import path from 'node:path'; +import sharp, { type Metadata, type Sharp } from 'sharp'; import type { Ctx } from '../context.js'; import { defaultUploadDir } from '../demo/demoChurch.js'; import { INCLUDED_STORAGE_BYTES } from '../hub/client.js'; @@ -82,11 +85,63 @@ export async function upload(ctx: Ctx, body: Buffer, alt: string, by: string) { throw new ApiError(409, 'STORAGE_FULL', 'Your website\'s storage is full, so uploads have stopped. To get more (5 GB at a time), contact Cross Code; everything already uploaded keeps showing.'); } const now = ctx.now(); - const rel = `${now.getUTCFullYear()}/${String(now.getUTCMonth() + 1).padStart(2, '0')}/${crypto.randomUUID()}.${kind.ext}`; - const file = path.join(uploadDir(ctx), rel); - await fs.mkdir(path.dirname(file), { recursive: true }); - await fs.writeFile(file, body, { mode: 0o644 }); - const { width, height } = dimensions(body, kind); - const row = await ctx.db.mediaAsset.create({ data: { filename: rel, mime: kind.mime, bytes: body.length, width, height, alt: alt.trim().slice(0, 500), uploadedBy: by } }); + const base = `${now.getUTCFullYear()}/${String(now.getUTCMonth() + 1).padStart(2, '0')}/${crypto.randomUUID()}`; + const dir = uploadDir(ctx); + await fs.mkdir(path.join(dir, path.dirname(base)), { recursive: true }); + const made = await processImage(body, kind, path.join(dir, base)); + const bytes = made.files.reduce((t, f) => t + f.bytes, 0); + if (s.usedBytes + bytes > s.limitBytes) { + await Promise.all(made.files.map((f) => fs.rm(path.join(dir, path.dirname(base), f.name), { force: true }))); + throw new ApiError(409, 'STORAGE_FULL', 'That photo doesn\'t fit in the storage that\'s left, so it wasn\'t added. To get more (5 GB at a time), contact Cross Code.'); + } + const filename = `${base}.${made.main.ext}`; + const row = await ctx.db.mediaAsset.create({ + data: { filename, mime: made.main.mime, bytes, width: made.width, height: made.height, alt: alt.trim().slice(0, 500), sizes: made.sizes as never, uploadedBy: by }, + }); return { ...row, url: mediaUrl(row.filename) }; } + +export const MAX_WIDTH = 2400; +export const WIDTHS = [480, 960, 1600] as const; + +export type Sizes = { w: number; webp: string; jpg: string }[]; + +/** + * The photo as kept (upright, no metadata, at most MAX_WIDTH wide, in its own format) and its + * responsive sizes, written next to `basePath` (`.`, `-.webp`, `-.jpg`). + * A photo the library can't read is refused rather than kept as uploaded. + */ +export async function processImage(body: Buffer, kind: Kind, basePath: string) { + let img: Sharp; + let meta: Metadata; + try { + img = sharp(body, { failOn: 'error' }).rotate(); + meta = await img.metadata(); + } 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.'); + } + // After rotate(), width and height follow the EXIF orientation. + const swap = (meta.orientation ?? 1) >= 5; + const fullW = (swap ? meta.height : meta.width) ?? dimensions(body, kind).width ?? MAX_WIDTH; + const fullH = (swap ? meta.width : meta.height) ?? dimensions(body, kind).height ?? null; + const width = Math.min(fullW, MAX_WIDTH); + const height = fullH ? Math.round((fullH * width) / fullW) : null; + const name = path.basename(basePath); + const files: { name: string; bytes: number }[] = []; + const write = async (pipeline: Sharp, file: string) => { + const info = await pipeline.toFile(path.join(path.dirname(basePath), file)); + files.push({ name: file, bytes: info.size }); + }; + // sharp writes no metadata unless asked (withMetadata), so EXIF, GPS and XMP are gone. + const main = kind.ext === 'png' ? { ext: 'png', mime: 'image/png' } : kind.ext === 'webp' ? { ext: 'webp', mime: 'image/webp' } : { ext: 'jpg', mime: 'image/jpeg' }; + const resized = () => img.clone().resize({ width, withoutEnlargement: true }); + await write(main.ext === 'png' ? resized().png({ compressionLevel: 9 }) : main.ext === 'webp' ? resized().webp({ quality: 82 }) : resized().jpeg({ quality: 82, mozjpeg: true }), `${name}.${main.ext}`); + const sizes: Sizes = []; + for (const w of WIDTHS) { + if (w >= width) continue; + await write(img.clone().resize({ width: w }).webp({ quality: 78 }), `${name}-${w}.webp`); + await write(img.clone().resize({ width: w }).flatten({ background: '#ffffff' }).jpeg({ quality: 80, mozjpeg: true }), `${name}-${w}.jpg`); + sizes.push({ w, webp: `${name}-${w}.webp`, jpg: `${name}-${w}.jpg` }); + } + return { main, width, height, sizes, files }; +} diff --git a/apps/website/backend/src/site/content.ts b/apps/website/backend/src/site/content.ts index 120669b..38b8778 100644 --- a/apps/website/backend/src/site/content.ts +++ b/apps/website/backend/src/site/content.ts @@ -8,7 +8,7 @@ import { TEMPLATE_FONT_PAIRINGS, type Church, type CrosscodeEvent, type WebsiteT import type { Ctx } from '../context.js'; import { churchProfile } from '../church/profile.js'; import { buildPalette, type Palette } from './palette.js'; -import { buildSnapshot, mediaUrl, publishedSnapshot, type Image, type Snapshot } from './snapshot.js'; +import { buildSnapshot, imageOf, publishedSnapshot, type Image, type Snapshot } from './snapshot.js'; import { headerIsTransparent, TEMPLATE_STYLE, type Variant } from './variants.js'; export type SiteEvent = { @@ -112,7 +112,7 @@ async function liveEvents(ctx: Ctx): Promise { ]); const image = (id: string | null) => { const m = id ? media.find((x) => x.id === id) : null; - return m ? { url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height } : null; + return m ? imageOf(m) : null; }; const own: SiteEvent[] = simple.map((e) => ({ title: e.title, summary: e.description ? e.description.slice(0, 200) : null, startsAt: e.startsAt.toISOString(), endsAt: e.endsAt?.toISOString() ?? null, diff --git a/apps/website/backend/src/site/snapshot.ts b/apps/website/backend/src/site/snapshot.ts index 47c9e8a..b6f169f 100644 --- a/apps/website/backend/src/site/snapshot.ts +++ b/apps/website/backend/src/site/snapshot.ts @@ -15,7 +15,10 @@ import { defaultDesign, isVariant, SECTION_TYPES, type SectionType, type SiteDes export const SNAPSHOT_VERSION = 1; -export type Image = { url: string; alt: string; width: number | null; height: number | null }; +/** An image to show: the photo, and its responsive sizes as `srcset`s when it has them (§3). */ +export type Image = { url: string; alt: string; width: number | null; height: number | null; srcset?: { webp: string; jpg: string } }; + +type MediaRow = { id: string; filename: string; alt: string; width: number | null; height: number | null; sizes?: unknown }; export type SnapshotSection = { type: string; variant: string | null; data: Record }; @@ -47,6 +50,18 @@ export type Snapshot = { export const mediaUrl = (filename: string) => `/api/uploads/${filename.split('/').map(encodeURIComponent).join('/')}`; +/** A media row as an Image, with `srcset`s from its sizes and the photo itself as the widest. */ +export function imageOf(m: MediaRow): Image { + const img: Image = { url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height }; + const sizes = Array.isArray(m.sizes) ? (m.sizes as { w: number; webp: string; jpg: string }[]) : []; + if (sizes.length && m.width) { + const dir = m.filename.includes('/') ? m.filename.slice(0, m.filename.lastIndexOf('/') + 1) : ''; + const set = (key: 'webp' | 'jpg') => [...sizes.map((x) => `${mediaUrl(dir + x[key])} ${x.w}w`), `${img.url} ${m.width}w`].join(', '); + img.srcset = { webp: set('webp'), jpg: set('jpg') }; + } + return img; +} + /** The design as saved, made safe: an unknown template, variant or section falls back to the default. */ export function cleanDesign(saved: { template: string; variants: unknown; home: unknown; style: unknown } | null): SiteDesign { const template: WebsiteTemplate = saved && (WEBSITE_TEMPLATES as readonly string[]).includes(saved.template) ? (saved.template as WebsiteTemplate) : 'heritage'; @@ -107,8 +122,8 @@ export async function buildSnapshot(ctx: Ctx): Promise { return snapshotFrom(toSource(w), media); } -export function snapshotFrom(source: Source, media: { id: string; filename: string; alt: string; width: number | null; height: number | null }[]): Snapshot { - const images = new Map(media.map((m) => [m.id, { url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height } satisfies Image])); +export function snapshotFrom(source: Source, media: MediaRow[]): Snapshot { + const images = new Map(media.map((m) => [m.id, imageOf(m)])); const image = (id: string | null | undefined) => (id ? images.get(id) ?? null : null); const used: Record = {}; const collect = (data: unknown) => { diff --git a/apps/website/backend/tests/admin.test.ts b/apps/website/backend/tests/admin.test.ts index a24430f..4005756 100644 --- a/apps/website/backend/tests/admin.test.ts +++ b/apps/website/backend/tests/admin.test.ts @@ -4,6 +4,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import request from 'supertest'; +import sharp from 'sharp'; import { loadDemo } from '../src/demo/demoChurch.js'; import { hashToken } from '../src/lib/crypto.js'; import { dimensions, sniff } from '../src/admin/media.js'; @@ -181,17 +182,45 @@ describe('uploads and storage (§10, decision 12)', () => { assert.equal(sniff(Buffer.from('')), null); }); - it('stores an upload, refuses what isn\'t a photo, and stops when storage is full', async () => { - const { as, db, dir } = await signedIn('editor'); - const up = await as.upload('/media?alt=The%20hall', png); + it('keeps a photo upright and without its location, in responsive sizes; refuses what isn\'t one', async () => { + const { as, dir, app } = await signedIn('editor'); + // A 2000 × 1200 phone photo with its GPS position in the metadata. + const photo = await sharp({ create: { width: 2000, height: 1200, channels: 3, background: '#1d5c63' } }) + .jpeg().withExifMerge({ IFD3: { GPSLatitudeRef: 'S', GPSLatitude: '25/1 44/1 46/1' } }).toBuffer(); + assert.ok((await sharp(photo).metadata()).exif, 'the test photo has EXIF'); + const up = await as.upload('/media?alt=The%20hall', photo); assert.equal(up.status, 200); - assert.equal(up.body.width, 640); - assert.ok(fs.existsSync(path.join(dir, up.body.filename))); - const notPhoto = await as.upload('/media', Buffer.from('')); - assert.equal(notPhoto.status, 415); - // Full: the media library already holds the included 5 GB. + assert.equal(up.body.width, 2000); + assert.deepEqual(up.body.sizes.map((x: { w: number }) => x.w), [480, 960, 1600]); + const file = path.join(dir, up.body.filename); + assert.equal((await sharp(fs.readFileSync(file)).metadata()).exif, undefined, 'no metadata kept'); + const files = fs.readdirSync(path.dirname(file)); + assert.equal(files.length, 7, 'the photo and 3 sizes in WebP and JPEG'); + const total = files.reduce((t, n) => t + fs.statSync(path.join(path.dirname(file), n)).size, 0); + assert.equal(up.body.bytes, total, 'every file counts towards storage'); + + // The site gets srcsets. + const about = (await as.get('/pages')).body.find((p: { kind: string }) => p.kind === 'about').id; + await as.put(`/pages/${about}`, { imageId: up.body.id }); + await as.post('/publish'); + const content = (await request(app).get('/api/v1/site/content')).body; + const img = content.snapshot.pages.find((p: { kind: string }) => p.kind === 'about').image; + assert.match(img.srcset.webp, /-480\.webp 480w, .*-960\.webp 960w, .*-1600\.webp 1600w, .*\.jpg 2000w$/); + + const big = await sharp({ create: { width: 4000, height: 3000, channels: 3, background: '#e0a458' } }).png().toBuffer(); + const b = await as.upload('/media', big); + assert.equal(b.body.width, 2400, 'kept at most 2400 wide'); + assert.equal(b.body.height, 1800); + assert.equal((await as.upload('/media', Buffer.from(''))).status, 415); + assert.equal((await as.upload('/media', png)).status, 415, 'a PNG header with nothing behind it'); + }); + + it('stops uploads when storage is full', async () => { + const { as, db } = await signedIn('editor'); + const photo = await sharp({ create: { width: 800, height: 600, channels: 3, background: '#ffffff' } }).jpeg().toBuffer(); + // The media library already holds the included 5 GB. await db.mediaAsset.create({ data: { filename: 'big.jpg', mime: 'image/jpeg', bytes: 5 * 1024 ** 3 } }); - const full = await as.upload('/media', png); + const full = await as.upload('/media', photo); assert.equal(full.status, 409); assert.equal(full.body.error.code, 'STORAGE_FULL'); assert.equal((await as.get('/media')).body.storage.full, true); diff --git a/apps/website/frontend/src/site/parts.tsx b/apps/website/frontend/src/site/parts.tsx index fc10fcf..8dd4b94 100644 --- a/apps/website/frontend/src/site/parts.tsx +++ b/apps/website/frontend/src/site/parts.tsx @@ -3,13 +3,26 @@ import type { Image } from "./types"; export const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" "); +/** + * An uploaded image at the size the screen needs (§3: responsive sizes in WebP and JPEG): the + * browser picks from the `srcset`s by `sizes`. `alt` overrides the image's own (e.g. "" when it's + * only decoration behind text). + */ +export function Picture({ image, className, sizes = "100vw", priority = false, alt }: { image: Image; className?: string; sizes?: string; priority?: boolean; alt?: string }) { + const img = ( + {alt + ); + return image.srcset ? {img} : img; +} + /** An image in a frame (Heritage frames, duotone tints), or a soft placeholder when there's none. */ export function Img({ image, className, sizes = "(min-width: 768px) 50vw, 100vw", priority = false, ratio = "aspect-[4/3]" }: { image: Image | null; className?: string; sizes?: string; priority?: boolean; ratio?: string }) { return (
{image ? ( - {image.alt} + ) : (