diff --git a/apps/website/CHANGELOG.md b/apps/website/CHANGELOG.md index 1c0fdcb..0511731 100644 --- a/apps/website/CHANGELOG.md +++ b/apps/website/CHANGELOG.md @@ -55,6 +55,16 @@ 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). - The admin page signs people in and out; `/auth/problem` explains a refused sign-in. - **The church's export** (`scripts/export-church.ts`): `export.json` in `crosscode.church-export/1` with its `website` part, for `crosscode export` and uninstall. diff --git a/apps/website/README.md b/apps/website/README.md index 8ebd9e5..8ebddd2 100644 --- a/apps/website/README.md +++ b/apps/website/README.md @@ -9,8 +9,9 @@ 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) and simple events. Still to come: +responsive image sizes, the event feed with Cross Events, the Hub's "Get more storage", Lighthouse +and the VM test. Not released; `website@1.0.0` is tagged when the plan is built. **Signing in** (`backend/src/auth/`): the Website registers with the Hub (its install id is its diff --git a/apps/website/backend/src/admin/happenings.ts b/apps/website/backend/src/admin/happenings.ts new file mode 100644 index 0000000..6eb3d01 --- /dev/null +++ b/apps/website/backend/src/admin/happenings.ts @@ -0,0 +1,160 @@ +/** + * 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'; + +type Who = { id: string; role: string }; + +function check(schema: z.ZodType, body: unknown): T { + const r = schema.safeParse(body); + if (!r.success) { + const fields: Record = {}; + 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.'); + return ctx.db.simpleEvent.update({ where: { id }, data }); + } + 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, + } }); + 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 } }); + await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'event_deleted', targetType: 'simple_event', targetId: id, metadata: { title: row.title } }); +} diff --git a/apps/website/backend/src/admin/people.ts b/apps/website/backend/src/admin/people.ts new file mode 100644 index 0000000..a644b47 --- /dev/null +++ b/apps/website/backend/src/admin/people.ts @@ -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(schema: z.ZodType, body: unknown): T { + const r = schema.safeParse(body); + if (!r.success) { + const fields: Record = {}; + 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 }; +} diff --git a/apps/website/backend/src/admin/routes.ts b/apps/website/backend/src/admin/routes.ts index 748f195..7077bc7 100644 --- a/apps/website/backend/src/admin/routes.ts +++ b/apps/website/backend/src/admin/routes.ts @@ -14,6 +14,9 @@ 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 { MAX_UPLOAD_BYTES, storage, upload } from './media.js'; import { createPreviewLink, listPreviewLinks, revokePreviewLink } from './previewLinks.js'; @@ -97,6 +100,31 @@ 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 }; })); + + // ─── 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) => { diff --git a/apps/website/backend/src/index.ts b/apps/website/backend/src/index.ts index d67117d..ac82468 100644 --- a/apps/website/backend/src/index.ts +++ b/apps/website/backend/src/index.ts @@ -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,7 @@ 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'; async function main() { const config = loadConfig(); @@ -21,6 +22,7 @@ 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); connectFromEnv(ctx).then((r) => { if (r.connected || r.reason === 'already') heartbeat(ctx).catch(() => {}); @@ -28,6 +30,7 @@ async function main() { const stop = async () => { stopHeartbeats(); + stopYoutube(); server.close(); await db.$disconnect(); process.exit(0); diff --git a/apps/website/backend/src/site/youtube.ts b/apps/website/backend/src/site/youtube.ts new file mode 100644 index 0000000..6d1463e --- /dev/null +++ b/apps/website/backend/src/site/youtube.ts @@ -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(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'|'/g, "'").replace(/&/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(/([\s\S]*?)<\/entry>/g)) { + const e = m[1]!; + const videoId = /([\w-]{6,20})<\/yt:videoId>/.exec(e)?.[1]; + const 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); }; +} diff --git a/apps/website/backend/tests/happenings.test.ts b/apps/website/backend/tests/happenings.test.ts new file mode 100644 index 0000000..a2b71f6 --- /dev/null +++ b/apps/website/backend/tests/happenings.test.ts @@ -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 + + yt:video:abcDEF12345 + abcDEF12345 + Hope & joy | Sunday 23 Nov + 2026-11-23T08:00:00+00:00 + + + + zzzYYY98765 + Bread for the road + 2026-11-16T08:00:00+00:00 + + No id2026-11-01T08:00:00+00:00 +`; + +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); + }); +}); diff --git a/apps/website/backend/tests/people.test.ts b/apps/website/backend/tests/people.test.ts new file mode 100644 index 0000000..233bcb8 --- /dev/null +++ b/apps/website/backend/tests/people.test.ts @@ -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 = {}; + 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); + }); +}); diff --git a/apps/website/backend/tests/support/harness.ts b/apps/website/backend/tests/support/harness.ts index 790d3b6..ba6faa2 100644 --- a/apps/website/backend/tests/support/harness.ts +++ b/apps/website/backend/tests/support/harness.ts @@ -20,6 +20,8 @@ export const ACCOUNTS_INSTALL_ID = '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c'; export type FakeAccounts = { next: Partial & { 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 & { 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) => { 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 } = {}) { 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); diff --git a/apps/website/e2e/admin.spec.ts b/apps/website/e2e/admin.spec.ts index db38a71..4025c29 100644 --- a/apps/website/e2e/admin.spec.ts +++ b/apps/website/e2e/admin.spec.ts @@ -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/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(); diff --git a/apps/website/frontend/src/admin/Shell.tsx b/apps/website/frontend/src/admin/Shell.tsx index 2f2e0bb..3d7b8d5 100644 --- a/apps/website/frontend/src/admin/Shell.tsx +++ b/apps/website/frontend/src/admin/Shell.tsx @@ -12,8 +12,11 @@ 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/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 +39,7 @@ export function AdminShell({ user, children }: { user: { name: string; role: str