/** * The Express app (docs/WEBSITE-1.0-PLAN.md §1). Everything is under /api, so the site and its API * share one address (as Events and Accounts): nginx sends /api to this backend and the rest to Next.js. * * /api/health version and database, for monitoring, `crosscode deploy` and the Hub * /api/v1/site/… the public site (what visitors see: the latest published version) * /api/uploads/… the church's uploaded images * /api/thumbnails/.jpg its messages' YouTube thumbnails, kept here (visitors never ask YouTube) * /api/auth/… signing in to the admin through the church's Accounts * /api/accounts/v1/events Accounts' signed calls (user.updated / export / deleted) * /api/links/v1/… Connect and Disconnect with the church's other products * /api/v1/admin/… the admin (signed in, by role) * * To come (§1): the admin's content, publish and preview links, uploading, the event feed. */ import path from 'node:path'; import express from 'express'; import { websiteTemplateSchema } from '@crosscode/contracts'; import type { Ctx } from './context.js'; import { authRouter } from './auth/routes.js'; import { adminRouter } from './admin/routes.js'; import { previewTokenValid } from './admin/previewLinks.js'; import { atLeast, currentSession } from './auth/sessions.js'; import { dbUp } from './hub/client.js'; import { ApiError, handle, sendError } from './http.js'; import { appVersion } from './lib/version.js'; import { linksRouter } from './links/routes.js'; import { defaultUploadDir } from './demo/demoChurch.js'; import { previewContent, siteContent } from './site/content.js'; import { siteStatus } from './site/status.js'; import { thumbnail } from './site/thumbnails.js'; export function createApp(ctx: Ctx) { const app = express(); app.disable('x-powered-by'); if (ctx.config.trustProxySetting !== false) app.set('trust proxy', ctx.config.trustProxySetting); app.use((_req, res, next) => { res.setHeader('X-Content-Type-Options', 'nosniff'); res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin'); // The API is never a page of its own in search results; the public pages are (ROADMAP-v3 §11). res.setHeader('X-Robots-Tag', 'noindex'); next(); }); app.get('/api/health', async (_req, res) => { const db = await dbUp(ctx); res.status(db ? 200 : 503).json({ status: db ? 'ok' : 'error', product: 'website', version: appVersion(), db }); }); const site = express.Router(); site.get('/status', handle(() => siteStatus(ctx))); // The preview (§4): the working copy, for a signed-in admin or a shared preview link. Never cached. site.get('/preview', handle(async (req, res) => { const signed = await currentSession(ctx, req); if (!signed && !(await previewTokenValid(ctx, req.get('x-preview-token')))) throw new ApiError(401, 'NO_PREVIEW', 'This preview has ended, or you need to sign in.'); res.set('Cache-Control', 'no-store'); res.set('X-Robots-Tag', 'noindex, nofollow'); // An admin trying a template on (Template and style): the content in it, nothing saved. const t = websiteTemplateSchema.safeParse(req.get('x-preview-template')); const asTemplate = signed && t.success ? t.data : undefined; return { ...(await previewContent(ctx, { asTemplate })), preview: { by: signed ? 'admin' : 'link', canPublish: !!signed && atLeast(signed.user.role, 'editor') && !asTemplate, template: asTemplate ?? null } }; })); site.get('/content', handle(async (_req, res) => { // Short: Publish shows within a minute even where a proxy caches. res.set('Cache-Control', 'public, max-age=30'); return siteContent(ctx); })); app.use('/api/v1/site', site); // Uploaded files: never a directory listing, never outside the folder (express.static checks). app.use('/api/uploads', express.static(path.resolve(ctx.config.uploadDir ?? defaultUploadDir()), { index: false, dotfiles: 'deny', fallthrough: false, maxAge: '7d', setHeaders: (res) => { // An uploaded SVG is shown as an image, never run as a page. res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; sandbox"); }, })); // A message's YouTube thumbnail, fetched once by the backend and kept (site/thumbnails.ts). app.get('/api/thumbnails/:file', async (req, res, next) => { try { const id = /^([A-Za-z0-9_-]+)\.jpg$/.exec(req.params.file)?.[1]; const body = id ? await thumbnail(ctx, id) : null; if (!body) { res.set('Cache-Control', 'no-store'); return sendError(res, new ApiError(404, 'NOT_FOUND', 'There is no such file.')); } res.set('Content-Type', 'image/jpeg'); res.set('Cache-Control', 'public, max-age=604800'); res.send(body); } catch (err) { next(err); } }); app.use('/api', authRouter(ctx)); app.use('/api', linksRouter(ctx)); app.use('/api/v1/admin', adminRouter(ctx)); app.use('/api', (_req, res) => { res.status(404).json({ error: { code: 'NOT_FOUND', message: 'There is no such API endpoint.' } }); }); app.use((err: unknown, _req: express.Request, res: express.Response, next: express.NextFunction) => { if (res.headersSent) return next(err); if (err instanceof ApiError) return sendError(res, err); const e = err as { type?: string; status?: number }; if (e?.type === 'entity.parse.failed') return sendError(res, new ApiError(400, 'VALIDATION', 'The body must be JSON.')); // A missing upload (express.static), or another known client error. if (typeof e?.status === 'number' && e.status >= 400 && e.status < 500) return sendError(res, new ApiError(e.status, e.status === 404 ? 'NOT_FOUND' : 'BAD_REQUEST', e.status === 404 ? 'There is no such file.' : "That request isn't valid.")); return sendError(res, err); }); return app; }