Files
crosscode-platform/apps/website/backend/tests/admin.test.ts
T
joshuaandClaude Opus 5.5 2ba755145d 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 <picture> 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 <noreply@anthropic.com>
2026-11-25 14:04:43 +02:00

229 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 { loadDemo } from '../src/demo/demoChurch.js';
import { hashToken } from '../src/lib/crypto.js';
import { dimensions, sniff } from '../src/admin/media.js';
import { harness, SITE } from './support/harness.js';
type Role = 'owner' | 'admin' | 'editor' | 'ministry_leader' | 'viewer';
/** The demo church, and a signed-in admin with `role`. Returns a request helper with their cookie. */
async function signedIn(role: Role = 'editor', opts: { ministryId?: string | null } = {}) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ccw-admin-'));
const h = await harness({ linked: false, env: { UPLOAD_DIR: dir } });
await loadDemo(h.ctx, 'heritage', { uploadDir: dir });
const id = `00000000-0000-4000-8000-00000000000${['owner', 'admin', 'editor', 'ministry_leader', 'viewer'].indexOf(role) + 1}`;
await h.db.websiteUser.create({ data: { id, name: `Sam the ${role}`, email: `${role}@hope.test`, role, ministryId: opts.ministryId ?? null } });
await h.db.session.create({ data: { tokenHash: hashToken(`token-${role}`), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
const cookie = `ccw_session=token-${role}`;
const as = {
get: (p: string) => request(h.app).get(`/api/v1/admin${p}`).set('Cookie', cookie),
put: (p: string, body: object) => request(h.app).put(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE).send(body),
post: (p: string, body: object = {}) => request(h.app).post(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE).send(body),
del: (p: string) => request(h.app).delete(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE),
upload: (p: string, bytes: Buffer) => request(h.app).post(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE).set('Content-Type', 'application/octet-stream').send(bytes),
};
const pages = (await as.get('/pages')).body as { id: string; kind: string; slug: string }[];
return { ...h, as, id, dir, cookie, page: (kind: string) => pages.find((p) => p.kind === kind)!.id };
}
describe('the admin: who may do what (§10)', () => {
it('lets a Viewer look but change nothing', async () => {
const { as, page } = await signedIn('viewer');
assert.equal((await as.get('/overview')).status, 200);
assert.equal((await as.put(`/pages/${page('about')}`, { title: 'Us' })).status, 403);
assert.equal((await as.post('/publish')).status, 403);
});
it('lets a Ministry leader change their own ministry only, and not publish', async () => {
const { as, db } = await signedIn('ministry_leader');
const list = (await as.get('/ministries')).body as { id: string; name: string }[];
await db.websiteUser.update({ where: { id: '00000000-0000-4000-8000-000000000004' }, data: { ministryId: list[0]!.id } });
assert.equal((await as.put(`/ministries/${list[0]!.id}`, { name: 'Kids church', summary: 'Ages 3 to 12' })).status, 200);
assert.equal((await as.put(`/ministries/${list[1]!.id}`, { name: 'Youth' })).status, 403);
assert.equal((await as.post('/publish')).status, 403);
});
it('refuses a change that didn\'t come from the site itself', async () => {
const { app, cookie, page } = await signedIn('editor');
const res = await request(app).put(`/api/v1/admin/pages/${page('about')}`).set('Cookie', cookie).set('Origin', 'https://evil.example').send({ title: 'x' });
assert.equal(res.status, 403);
});
});
describe('editing, publishing, discarding, restoring (§4)', () => {
it('lists a change with who made it; Publish puts it live; nothing left to publish', async () => {
const { as, page, app } = await signedIn('editor');
assert.deepEqual((await as.get('/changes')).body, []);
const r = await as.put(`/pages/${page('about')}`, { title: 'Our story' });
assert.equal(r.status, 200);
const pending = (await as.get('/changes')).body;
assert.equal(pending.length, 1);
assert.equal(pending[0].kind, 'changed');
assert.equal(pending[0].label, 'Our story');
assert.equal(pending[0].by, 'Sam the editor');
// Visitors still see the published title until Publish.
const before = (await request(app).get('/api/v1/site/content')).body;
assert.equal(before.snapshot.pages.find((p: { kind: string }) => p.kind === 'about').title, 'About us');
assert.equal(before.snapshot.source, undefined, 'never sent to visitors');
const pub = await as.post('/publish', { note: 'New page title' });
assert.equal(pub.status, 200);
assert.equal(pub.body.number, 2);
const after = (await request(app).get('/api/v1/site/content')).body;
assert.equal(after.snapshot.pages.find((p: { kind: string }) => p.kind === 'about').title, 'Our story');
assert.equal((await as.post('/publish')).body.error.code, 'NOTHING_TO_PUBLISH');
});
it('discards one change, back to its published value; an added page is archived', async () => {
const { as, page } = await signedIn('editor');
await as.put(`/pages/${page('about')}`, { title: 'Changed' });
const added = await as.post('/pages', { title: 'Youth camp', slug: 'youth-camp' });
assert.equal(added.status, 200);
assert.equal((await as.get('/changes')).body.length, 2);
assert.equal((await as.post('/discard', { key: `page:${page('about')}` })).status, 200);
assert.equal((await as.get(`/pages/${page('about')}`)).body.title, 'About us');
await as.post('/discard', { key: `page:${added.body.id}` });
assert.deepEqual((await as.get('/changes')).body, []);
assert.equal((await as.get(`/pages/${added.body.id}`)).status, 404);
assert.equal((await as.post('/discard', { key: 'page:nope' })).status, 404);
});
it('restores an older version into the working copy, to preview and publish', async () => {
const { as, page } = await signedIn('editor');
await as.put(`/pages/${page('about')}`, { title: 'Version two' });
await as.post('/publish');
await as.del(`/pages/${page('give')}`);
await as.post('/publish');
const r = await as.post('/versions/1/restore');
assert.equal(r.status, 200);
assert.equal((await as.get(`/pages/${page('about')}`)).body.title, 'About us');
assert.equal((await as.get(`/pages/${page('give')}`)).status, 200, 'the removed page is back');
assert.equal(r.body.pending, 2);
const versions = (await as.get('/versions')).body;
assert.deepEqual(versions.map((v: { number: number }) => v.number), [3, 2, 1]);
});
it('switches template, keeping the church\'s own choices, and says what moved', async () => {
const { as } = await signedIn('editor');
await as.put('/design', { variants: { team: 'list' } });
const r = await as.put('/design', { template: 'bold' });
assert.equal(r.status, 200);
assert.equal(r.body.design.template, 'bold');
assert.equal(r.body.design.variants.team, 'list', 'kept');
assert.equal(r.body.design.variants.hero, 'video', 'moved to Bold\'s default');
assert.ok(r.body.moved.some((m: { what: string }) => m.what === 'hero.variant'));
assert.equal((await as.put('/design', { variants: { hero: 'spinning' } })).status, 400);
assert.equal((await as.put('/design', { style: { header: 'centred' } })).status, 400, 'a Heritage header on Bold');
});
it('checks a section\'s data and says which field is wrong', async () => {
const { as, page } = await signedIn('editor');
const bad = await as.put(`/pages/${page('home')}/home/hero`, { data: { headline: '', button: { label: 'Go', href: 'javascript:x' } } });
assert.equal(bad.status, 400);
assert.ok(bad.body.error.fields.headline);
assert.ok(bad.body.error.fields['button.href']);
const good = await as.put(`/pages/${page('home')}/home/hero`, { data: { headline: 'Welcome home' } });
assert.equal(good.status, 200);
});
it('adds, moves and removes blocks on a page; refuses an address the site uses', async () => {
const { as, page } = await signedIn('editor');
const id = page('about');
const added = (await as.post(`/pages/${id}/blocks`, { type: 'quote' })).body;
assert.equal(added.sections.at(-1).type, 'quote');
const quote = added.sections.at(-1).id;
const moved = (await as.post(`/pages/${id}/blocks/${quote}/move`, { direction: 'up' })).body;
assert.equal(moved.sections.at(-2).id, quote);
assert.equal((await as.del(`/pages/${id}/blocks/${quote}`)).body.sections.some((s: { id: string }) => s.id === quote), false);
assert.equal((await as.post('/pages', { title: 'Admin', slug: 'admin' })).status, 400);
assert.equal((await as.post('/pages', { title: 'Visit', slug: 'visit' })).body.error.code, 'SLUG_TAKEN');
});
});
describe('the preview (§4)', () => {
it('shows the working copy to a signed-in admin, never to anyone else', async () => {
const { as, app, cookie, page } = await signedIn('editor');
await as.put(`/pages/${page('about')}`, { title: 'Draft title' });
assert.equal((await request(app).get('/api/v1/site/preview')).status, 401);
const p = await request(app).get('/api/v1/site/preview').set('Cookie', cookie);
assert.equal(p.status, 200);
assert.equal(p.body.snapshot.pages.find((x: { kind: string }) => x.kind === 'about').title, 'Draft title');
assert.equal(p.body.preview.canPublish, true);
assert.match(String(p.headers['x-robots-tag']), /noindex/);
});
it('a shared link works signed out for 7 days, until revoked', async () => {
const { as, app } = await signedIn('editor');
const link = (await as.post('/preview-links')).body;
const token = link.url.split('/preview/')[1];
const p = await request(app).get('/api/v1/site/preview').set('x-preview-token', token);
assert.equal(p.status, 200);
assert.equal(p.body.preview.canPublish, false);
await as.del(`/preview-links/${link.id}`);
assert.equal((await request(app).get('/api/v1/site/preview').set('x-preview-token', token)).status, 401);
assert.equal((await as.get('/preview-links')).body[0].active, false);
});
});
describe('uploads and storage (§10, decision 12)', () => {
const png = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13]), Buffer.from('IHDR'), Buffer.from([0, 0, 2, 128, 0, 0, 1, 224]), Buffer.alloc(40)]);
it('knows a photo by its bytes, and its size', () => {
assert.deepEqual(sniff(png), { ext: 'png', mime: 'image/png' });
assert.deepEqual(dimensions(png, { ext: 'png', mime: 'image/png' }), { width: 640, height: 480 });
assert.equal(sniff(Buffer.from('<svg>')), null);
});
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, 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('<svg onload=alert(1)>'))).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', photo);
assert.equal(full.status, 409);
assert.equal(full.body.error.code, 'STORAGE_FULL');
assert.equal((await as.get('/media')).body.storage.full, true);
});
});