website 1.11.0: layouts and backgrounds for the blocks; a video for the top of the page

- Blocks get layouts (BLOCK_VARIANTS: text standard/centred; image and text photo left,
  right or above; quote centred/with a line; call to action centred/banner), stored on
  Section.variant and checked against the type; an unknown one draws as the default, as
  every block looked before. The demo's image-text block id is now image-left.
- Each block has its own background (Section.background, migration
  20261201000000_block_background), in the published source only when set, put back by
  Discard and Restore, drawn as the homepage's (data-bg).
- MP4 uploads up to 20 MB for the hero's Video layout: QuickTime refused, metadata boxes
  (udta, meta, uuid) blanked into free boxes of the same size so where it was filmed is
  gone and the frame offsets hold; size read from tkhd. GET /media lists mime.
- Admin: a block's Layout and Background when open; the hero's Video field (only videos;
  photo fields only photos); the media library shows and takes videos. An upload over the
  limit says so instead of "That request isn't valid."
- Tests: backend (152, three new); e2e for block layouts and a video upload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 09:57:02 +02:00
co-authored by Claude Opus 5.5
parent a38468ba47
commit f5f778f0d7
28 changed files with 543 additions and 69 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/website-backend",
"version": "1.10.0",
"version": "1.11.0",
"description": "Church Website: the public site's content API, the admin API, publishing and uploads",
"private": true,
"type": "module",
@@ -0,0 +1,2 @@
-- A block's own background, in the church's colours (Website 1.11.0).
ALTER TABLE "Section" ADD COLUMN "background" TEXT;
+5 -1
View File
@@ -81,7 +81,8 @@ model Page {
}
/// A section or block on a page. `data` is validated with the zod schema for its `type`; `variant`
/// is one of that type's ids. Content is never tied to a template (§2).
/// is one of that type's ids (a homepage section's is on the design; a block's, BLOCK_VARIANTS, here).
/// Content is never tied to a template (§2).
model Section {
id String @id @default(uuid())
pageId String
@@ -90,6 +91,9 @@ model Section {
variant String?
position Int @default(0)
hidden Boolean @default(false)
/// A block's own background (variants.ts SECTION_BACKGROUNDS), or null to follow the style.
/// Homepage sections keep theirs on the design's home entries instead.
background String?
data Json
updatedAt DateTime @updatedAt
updatedBy String?
+17 -3
View File
@@ -13,7 +13,7 @@ import { Prisma } from '../generated/prisma/client.js';
import { ApiError } from '../http.js';
import { BLOCK_SCHEMAS, isBlockType, rowFraming, SECTION_SCHEMAS } from '../site/sections.js';
import { cleanDesign } from '../site/snapshot.js';
import { BUTTONS, IMAGE_TREATMENTS, isVariant, SECTION_BACKGROUNDS, SECTION_COLOURS, SECTION_TYPES, sectionTypeSchema, SPACINGS, switchTemplate, TEMPLATE_HEADERS, type SectionType } from '../site/variants.js';
import { BLOCK_VARIANTS, BUTTONS, IMAGE_TREATMENTS, isVariant, SECTION_BACKGROUNDS, SECTION_COLOURS, SECTION_TYPES, sectionTypeSchema, SPACINGS, switchTemplate, TEMPLATE_HEADERS, type SectionType } from '../site/variants.js';
type Who = { id: string; role: string };
@@ -182,7 +182,8 @@ export async function saveHomeSection(ctx: Ctx, pageId: string, type: string, bo
return getPage(ctx, pageId);
}
const blockPatch = z.object({ data: z.unknown().optional(), variant: z.string().max(40).nullable().optional(), hidden: z.boolean().optional() });
/** A block's change: its data, its layout (one of its type's BLOCK_VARIANTS), whether it shows, its own background (null follows the style). */
const blockPatch = z.object({ data: z.unknown().optional(), variant: z.string().max(40).nullable().optional(), hidden: z.boolean().optional(), background: z.enum(SECTION_BACKGROUNDS).nullable().optional() });
/** The blocks of any other page: add, change, move, remove. */
export async function addBlock(ctx: Ctx, pageId: string, body: unknown, by: Who) {
@@ -203,7 +204,20 @@ export async function saveBlock(ctx: Ctx, pageId: string, sectionId: string, bod
const patch = check(blockPatch, body);
await notChangedSince(ctx, s, body, by);
const data = patch.data === undefined ? undefined : check(schemaFor(s.type), patch.data);
await ctx.db.section.update({ where: { id: sectionId }, data: { ...(data !== undefined ? { data: data as never } : {}), ...(patch.hidden !== undefined ? { hidden: patch.hidden } : {}), ...(patch.variant !== undefined ? { variant: patch.variant } : {}), updatedBy: by.id } });
const layouts = (BLOCK_VARIANTS as Record<string, readonly string[]>)[s.type] ?? [];
if (patch.variant && !layouts.includes(patch.variant)) {
throw new ApiError(400, 'VALIDATION', `"${patch.variant}" isn't a layout of this block.`, { variant: `One of ${layouts.join(', ')}` });
}
await ctx.db.section.update({
where: { id: sectionId },
data: {
...(data !== undefined ? { data: data as never } : {}),
...(patch.hidden !== undefined ? { hidden: patch.hidden } : {}),
...(patch.variant !== undefined ? { variant: patch.variant } : {}),
...(patch.background !== undefined ? { background: patch.background } : {}),
updatedBy: by.id,
},
});
await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } });
return getPage(ctx, pageId);
}
+91 -2
View File
@@ -21,11 +21,21 @@ import { audit } from '../lib/audit.js';
import { mediaUrl } from '../site/snapshot.js';
export const MAX_UPLOAD_BYTES = 15 * 1024 * 1024;
/**
* A video for the top of the page's Video layout: a short muted loop, so 20 MB is plenty, and it
* stays under the installers' nginx `client_max_body_size 25m`.
*/
export const MAX_VIDEO_BYTES = 20 * 1024 * 1024;
/** The most the upload route reads, photo or video. */
export const MAX_BODY_BYTES = Math.max(MAX_UPLOAD_BYTES, MAX_VIDEO_BYTES);
type Kind = { ext: string; mime: string };
/** What the bytes are, whatever the name says. */
export function sniff(b: Buffer): Kind | null {
// An ISO media file (MP4): its first box is `ftyp`. QuickTime (.mov, brand `qt `) is left out:
// browsers other than Safari often can't play it.
if (b.length > 12 && b.toString('ascii', 4, 8) === 'ftyp') return b.toString('ascii', 8, 12) === 'qt ' ? { ext: 'mov', mime: 'video/quicktime' } : { ext: 'mp4', mime: 'video/mp4' };
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' };
@@ -78,9 +88,10 @@ export const uploadDir = (ctx: Ctx) => path.resolve(ctx.config.uploadDir ?? defa
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 file 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.');
if (kind?.mime.startsWith('video/')) return uploadVideo(ctx, body, kind, alt, by);
if (body.length > MAX_UPLOAD_BYTES) throw new ApiError(413, 'TOO_LARGE', 'That file is larger than 15 MB. Make it smaller and try again.');
if (!kind) throw new ApiError(415, 'NOT_AN_IMAGE', 'Upload a photo as JPEG, PNG or WebP, or a video as MP4.');
const s = await storage(ctx);
if (s.usedBytes + body.length > s.limitBytes) {
throw new ApiError(409, 'STORAGE_FULL', 'Your website\'s storage is full, so uploads have stopped. An Owner or Admin can get more under Media library; everything already uploaded keeps showing.');
@@ -102,6 +113,84 @@ export async function upload(ctx: Ctx, body: Buffer, alt: string, by: string) {
return { ...row, url: mediaUrl(row.filename) };
}
/**
* A video (MP4), kept as uploaded apart from its metadata (cleanVideo), with no other sizes: the
* site plays it as it is. Counted towards storage like a photo.
*/
async function uploadVideo(ctx: Ctx, body: Buffer, kind: Kind, alt: string, by: string) {
if (kind.ext !== 'mp4') throw new ApiError(415, 'NOT_MP4', 'That video is a QuickTime (.mov) file, which most browsers can\'t play. Save or export it as MP4 and try again.');
if (body.length > MAX_VIDEO_BYTES) throw new ApiError(413, 'TOO_LARGE', 'That video is larger than 20 MB. Use a shorter clip (10 to 20 seconds is plenty for a loop), or make it smaller, and try again.');
const clean = cleanVideo(body);
if (!clean) throw new ApiError(415, 'NOT_A_VIDEO', 'That video can\'t be read. Save it again as MP4 and try again.');
const s = await storage(ctx);
if (s.usedBytes + clean.bytes.length > s.limitBytes) {
throw new ApiError(409, 'STORAGE_FULL', 'Your website\'s storage is full, so uploads have stopped. An Owner or Admin can get more under Media library; everything already uploaded keeps showing.');
}
const now = ctx.now();
const filename = `${now.getUTCFullYear()}/${String(now.getUTCMonth() + 1).padStart(2, '0')}/${crypto.randomUUID()}.mp4`;
const dir = uploadDir(ctx);
await fs.mkdir(path.join(dir, path.dirname(filename)), { recursive: true });
await fs.writeFile(path.join(dir, filename), clean.bytes);
const row = await ctx.db.mediaAsset.create({
data: { filename, mime: kind.mime, bytes: clean.bytes.length, width: clean.width, height: clean.height, alt: alt.trim().slice(0, 500), sizes: [] as never, uploadedBy: by },
});
return { ...row, url: mediaUrl(row.filename) };
}
/** Boxes that hold a video's own boxes, which are searched for metadata. */
const VIDEO_CONTAINERS = new Set(['moov', 'trak', 'mdia', 'minf', 'edts']);
/** Boxes that hold metadata: where and when it was filmed (`©xyz`, Apple's location keys), the camera, XMP. */
const VIDEO_METADATA = new Set(['udta', 'meta', 'uuid']);
/**
* An MP4 without its metadata, as photos lose theirs (a phone video can carry the place it was
* filmed): every metadata box is turned into a `free` box of the same size, filled with zeros, so
* nothing moves and the offsets to the frames stay right. Also reads the picture's size from the
* first video track (`tkhd`). Null when the boxes don't add up or there's no `moov` (not a video).
*/
export function cleanVideo(input: Buffer): { bytes: Buffer; width: number | null; height: number | null } | null {
const b = Buffer.from(input);
let moov = false;
let width: number | null = null;
let height: number | null = null;
const walk = (start: number, end: number, depth: number): boolean => {
let i = start;
while (i < end) {
if (end - i < 8) return false;
let size = b.readUInt32BE(i);
const type = b.toString('latin1', i + 4, i + 8);
let header = 8;
if (size === 1) {
if (end - i < 16) return false;
const big = b.readBigUInt64BE(i + 8);
if (big > BigInt(end - i)) return false;
size = Number(big);
header = 16;
} else if (size === 0) size = end - i;
if (size < header || i + size > end) return false;
if (depth === 0 && type === 'moov') moov = true;
if (VIDEO_METADATA.has(type)) {
b.write('free', i + 4, 'latin1');
b.fill(0, i + header, i + size);
} else if (VIDEO_CONTAINERS.has(type)) {
if (!walk(i + header, i + size, depth + 1)) return false;
} else if (type === 'tkhd' && width === null) {
const v1 = b[i + header] === 1;
const at = i + header + (v1 ? 88 : 76);
if (at + 8 <= i + size) {
const w = b.readUInt32BE(at) >>> 16;
const h = b.readUInt32BE(at + 4) >>> 16;
if (w > 0 && h > 0) [width, height] = [w, h];
}
}
i += size;
}
return true;
};
if (!walk(0, b.length, 0) || !moov) return null;
return { bytes: b, width, height };
}
export const MAX_WIDTH = 2400;
export const WIDTHS = [480, 960, 1600] as const;
+3 -3
View File
@@ -22,7 +22,7 @@ import { syncYoutube } from '../site/youtube.js';
import { publishOn, syncLink } from '../feed/feed.js';
import { connectTo, disconnectFrom } from '../links/connect.js';
import { linkedProducts } from '../links/store.js';
import { deleteMedia, MAX_UPLOAD_BYTES, mediaUsage, requestMoreStorage, storage, storageRequestStatus, upload } from './media.js';
import { deleteMedia, MAX_BODY_BYTES, mediaUsage, requestMoreStorage, storage, storageRequestStatus, upload } from './media.js';
import { createPreviewLink, listPreviewLinks, revokePreviewLink } from './previewLinks.js';
import { maintenanceRouter } from './maintenance.js';
@@ -97,10 +97,10 @@ export function adminRouter(ctx: Ctx) {
// ─── Media library and storage ───
r.get('/media', handle(async () => {
const [rows, s, usedIn] = await Promise.all([ctx.db.mediaAsset.findMany({ orderBy: { createdAt: 'desc' } }), storage(ctx), mediaUsage(ctx)]);
return { storage: s, request: await storageRequestStatus(ctx, s.limitBytes), items: rows.map((m) => ({ id: m.id, url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height, bytes: m.bytes, usedIn: usedIn(m) })) };
return { storage: s, request: await storageRequestStatus(ctx, s.limitBytes), items: rows.map((m) => ({ id: m.id, url: mediaUrl(m.filename), mime: m.mime, alt: m.alt, width: m.width, height: m.height, bytes: m.bytes, usedIn: usedIn(m) })) };
}));
r.delete('/media/:id', editor, handle(async (req) => { await deleteMedia(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
r.post('/media', editor, express.raw({ type: () => true, limit: MAX_UPLOAD_BYTES + 1 }), handle((req) =>
r.post('/media', editor, express.raw({ type: () => true, limit: MAX_BODY_BYTES + 1 }), handle((req) =>
upload(ctx, Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0), String(req.query.alt ?? ''), who(req).id)));
// Get more storage: it costs the church, so an Owner or Admin asks (decision 12).
r.post('/storage-request', requireRole(ctx, 'admin'), json, handle((req) => requestMoreStorage(ctx, Number(req.body?.steps ?? 1), who(req))));
+2
View File
@@ -108,6 +108,8 @@ export function createApp(ctx: Ctx) {
if (err instanceof ApiError) return sendError(res, err);
const e = err as { type?: string; status?: number };
if (e?.type === 'entity.parse.failed') return sendError(res, new ApiError(400, 'VALIDATION', 'The body must be JSON.'));
// Only an upload is ever this large (express.raw's limit on POST /media).
if (e?.type === 'entity.too.large') return sendError(res, new ApiError(413, 'TOO_LARGE', 'That file is too large: photos can be up to 15 MB and videos up to 20 MB. Make it smaller and try again.'));
// A missing upload (express.static), or another known client error.
if (typeof e?.status === 'number' && e.status >= 400 && e.status < 500) return sendError(res, new ApiError(e.status, e.status === 404 ? 'NOT_FOUND' : 'BAD_REQUEST', e.status === 404 ? 'There is no such file.' : "That request isn't valid."));
return sendError(res, err);
+1 -1
View File
@@ -333,7 +333,7 @@ export async function loadDemo(ctx: Ctx, what: WebsiteTemplate | agent.WebsiteDe
{
kind: 'visit', slug: 'visit', title: 'Plan your visit', position: 1, description: d('visit', 'What to expect on your first Sunday at {name}.'), sections: [
{ type: 'text', data: { heading: 'What to expect', body: t(seed.visit.expect) } },
{ type: 'image-text', variant: 'image-text', data: { heading: 'Bringing children', body: t(seed.visit.kids), imageId: img.ministry0, button: null } },
{ type: 'image-text', variant: 'image-left', data: { heading: 'Bringing children', body: t(seed.visit.kids), imageId: img.ministry0, button: null } },
{ type: 'cta', data: { heading: t(seed.visit.cta), text: extra?.ctaText ?? 'Send us a message and we will get back to you.', button: { label: 'Contact us', href: '/contact' } } },
],
},
+6 -5
View File
@@ -11,7 +11,7 @@ import { WEBSITE_TEMPLATES, type WebsiteTemplate } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { audit } from '../lib/audit.js';
import { parseSectionData } from './sections.js';
import { defaultDesign, isVariant, SECTION_BACKGROUNDS, SECTION_TYPES, switchTemplate, type SectionBackground, type SectionType, type SiteDesign } from './variants.js';
import { blockVariant, defaultDesign, isSectionBackground, isVariant, SECTION_BACKGROUNDS, SECTION_TYPES, switchTemplate, type SectionBackground, type SectionType, type SiteDesign } from './variants.js';
export const SNAPSHOT_VERSION = 1;
@@ -34,7 +34,7 @@ export const framed = (img: Image | null, f: unknown): Image | null => {
type MediaRow = { id: string; filename: string; alt: string; width: number | null; height: number | null; sizes?: unknown };
/** `background`: a homepage section's own background (variants.ts SECTION_BACKGROUNDS), when it has one. */
/** `background`: a homepage section's or block's own background (variants.ts SECTION_BACKGROUNDS), when it has one. */
export type SnapshotSection = { type: string; variant: string | null; data: Record<string, unknown>; background?: SectionBackground };
export type SnapshotPage = {
@@ -106,7 +106,8 @@ export type Source = {
pages: {
id: string; kind: string; slug: string; title: string; seoTitle: string | null; description: string | null; navLabel: string | null;
inNav: boolean; position: number; imageId: string | null;
sections: { id: string; type: string; variant: string | null; position: number; hidden: boolean; data: unknown }[];
/** `background` only when a block has one, so versions published before it compare equal. */
sections: { id: string; type: string; variant: string | null; position: number; hidden: boolean; background?: string; data: unknown }[];
}[];
ministries: { id: string; slug: string; name: string; summary: string | null; body: string | null; imageId: string | null; framing?: unknown; position: number }[];
leaders: { id: string; name: string; role: string | null; bio: string | null; photoId: string | null; framing?: unknown; position: number }[];
@@ -133,7 +134,7 @@ export function toSource(w: Awaited<ReturnType<typeof readWorkingCopy>>): Source
pages: w.pages.map((p) => ({
id: p.id, kind: p.kind, slug: p.slug, title: p.title, seoTitle: p.seoTitle, description: p.description, navLabel: p.navLabel, inNav: p.inNav,
position: p.position, imageId: p.imageId,
sections: p.sections.map((x) => ({ id: x.id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, data: x.data })),
sections: p.sections.map((x) => ({ id: x.id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, ...(x.background ? { background: x.background } : {}), data: x.data })),
})),
ministries: w.ministries.map((m) => ({ id: m.id, slug: m.slug, name: m.name, summary: m.summary, body: m.body, imageId: m.imageId, ...withFraming(m.framing), position: m.position })),
leaders: w.leaders.map((l) => ({ id: l.id, name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, ...withFraming(l.framing), position: l.position })),
@@ -189,7 +190,7 @@ export function snapshotFrom(source: Source, media: MediaRow[]): Snapshot {
const data = parseSectionData(x.type, x.data);
if (!data) continue;
collect(data);
sections.push({ type: x.type, variant: x.variant, data });
sections.push({ type: x.type, variant: blockVariant(x.type, x.variant), data, ...(isSectionBackground(x.background) ? { background: x.background } : {}) });
}
}
return {
+23
View File
@@ -114,6 +114,29 @@ export function headerIsTransparent(template: WebsiteTemplate, header: string, h
export const SECTION_BACKGROUNDS = ['light', 'tint', 'accent', 'brand', 'dark'] as const;
export type SectionBackground = (typeof SECTION_BACKGROUNDS)[number];
export const isSectionBackground = (v: unknown): v is SectionBackground => (SECTION_BACKGROUNDS as readonly unknown[]).includes(v);
/**
* The layouts of the other pages' blocks, the default first. Stored on the block's own row
* (`Section.variant`); like the homepage's, **an id never changes or goes away** once released,
* and one that isn't listed (an older row's) is drawn as the default.
*/
export const BLOCK_VARIANTS = {
text: ['standard', 'centred'],
'image-text': ['image-left', 'image-right', 'image-above'],
quote: ['centred', 'line'],
cta: ['centred', 'banner'],
} as const;
export type BlockVariantType = keyof typeof BLOCK_VARIANTS;
/** A block's layout as drawn: its own when it's one of its type's, else the type's default (null for an unknown type). */
export function blockVariant(type: string, variant: string | null | undefined): string | null {
const list = (BLOCK_VARIANTS as Record<string, readonly string[]>)[type];
if (!list) return variant ?? null;
return variant && list.includes(variant) ? variant : list[0]!;
}
/** A homepage entry: the section, whether it shows, and its own background when it has one. */
export type HomeEntry = { section: SectionType; hidden: boolean; background?: SectionBackground };
+1 -1
View File
@@ -98,7 +98,7 @@ async function apply(ctx: Ctx, key: string, source: Source | null, by: Who) {
const data = { kind: p.kind as never, slug: p.slug, title: p.title, seoTitle: p.seoTitle, description: p.description, navLabel: p.navLabel, inNav: p.inNav, position: p.position, imageId: p.imageId, archivedAt: null, ...stamp };
await db.page.upsert({ where: { id }, create: { id, ...data }, update: data });
await db.section.deleteMany({ where: { pageId: id } });
for (const x of p.sections) await db.section.create({ data: { id: x.id, pageId: id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, data: x.data as never, ...stamp } });
for (const x of p.sections) await db.section.create({ data: { id: x.id, pageId: id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, background: x.background ?? null, data: x.data as never, ...stamp } });
return;
}
if (what === 'ministry') {
@@ -4,6 +4,7 @@ import request from 'supertest';
import { hashToken } from '../src/lib/crypto.js';
import { previewContent, siteContent } from '../src/site/content.js';
import { publish } from '../src/site/snapshot.js';
import { changes, discard } from '../src/site/workingCopy.js';
import { harness, SITE } from './support/harness.js';
async function site() {
@@ -85,3 +86,42 @@ describe('an address that changed (§6)', () => {
assert.deepEqual(after.mode === 'published' && after.snapshot.redirects, { 'youth-camp': '/summer-camp' });
});
});
describe("a block's layout and background", () => {
it('saves one of its own layouts and a background from the church\'s colours, previews them, and discards them', async () => {
const { ctx, db, as } = await site();
const page = await db.page.create({ data: { kind: 'custom', slug: 'join', title: 'Join us' } });
const block = await db.section.create({ data: { pageId: page.id, type: 'cta', data: { heading: 'Come along', text: null, button: null } } });
await db.section.create({ data: { pageId: page.id, type: 'text', variant: 'something-old', data: { heading: null, body: 'Hi' } } });
await publish(ctx, { id: 'x', role: 'system' });
// Drawn with its type's default until it has a layout; an id it doesn't know is drawn so too.
const shown = async () => {
const c = await previewContent(ctx);
assert.ok(c.mode === 'published');
return c.snapshot.pages.find((p) => p.slug === 'join')!.sections.map((s) => ({ type: s.type, variant: s.variant, background: s.background }));
};
assert.deepEqual(await shown(), [{ type: 'cta', variant: 'centred', background: undefined }, { type: 'text', variant: 'standard', background: undefined }]);
const put = (b: object) => as('ann')('put', `/pages/${page.id}/blocks/${block.id}`, b);
assert.equal((await put({ variant: 'banner' })).status, 200);
assert.equal((await put({ background: 'dark' })).status, 200);
const wrong = await put({ variant: 'image-left' });
assert.equal(wrong.status, 400);
assert.match(wrong.body.error.message, /isn't a layout of this block/);
assert.equal((await put({ background: 'pink' })).status, 400);
assert.deepEqual((await shown())[0], { type: 'cta', variant: 'banner', background: 'dark' });
// A change like any other: listed, and discarded back to what's published.
const pending = (await changes(ctx)).find((c) => c.key === `page:${page.id}`);
assert.ok(pending);
await discard(ctx, `page:${page.id}`, { id: 'x', role: 'editor' });
const back = await db.section.findUnique({ where: { id: block.id } });
assert.equal(back?.background, null);
assert.equal(back?.variant, null);
// Back to null follows the style again.
assert.equal((await put({ background: 'tint' })).status, 200);
assert.equal((await put({ background: null })).status, 200);
assert.equal((await shown())[0]!.background, undefined);
});
});
+69
View File
@@ -5,6 +5,7 @@ import os from 'node:os';
import path from 'node:path';
import request from 'supertest';
import { hashToken } from '../src/lib/crypto.js';
import { cleanVideo } from '../src/admin/media.js';
import { parseSectionData } from '../src/site/sections.js';
import { harness, SITE } from './support/harness.js';
@@ -56,3 +57,71 @@ describe('framing a photo in its frame', () => {
assert.equal(parseSectionData('hero', { headline: 'Hi', framing: { [id]: { x: 300, y: 0, zoom: 1 } } }), null);
});
});
/** An MP4 box: its size, its type, then what's in it. */
const box = (type: string, ...parts: Buffer[]) => {
const body = Buffer.concat(parts);
const head = Buffer.alloc(8);
head.writeUInt32BE(8 + body.length, 0);
head.write(type, 4, 'latin1');
return Buffer.concat([head, body]);
};
/** A version 0 track header for a picture `w` by `h` (16.16 fixed point at its end). */
const tkhd = (w: number, h: number) => {
const b = Buffer.alloc(84);
b.writeUInt32BE(w << 16, 76);
b.writeUInt32BE(h << 16, 80);
return box('tkhd', b);
};
const PLACE = '+52.3676+004.9041/';
/** A small MP4 filmed somewhere: where in `udta` (©xyz) and Apple's `meta`, as phones save them. */
function mp4(brand = 'isom') {
return Buffer.concat([
box('ftyp', Buffer.from(`${brand}\0\0\0\0isommp42`, 'latin1')),
box('moov',
box('mvhd', Buffer.alloc(100)),
box('trak', tkhd(640, 360), box('mdia', box('mdhd', Buffer.alloc(24)))),
box('udta', box('©xyz', Buffer.from(PLACE, 'latin1'))),
box('meta', Buffer.from(`com.apple.quicktime.location.ISO6709${PLACE}`, 'latin1'))),
box('mdat', Buffer.from('frames go here')),
]);
}
describe('a video for the top of the page', () => {
it('takes away where it was filmed without moving anything, and reads its size', () => {
const v = mp4();
const clean = cleanVideo(v)!;
assert.equal(clean.bytes.length, v.length);
assert.equal(clean.bytes.includes(Buffer.from(PLACE)), false);
assert.equal(clean.bytes.includes(Buffer.from('com.apple.quicktime.location')), false);
assert.ok(clean.bytes.includes(Buffer.from('frames go here')));
// The frames sit where they did, so the offsets to them still hold.
assert.equal(clean.bytes.indexOf('mdat'), v.indexOf('mdat'));
assert.deepEqual([clean.width, clean.height], [640, 360]);
// The upload itself isn't changed.
assert.ok(v.includes(Buffer.from(PLACE)));
// Boxes that don't add up, or no moov: not a video.
assert.equal(cleanVideo(Buffer.concat([v.subarray(0, 40), Buffer.from([0, 0, 1, 0])])), null);
assert.equal(cleanVideo(box('ftyp', Buffer.from('isom\0\0\0\0', 'latin1'))), null);
});
it('uploads an MP4 to the library, and refuses QuickTime and one too large', async () => {
const { app, db, uploads } = await site();
const post = (b: Buffer) => request(app).post('/api/v1/admin/media?alt=People%20arriving').set('Cookie', 'ccw_session=ann').set('Origin', SITE).set('Content-Type', 'application/octet-stream').send(b);
const ok = await post(mp4());
assert.equal(ok.status, 200, JSON.stringify(ok.body));
assert.equal(ok.body.mime, 'video/mp4');
assert.match(ok.body.url, /\.mp4$/);
const row = await db.mediaAsset.findUnique({ where: { id: ok.body.id } });
assert.deepEqual([row?.width, row?.height, row?.alt], [640, 360, 'People arriving']);
const saved = await fs.readFile(path.join(uploads, String(row!.filename)));
assert.equal(saved.includes(Buffer.from(PLACE)), false);
const mov = await post(mp4('qt '));
assert.equal(mov.status, 415);
assert.match(mov.body.error.message, /MP4/);
const big = await post(Buffer.concat([mp4(), Buffer.alloc(20 * 1024 * 1024)]));
assert.equal(big.status, 413);
assert.match(big.body.error.message, /20 MB/);
});
});
@@ -13,7 +13,7 @@ const DEFAULTS: Record<string, () => Row> = {
leader: () => ({ role: null, bio: null, photoId: null, framing: null, position: 0, archivedAt: null, updatedBy: null }),
messageSeries: () => ({ summary: null, imageId: null }),
page: () => ({ seoTitle: null, description: null, navLabel: null, inNav: true, position: 0, imageId: null, archivedAt: null, updatedBy: null }),
section: () => ({ variant: null, position: 0, hidden: false, updatedBy: null }),
section: () => ({ variant: null, background: null, position: 0, hidden: false, updatedBy: null }),
message: () => ({ externalId: null, thumbnailUrl: null, speaker: null, passage: null, notes: null, seriesId: null, hidden: false, publishedAt: null, updatedBy: null }),
simpleEvent: () => ({ endsAt: null, allDay: false, timezone: 'Africa/Johannesburg', location: null, description: null, imageId: null, framing: null, link: null, cancelled: false, publishedAt: null, updatedBy: null }),
mediaAsset: () => ({ width: null, height: null, alt: '', sizes: null, uploadedBy: null }),