Compare commits

...
Author SHA1 Message Date
joshuaandClaude Opus 5.5 b767b45e64 feat(website): the event feed both ways, and Linked products
Publish my events: the Website's simple events as crosscode.event/1
(GET /api/feed/v1/events, updatedSince, removals in deleted for 90
days) and a signed event.changed to linked siblings. Show events
from: each sibling's feed every 15 minutes and at once on its signed
event.changed; read-only copies of only that sibling's events, one
bad event skipped, the last good copy kept. Admin: Linked products.
church.changed from Accounts refreshes the profile at once. Plan:
the video hero, more blocks and more pages move to website@1.1.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:37:42 +02:00
joshua 193a338ed2 Merge branch 'feat/website-image-sizes' 2026-11-25 14:04:44 +02:00
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
joshua 6be1a2782d Merge branch 'feat/website-people-messages-events' 2026-11-25 13:05:35 +02:00
joshuaandClaude Opus 5.5 37a1f6acf1 feat(website): people and roles, messages with the YouTube feed, simple events
People: Owners and Admins add someone by email (people.ensure through
Accounts), change roles, remove access; only Owners touch Owners,
nobody changes themselves, a lower role ends sessions at once.
Messages: from a YouTube channel or playlist every hour (public feed,
no key) or by hand with a YouTube or Spotify link; own publish, hide.
Simple events: own publish, cancel, remove. Tests and e2e with axe on
the new screens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:05:33 +02:00
joshua 9b8f10e3c8 Merge branch 'feat/website-admin' 2026-11-25 12:30:29 +02:00
34 changed files with 1738 additions and 55 deletions
+24
View File
@@ -55,6 +55,30 @@
editing, Publish); a **shared preview link** works signed out for 7 days or until revoked, and
can't change anything. Publish refreshes the public pages at once (`WEBSITE_CONTENT_CACHE_SECONDS`,
30 by default, is how long they're kept otherwise).
- **People** (§10): Owners and Admins add someone by email (their account comes from the church's
Accounts through `people.ensure`, with a "choose your password" email when it's new), change
roles and remove access. Only an Owner touches Owners; nobody changes themselves; a lower role or
removal ends that person's sessions at once. A Ministry leader is tied to their ministry.
- **Messages** (§7): from the church's YouTube channel or playlist automatically (YouTube's public
feed, every hour, no API key; each new video goes live by itself), or by hand with a YouTube or
Spotify link; speaker, series, passage and notes; publish, unpublish, hide. A video is never
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 (`<picture>`, `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 event feed** (§8, roadmap §4), both ways, as Cross Events 2.4: **Publish my events** serves
the Website's published simple events as `crosscode.event/1` (`GET /api/feed/v1/events`,
`?updatedSince=`; unpublished and removed ones in `deleted` for 90 days) and tells linked siblings
with a signed `event.changed`; **Show events from** fetches each linked sibling's feed every 15
minutes and at once on its signed `event.changed`, keeping read-only copies that link back to the
origin (for registering), only of events that really come from that sibling, one bad event
skipped, and the last good copy kept when a fetch fails. Admin → **Linked products**: Connect,
Disconnect, Show events from, Publish my events, Check now. Accounts' signed `church.changed` now
fetches the church profile again at once.
- 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.
+2 -2
View File
@@ -9,8 +9,8 @@ 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. Still to come: managing who has which role, messages and events in the admin (YouTube feed),
responsive image sizes, the event feed, the Hub's "Get more storage", Lighthouse and the VM test. Not released;
church, people and roles, messages (with the YouTube feed), simple events and the event feed with
Cross Events. Still to come: the Hub's "Get more storage", Lighthouse and the VM test. Not released;
`website@1.0.0` is tagged when the plan is built.
**Signing in** (`backend/src/auth/`): the Website registers with the Hub (its install id is its
+1
View File
@@ -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": {
@@ -1,4 +1,4 @@
-- Church Website 1.0.0: the first schema (docs/WEBSITE-1.0-PLAN.md §1, §2, §4, §10).
-- Church Website 1.0.0: the first schema (docs/WEBSITE-1.0-PLAN.md §1, §2, §4, §8, §10).
-- CreateSchema
CREATE SCHEMA IF NOT EXISTS "public";
@@ -148,15 +148,25 @@ CREATE TABLE "SimpleEvent" (
-- CreateTable
CREATE TABLE "ImportedEvent" (
"id" TEXT NOT NULL,
"linkId" TEXT NOT NULL,
"originProduct" TEXT NOT NULL,
"originId" TEXT NOT NULL,
"startsAt" TIMESTAMP(3) NOT NULL,
"endsAt" TIMESTAMP(3) NOT NULL,
"data" JSONB NOT NULL,
"syncedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "ImportedEvent_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "FeedRemoval" (
"eventId" TEXT NOT NULL,
"removedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "FeedRemoval_pkey" PRIMARY KEY ("eventId")
);
-- CreateTable
CREATE TABLE "MediaAsset" (
"id" TEXT NOT NULL,
@@ -234,6 +244,9 @@ CREATE TABLE "ProductLink" (
"secret" TEXT NOT NULL,
"connectedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"connectedById" TEXT,
"showEvents" BOOLEAN NOT NULL DEFAULT true,
"lastSyncAt" TIMESTAMP(3),
"lastGoodAt" TIMESTAMP(3),
"lastSyncError" TEXT,
"updatedAt" TIMESTAMP(3) NOT NULL,
@@ -305,6 +318,9 @@ CREATE INDEX "SimpleEvent_startsAt_idx" ON "SimpleEvent"("startsAt");
-- CreateIndex
CREATE INDEX "ImportedEvent_startsAt_idx" ON "ImportedEvent"("startsAt");
-- CreateIndex
CREATE INDEX "ImportedEvent_linkId_idx" ON "ImportedEvent"("linkId");
-- CreateIndex
CREATE UNIQUE INDEX "ImportedEvent_originProduct_originId_key" ON "ImportedEvent"("originProduct", "originId");
@@ -332,5 +348,8 @@ ALTER TABLE "Section" ADD CONSTRAINT "Section_pageId_fkey" FOREIGN KEY ("pageId"
-- AddForeignKey
ALTER TABLE "Message" ADD CONSTRAINT "Message_seriesId_fkey" FOREIGN KEY ("seriesId") REFERENCES "MessageSeries"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ImportedEvent" ADD CONSTRAINT "ImportedEvent_linkId_fkey" FOREIGN KEY ("linkId") REFERENCES "ProductLink"("installId") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "WebsiteUser" ADD CONSTRAINT "WebsiteUser_ministryId_fkey" FOREIGN KEY ("ministryId") REFERENCES "Ministry"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+21 -3
View File
@@ -179,17 +179,29 @@ model SimpleEvent {
@@index([startsAt])
}
/// A read-only copy of a sibling's event from the feed (crosscode.event/1, ROADMAP-v3 §4).
/// A read-only copy of a sibling's event from the feed (crosscode.event/1, ROADMAP-v3 §4). It goes
/// with its link (a disconnect, or "Show events" switched off).
model ImportedEvent {
id String @id @default(uuid())
id String @id @default(uuid())
linkId String
link ProductLink @relation(fields: [linkId], references: [installId], onDelete: Cascade)
originProduct String
originId String
startsAt DateTime
endsAt DateTime
data Json
syncedAt DateTime @default(now())
syncedAt DateTime @default(now())
@@unique([originProduct, originId])
@@index([startsAt])
@@index([linkId])
}
/// A simple event that left the feed (unpublished or removed), listed in `deleted` for 90 days so
/// siblings drop their copy (ROADMAP-v3 §4).
model FeedRemoval {
eventId String @id
removedAt DateTime @default(now())
}
/// An upload: counted towards storage (§10) until neither the working copy nor the last 10
@@ -270,8 +282,14 @@ model ProductLink {
secret String
connectedAt DateTime @default(now())
connectedById String?
/// Show this sibling's events here (the event feed, §8). Accounts has none.
showEvents Boolean @default(true)
lastSyncAt DateTime?
/// The `generatedAt` of the last feed taken: the next fetch asks for what changed since.
lastGoodAt DateTime?
lastSyncError String?
updatedAt DateTime @updatedAt
imported ImportedEvent[]
}
/// Nonces of link messages seen in the last hour (replays are refused).
@@ -0,0 +1,171 @@
/**
* Messages and simple events in the admin (WEBSITE-1.0-PLAN §7, §8). They're things that happen
* rather than the site's design, so each has its own Publish (decision 9) and doesn't wait for the
* site's. Registrations and payments are only Cross Events' (roadmap decision 4): a simple event has
* at most a link.
*/
import { z } from 'zod';
import type { Ctx } from '../context.js';
import { ApiError } from '../http.js';
import { audit } from '../lib/audit.js';
import { youtubeId, spotifyEmbed } from '../site/content.js';
import { mediaUrl } from '../site/snapshot.js';
import { getSource, setSource, syncYoutube, uniqueSlug } from '../site/youtube.js';
import { markRemoved, notifyLinks } from '../feed/feed.js';
type Who = { id: string; role: string };
function check<T>(schema: z.ZodType<T>, body: unknown): T {
const r = schema.safeParse(body);
if (!r.success) {
const fields: Record<string, string> = {};
for (const i of r.error.issues) fields[i.path.join('.') || '_'] ??= i.message;
throw new ApiError(400, 'VALIDATION', 'Some fields need another look.', fields);
}
return r.data;
}
const optional = (max: number) => z.string().trim().max(max).nullable().default(null).transform((v) => v || null);
// ─── Messages ──────────────────────────────────────────────────────────────────
const messageSchema = z.object({
title: z.string().trim().min(1).max(500),
date: z.iso.date().or(z.iso.datetime()),
mediaUrl: z.string().trim().max(500).refine((u) => !!youtubeId(u) || !!spotifyEmbed(u), 'A YouTube video or Spotify episode link'),
speaker: optional(300),
passage: optional(300),
notes: optional(8000),
series: optional(300),
hidden: z.boolean().default(false),
});
async function seriesId(ctx: Ctx, title: string | null) {
if (!title) return null;
const found = await ctx.db.messageSeries.findFirst({ where: { title } });
if (found) return found.id;
const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'series';
return (await ctx.db.messageSeries.create({ data: { title, slug: `${slug}-${Date.now().toString(36)}` } })).id;
}
export async function listMessages(ctx: Ctx) {
const [rows, source, lastSync, lastError] = await Promise.all([
ctx.db.message.findMany({ orderBy: { date: 'desc' }, take: 200, include: { series: true } }),
getSource(ctx), ctx.settings.get('youtube_last_sync_at'), ctx.settings.get('youtube_last_error'),
]);
return {
youtube: { source, lastSync, lastError },
items: rows.map((m) => ({
id: m.id, title: m.title, date: m.date.toISOString(), mediaUrl: m.mediaUrl, source: m.source, speaker: m.speaker, passage: m.passage, notes: m.notes,
series: m.series?.title ?? null, hidden: m.hidden, published: m.publishedAt !== null, thumbnail: m.thumbnailUrl,
})),
};
}
export async function saveMessage(ctx: Ctx, id: string | null, body: unknown, by: Who) {
const m = check(messageSchema, body);
const yt = youtubeId(m.mediaUrl);
const externalId = yt ?? /\/episode\/([A-Za-z0-9]+)/.exec(m.mediaUrl)?.[1] ?? null;
if (externalId) {
const dup = await ctx.db.message.findFirst({ where: { externalId, ...(id ? { NOT: { id } } : {}) } });
if (dup) throw new ApiError(409, 'DUPLICATE', `That video is already a message (“${dup.title}”).`, { mediaUrl: 'Already a message' });
}
const data = {
title: m.title, date: new Date(m.date), mediaUrl: m.mediaUrl, externalId, speaker: m.speaker, passage: m.passage, notes: m.notes,
seriesId: await seriesId(ctx, m.series), hidden: m.hidden, updatedBy: by.id,
};
if (id) {
const row = await ctx.db.message.findUnique({ where: { id } });
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That message doesn\'t exist.');
// A video from the feed keeps its address and source; its details can be filled in.
const keep = row.source === 'youtube_feed' ? { mediaUrl: row.mediaUrl, externalId: row.externalId } : {};
return ctx.db.message.update({ where: { id }, data: { ...data, ...keep } });
}
return ctx.db.message.create({
data: { ...data, slug: await uniqueSlug(ctx, m.title, 'message'), source: yt ? 'youtube' : 'spotify', thumbnailUrl: yt ? `https://i.ytimg.com/vi/${yt}/hqdefault.jpg` : null },
});
}
/** A message's own Publish (decision 9): live, or back off the site. */
export async function publishMessage(ctx: Ctx, id: string, live: boolean, by: Who) {
const row = await ctx.db.message.findUnique({ where: { id } });
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That message doesn\'t exist.');
await ctx.db.message.update({ where: { id }, data: { publishedAt: live ? ctx.now() : null, updatedBy: by.id } });
await audit(ctx, { actorId: by.id, actorRole: by.role, action: live ? 'message_published' : 'message_unpublished', targetType: 'message', targetId: id, metadata: { title: row.title } });
}
export async function deleteMessage(ctx: Ctx, id: string, by: Who) {
const row = await ctx.db.message.findUnique({ where: { id } });
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That message doesn\'t exist.');
// One from the feed would just come back at the next sync: hide it instead.
if (row.source === 'youtube_feed') throw new ApiError(400, 'FROM_FEED', 'That one comes from YouTube and would come back: hide it instead.');
await ctx.db.message.delete({ where: { id } });
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'message_deleted', targetType: 'message', targetId: id, metadata: { title: row.title } });
}
export async function saveYoutube(ctx: Ctx, body: unknown, by: Who) {
const { youtube } = check(z.object({ youtube: z.string().max(300).nullable() }), body);
const source = await setSource(ctx, youtube);
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'youtube_source_set', targetType: 'setting', targetId: 'youtube_source', metadata: { source } });
return { source, sync: source ? await syncYoutube(ctx) : null };
}
// ─── Simple events ─────────────────────────────────────────────────────────────
const eventSchema = z.object({
title: z.string().trim().min(1).max(300),
startsAt: z.iso.datetime({ offset: true }),
endsAt: z.iso.datetime({ offset: true }).nullable().default(null),
allDay: z.boolean().default(false),
location: optional(500),
description: optional(8000),
imageId: z.string().uuid().nullable().default(null),
link: z.string().trim().max(500).nullable().default(null).refine((v) => !v || /^https:\/\//.test(v), 'An https:// address').transform((v) => v || null),
}).refine((e) => !e.endsAt || new Date(e.endsAt) >= new Date(e.startsAt), { message: 'It ends before it starts', path: ['endsAt'] });
export async function listEvents(ctx: Ctx) {
const [rows, media] = await Promise.all([ctx.db.simpleEvent.findMany({ orderBy: { startsAt: 'desc' }, take: 300 }), ctx.db.mediaAsset.findMany()]);
const urls = new Map(media.map((m) => [m.id, mediaUrl(m.filename)]));
return rows.map((e) => ({
id: e.id, slug: e.slug, title: e.title, startsAt: e.startsAt.toISOString(), endsAt: e.endsAt?.toISOString() ?? null, allDay: e.allDay, location: e.location,
description: e.description, imageId: e.imageId, image: e.imageId ? urls.get(e.imageId) ?? null : null, link: e.link, cancelled: e.cancelled, published: e.publishedAt !== null,
}));
}
export async function saveEvent(ctx: Ctx, id: string | null, body: unknown, by: Who) {
const e = check(eventSchema, body);
const data = { title: e.title, startsAt: new Date(e.startsAt), endsAt: e.endsAt ? new Date(e.endsAt) : null, allDay: e.allDay, location: e.location, description: e.description, imageId: e.imageId, link: e.link, timezone: ctx.config.timezone, updatedBy: by.id };
if (id) {
if (!(await ctx.db.simpleEvent.findUnique({ where: { id } }))) throw new ApiError(404, 'NOT_FOUND', 'That event doesn\'t exist.');
const saved = await ctx.db.simpleEvent.update({ where: { id }, data });
// A live event changed: the church's other sites fetch it now.
if (saved.publishedAt) void notifyLinks(ctx, [id]).catch(() => {});
return saved;
}
return ctx.db.simpleEvent.create({ data: { ...data, slug: await uniqueSlug(ctx, e.title, 'simpleEvent') } });
}
export async function setEventState(ctx: Ctx, id: string, change: { published?: boolean; cancelled?: boolean }, by: Who) {
const row = await ctx.db.simpleEvent.findUnique({ where: { id } });
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That event doesn\'t exist.');
await ctx.db.simpleEvent.update({ where: { id }, data: {
...(change.published !== undefined ? { publishedAt: change.published ? ctx.now() : null } : {}),
...(change.cancelled !== undefined ? { cancelled: change.cancelled } : {}),
updatedBy: by.id,
} });
// In or out of the feed (ROADMAP-v3 §4: an unpublished event goes in `deleted`), and siblings told.
if (change.published !== undefined) await markRemoved(ctx, id, !change.published);
if (row.publishedAt || change.published) void notifyLinks(ctx, [id]).catch(() => {});
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'event_changed', targetType: 'simple_event', targetId: id, metadata: { title: row.title, ...change } });
}
export async function deleteEvent(ctx: Ctx, id: string, by: Who) {
const row = await ctx.db.simpleEvent.findUnique({ where: { id } });
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That event doesn\'t exist.');
await ctx.db.simpleEvent.delete({ where: { id } });
if (row.publishedAt) {
await markRemoved(ctx, id, true);
void notifyLinks(ctx, [id]).catch(() => {});
}
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'event_deleted', targetType: 'simple_event', targetId: id, metadata: { title: row.title } });
}
+62 -7
View File
@@ -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` (`<base>.<ext>`, `<base>-<w>.webp`, `<base>-<w>.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 };
}
+105
View File
@@ -0,0 +1,105 @@
/**
* Who can use the admin, and as what (WEBSITE-1.0-PLAN §10). Roles are the Website's own, keyed by
* the account's `sub` in the church's Accounts: adding someone by email asks Accounts for their
* account (`people.ensure`), which makes one, with a "choose your password" email, if they have none.
*
* Owner everything, including who is Owner
* Admin everything but Owners (can't add, change or remove one, or make one)
* Others can't manage people
*
* Nobody changes or removes themselves, so a site is never left without an Owner by accident.
*/
import { z } from 'zod';
import type { Ctx } from '../context.js';
import type { WebsiteRole } from '../generated/prisma/client.js';
import { accounts } from '../auth/accounts.js';
import { atLeast, ROLES } from '../auth/sessions.js';
import { ApiError } from '../http.js';
import { audit } from '../lib/audit.js';
type Who = { id: string; role: WebsiteRole };
const roleSchema = z.enum(ROLES as [WebsiteRole, ...WebsiteRole[]]);
const addSchema = z.object({
name: z.string().trim().min(1).max(200),
email: z.email().trim().toLowerCase().max(254),
role: roleSchema,
ministryId: z.string().uuid().nullable().default(null),
});
const changeSchema = z.object({ role: roleSchema, ministryId: z.string().uuid().nullable().default(null) });
function check<T>(schema: z.ZodType<T>, body: unknown): T {
const r = schema.safeParse(body);
if (!r.success) {
const fields: Record<string, string> = {};
for (const i of r.error.issues) fields[i.path.join('.') || '_'] ??= i.message;
throw new ApiError(400, 'VALIDATION', 'Some fields need another look.', fields);
}
return r.data;
}
/** May `by` give (or take) `role`? */
function mayManage(by: Who, role: WebsiteRole) {
if (!atLeast(by.role, 'admin')) throw new ApiError(403, 'FORBIDDEN', 'Only an Owner or Admin can manage who has access.');
if (role === 'owner' && by.role !== 'owner') throw new ApiError(403, 'OWNERS_ONLY', 'Only an Owner can add, change or remove an Owner.');
}
async function ministryFor(ctx: Ctx, role: WebsiteRole, ministryId: string | null) {
if (role !== 'ministry_leader') return null;
if (!ministryId) throw new ApiError(400, 'VALIDATION', 'Choose the ministry they lead.', { ministryId: 'Choose their ministry' });
const m = await ctx.db.ministry.findUnique({ where: { id: ministryId } });
if (!m || m.archivedAt) throw new ApiError(400, 'VALIDATION', 'That ministry doesn\'t exist.', { ministryId: 'Not a ministry' });
return ministryId;
}
export async function listPeople(ctx: Ctx) {
const [users, ministries] = await Promise.all([ctx.db.websiteUser.findMany({ orderBy: { name: 'asc' } }), ctx.db.ministry.findMany()]);
const names = new Map(ministries.map((m) => [m.id, m.name]));
return users.map((u) => ({
id: u.id, name: u.name, email: u.email, role: u.role, ministryId: u.ministryId, ministry: u.ministryId ? names.get(u.ministryId) ?? null : null,
lastSignInAt: u.lastSignInAt?.toISOString() ?? null,
}));
}
export async function addPerson(ctx: Ctx, body: unknown, by: Who) {
const p = check(addSchema, body);
mayManage(by, p.role);
const ministryId = await ministryFor(ctx, p.role, p.ministryId);
const reply = await (await accounts(ctx)).request<{ sub: string; created: boolean; emailSent?: boolean }>({
type: 'people.ensure', actor: by.id, name: p.name, email: p.email, phone: null, returnUrl: `${ctx.config.publicUrl}/admin`,
});
if (await ctx.db.websiteUser.findUnique({ where: { id: reply.sub } })) throw new ApiError(409, 'ALREADY_ADDED', 'They already have access. Change their role instead.');
const user = await ctx.db.websiteUser.create({ data: { id: reply.sub, name: p.name, email: p.email, role: p.role, ministryId } });
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'website_user_added', targetType: 'website_user', targetId: user.id, metadata: { role: p.role, newAccount: reply.created } });
return { id: user.id, newAccount: reply.created, emailSent: reply.emailSent ?? null };
}
async function target(ctx: Ctx, id: string, by: Who) {
if (id === by.id) throw new ApiError(400, 'SELF', 'You can\'t change or remove your own access. Ask another Owner or Admin.');
const user = await ctx.db.websiteUser.findUnique({ where: { id } });
if (!user) throw new ApiError(404, 'NOT_FOUND', 'That person doesn\'t have access.');
mayManage(by, user.role);
return user;
}
export async function changePerson(ctx: Ctx, id: string, body: unknown, by: Who) {
const user = await target(ctx, id, by);
const c = check(changeSchema, body);
mayManage(by, c.role);
const ministryId = await ministryFor(ctx, c.role, c.ministryId);
await ctx.db.websiteUser.update({ where: { id }, data: { role: c.role, ministryId } });
// A lower role takes effect at once: their sessions end, and they sign in again.
if (ROLES.indexOf(c.role) < ROLES.indexOf(user.role)) await ctx.db.session.deleteMany({ where: { userId: id } });
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'website_user_role_changed', targetType: 'website_user', targetId: id, metadata: { from: user.role, to: c.role } });
return { ok: true };
}
export async function removePerson(ctx: Ctx, id: string, by: Who) {
const user = await target(ctx, id, by);
await ctx.db.session.deleteMany({ where: { userId: id } });
await ctx.db.websiteUser.delete({ where: { id } });
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'website_user_removed', targetType: 'website_user', targetId: id, metadata: { role: user.role } });
return { ok: true };
}
+78
View File
@@ -14,6 +14,12 @@ import { mediaUrl, publish } from '../site/snapshot.js';
import { TEMPLATE_HEADERS, TEMPLATE_HOME_ORDER, TEMPLATE_VARIANTS } from '../site/variants.js';
import { changes, discard, restore } from '../site/workingCopy.js';
import * as content from './content.js';
import * as people from './people.js';
import * as happenings from './happenings.js';
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 { MAX_UPLOAD_BYTES, storage, upload } from './media.js';
import { createPreviewLink, listPreviewLinks, revokePreviewLink } from './previewLinks.js';
@@ -97,6 +103,78 @@ export function adminRouter(ctx: Ctx) {
return { id: m.id, alt: m.alt };
}));
// ─── Messages and simple events: each publishes on its own (decision 9) ───
r.get('/messages', handle(() => happenings.listMessages(ctx)));
r.post('/messages', editor, json, handle((req) => happenings.saveMessage(ctx, null, req.body, who(req))));
r.put('/messages/:id', editor, json, handle((req) => happenings.saveMessage(ctx, param(req, 'id'), req.body, who(req))));
r.post('/messages/:id/publish', editor, json, handle(async (req) => { await happenings.publishMessage(ctx, param(req, 'id'), req.body?.live !== false, who(req)); return { ok: true }; }));
r.delete('/messages/:id', editor, handle(async (req) => { await happenings.deleteMessage(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
r.put('/messages-youtube', editor, json, handle((req) => happenings.saveYoutube(ctx, req.body, who(req))));
r.post('/messages-youtube/sync', editor, handle(() => syncYoutube(ctx)));
r.get('/events', handle(() => happenings.listEvents(ctx)));
r.post('/events', editor, json, handle((req) => happenings.saveEvent(ctx, null, req.body, who(req))));
r.put('/events/:id', editor, json, handle((req) => happenings.saveEvent(ctx, param(req, 'id'), req.body, who(req))));
r.post('/events/:id/state', editor, json, handle(async (req) => {
const b = req.body ?? {};
await happenings.setEventState(ctx, param(req, 'id'), { ...(typeof b.published === 'boolean' ? { published: b.published } : {}), ...(typeof b.cancelled === 'boolean' ? { cancelled: b.cancelled } : {}) }, who(req));
return { ok: true };
}));
r.delete('/events/:id', editor, handle(async (req) => { await happenings.deleteEvent(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
// ─── Linked products and the event feed (§8, §9) ───
r.get('/links', handle(async () => {
const [listed, links, publishing] = await Promise.all([linkedProducts(ctx), ctx.db.productLink.findMany(), publishOn(ctx)]);
const counts = new Map<string, number>();
for (const l of links) counts.set(l.installId, await ctx.db.importedEvent.count({ where: { linkId: l.installId } }));
const ids = new Set([...listed.map((l) => l.installId), ...links.map((l) => l.installId)]);
return {
publishMyEvents: publishing,
products: [...ids].map((id) => {
const l = listed.find((x) => x.installId === id);
const link = links.find((x) => x.installId === id);
return {
installId: id, product: link?.product ?? l!.product, url: link?.url ?? l!.url, connected: !!link, listed: !!l,
showEvents: link?.showEvents ?? null, events: counts.get(id) ?? 0,
lastSyncAt: link?.lastSyncAt?.toISOString() ?? null, lastSyncError: link?.lastSyncError ?? null,
};
}),
};
}));
const linkAdmin = requireRole(ctx, 'admin');
r.post('/links/:id/connect', linkAdmin, handle(async (req) => {
const link = await connectTo(ctx, param(req, 'id'), who(req), req);
if (link.product !== 'accounts') await syncLink(ctx, link);
return { ok: true };
}));
r.delete('/links/:id', linkAdmin, handle(async (req) => {
const link = await ctx.db.productLink.findUnique({ where: { installId: param(req, 'id') } });
if (link?.product === 'accounts') throw new ApiError(400, 'ACCOUNTS', 'The Website signs in through Accounts, so that link stays.');
return disconnectFrom(ctx, param(req, 'id'), who(req), req);
}));
r.put('/links/:id', editor, json, handle(async (req) => {
const id = param(req, 'id');
const link = await ctx.db.productLink.findUnique({ where: { installId: id } });
if (!link) throw new ApiError(404, 'NOT_LINKED', "That product isn't connected.");
const updated = await ctx.db.productLink.update({ where: { installId: id }, data: { showEvents: !!req.body?.showEvents } });
return syncLink(ctx, updated);
}));
r.post('/links/:id/sync', editor, handle(async (req) => {
const link = await ctx.db.productLink.findUnique({ where: { installId: param(req, 'id') } });
if (!link) throw new ApiError(404, 'NOT_LINKED', "That product isn't connected.");
return syncLink(ctx, link);
}));
r.put('/feed', editor, json, handle(async (req) => {
await ctx.settings.set('feed_publish', req.body?.publish === false ? 'false' : 'true');
return { publishMyEvents: await publishOn(ctx) };
}));
// ─── People: who can use the admin, as what (Owner and Admin) ───
const admin = requireRole(ctx, 'admin');
r.get('/people', admin, handle(() => people.listPeople(ctx)));
r.post('/people', admin, json, handle((req) => people.addPerson(ctx, req.body, who(req))));
r.put('/people/:id', admin, json, handle((req) => people.changePerson(ctx, param(req, 'id'), req.body, who(req))));
r.delete('/people/:id', admin, handle((req) => people.removePerson(ctx, param(req, 'id'), who(req))));
// ─── Publish, discard, restore, versions, shared previews (§4) ───
r.get('/changes', handle(() => changes(ctx)));
r.post('/publish', editor, json, handle(async (req) => {
+173
View File
@@ -0,0 +1,173 @@
/**
* The event feed (WEBSITE-1.0-PLAN §8, ROADMAP-v3 §4), both ways, as Cross Events 2.4:
*
* - **Publish my events** (AppSetting `feed_publish`, on by default): the Website's published simple
* events as `crosscode.event/1` at `GET /api/feed/v1/events?updatedSince=`, with removed ones in
* `deleted` for 90 days. Only events it made itself, never ones it imported (no loops).
* - **Show events from** each linked sibling (`ProductLink.showEvents`): fetched every 15 minutes and
* at once on its signed `event.changed`; read-only copies, the last good copy kept when a fetch
* fails, one bad event skipped without holding up the rest, and only events that really come
* from that sibling.
* - Linked siblings are told (`event.changed`) when one of the Website's events changes.
*/
import { EVENT_FEED_SCHEMA, EVENT_SCHEMA, eventSchema, FEED_PATHS, parseEventFeed, type CrosscodeEvent, type EventChanged, type EventFeed } from '@crosscode/contracts';
import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing';
import type { Ctx } from '../context.js';
import { callSibling, siblingUrl } from '../links/http.js';
import { imageOf } from '../site/snapshot.js';
const DAY = 864e5;
export const ENDED_KEEP_DAYS = 30;
export const REMOVED_KEEP_DAYS = 90;
/** Fetch from a little before the last good fetch, so an event saved during it isn't missed. */
const OVERLAP_MS = 5 * 60 * 1000;
export const publishOn = (ctx: Ctx) => ctx.settings.bool('feed_publish', true);
type SimpleRow = {
id: string; slug: string; title: string; startsAt: Date; endsAt: Date | null; allDay: boolean; timezone: string; location: string | null;
description: string | null; imageId: string | null; link: string | null; cancelled: boolean; updatedAt: Date;
};
/** One of the Website's simple events as `crosscode.event/1`. */
export function toCrosscodeEvent(ctx: Ctx, e: SimpleRow, installId: string, imageUrl: string | null): CrosscodeEvent {
const url = `${ctx.config.publicUrl}/events/${e.slug}`;
const ends = e.endsAt ?? new Date(e.startsAt.getTime() + (e.allDay ? DAY - 60e3 : 2 * 3600e3));
return {
schema: EVENT_SCHEMA,
id: e.id,
origin: { product: 'website', installId, url },
status: e.cancelled ? 'cancelled' : 'published',
updatedAt: e.updatedAt.toISOString(),
title: e.title.slice(0, 200),
summary: e.description ? e.description.replace(/\s+/g, ' ').slice(0, 300) : null,
description: e.description,
imageUrl,
timezone: e.timezone,
startsAt: e.startsAt.toISOString(),
endsAt: ends.toISOString(),
allDay: e.allDay,
sessions: [],
location: e.location ? { name: e.location.slice(0, 200), address: null, onlineUrl: null } : null,
campus: null,
series: null,
tags: [],
// Only Cross Events takes registrations: a link, or nothing (roadmap decision 4).
registration: e.link ? { mode: 'external', url: e.link, status: 'open', opensAt: null, closesAt: null, priceFrom: null } : { mode: 'none', url: null, status: 'open', opensAt: null, closesAt: null, priceFrom: null },
} as CrosscodeEvent;
}
/** `GET /api/feed/v1/events`: what changed since `since` (everything when null). */
export async function buildFeed(ctx: Ctx, since: Date | null): Promise<EventFeed> {
const now = ctx.now();
const installId = (await ctx.settings.get('hub_install_id'))!;
const [rows, media, removals] = await Promise.all([
ctx.db.simpleEvent.findMany({ where: { publishedAt: { not: null }, startsAt: { gte: new Date(now.getTime() - (ENDED_KEEP_DAYS + 30) * DAY) } }, orderBy: { startsAt: 'asc' } }),
ctx.db.mediaAsset.findMany(),
ctx.db.feedRemoval.findMany({ where: { removedAt: { gte: new Date(now.getTime() - REMOVED_KEEP_DAYS * DAY), ...(since ? { gt: since } : {}) } } }),
]);
const byId = new Map(media.map((m) => [m.id, m]));
const events: CrosscodeEvent[] = [];
for (const row of rows) {
const ends = row.endsAt ?? row.startsAt;
if (ends.getTime() < now.getTime() - ENDED_KEEP_DAYS * DAY) continue;
if (since && row.updatedAt <= since) continue;
const m = row.imageId ? byId.get(row.imageId) : null;
const e = toCrosscodeEvent(ctx, row, installId, m ? `${ctx.config.publicUrl}${imageOf(m).url}` : null);
// Never publish something the contract refuses.
if (eventSchema.safeParse(e).success) events.push(e);
}
return { schema: EVENT_FEED_SCHEMA, generatedAt: now.toISOString(), events, deleted: removals.map((r) => ({ id: r.eventId, deletedAt: r.removedAt.toISOString() })) };
}
/** A simple event left the feed: siblings drop their copy. Back on it (published again): no longer removed. */
export async function markRemoved(ctx: Ctx, eventId: string, removed: boolean) {
if (removed) await ctx.db.feedRemoval.upsert({ where: { eventId }, create: { eventId, removedAt: ctx.now() }, update: { removedAt: ctx.now() } });
else await ctx.db.feedRemoval.deleteMany({ where: { eventId } });
}
/** Tells every linked sibling (not Accounts) that these events changed. One try; their poll catches up. */
export async function notifyLinks(ctx: Ctx, eventIds: string[]): Promise<{ told: number; failed: number }> {
if (!eventIds.length || !(await publishOn(ctx))) return { told: 0, failed: 0 };
const senderId = await ctx.settings.get('hub_install_id');
if (!senderId) return { told: 0, failed: 0 };
const links = await ctx.db.productLink.findMany({ where: { product: { not: 'accounts' } } });
const body: EventChanged = { schema: EVENT_FEED_SCHEMA, type: 'event.changed', occurredAt: ctx.now().toISOString(), eventIds: eventIds.slice(0, 100) };
const raw = JSON.stringify(body);
let told = 0;
let failed = 0;
await Promise.all(links.map(async (link) => {
try {
const headers = signedHeaders(LINK_HEADERS, { senderId, secret: ctx.secrets.decrypt(link.secret), rawBody: raw });
await callSibling(await siblingUrl(ctx, link.url, FEED_PATHS.changed), { method: 'POST', body: raw, headers });
told++;
} catch (e) {
failed++;
console.warn(`[feed] event.changed to ${link.url} failed (its poll will catch up):`, (e as Error).message);
}
}));
return { told, failed };
}
type LinkRow = { installId: string; product: string; url: string; showEvents: boolean; lastGoodAt: Date | null };
export type SyncResult = { installId: string; ok: boolean; imported?: number; deleted?: number; rejected?: number; error?: string };
/** Fetches one sibling's feed into read-only copies. */
export async function syncLink(ctx: Ctx, link: LinkRow): Promise<SyncResult> {
if (link.product === 'accounts') return { installId: link.installId, ok: true, imported: 0 };
if (!link.showEvents) {
const gone = (await ctx.db.importedEvent.deleteMany({ where: { linkId: link.installId } })).count;
return { installId: link.installId, ok: true, imported: 0, deleted: gone };
}
const now = ctx.now();
const since = link.lastGoodAt ? new Date(link.lastGoodAt.getTime() - OVERLAP_MS) : null;
try {
const url = await siblingUrl(ctx, link.url, FEED_PATHS.events);
if (since) url.searchParams.set('updatedSince', since.toISOString());
const parsed = parseEventFeed(await callSibling(url, { method: 'GET' }));
if (!parsed.ok) throw new Error(`The feed isn't a crosscode.event-feed/1 (${parsed.error.issues.slice(0, 2).map((i) => `${i.path.join('.')} ${i.message}`).join('; ')})`);
const { feed, rejected } = parsed;
for (const r of rejected) console.warn(`[feed] skipped an event from ${link.url} (${r.id ?? `#${r.index}`})`);
// Only events that really come from this sibling: one product can't speak for another.
const theirs = feed.events.filter((e) => e.origin.installId === link.installId && e.origin.product === link.product);
for (const e of theirs) {
const data = { linkId: link.installId, startsAt: new Date(e.startsAt), endsAt: new Date(e.endsAt), data: e as never, syncedAt: now };
const existing = await ctx.db.importedEvent.findFirst({ where: { originProduct: e.origin.product, originId: e.id } });
if (existing) await ctx.db.importedEvent.update({ where: { id: existing.id }, data });
else await ctx.db.importedEvent.create({ data: { ...data, originProduct: e.origin.product, originId: e.id } });
}
let deleted = 0;
for (const d of feed.deleted) deleted += (await ctx.db.importedEvent.deleteMany({ where: { linkId: link.installId, originId: d.id } })).count;
// A full fetch is the whole list: anything not in it is gone.
if (!since) deleted += (await ctx.db.importedEvent.deleteMany({ where: { linkId: link.installId, originId: { notIn: theirs.map((e) => e.id) } } })).count;
await ctx.db.productLink.update({
where: { installId: link.installId },
data: { lastSyncAt: now, lastGoodAt: new Date(feed.generatedAt), lastSyncError: rejected.length ? `${rejected.length} event(s) skipped: they don't fit crosscode.event/1` : null },
});
return { installId: link.installId, ok: true, imported: theirs.length, deleted, rejected: rejected.length };
} catch (e) {
const error = String((e as Error)?.message || e).slice(0, 500);
await ctx.db.productLink.update({ where: { installId: link.installId }, data: { lastSyncAt: now, lastSyncError: error } }).catch(() => {});
return { installId: link.installId, ok: false, error };
}
}
/** Every linked sibling, one after another; one failing never stops the rest. */
export async function syncAll(ctx: Ctx) {
const links = await ctx.db.productLink.findMany({ where: { product: { not: 'accounts' } } });
let failed = 0;
for (const link of links) if (!(await syncLink(ctx, link)).ok) failed++;
return { links: links.length, failed };
}
/** Every 15 minutes (ROADMAP-v3 §4: "consumers also poll every 15 minutes as a fallback"). */
export function startFeedSync(ctx: Ctx): () => void {
if (!ctx.config.jobsEnabled) return () => {};
const run = () => syncAll(ctx).catch((e) => console.warn('[feed]', (e as Error).message));
const first = setTimeout(run, 20_000);
const timer = setInterval(run, 15 * 60 * 1000);
first.unref?.();
timer.unref?.();
return () => { clearTimeout(first); clearInterval(timer); };
}
+8 -2
View File
@@ -1,8 +1,8 @@
/**
* Starts the Church Website's backend: database, HTTP server, and (on a Hub install) registering
* with the Hub from HUB_LICENCE_KEY, then heartbeats, which also link the site to the church's
* Accounts once the Hub lists it. The other jobs (YouTube feed, storage count, sitemap, feed sync)
* come with their features (docs/WEBSITE-1.0-PLAN.md §1).
* Accounts once the Hub lists it, and the hourly YouTube feed (§7). The other jobs (storage emails,
* the event feed) come with their features (docs/WEBSITE-1.0-PLAN.md §1).
*/
import 'dotenv/config';
import { PrismaPg } from '@prisma/adapter-pg';
@@ -11,6 +11,8 @@ import { createApp } from './app.js';
import { createCtx } from './context.js';
import { connectFromEnv, heartbeat, startHeartbeats } from './hub/client.js';
import { loadConfig } from './lib/config.js';
import { startYoutubeSync } from './site/youtube.js';
import { startFeedSync } from './feed/feed.js';
async function main() {
const config = loadConfig();
@@ -21,6 +23,8 @@ async function main() {
const app = createApp(ctx);
const server = app.listen(config.port, () => console.log(`[website] Listening on ${config.port} (${config.publicUrl}).`));
const stopHeartbeats = startHeartbeats(ctx);
const stopYoutube = startYoutubeSync(ctx);
const stopFeed = startFeedSync(ctx);
connectFromEnv(ctx).then((r) => {
if (r.connected || r.reason === 'already') heartbeat(ctx).catch(() => {});
@@ -28,6 +32,8 @@ async function main() {
const stop = async () => {
stopHeartbeats();
stopYoutube();
stopFeed();
server.close();
await db.$disconnect();
process.exit(0);
+79 -5
View File
@@ -1,20 +1,30 @@
/**
* The link endpoints siblings call (`crosscode.link/1`): Accounts (or Events) connecting to and
* disconnecting from this site. Errors use the link protocol's `{ code, message }`.
* What the church's other products call (`crosscode.link/1` and friends), as Cross Events'
* cross-product routes. Errors use the link protocol's `{ code, message }`.
*
* POST /links/v1/connect, /disconnect a sibling connects or disconnects
* GET /feed/v1/events?updatedSince= the Website's events (crosscode.event-feed/1), public
* POST /feed/v1/changed a sibling's events changed: fetch them now (signed)
* POST /church/v1/changed Accounts: the church profile changed (signed)
*/
import express from 'express';
import { LINK_PATHS } from '@crosscode/contracts';
import { CHURCH_PATHS, churchChangedSchema, eventChangedSchema, FEED_PATHS, LINK_PATHS } from '@crosscode/contracts';
import { LINK_HEADERS, verify } from '@crosscode/contracts/signing';
import type { Ctx } from '../context.js';
import { churchChanged } from '../church/profile.js';
import { buildFeed, publishOn, syncLink } from '../feed/feed.js';
import { acceptConnect, acceptDisconnect, LinkError } from './connect.js';
export function linksRouter(ctx: Ctx) {
const r = express.Router();
const json = express.json({ limit: '32kb' });
const say = (res: express.Response, status: number, code: string, message: string) => res.status(status).json({ code, message });
const fail = (res: express.Response, e: unknown) => {
if (e instanceof LinkError) return res.status(e.status).json({ code: e.code, message: e.message });
if (e instanceof LinkError) return say(res, e.status, e.code, e.message);
console.error('[links]', e);
return res.status(500).json({ code: 'INTERNAL', message: 'Something went wrong.' });
return say(res, 500, 'INTERNAL', 'Something went wrong.');
};
r.post(LINK_PATHS.connect.replace(/^\/api/, ''), json, async (req, res) => {
try {
res.json(await acceptConnect(ctx, req.body, req));
@@ -30,5 +40,69 @@ export function linksRouter(ctx: Ctx) {
fail(res, e);
}
});
r.get(FEED_PATHS.events.replace(/^\/api/, ''), async (req, res) => {
try {
if (!(await publishOn(ctx))) return say(res, 404, 'FEED_OFF', 'This site doesn\'t publish its events.');
if (!(await ctx.settings.get('hub_install_id'))) return say(res, 503, 'FEED_UNAVAILABLE', 'This site isn\'t connected to the Hub yet, so it has no feed.');
const raw = typeof req.query.updatedSince === 'string' ? req.query.updatedSince : null;
const since = raw ? new Date(raw) : null;
if (raw && (!since || !Number.isFinite(since.getTime()))) return say(res, 400, 'INVALID_REQUEST', 'updatedSince must be an ISO 8601 date and time.');
res.set('Cache-Control', 'no-store');
return res.json(await buildFeed(ctx, since));
} catch (e) {
return fail(res, e);
}
});
/** A signed message from a linked sibling: its link, or the reason it's refused. */
async function signedBy(req: express.Request, res: express.Response, accountsOnly = false) {
const sender = String(req.get(LINK_HEADERS.sender) || '');
const link = sender ? await ctx.db.productLink.findUnique({ where: { installId: sender } }) : null;
if (!link || (accountsOnly && link.product !== 'accounts')) {
say(res, 404, 'NOT_LINKED', 'This site has no link with that install.');
return null;
}
const rawBody: Buffer = Buffer.isBuffer(req.body) ? req.body : Buffer.from('');
const check = verify({ secret: ctx.secrets.decrypt(link.secret), timestamp: req.get(LINK_HEADERS.timestamp), signature: req.get(LINK_HEADERS.signature), rawBody, now: ctx.now() });
if (!check.ok) {
say(res, 401, check.code, 'The signature doesn\'t match this link.');
return null;
}
let body: unknown;
try {
body = JSON.parse(rawBody.toString('utf8'));
} catch {
body = null;
}
return { link, body };
}
const raw = express.raw({ type: () => true, limit: '16kb' });
r.post(FEED_PATHS.changed.replace(/^\/api/, ''), raw, async (req, res) => {
try {
const got = await signedBy(req, res);
if (!got) return undefined;
if (!eventChangedSchema.safeParse(got.body).success) return say(res, 400, 'INVALID_REQUEST', 'That isn\'t an event.changed message.');
// Fetched after answering: the sibling doesn't wait for it.
if (got.link.showEvents) setImmediate(() => { syncLink(ctx, got.link).catch(() => {}); });
return res.status(202).json({ accepted: true, fetching: got.link.showEvents });
} catch (e) {
return fail(res, e);
}
});
r.post(CHURCH_PATHS.changed.replace(/^\/api/, ''), raw, async (req, res) => {
try {
const got = await signedBy(req, res, true);
if (!got) return undefined;
if (!churchChangedSchema.safeParse(got.body).success) return say(res, 400, 'INVALID_REQUEST', 'That isn\'t a church.changed message.');
churchChanged(ctx);
return res.status(202).json({ accepted: true });
} catch (e) {
return fail(res, e);
}
});
return r;
}
+2 -2
View File
@@ -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<SiteEvent[]> {
]);
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,
+18 -3
View File
@@ -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<string, unknown> };
@@ -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<Snapshot> {
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<string, Image> = {};
const collect = (data: unknown) => {
+111
View File
@@ -0,0 +1,111 @@
/**
* Messages from YouTube, automatically (WEBSITE-1.0-PLAN §7, decision 7): the church's channel or a
* playlist, read from YouTube's public feed (no API key) every hour. Each new video becomes a
* message, live at once (decision 9); admins add the speaker, series and passage afterwards, or hide
* one. A video already here (by its id, however it came in) is never added twice.
*/
import type { Ctx } from '../context.js';
import { ApiError } from '../http.js';
export type YoutubeSource = { kind: 'channel' | 'playlist'; id: string };
/** A channel id (UC…), a channel or playlist address, or a playlist id (PL…, UU…, OL…). */
export function parseSource(input: string): YoutubeSource | null {
const v = input.trim();
const channel = /(?:^|\/channel\/)(UC[\w-]{22})(?:[/?#]|$)/.exec(v);
if (channel) return { kind: 'channel', id: channel[1]! };
const list = /[?&]list=([\w-]{10,64})/.exec(v) ?? /^((?:PL|UU|OL|FL)[\w-]{10,62})$/.exec(v);
if (list) return { kind: 'playlist', id: list[1]! };
return null;
}
export const feedUrl = (s: YoutubeSource) => `https://www.youtube.com/feeds/videos.xml?${s.kind === 'channel' ? 'channel_id' : 'playlist_id'}=${encodeURIComponent(s.id)}`;
export type FeedVideo = { videoId: string; title: string; published: Date; thumbnail: string | null };
const unescape = (s: string) => s.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;|&apos;/g, "'").replace(/&amp;/g, '&');
/** The videos in a YouTube Atom feed. Entries without an id, title or date are left out. */
export function parseFeed(xml: string): FeedVideo[] {
const out: FeedVideo[] = [];
for (const m of xml.matchAll(/<entry>([\s\S]*?)<\/entry>/g)) {
const e = m[1]!;
const videoId = /<yt:videoId>([\w-]{6,20})<\/yt:videoId>/.exec(e)?.[1];
const title = /<title>([\s\S]*?)<\/title>/.exec(e)?.[1];
const published = /<published>([^<]+)<\/published>/.exec(e)?.[1];
const thumbnail = /<media:thumbnail url="([^"]+)"/.exec(e)?.[1] ?? null;
const date = published ? new Date(published) : null;
if (!videoId || !title || !date || Number.isNaN(date.getTime())) continue;
out.push({ videoId, title: unescape(title.trim()).slice(0, 500), published: date, thumbnail: thumbnail && thumbnail.startsWith('https://') ? thumbnail : null });
}
return out;
}
export async function getSource(ctx: Ctx): Promise<YoutubeSource | null> {
return ctx.settings.json<YoutubeSource | null>('youtube_source', null);
}
export async function setSource(ctx: Ctx, input: string | null): Promise<YoutubeSource | null> {
if (!input?.trim()) {
await ctx.settings.set('youtube_source', null);
return null;
}
const s = parseSource(input);
if (!s) throw new ApiError(400, 'VALIDATION', 'That isn\'t a YouTube channel id (UC…) or playlist address.', { youtube: 'A channel id (UC…) or a playlist link' });
await ctx.settings.set('youtube_source', JSON.stringify(s));
return s;
}
const slugify = (s: string) => s.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'message';
export async function uniqueSlug(ctx: Ctx, title: string, model: 'message' | 'simpleEvent', except?: string) {
const base = slugify(title);
for (let n = 1; ; n++) {
const slug = n === 1 ? base : `${base}-${n}`;
const taken = model === 'message'
? await ctx.db.message.findFirst({ where: { slug, ...(except ? { NOT: { id: except } } : {}) } })
: await ctx.db.simpleEvent.findFirst({ where: { slug, ...(except ? { NOT: { id: except } } : {}) } });
if (!taken) return slug;
}
}
type Fetcher = (url: string) => Promise<{ ok: boolean; status: number; text: () => Promise<string> }>;
/** The hourly job: new videos become messages. Returns how many were added. */
export async function syncYoutube(ctx: Ctx, fetcher: Fetcher = (u) => fetch(u, { signal: AbortSignal.timeout(15000), headers: { accept: 'application/atom+xml' } })) {
const source = await getSource(ctx);
if (!source) return { added: 0, skipped: 'no source' };
let videos: FeedVideo[];
try {
const res = await fetcher(feedUrl(source));
if (!res.ok) throw new Error(`YouTube answered ${res.status}`);
videos = parseFeed(await res.text());
} catch (e) {
await ctx.settings.set('youtube_last_error', `${ctx.now().toISOString()} ${(e as Error).message}`.slice(0, 300));
return { added: 0, error: (e as Error).message };
}
let added = 0;
for (const v of videos) {
if (await ctx.db.message.findUnique({ where: { externalId: v.videoId } })) continue;
await ctx.db.message.create({
data: {
slug: await uniqueSlug(ctx, v.title, 'message'), title: v.title, date: v.published, source: 'youtube_feed',
mediaUrl: `https://www.youtube.com/watch?v=${v.videoId}`, externalId: v.videoId, thumbnailUrl: v.thumbnail, publishedAt: ctx.now(),
},
});
added++;
}
await ctx.settings.setMany({ youtube_last_sync_at: ctx.now().toISOString(), youtube_last_error: null });
return { added };
}
/** Every hour while the site runs (pg-boss comes with the other jobs). */
export function startYoutubeSync(ctx: Ctx): () => void {
if (!ctx.config.jobsEnabled) return () => {};
const run = () => syncYoutube(ctx).catch((e) => console.warn('[youtube]', (e as Error).message));
const first = setTimeout(run, 30_000);
const timer = setInterval(run, 60 * 60 * 1000);
first.unref?.();
timer.unref?.();
return () => { clearTimeout(first); clearInterval(timer); };
}
+38 -9
View File
@@ -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('<svg>')), 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('<svg onload=alert(1)>'));
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('<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', 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);
+175
View File
@@ -0,0 +1,175 @@
import { after, describe, it } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import express from 'express';
import request from 'supertest';
import { EVENT_FEED_SCHEMA, EVENT_SCHEMA, eventFeedSchema, eventSchema } from '@crosscode/contracts';
import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing';
import { hashToken } from '../src/lib/crypto.js';
import { buildFeed, syncLink } from '../src/feed/feed.js';
import { siteContent } from '../src/site/content.js';
import { publish } from '../src/site/snapshot.js';
import { harness, INSTALL_ID, SITE } from './support/harness.js';
const EVENTS_ID = '5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e';
const SECRET = 'events-link-secret-0123456789abcdef';
/** A Cross Events event, as its feed sends it. */
function ev(id: string, title: string, inDays: number, over: Record<string, unknown> = {}) {
const start = new Date(Date.now() + inDays * 864e5);
return {
schema: EVENT_SCHEMA, id, origin: { product: 'events', installId: EVENTS_ID, url: `https://events.hope.test/events/${id.slice(0, 4)}` },
status: 'published', updatedAt: new Date().toISOString(), title, summary: null, description: null, imageUrl: null, timezone: 'Africa/Johannesburg',
startsAt: start.toISOString(), endsAt: new Date(start.getTime() + 3600e3).toISOString(), allDay: false, sessions: [], location: { name: 'The hall', address: null, onlineUrl: null },
campus: null, series: null, tags: [], registration: { mode: 'origin', url: `https://events.hope.test/events/${id.slice(0, 4)}`, status: 'open', opensAt: null, closesAt: null, priceFrom: { amountCents: 45000, currency: 'ZAR' } },
...over,
};
}
/** A Cross Events site: serves whatever feed the test sets, and records what it's told. */
async function fakeEvents() {
const state = { feed: null as unknown, status: 200, asked: [] as string[], told: [] as { headers: http.IncomingHttpHeaders; body: string }[] };
const app = express();
app.get('/api/feed/v1/events', (req, res) => { state.asked.push(req.url); res.status(state.status).json(state.feed); });
app.post('/api/feed/v1/changed', express.text({ type: () => true }), (req, res) => { state.told.push({ headers: req.headers, body: req.body }); res.status(202).json({ accepted: true }); });
const server = http.createServer(app);
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
closers.push(() => new Promise((r) => server.close(r)));
return { url, state };
}
const closers: (() => Promise<unknown>)[] = [];
after(async () => { for (const c of closers) await c(); });
async function site() {
const h = await harness({ env: { LINKS_ALLOW_PRIVATE: 'true' } });
const events = await fakeEvents();
await h.db.productLink.create({ data: { installId: EVENTS_ID, product: 'events', url: events.url, publicKey: 'x', secret: h.ctx.secrets.encrypt(SECRET), connectedAt: new Date() } });
await h.db.websiteUser.create({ data: { id: '00000000-0000-4000-8000-000000000001', name: 'O', email: 'o@hope.test', role: 'owner' } });
await h.db.session.create({ data: { tokenHash: hashToken('t'), userId: '00000000-0000-4000-8000-000000000001', expiresAt: new Date(Date.now() + 864e5) } });
await publish(h.ctx, { id: 'x', role: 'system' });
const go = (m: 'get' | 'post' | 'put' | 'delete', p: string, b?: object) => {
const r = request(h.app)[m](`/api/v1/admin${p}`).set('Cookie', 'ccw_session=t').set('Origin', SITE);
return b ? r.send(b) : r;
};
const link = async () => (await h.db.productLink.findUnique({ where: { installId: EVENTS_ID } })) as unknown as Parameters<typeof syncLink>[1];
return { ...h, events, go, link };
}
describe('publishing the Website\'s events (Publish my events)', () => {
it('serves its published simple events as crosscode.event/1, removed ones as deleted', async () => {
const { go, app } = await site();
const start = new Date(Date.now() + 5 * 864e5).toISOString();
const a = (await go('post', '/events', { title: 'Picnic', startsAt: start, location: 'The park', link: 'https://forms.example/p' })).body;
const b = (await go('post', '/events', { title: 'Carols', startsAt: start })).body;
await go('post', `/events/${a.id}/state`, { published: true });
await go('post', `/events/${b.id}/state`, { published: true });
const feed = (await request(app).get('/api/feed/v1/events')).body;
assert.ok(eventFeedSchema.safeParse(feed).success);
assert.equal(feed.events.length, 2);
const picnic = feed.events.find((e: { title: string }) => e.title === 'Picnic');
assert.ok(eventSchema.safeParse(picnic).success);
assert.deepEqual(picnic.origin, { product: 'website', installId: INSTALL_ID, url: `${SITE}/events/picnic` });
assert.deepEqual([picnic.registration.mode, picnic.registration.url], ['external', 'https://forms.example/p']);
const before = new Date().toISOString();
await go('post', `/events/${b.id}/state`, { published: false });
const since = (await request(app).get(`/api/feed/v1/events?updatedSince=${encodeURIComponent(before)}`)).body;
assert.deepEqual(since.deleted.map((d: { id: string }) => d.id), [b.id]);
assert.equal(since.events.length, 0, 'nothing else changed since');
assert.equal((await request(app).get('/api/feed/v1/events?updatedSince=nonsense')).status, 400);
await go('put', '/feed', { publish: false });
assert.equal((await request(app).get('/api/feed/v1/events')).status, 404);
});
it('tells the church\'s Events, signed, when one of its events changes', async () => {
const { go, events } = await site();
const e = (await go('post', '/events', { title: 'Picnic', startsAt: new Date(Date.now() + 864e5).toISOString() })).body;
await go('post', `/events/${e.id}/state`, { published: true });
await new Promise((r) => setTimeout(r, 200));
const told = events.state.told.at(-1)!;
assert.equal(told.headers[LINK_HEADERS.sender], INSTALL_ID);
assert.deepEqual(JSON.parse(told.body).eventIds, [e.id]);
});
});
describe('showing events from Cross Events (Show events from)', () => {
it('imports only its own, valid events; they show on the site and link back to Events', async () => {
const { ctx, events, link, db } = await site();
events.state.feed = {
schema: EVENT_FEED_SCHEMA, generatedAt: new Date().toISOString(), deleted: [],
events: [
ev('6c7d8e9f-0a1b-4c2d-8e3f-4a5b6c7d8e9f', 'Youth camp', 10),
ev('7d8e9f0a-1b2c-4d3e-9f4a-5b6c7d8e9f0a', 'From someone else', 4, { origin: { product: 'events', installId: '00000000-0000-4000-8000-0000000000ff', url: 'https://other.test/e' } }),
{ ...ev('8e9f0a1b-2c3d-4e4f-8a5b-6c7d8e9f0a1b', 'Broken', 3), startsAt: 'not a date' },
],
};
const r = await syncLink(ctx, await link());
assert.deepEqual([r.ok, r.imported, r.rejected], [true, 1, 1]);
const c = await siteContent(ctx);
assert.equal(c.mode === 'published' && c.events.length, 1);
if (c.mode === 'published') {
assert.equal(c.events[0]!.title, 'Youth camp');
assert.equal(c.events[0]!.url, 'https://events.hope.test/events/6c7d');
assert.deepEqual(c.events[0]!.registration, { status: 'open', priceFromCents: 45000 });
}
assert.match(String((await db.productLink.findUnique({ where: { installId: EVENTS_ID } }))!.lastSyncError), /1 event\(s\) skipped/);
});
it('asks only for what changed next time, drops deleted ones, and keeps the last good copy when Events is down', async () => {
const { ctx, events, link, db } = await site();
const id = '6c7d8e9f-0a1b-4c2d-8e3f-4a5b6c7d8e9f';
events.state.feed = { schema: EVENT_FEED_SCHEMA, generatedAt: new Date().toISOString(), deleted: [], events: [ev(id, 'Youth camp', 10)] };
await syncLink(ctx, await link());
events.state.status = 503;
const down = await syncLink(ctx, await link());
assert.equal(down.ok, false);
assert.equal(await db.importedEvent.count(), 1, 'the last good copy stays');
assert.match(events.state.asked.at(-1)!, /updatedSince=/);
events.state.status = 200;
events.state.feed = { schema: EVENT_FEED_SCHEMA, generatedAt: new Date().toISOString(), deleted: [{ id, deletedAt: new Date().toISOString() }], events: [] };
await syncLink(ctx, await link());
assert.equal(await db.importedEvent.count(), 0);
});
it('switching Show events off removes its events; a signed event.changed fetches at once', async () => {
const { ctx, events, link, db, go, app } = await site();
events.state.feed = { schema: EVENT_FEED_SCHEMA, generatedAt: new Date().toISOString(), deleted: [], events: [ev('6c7d8e9f-0a1b-4c2d-8e3f-4a5b6c7d8e9f', 'Youth camp', 10)] };
await syncLink(ctx, await link());
await go('put', `/links/${EVENTS_ID}`, { showEvents: false });
assert.equal(await db.importedEvent.count(), 0);
await go('put', `/links/${EVENTS_ID}`, { showEvents: true });
assert.equal(await db.importedEvent.count(), 1);
const body = JSON.stringify({ schema: EVENT_FEED_SCHEMA, type: 'event.changed', occurredAt: new Date().toISOString(), eventIds: [] });
const asked = events.state.asked.length;
const ok = await request(app).post('/api/feed/v1/changed').set(signedHeaders(LINK_HEADERS, { senderId: EVENTS_ID, secret: SECRET, rawBody: body })).set('Content-Type', 'application/json').send(body);
assert.equal(ok.status, 202);
await new Promise((r) => setTimeout(r, 200));
assert.equal(events.state.asked.length, asked + 1);
const forged = await request(app).post('/api/feed/v1/changed').set(signedHeaders(LINK_HEADERS, { senderId: EVENTS_ID, secret: 'wrong-secret-0123456789abcdefghij', rawBody: body })).set('Content-Type', 'application/json').send(body);
assert.equal(forged.status, 401);
const links = (await go('get', '/links')).body;
assert.equal(links.products.find((p: { product: string }) => p.product === 'events').events, 1);
});
it('takes church.changed only from Accounts, signed', async () => {
const { app, db, ctx } = await site();
const accounts = (await db.productLink.findFirst({ where: { product: 'accounts' } }))!;
const body = JSON.stringify({ schema: 'crosscode.church/1', type: 'church.changed', occurredAt: new Date().toISOString(), updatedAt: new Date().toISOString() });
const send = (sender: string, secret: string) => request(app).post('/api/church/v1/changed').set(signedHeaders(LINK_HEADERS, { senderId: sender, secret, rawBody: body })).set('Content-Type', 'application/json').send(body);
assert.equal((await send(String(accounts.installId), ctx.secrets.decrypt(String(accounts.secret)))).status, 202);
assert.equal((await send(EVENTS_ID, SECRET)).status, 404, 'Events isn\'t Accounts');
});
});
describe('the feed builder', () => {
it('leaves out events that ended over 30 days ago', async () => {
const { ctx, db } = await site();
await db.simpleEvent.create({ data: { slug: 'old', title: 'Old', startsAt: new Date(Date.now() - 40 * 864e5), publishedAt: new Date() } });
assert.equal((await buildFeed(ctx, null)).events.length, 0);
});
});
@@ -0,0 +1,111 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { hashToken } from '../src/lib/crypto.js';
import { siteContent } from '../src/site/content.js';
import { publish } from '../src/site/snapshot.js';
import { parseFeed, parseSource, syncYoutube } from '../src/site/youtube.js';
import { harness, SITE } from './support/harness.js';
const FEED = `<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns:yt="http://www.youtube.com/xml/schemas/2015" xmlns:media="http://search.yahoo.com/mrss/" xmlns="http://www.w3.org/2005/Atom">
<title>Hope Family Church</title>
<entry>
<id>yt:video:abcDEF12345</id>
<yt:videoId>abcDEF12345</yt:videoId>
<title>Hope &amp; joy | Sunday 23 Nov</title>
<published>2026-11-23T08:00:00+00:00</published>
<media:group><media:thumbnail url="https://i1.ytimg.com/vi/abcDEF12345/hqdefault.jpg" width="480" height="360"/></media:group>
</entry>
<entry>
<yt:videoId>zzzYYY98765</yt:videoId>
<title>Bread for the road</title>
<published>2026-11-16T08:00:00+00:00</published>
</entry>
<entry><title>No id</title><published>2026-11-01T08:00:00+00:00</published></entry>
</feed>`;
async function signedIn() {
const h = await harness({ linked: false });
await h.db.websiteUser.create({ data: { id: '00000000-0000-4000-8000-000000000003', name: 'Ed', email: 'ed@hope.test', role: 'editor' } });
await h.db.session.create({ data: { tokenHash: hashToken('t'), userId: '00000000-0000-4000-8000-000000000003', expiresAt: new Date(Date.now() + 864e5) } });
const go = (m: 'get' | 'post' | 'put' | 'delete', p: string, b?: object) => {
const r = request(h.app)[m](`/api/v1/admin${p}`).set('Cookie', 'ccw_session=t').set('Origin', SITE);
return b ? r.send(b) : r;
};
await publish(h.ctx, { id: 'x', role: 'system' });
return { ...h, go };
}
describe('messages from YouTube (§7)', () => {
it('reads a channel id, a channel address or a playlist', () => {
assert.deepEqual(parseSource('UCaBcDeFgHiJkLmNoPqRsTuV'), { kind: 'channel', id: 'UCaBcDeFgHiJkLmNoPqRsTuV' });
assert.deepEqual(parseSource('https://www.youtube.com/channel/UCaBcDeFgHiJkLmNoPqRsTuV/videos'), { kind: 'channel', id: 'UCaBcDeFgHiJkLmNoPqRsTuV' });
assert.deepEqual(parseSource('https://www.youtube.com/playlist?list=PLabcdefghij123'), { kind: 'playlist', id: 'PLabcdefghij123' });
assert.equal(parseSource('https://www.youtube.com/@hopefamily'), null);
});
it('parses the feed, leaving out entries it can\'t use', () => {
const v = parseFeed(FEED);
assert.equal(v.length, 2);
assert.equal(v[0]!.title, 'Hope & joy | Sunday 23 Nov');
assert.equal(v[0]!.thumbnail, 'https://i1.ytimg.com/vi/abcDEF12345/hqdefault.jpg');
});
it('adds new videos as live messages, once, and says when YouTube can\'t be reached', async () => {
const h = await harness({ linked: false });
await h.ctx.settings.set('youtube_source', JSON.stringify({ kind: 'channel', id: 'UCaBcDeFgHiJkLmNoPqRsTuV' }));
let asked = '';
const ok = async (u: string) => { asked = u; return { ok: true, status: 200, text: async () => FEED }; };
assert.deepEqual(await syncYoutube(h.ctx, ok), { added: 2 });
assert.equal(asked, 'https://www.youtube.com/feeds/videos.xml?channel_id=UCaBcDeFgHiJkLmNoPqRsTuV');
assert.deepEqual(await syncYoutube(h.ctx, ok), { added: 0 });
await publish(h.ctx, { id: 'x', role: 'system' });
const c = await siteContent(h.ctx);
assert.equal(c.mode === 'published' && c.messages[0]!.title, 'Hope & joy | Sunday 23 Nov');
const down = await syncYoutube(h.ctx, async () => ({ ok: false, status: 503, text: async () => '' }));
assert.match(String(down.error), /503/);
assert.match(String(await h.ctx.settings.get('youtube_last_error')), /503/);
});
});
describe('messages and events in the admin (decision 9)', () => {
it('adds a message by link, publishes it on its own, and refuses a duplicate or a stranger link', async () => {
const { go, ctx } = await signedIn();
const m = await go('post', '/messages', { title: 'Grace', date: '2026-11-22', mediaUrl: 'https://youtu.be/abcDEF12345', speaker: 'Thandi', series: 'Hope' });
assert.equal(m.status, 200);
let c = await siteContent(ctx);
assert.equal(c.mode === 'published' && c.messages.length, 0, 'not live until its own Publish');
await go('post', `/messages/${m.body.id}/publish`, { live: true });
c = await siteContent(ctx);
assert.equal(c.mode === 'published' && c.messages[0]!.series, 'Hope');
assert.equal((await go('post', '/messages', { title: 'Again', date: '2026-11-22', mediaUrl: 'https://www.youtube.com/watch?v=abcDEF12345' })).body.error.code, 'DUPLICATE');
assert.equal((await go('post', '/messages', { title: 'X', date: '2026-11-22', mediaUrl: 'https://evil.example/v' })).status, 400);
const spotify = await go('post', '/messages', { title: 'Podcast', date: '2026-11-22', mediaUrl: 'https://open.spotify.com/episode/4rOoJ6Egrf8K2IrywzwOMk' });
assert.equal(spotify.body.source, 'spotify');
});
it('keeps a feed message from being deleted (it would come back): hide it instead', async () => {
const { go, db } = await signedIn();
const row = await db.message.create({ data: { slug: 'x', title: 'From YouTube', date: new Date(), source: 'youtube_feed', mediaUrl: 'https://www.youtube.com/watch?v=abcDEF12345', externalId: 'abcDEF12345' } });
assert.equal((await go('delete', `/messages/${row.id}`)).body.error.code, 'FROM_FEED');
});
it('creates, publishes, cancels and removes a simple event', async () => {
const { go, ctx } = await signedIn();
const start = new Date(Date.now() + 7 * 864e5).toISOString();
const bad = await go('post', '/events', { title: 'Picnic', startsAt: start, endsAt: new Date(Date.now()).toISOString() });
assert.ok(bad.body.error.fields.endsAt);
const e = await go('post', '/events', { title: 'Picnic', startsAt: start, location: 'The park', link: 'https://forms.example/picnic' });
assert.equal(e.status, 200);
assert.equal(e.body.slug, 'picnic');
await go('post', `/events/${e.body.id}/state`, { published: true });
let c = await siteContent(ctx);
assert.equal(c.mode === 'published' && c.events[0]!.url, 'https://forms.example/picnic');
await go('post', `/events/${e.body.id}/state`, { cancelled: true });
c = await siteContent(ctx);
assert.equal(c.mode === 'published' && c.events.length, 0);
assert.equal((await go('delete', `/events/${e.body.id}`)).status, 200);
assert.equal((await go('get', '/events')).body.length, 0);
});
});
+69
View File
@@ -0,0 +1,69 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { hashToken } from '../src/lib/crypto.js';
import { harness, SITE } from './support/harness.js';
type Role = 'owner' | 'admin' | 'editor' | 'ministry_leader' | 'viewer';
/** A site linked to Accounts, with an Owner and an Admin signed in (each with their own cookie). */
async function site() {
const h = await harness();
const people: Record<string, { id: string; cookie: string }> = {};
for (const [n, role] of (['owner', 'admin', 'editor'] as Role[]).entries()) {
const id = `00000000-0000-4000-8000-00000000000${n + 1}`;
await h.db.websiteUser.create({ data: { id, name: role, email: `${role}@hope.test`, role } });
await h.db.session.create({ data: { tokenHash: hashToken(`t-${role}`), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
people[role] = { id, cookie: `ccw_session=t-${role}` };
}
const as = (role: string) => ({
get: (p: string) => request(h.app).get(`/api/v1/admin${p}`).set('Cookie', people[role]!.cookie),
post: (p: string, b: object) => request(h.app).post(`/api/v1/admin${p}`).set('Cookie', people[role]!.cookie).set('Origin', SITE).send(b),
put: (p: string, b: object) => request(h.app).put(`/api/v1/admin${p}`).set('Cookie', people[role]!.cookie).set('Origin', SITE).send(b),
del: (p: string) => request(h.app).delete(`/api/v1/admin${p}`).set('Cookie', people[role]!.cookie).set('Origin', SITE),
});
return { ...h, people, as };
}
describe('who can use the admin (§10)', () => {
it('adds someone by email through Accounts, who can then sign in with that role', async () => {
const { as, fake, db } = await site();
const r = await as('admin').post('/people', { name: 'New Editor', email: 'New@Hope.test', role: 'editor' });
assert.equal(r.status, 200);
assert.equal(r.body.newAccount, true);
assert.deepEqual(fake.requests[0], { type: 'people.ensure', actor: '00000000-0000-4000-8000-000000000002', name: 'New Editor', email: 'new@hope.test', phone: null, returnUrl: `${SITE}/admin` });
const u = await db.websiteUser.findUnique({ where: { id: r.body.id } });
assert.equal(u!.role, 'editor');
assert.equal((await as('admin').post('/people', { name: 'Again', email: 'new@hope.test', role: 'viewer' })).body.error.code, 'ALREADY_ADDED');
const list = (await as('owner').get('/people')).body;
assert.equal(list.length, 4);
});
it('needs a ministry for a Ministry leader', async () => {
const { as, db } = await site();
assert.equal((await as('admin').post('/people', { name: 'L', email: 'l@hope.test', role: 'ministry_leader' })).status, 400);
const m = await db.ministry.create({ data: { slug: 'kids', name: 'Kids' } });
const r = await as('admin').post('/people', { name: 'L', email: 'l@hope.test', role: 'ministry_leader', ministryId: m.id });
assert.equal(r.status, 200);
assert.equal((await as('admin').get('/people')).body.find((p: { id: string }) => p.id === r.body.id).ministry, 'Kids');
});
it('keeps Owners to Owners, and nobody changes themselves', async () => {
const { as, people } = await site();
assert.equal((await as('admin').post('/people', { name: 'O', email: 'o@hope.test', role: 'owner' })).body.error.code, 'OWNERS_ONLY');
assert.equal((await as('admin').put(`/people/${people.owner!.id}`, { role: 'viewer' })).body.error.code, 'OWNERS_ONLY');
assert.equal((await as('admin').del(`/people/${people.owner!.id}`)).body.error.code, 'OWNERS_ONLY');
assert.equal((await as('owner').put(`/people/${people.owner!.id}`, { role: 'viewer' })).body.error.code, 'SELF');
assert.equal((await as('editor').get('/people')).status, 403);
assert.equal((await as('owner').post('/people', { name: 'Second owner', email: 'o@hope.test', role: 'owner' })).status, 200);
});
it('a lower role takes effect at once; removing someone ends their sessions', async () => {
const { as, people, db } = await site();
assert.equal((await as('owner').put(`/people/${people.editor!.id}`, { role: 'viewer' })).status, 200);
assert.equal(await db.session.count({ where: { userId: people.editor!.id } }), 0);
assert.equal((await as('owner').del(`/people/${people.admin!.id}`)).status, 200);
assert.equal(await db.websiteUser.count({ where: { id: people.admin!.id } }), 0);
assert.equal((await as('admin').get('/people')).status, 401);
});
});
+10 -1
View File
@@ -20,6 +20,8 @@ export const ACCOUNTS_INSTALL_ID = '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c';
export type FakeAccounts = {
next: Partial<IdentityClaims> & { sub: string };
started: { returnTo: string; requireTwoFactor: boolean }[];
/** Requests to Accounts (people.ensure, …). */
requests: { type: string; email?: string; actor?: string | null }[];
};
export function claims(over: Partial<IdentityClaims> & { sub: string }): IdentityClaims {
@@ -63,6 +65,13 @@ function fakeAuthClient(fake: FakeAccounts): AuthClientModule {
throw new SignInError('bad', 'BAD_TOKEN');
}
},
/** people.ensure: the same sub for the same email; "new@…" is a new account. */
request: async (input: { type: string; email?: string; actor?: string | null }) => {
fake.requests.push(input);
if (input.type !== 'people.ensure') throw new Error(`not faked: ${input.type}`);
const hex = Buffer.from(input.email ?? '').toString('hex').padEnd(12, '0').slice(0, 12);
return { schema: 'crosscode.identity-request/1', sub: `22222222-2222-4222-8222-${hex}`, created: input.email?.startsWith('new@') ?? false, emailSent: true };
},
verifyAccountsCall: (raw: Buffer, headers: Record<string, unknown>) => {
if (headers['x-test-signed'] !== 'yes') throw new SignInError('That call isn\'t signed by Accounts.', 'BAD_SIGNATURE');
return JSON.parse(raw.toString('utf8'));
@@ -73,7 +82,7 @@ function fakeAuthClient(fake: FakeAccounts): AuthClientModule {
export async function harness(opts: { linked?: boolean; env?: Record<string, string> } = {}) {
const db = memoryDb();
const fake: FakeAccounts = { next: { sub: '11111111-1111-4111-8111-111111111111' }, started: [] };
const fake: FakeAccounts = { next: { sub: '11111111-1111-4111-8111-111111111111' }, started: [], requests: [] };
const config = loadConfig({ WEBSITE_URL: SITE, HUB_ADMIN_EMAIL: ADMIN_EMAIL.toUpperCase(), ...opts.env });
const ctx = createCtx(config, db as unknown as Db, { authClient: async () => fakeAuthClient(fake) });
await ctx.settings.set('hub_install_id', INSTALL_ID);
@@ -20,10 +20,10 @@ const DEFAULTS: Record<string, () => Row> = {
siteVersion: () => ({ note: null }),
websiteUser: () => ({ ministryId: null, lastSignInAt: null }),
session: () => ({ sid: null, mfa: false, idToken: null, lastSeenAt: new Date() }),
productLink: () => ({ connectedById: null, lastSyncError: null }),
productLink: () => ({ connectedById: null, lastSyncError: null, showEvents: true, lastSyncAt: null, lastGoodAt: null }),
auditLog: () => ({ actorId: null, targetId: null, metadata: null, ip: null }),
};
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce' };
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', feedRemoval: 'eventId' };
const UNIQUE: Record<string, string[]> = { session: ['tokenHash'], siteVersion: ['number'], page: ['slug'], message: ['slug', 'externalId'], previewLink: ['tokenHash'] };
const HAS_UPDATED_AT = new Set(['siteDesign', 'page', 'section', 'ministry', 'leader', 'message', 'simpleEvent', 'appSetting', 'productLink']);
/** `include` support: model → relation → [other model, foreign key on the other (many) or on this row (one)]. */
@@ -155,6 +155,7 @@ function model(name: string, tables: Map<string, Map<unknown, Row>>) {
};
const cascade = (from: string, id: unknown) => {
if (from === 'page') for (const [k, r] of tables.get('section') ?? []) if (r.pageId === id) tables.get('section')!.delete(k);
if (from === 'productLink') for (const [k, r] of tables.get('importedEvent') ?? []) if (r.linkId === id) tables.get('importedEvent')!.delete(k);
};
const withIncludes = (row: Row, include?: Row) => {
for (const [rel, on] of Object.entries(include ?? {})) {
+17 -2
View File
@@ -132,9 +132,24 @@ test("a Viewer sees the admin but can't publish", async ({ page, context }) => {
await expect(page.getByRole("button", { name: /Publish/ })).toHaveCount(0);
});
test("the admin's screens are accessible", async ({ page, context }) => {
test("an event added and published shows on the site at once (its own Publish)", async ({ page, context }) => {
await signIn(context);
for (const path of ["/admin", "/admin/template", "/admin/pages", "/admin/ministries", "/admin/leaders", "/admin/media", "/admin/publish"]) {
await page.goto("/admin/events");
await page.getByRole("button", { name: "Add an event" }).click();
await page.getByLabel("Title").fill("Prayer breakfast");
await page.getByLabel("Date", { exact: true }).fill(new Date(Date.now() + 3 * 864e5).toISOString().slice(0, 10));
await page.getByLabel("Where", { exact: true }).fill("The hall");
await page.getByRole("button", { name: "Save" }).click();
await expect(page.getByText("Not published").first()).toBeVisible();
await page.getByRole("listitem").filter({ hasText: "Prayer breakfast" }).getByRole("button", { name: "Publish" }).click();
await expect(page.getByText("On the site now.")).toBeVisible();
await page.goto("/events");
await expect(page.getByRole("link", { name: "Prayer breakfast" })).toBeVisible();
});
test("the admin's screens are accessible", async ({ page, context }) => {
await signIn(context, "owner");
for (const path of ["/admin", "/admin/template", "/admin/pages", "/admin/ministries", "/admin/leaders", "/admin/messages", "/admin/events", "/admin/linked", "/admin/media", "/admin/publish", "/admin/people"]) {
await page.goto(path);
await expect(page.getByRole("heading", { level: 1 })).toBeVisible();
const axe = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21aa", "wcag22aa"]).analyze();
+5 -1
View File
@@ -12,8 +12,12 @@ const NAV = [
{ href: "/admin/pages", label: "Pages" },
{ href: "/admin/ministries", label: "Ministries" },
{ href: "/admin/leaders", label: "Leadership" },
{ href: "/admin/messages", label: "Messages" },
{ href: "/admin/events", label: "Events" },
{ href: "/admin/linked", label: "Linked products" },
{ href: "/admin/media", label: "Media library" },
{ href: "/admin/publish", label: "Publish and history" },
{ href: "/admin/people", label: "People", managers: true },
];
export function AdminShell({ user, children }: { user: { name: string; role: string }; children: React.ReactNode }) {
@@ -36,7 +40,7 @@ export function AdminShell({ user, children }: { user: { name: string; role: str
<div className="mx-auto grid max-w-6xl gap-6 px-4 py-6 md:grid-cols-[13rem_1fr]">
<nav aria-label="Admin">
<ul className="flex gap-1 overflow-x-auto md:flex-col">
{NAV.map((n) => {
{NAV.filter((n) => !("managers" in n) || ["owner", "admin"].includes(user.role)).map((n) => {
const current = n.href === "/admin" ? path === "/admin" : path.startsWith(n.href);
return (
<li key={n.href}>
@@ -0,0 +1,113 @@
"use client";
/**
* Simple events (§8): title, date and time, place, description, a photo and an optional link (a
* sign-up form elsewhere, say). Registrations and payments are Cross Events'. Each publishes on its
* own (decision 9). Events from Cross Events show on the site by themselves once it's linked.
*/
import { useState } from "react";
import { api, canEdit } from "@/admin/api";
import { ImagePicker } from "@/admin/media";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
type Ev = { id: string; slug: string; title: string; startsAt: string; endsAt: string | null; allDay: boolean; location: string | null; description: string | null; imageId: string | null; image: string | null; link: string | null; cancelled: boolean; published: boolean };
type Form = { title: string; date: string; time: string; endDate: string; endTime: string; allDay: boolean; location: string; description: string; imageId: string | null; link: string };
/** "2026-12-05" + "18:30" in the browser's time zone (the church's, for its admins) → ISO with offset. */
const iso = (date: string, time: string) => (date ? new Date(`${date}T${time || "00:00"}`).toISOString() : null);
const local = (s: string | null) => {
if (!s) return { d: "", t: "" };
const x = new Date(s);
const p = (n: number) => String(n).padStart(2, "0");
return { d: `${x.getFullYear()}-${p(x.getMonth() + 1)}-${p(x.getDate())}`, t: `${p(x.getHours())}:${p(x.getMinutes())}` };
};
function EventForm({ initial, onSave, onCancel }: { initial: Form; onSave: (body: object) => Promise<unknown>; onCancel: () => void }) {
const [v, setV] = useState(initial);
const { busy, message, fields, run } = useAction();
const set = (k: keyof Form, x: unknown) => setV({ ...v, [k]: x });
return (
<div className="space-y-3">
<Field label="Title" error={fields.title}><input className={inputClass} value={v.title} maxLength={300} onChange={(e) => set("title", e.target.value)} /></Field>
<div className="grid gap-3 sm:grid-cols-4">
<Field label="Date" error={fields.startsAt}><input type="date" className={inputClass} value={v.date} onChange={(e) => set("date", e.target.value)} /></Field>
{!v.allDay && <Field label="Time"><input type="time" className={inputClass} value={v.time} onChange={(e) => set("time", e.target.value)} /></Field>}
<Field label="Ends (date)" error={fields.endsAt}><input type="date" className={inputClass} value={v.endDate} onChange={(e) => set("endDate", e.target.value)} /></Field>
{!v.allDay && <Field label="Ends (time)"><input type="time" className={inputClass} value={v.endTime} onChange={(e) => set("endTime", e.target.value)} /></Field>}
</div>
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={v.allDay} onChange={(e) => set("allDay", e.target.checked)} />All day</label>
<Field label="Where" error={fields.location}><input className={inputClass} value={v.location} maxLength={500} onChange={(e) => set("location", e.target.value)} /></Field>
<Field label="About it" error={fields.description}><textarea className={inputClass} rows={4} value={v.description} maxLength={8000} onChange={(e) => set("description", e.target.value)} /></Field>
<Field label="Link (optional)" hint="A sign-up form or more information elsewhere: https://…" error={fields.link}><input className={inputClass} value={v.link} onChange={(e) => set("link", e.target.value)} /></Field>
<ImagePicker label="Photo" value={v.imageId} onChange={(id) => set("imageId", id)} />
<div className="flex gap-2">
<Btn kind="primary" busy={busy} onClick={() => run(() => onSave({
title: v.title, startsAt: iso(v.date, v.allDay ? "00:00" : v.time), endsAt: v.endDate ? iso(v.endDate, v.allDay ? "23:59" : v.endTime) : null,
allDay: v.allDay, location: v.location || null, description: v.description || null, imageId: v.imageId, link: v.link || null,
}))}>Save</Btn>
<Btn onClick={onCancel}>Cancel</Btn>
</div>
{message && <Notice tone={message.tone}>{message.text}</Notice>}
</div>
);
}
const empty: Form = { title: "", date: "", time: "10:00", endDate: "", endTime: "", allDay: false, location: "", description: "", imageId: null, link: "" };
export default function Events() {
const me = useAdmin<{ user: { role: string } }>("/me");
const { data, error, reload } = useAdmin<Ev[]>("/events");
const [editing, setEditing] = useState<string | null>(null);
const { busy, message, run } = useAction();
if (!data || !me.data) return <Loading error={error ?? me.error} />;
const editor = canEdit(me.data.user.role);
const toForm = (e: Ev): Form => {
const s = local(e.startsAt);
const f = local(e.endsAt);
return { title: e.title, date: s.d, time: s.t, endDate: f.d, endTime: f.t, allDay: e.allDay, location: e.location ?? "", description: e.description ?? "", imageId: e.imageId, link: e.link ?? "" };
};
const state = (e: Ev, change: object, done: string) => run(async () => { await api(`/events/${e.id}/state`, { body: change }); await reload(); }, done);
return (
<>
<Title sub="Simple events made here. Events with registration and payment belong in Cross Events; they show here by themselves once it's linked.">Events</Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<div className="space-y-6">
{editor && (
<Panel title="Add an event">
{editing === "new"
? <EventForm initial={empty} onCancel={() => setEditing(null)} onSave={async (b) => { await api("/events", { body: b }); setEditing(null); await reload(); }} />
: <Btn kind="primary" onClick={() => setEditing("new")}>Add an event</Btn>}
</Panel>
)}
<Panel title="Your events">
{data.length === 0 && <p className="text-gray-600">None yet.</p>}
<ul className="divide-y divide-gray-200">
{data.map((e) => (
<li key={e.id} className="py-3">
{editing === e.id ? (
<EventForm initial={toForm(e)} onCancel={() => setEditing(null)} onSave={async (b) => { await api(`/events/${e.id}`, { method: "PUT", body: b }); setEditing(null); await reload(); }} />
) : (
<div className="flex flex-wrap items-center gap-4">
<div className="min-w-0 flex-1">
<p className="font-medium">{e.title}</p>
<p className="text-sm text-gray-600">{when(e.startsAt)}{e.location && ` · ${e.location}`}</p>
<p className="text-xs">{e.cancelled ? <span className="text-red-700">Cancelled</span> : e.published ? <span className="text-green-800">On the site</span> : <span className="text-gray-500">Not published</span>}</p>
</div>
{editor && (
<div className="flex flex-wrap gap-2">
<Btn onClick={() => setEditing(e.id)}>Edit</Btn>
<Btn busy={busy} onClick={() => state(e, { published: !e.published }, e.published ? "Taken off the site." : "On the site now.")}>{e.published ? "Unpublish" : "Publish"}</Btn>
<Btn busy={busy} onClick={() => state(e, { cancelled: !e.cancelled }, e.cancelled ? "Back on." : "Cancelled: it's off the site.")}>{e.cancelled ? "Not cancelled" : "Cancel it"}</Btn>
<Btn kind="danger" busy={busy} onClick={() => run(async () => { await api(`/events/${e.id}`, { method: "DELETE" }); await reload(); }, "Removed.")}>Remove</Btn>
</div>
)}
</div>
)}
</li>
))}
</ul>
</Panel>
</div>
</>
);
}
@@ -0,0 +1,70 @@
"use client";
/**
* Linked products (§8, §9): the church's other sites as the Hub lists them. Accounts is how
* people sign in here (the Website links to it by itself). With Cross Events (and later the App),
* events flow either way: "Show events from" brings its events here, read-only and linking back
* for registering; "Publish my events" offers this site's simple events to them.
*/
import { api, canEdit } from "@/admin/api";
import { Btn, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
type Product = { installId: string; product: string; url: string; connected: boolean; listed: boolean; showEvents: boolean | null; events: number; lastSyncAt: string | null; lastSyncError: string | null };
const NAMES: Record<string, string> = { accounts: "Accounts (sign-in)", events: "Cross Events", app: "Church App", website: "Website" };
export default function Linked() {
const me = useAdmin<{ user: { role: string } }>("/me");
const { data, error, reload } = useAdmin<{ publishMyEvents: boolean; products: Product[] }>("/links");
const { busy, message, run } = useAction();
if (!data || !me.data) return <Loading error={error ?? me.error} />;
const editor = canEdit(me.data.user.role);
const manager = ["owner", "admin"].includes(me.data.user.role);
return (
<>
<Title sub="Your church's other sites. Events can flow between them in either direction.">Linked products</Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<div className="space-y-6">
<Panel title="Publish my events">
<label className="flex items-start gap-3">
<input type="checkbox" className="mt-1" checked={data.publishMyEvents} disabled={!editor || busy}
onChange={(e) => run(async () => { await api("/feed", { method: "PUT", body: { publish: e.target.checked } }); await reload(); }, "Saved.")} />
<span>Offer the events you make here to your church&apos;s other sites (Cross Events, the App). They show them as read-only copies that link back here.</span>
</label>
</Panel>
{data.products.length === 0 && <Notice>No other sites yet. When your church has Cross Events or the App, they show here within 15 minutes.</Notice>}
{data.products.map((p) => (
<Panel key={p.installId}>
<div className="flex flex-wrap items-start justify-between gap-4">
<div>
<h2 className="text-lg font-semibold">{NAMES[p.product] ?? p.product}</h2>
<a href={p.url} className="text-sm text-brand-text underline-offset-4 hover:underline" rel="noopener">{p.url}</a>
<p className="mt-1 text-sm">{p.connected ? <span className="text-green-800">Connected</span> : <span className="text-gray-600">Not connected</span>}</p>
</div>
{manager && !p.connected && p.listed && <Btn kind="primary" busy={busy} onClick={() => run(async () => { await api(`/links/${p.installId}/connect`, { body: {} }); await reload(); }, "Connected.")}>Connect</Btn>}
{manager && p.connected && p.product !== "accounts" && <Btn kind="danger" busy={busy} onClick={() => run(async () => { await api(`/links/${p.installId}`, { method: "DELETE" }); await reload(); }, "Disconnected: its events are gone from here.")}>Disconnect</Btn>}
</div>
{p.product === "accounts" && p.connected && <p className="mt-3 text-sm text-gray-600">People sign in to this website&apos;s admin through it. This link stays.</p>}
{p.connected && p.product !== "accounts" && (
<div className="mt-4 space-y-2 border-t border-gray-200 pt-4">
<label className="flex items-center gap-3">
<input type="checkbox" checked={!!p.showEvents} disabled={!editor || busy}
onChange={(e) => run(async () => { await api(`/links/${p.installId}`, { method: "PUT", body: { showEvents: e.target.checked } }); await reload(); }, e.target.checked ? "Its events show here now." : "Its events are gone from here.")} />
<span>Show events from {NAMES[p.product]} on this website</span>
</label>
{p.showEvents && (
<p className="text-sm text-gray-600">
{p.events} {p.events === 1 ? "event" : "events"} from it{p.lastSyncAt && `, last checked ${when(p.lastSyncAt)}`}.{" "}
{editor && <Btn kind="link" onClick={() => run(async () => { await api(`/links/${p.installId}/sync`, { body: {} }); await reload(); }, "Checked.")}>Check now</Btn>}
</p>
)}
{p.lastSyncError && <Notice tone="warning">Last time: {p.lastSyncError}. The events from before keep showing.</Notice>}
</div>
)}
</Panel>
))}
</div>
</>
);
}
@@ -0,0 +1,110 @@
"use client";
/**
* Messages (§7): from the church's YouTube channel or playlist automatically, or added by hand with
* a YouTube or Spotify link. Each publishes on its own (decision 9); ones from YouTube go live by
* themselves. Add the speaker, series and passage afterwards, or hide one.
*/
import { useState } from "react";
import { api, canEdit } from "@/admin/api";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
type Message = { id: string; title: string; date: string; mediaUrl: string; source: string; speaker: string | null; passage: string | null; notes: string | null; series: string | null; hidden: boolean; published: boolean; thumbnail: string | null };
type Data = { youtube: { source: { kind: string; id: string } | null; lastSync: string | null; lastError: string | null }; items: Message[] };
const blank = { title: "", date: new Date().toISOString().slice(0, 10), mediaUrl: "", speaker: "", passage: "", series: "", notes: "", hidden: false };
function MessageForm({ initial, fromFeed, onSave, onCancel }: { initial: typeof blank; fromFeed: boolean; onSave: (v: typeof blank) => Promise<unknown>; onCancel: () => void }) {
const [v, setV] = useState(initial);
const { busy, message, fields, run } = useAction();
const set = (k: keyof typeof blank, x: string | boolean) => setV({ ...v, [k]: x });
return (
<div className="space-y-3">
<div className="grid gap-3 sm:grid-cols-2">
<Field label="Title" error={fields.title}><input className={inputClass} value={v.title} maxLength={500} onChange={(e) => set("title", e.target.value)} /></Field>
<Field label="Date" error={fields.date}><input type="date" className={inputClass} value={v.date.slice(0, 10)} onChange={(e) => set("date", e.target.value)} /></Field>
{!fromFeed && <Field label="YouTube or Spotify link" hint="A video (youtube.com/watch?v=…, youtu.be/…) or a Spotify episode." error={fields.mediaUrl}><input className={inputClass} value={v.mediaUrl} onChange={(e) => set("mediaUrl", e.target.value)} /></Field>}
<Field label="Speaker" error={fields.speaker}><input className={inputClass} value={v.speaker} maxLength={300} onChange={(e) => set("speaker", e.target.value)} /></Field>
<Field label="Series" hint="Messages with the same series name are grouped." error={fields.series}><input className={inputClass} value={v.series} maxLength={300} onChange={(e) => set("series", e.target.value)} /></Field>
<Field label="Bible passage" error={fields.passage}><input className={inputClass} value={v.passage} maxLength={300} onChange={(e) => set("passage", e.target.value)} /></Field>
</div>
<Field label="Notes" error={fields.notes}><textarea className={inputClass} rows={3} value={v.notes} maxLength={8000} onChange={(e) => set("notes", e.target.value)} /></Field>
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={v.hidden} onChange={(e) => set("hidden", e.target.checked)} />Hide it from the site</label>
<div className="flex gap-2"><Btn kind="primary" busy={busy} onClick={() => run(() => onSave(v))}>Save</Btn><Btn onClick={onCancel}>Cancel</Btn></div>
{message && <Notice tone={message.tone}>{message.text}</Notice>}
</div>
);
}
export default function Messages() {
const me = useAdmin<{ user: { role: string } }>("/me");
const { data, error, reload } = useAdmin<Data>("/messages");
const [editing, setEditing] = useState<string | null>(null);
const [youtube, setYoutube] = useState<string | null>(null);
const { busy, message, fields, run } = useAction();
if (!data || !me.data) return <Loading error={error ?? me.error} />;
const editor = canEdit(me.data.user.role);
const body = (v: typeof blank) => ({ ...v, date: v.date, speaker: v.speaker || null, passage: v.passage || null, series: v.series || null, notes: v.notes || null });
const yt = data.youtube;
return (
<>
<Title sub="Sermons. Audio and video stay on YouTube or Spotify: nothing is uploaded.">Messages</Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<div className="space-y-6">
<Panel title="From YouTube, automatically">
<p className="mb-3 text-sm text-gray-600">Each new video becomes a message within the hour. A playlist is better when your channel has other videos too.</p>
<div className="flex flex-wrap items-end gap-3">
<div className="min-w-[18rem] flex-1">
<Field label="Channel id or playlist link" hint="Your channel id starts with UC: on YouTube, open Settings → Advanced settings. Or paste a playlist's address." error={fields.youtube}>
<input className={inputClass} value={youtube ?? (yt.source ? (yt.source.kind === "playlist" ? `https://www.youtube.com/playlist?list=${yt.source.id}` : yt.source.id) : "")} disabled={!editor} onChange={(e) => setYoutube(e.target.value)} />
</Field>
</div>
{editor && <Btn kind="primary" busy={busy} onClick={() => run(async () => { const r = await api<{ sync: { added: number } | null }>("/messages-youtube", { method: "PUT", body: { youtube: youtube ?? "" } }); setYoutube(null); await reload(); return r; }, "Saved. New videos come in every hour.")}>Save</Btn>}
{editor && yt.source && <Btn busy={busy} onClick={() => run(async () => { await api("/messages-youtube/sync", { body: {} }); await reload(); }, "Checked YouTube.")}>Check now</Btn>}
</div>
{yt.lastSync && <p className="mt-2 text-xs text-gray-500">Last checked {when(yt.lastSync)}</p>}
{yt.lastError && <div className="mt-2"><Notice tone="warning">YouTube couldn&apos;t be reached last time: {yt.lastError.replace(/^\S+\s/, "")}</Notice></div>}
</Panel>
{editor && (
<Panel title="Add one by hand">
{editing === "new"
? <MessageForm initial={blank} fromFeed={false} onCancel={() => setEditing(null)} onSave={async (v) => { await api("/messages", { body: body(v) }); setEditing(null); await reload(); }} />
: <Btn kind="primary" onClick={() => setEditing("new")}>Add a message</Btn>}
</Panel>
)}
<Panel title="All messages">
{data.items.length === 0 && <p className="text-gray-600">None yet.</p>}
<ul className="divide-y divide-gray-200">
{data.items.map((m) => (
<li key={m.id} className="py-3">
{editing === m.id ? (
<MessageForm fromFeed={m.source === "youtube_feed"} onCancel={() => setEditing(null)}
initial={{ title: m.title, date: m.date.slice(0, 10), mediaUrl: m.mediaUrl, speaker: m.speaker ?? "", passage: m.passage ?? "", series: m.series ?? "", notes: m.notes ?? "", hidden: m.hidden }}
onSave={async (v) => { await api(`/messages/${m.id}`, { method: "PUT", body: body(v) }); setEditing(null); await reload(); }} />
) : (
<div className="flex flex-wrap items-center gap-4">
{m.thumbnail ? <img src={m.thumbnail} alt="" className="h-14 w-24 rounded object-cover" /> : <div className="h-14 w-24 rounded bg-gray-100" />}
<div className="min-w-0 flex-1">
<p className="font-medium">{m.title}</p>
<p className="text-sm text-gray-600">{[when(m.date).split(",")[0], m.speaker, m.series, m.source === "youtube_feed" ? "from YouTube" : m.source === "spotify" ? "Spotify" : "YouTube"].filter(Boolean).join(" · ")}</p>
<p className="text-xs">{m.hidden ? <span className="text-amber-800">Hidden</span> : m.published ? <span className="text-green-800">On the site</span> : <span className="text-gray-500">Not published</span>}</p>
</div>
{editor && (
<div className="flex flex-wrap gap-2">
<Btn onClick={() => setEditing(m.id)}>Edit</Btn>
<Btn busy={busy} onClick={() => run(async () => { await api(`/messages/${m.id}/publish`, { body: { live: !m.published } }); await reload(); }, m.published ? "Taken off the site." : "On the site now.")}>{m.published ? "Unpublish" : "Publish"}</Btn>
{m.source !== "youtube_feed" && <Btn kind="danger" busy={busy} onClick={() => run(async () => { await api(`/messages/${m.id}`, { method: "DELETE" }); await reload(); }, "Removed.")}>Remove</Btn>}
</div>
)}
</div>
)}
</li>
))}
</ul>
</Panel>
</div>
</>
);
}
@@ -0,0 +1,104 @@
"use client";
/**
* People (§10): who can use this website's admin, and as what. Adding someone by email gives them
* an account at the church's sign-in if they have none (they get an email to choose a password).
*/
import { useState } from "react";
import { api, ROLE_NAMES } from "@/admin/api";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
type Person = { id: string; name: string; email: string; role: string; ministryId: string | null; ministry: string | null; lastSignInAt: string | null };
const ROLE_TEXT: Record<string, string> = {
owner: "Everything, including who is Owner",
admin: "Everything but Owners",
editor: "Edits everything and publishes",
ministry_leader: "Edits their own ministry; an Editor publishes it",
viewer: "Looks, changes nothing",
};
function RolePicker({ role, ministryId, onChange, ministries, canOwner, errors }: { role: string; ministryId: string | null; onChange: (r: string, m: string | null) => void; ministries: { id: string; name: string }[]; canOwner: boolean; errors: Record<string, string> }) {
return (
<div className="grid gap-3 sm:grid-cols-2">
<Field label="Role" hint={ROLE_TEXT[role]} error={errors.role}>
<select className={inputClass} value={role} onChange={(e) => onChange(e.target.value, ministryId)}>
{Object.keys(ROLE_TEXT).filter((r) => canOwner || r !== "owner").map((r) => <option key={r} value={r}>{ROLE_NAMES[r]}</option>)}
</select>
</Field>
{role === "ministry_leader" && (
<Field label="Their ministry" error={errors.ministryId}>
<select className={inputClass} value={ministryId ?? ""} onChange={(e) => onChange(role, e.target.value || null)}>
<option value="">Choose…</option>
{ministries.map((m) => <option key={m.id} value={m.id}>{m.name}</option>)}
</select>
</Field>
)}
</div>
);
}
export default function People() {
const me = useAdmin<{ user: { id: string; role: string } }>("/me");
const list = useAdmin<Person[]>("/people");
const ministries = useAdmin<{ id: string; name: string }[]>("/ministries");
const [add, setAdd] = useState({ name: "", email: "", role: "editor", ministryId: null as string | null });
const [editing, setEditing] = useState<{ id: string; role: string; ministryId: string | null } | null>(null);
const { busy, message, fields, run } = useAction();
if (!list.data || !me.data) return <Loading error={list.error ?? me.error} />;
const owner = me.data.user.role === "owner";
const mayTouch = (p: Person) => p.id !== me.data!.user.id && (owner || p.role !== "owner");
return (
<>
<Title sub="Who can use this website's admin. They sign in with their church account.">People</Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<div className="grid gap-6 lg:grid-cols-[3fr_2fr]">
<Panel>
<ul className="divide-y divide-gray-200">
{list.data.map((p) => (
<li key={p.id} className="py-3">
{editing?.id === p.id ? (
<div className="space-y-3">
<p className="font-medium">{p.name}</p>
<RolePicker role={editing.role} ministryId={editing.ministryId} ministries={ministries.data ?? []} canOwner={owner} errors={fields} onChange={(role, ministryId) => setEditing({ ...editing, role, ministryId })} />
<div className="flex gap-2">
<Btn kind="primary" busy={busy} onClick={() => run(async () => { await api(`/people/${p.id}`, { method: "PUT", body: { role: editing.role, ministryId: editing.ministryId } }); setEditing(null); await list.reload(); }, "Saved. A lower role takes effect at once.")}>Save</Btn>
<Btn onClick={() => setEditing(null)}>Cancel</Btn>
</div>
</div>
) : (
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<p className="font-medium">{p.name}{p.id === me.data!.user.id && " (you)"}</p>
<p className="text-sm text-gray-600">{p.email} · {ROLE_NAMES[p.role]}{p.ministry && ` of ${p.ministry}`}</p>
<p className="text-xs text-gray-500">{p.lastSignInAt ? `Last signed in ${when(p.lastSignInAt)}` : "Hasn't signed in yet"}</p>
</div>
{mayTouch(p) && (
<div className="flex gap-2">
<Btn onClick={() => setEditing({ id: p.id, role: p.role, ministryId: p.ministryId })}>Change role</Btn>
<Btn kind="danger" onClick={() => run(async () => { await api(`/people/${p.id}`, { method: "DELETE" }); await list.reload(); }, `${p.name} no longer has access.`)}>Remove</Btn>
</div>
)}
</div>
)}
</li>
))}
</ul>
</Panel>
<Panel title="Add someone">
<div className="space-y-3">
<Field label="Name" error={fields.name}><input className={inputClass} value={add.name} maxLength={200} onChange={(e) => setAdd({ ...add, name: e.target.value })} /></Field>
<Field label="Email" hint="If they have no church account yet, they get an email to choose a password." error={fields.email}><input type="email" className={inputClass} value={add.email} onChange={(e) => setAdd({ ...add, email: e.target.value })} /></Field>
<RolePicker role={add.role} ministryId={add.ministryId} ministries={ministries.data ?? []} canOwner={owner} errors={fields} onChange={(role, ministryId) => setAdd({ ...add, role, ministryId })} />
<Btn kind="primary" busy={busy} disabled={!add.name || !add.email} onClick={() => run(async () => {
const r = await api<{ newAccount: boolean }>("/people", { body: add });
setAdd({ name: "", email: "", role: "editor", ministryId: null });
await list.reload();
return r;
}, "Added. They can sign in now.")}>Add</Btn>
</div>
</Panel>
</div>
</>
);
}
+15 -2
View File
@@ -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 = (
<img src={image.url} srcSet={image.srcset?.jpg} sizes={image.srcset ? sizes : undefined} alt={alt ?? image.alt}
width={image.width ?? undefined} height={image.height ?? undefined}
loading={priority ? "eager" : "lazy"} fetchPriority={priority ? "high" : undefined} decoding="async" className={className} />
);
return image.srcset ? <picture><source type="image/webp" srcSet={image.srcset.webp} sizes={sizes} />{img}</picture> : 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 (
<div className={cx("cc-frame", ratio, className)}>
{image ? (
<img src={image.url} alt={image.alt} sizes={sizes} width={image.width ?? undefined} height={image.height ?? undefined}
loading={priority ? "eager" : "lazy"} fetchPriority={priority ? "high" : undefined} decoding="async" className="cc-img" />
<Picture image={image} sizes={sizes} priority={priority} className="cc-img" />
) : (
<div aria-hidden="true" className="h-full w-full bg-gradient-to-br from-brand/25 via-brand-tint to-accent/30" />
)}
@@ -5,7 +5,7 @@
* photo.
*/
import { media } from "../load";
import { Button, cx, Img, type ButtonData } from "../parts";
import { Button, cx, Img, Picture, type ButtonData } from "../parts";
import type { Image, SectionProps } from "../types";
type HeroData = { headline: string; subline: string | null; images: string[]; videoId: string | null; button: ButtonData };
@@ -24,7 +24,7 @@ function Words({ d, centred, light, size = "cc-h1" }: { d: HeroData; centred?: b
function Video({ video, still, className }: { video: Image | null; still: Image | null; className?: string }) {
return (
<div className={cx("relative h-full w-full", className)}>
{still ? <img src={still.url} alt={still.alt} className="cc-img absolute inset-0" fetchPriority="high" /> : <div className="absolute inset-0 bg-brand" />}
{still ? <Picture image={still} priority className="cc-img absolute inset-0" /> : <div className="absolute inset-0 bg-brand" />}
{video && (
<video className="cc-motion cc-img absolute inset-0 hidden sm:block" src={video.url} poster={still?.url} autoPlay muted loop playsInline aria-hidden="true" />
)}
@@ -79,7 +79,7 @@ export function Hero({ section, site, template }: SectionProps) {
if (template === "bold") {
return (
<section className="cc-section-hero grid bg-gray-950 text-white md:min-h-[80vh] md:grid-cols-2">
<div className="relative min-h-[50vh] md:order-2">{first && <img src={first.url} alt={first.alt} className="cc-img absolute inset-0" fetchPriority="high" />}</div>
<div className="relative min-h-[50vh] md:order-2">{first && <Picture image={first} sizes="(min-width: 768px) 50vw, 100vw" priority className="cc-img absolute inset-0" />}</div>
<div className="flex flex-col justify-center px-6 pb-16 pt-32 sm:px-12"><Words d={d} light /></div>
</section>
);
@@ -100,7 +100,7 @@ export function Hero({ section, site, template }: SectionProps) {
return (
<Fullbleed d={d} site={site}>
<div className="grid h-full grid-cols-3 gap-1">
{three.map((im, i) => <div key={i} className="relative">{im ? <img src={im.url} alt={im.alt} className="cc-img absolute inset-0" /> : <div className="absolute inset-0 bg-brand/60" />}</div>)}
{three.map((im, i) => <div key={i} className="relative">{im ? <Picture image={im} sizes="34vw" priority={i === 0} className="cc-img absolute inset-0" /> : <div className="absolute inset-0 bg-brand/60" />}</div>)}
</div>
</Fullbleed>
);
@@ -134,7 +134,7 @@ export function Hero({ section, site, template }: SectionProps) {
}
// photo (and video, drawn the same way with its loop).
const visual = variant === "video" ? <Video video={video} still={first} /> : first ? <img src={first.url} alt={first.alt} className="cc-img absolute inset-0" fetchPriority="high" /> : null;
const visual = variant === "video" ? <Video video={video} still={first} /> : first ? <Picture image={first} priority className="cc-img absolute inset-0" /> : null;
if (template === "bold") return <Fullbleed d={d} site={site}>{visual ?? <div className="h-full w-full bg-brand" />}</Fullbleed>;
if (template === "heritage") {
return (
@@ -4,7 +4,7 @@
*/
import { MessagePlayer } from "../MessagePlayer";
import { media, str, t } from "../load";
import { Button, cx, DateBadge, dayName, fmtDate, fmtTime, Img, Paragraphs, SectionHeading, type ButtonData } from "../parts";
import { Button, cx, DateBadge, dayName, fmtDate, fmtTime, Img, Paragraphs, Picture, SectionHeading, type ButtonData } from "../parts";
import type { SectionProps, SiteEvent } from "../types";
import { Hero } from "./Hero";
@@ -394,7 +394,7 @@ function Invitation(p: SectionProps) {
const img = media(p.site, d.imageId);
return (
<section className="cc-section cc-own-bg cc-dark relative isolate overflow-hidden bg-gray-900 text-white">
{img && <img src={img.url} alt="" className="cc-img absolute inset-0 -z-10" loading="lazy" />}
{img && <Picture image={img} alt="" className="cc-img absolute inset-0 -z-10" />}
<div className="absolute inset-0 -z-10 bg-black/60" aria-hidden="true" />
<div className="cc-wrap py-10 text-center">
<h2 className="cc-h2">{d.heading}</h2>
+2 -1
View File
@@ -6,7 +6,8 @@ import type { Church } from "@crosscode/contracts";
export type Template = "heritage" | "bold" | "community" | "clean";
export type Image = { url: string; alt: string; width: number | null; height: number | null };
/** An uploaded image; `srcset` lists its responsive sizes (WebP and JPEG) when it has them. */
export type Image = { url: string; alt: string; width: number | null; height: number | null; srcset?: { webp: string; jpg: string } };
export type Section = { type: string; variant: string | null; data: Record<string, unknown> };
+1 -1
View File
@@ -102,7 +102,7 @@ out").
[WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md): decisions all confirmed 2026-11-21. Font pairings
confirmed 2026-11-24 (§3). Order: ~~contracts 1.17.0~~ → ~~Accounts 1.7.0~~ (both released 2026-11-24; Accounts
ships with contracts because it answers the new `church.update`) → ~~Events 3.7.0~~ (shared fonts and footer; released 2026-11-24) → ~~Hub 2.21.0~~ (released
and deployed 2026-11-25; the plan said 2.13.0) → **`website@1.0.0`** (being built in `apps/website` since 2026-11-25: signing in, the four templates and public site, the admin with preview, publish and restore; next: roles, messages and events, image sizes, the event feed, Lighthouse, the VM test) → Hope Family Church → a second
and deployed 2026-11-25; the plan said 2.13.0) → **`website@1.0.0`** (being built in `apps/website` since 2026-11-25: signing in, the four templates and public site, the admin with preview, publish and restore, people and roles, messages with the YouTube feed, simple events, responsive photo sizes without metadata, the event feed both ways; next: Get more storage, Lighthouse, the VM test) → Hope Family Church → a second
church → crosscode-site 1.7.0.
Done (confirmed by Joshua 2026-11-25): `hope-events` is archived, and every FastPanel site set up
before Hub 2.10.0, and the Hub's own site, has `location ^~ /api/`.
+12
View File
@@ -589,6 +589,18 @@ Confirmed on 2026-11-25:
17. **The first Owner** (§10): whoever signs in through Accounts with the Hub's admin email
(`HUB_ADMIN_EMAIL`), verified in Accounts, while the site has no Owner.
## Moved to website@1.1.0
Decided by Joshua on 2026-11-25, to ship 1.0 sooner:
- **The Video hero with its own loop** (§3): 1.0 uploads photos only, so the Video layout shows its
still.
- **The other custom-page blocks** (§3, "Pages from blocks"): gallery, video, FAQ, map, people cards
and divider. 1.0 has text, image and text, quote and call to action.
- **More pages** (§6, §7, §8): a page per ministry (1.0: one Ministries page with a section each),
the events calendar and past events, message detail and series pages, and starter Terms and
Safeguarding pages.
## Still open
- Whether the App (phase 6) moves leaders, ministries and giving into `crosscode.church/1` or reads
+1 -4
View File
@@ -367,6 +367,7 @@
"@prisma/client": "^7.10.1",
"dotenv": "^16.3.1",
"express": "^5.3.0",
"sharp": "^0.35.5",
"zod": "^4.6.7"
},
"devDependencies": {
@@ -2053,7 +2054,6 @@
"resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",
"integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",
"license": "MIT",
"optional": true,
"engines": {
"node": ">=18"
}
@@ -10820,7 +10820,6 @@
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
"devOptional": true,
"license": "Apache-2.0",
"engines": {
"node": ">=8"
@@ -18907,7 +18906,6 @@
"resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz",
"integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==",
"license": "Apache-2.0",
"optional": true,
"dependencies": {
"@img/colour": "^1.1.0",
"detect-libc": "^2.1.2",
@@ -18957,7 +18955,6 @@
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz",
"integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==",
"license": "ISC",
"optional": true,
"bin": {
"semver": "bin/semver.js"
},