- The messages' YouTube thumbnails are served from the site (/api/thumbnails/<id>.jpg): the backend fetches a message's thumbnail once and keeps it in uploads/.thumbnails (only the site's own videos, only a JPEG), so visitors ask nothing of YouTube before pressing play. The messages page preloads the first one (its LCP: Heritage 89 -> 95). - Calendar events' dates read "Sun · November", not "Sun (month: November)". - e2e: no request to YouTube or Spotify before play; the variant screenshots round section heights to whole pixels (a one-pixel flake); the e2e thumbnail is one of the demo's illustrations. - crosscode script: a Website's export leaves out uploads/.thumbnails. - docs: release checks on 1.0.1, VERSIONS, handover. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
117 lines
5.8 KiB
TypeScript
117 lines
5.8 KiB
TypeScript
/**
|
|
* 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/<id>.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;
|
|
}
|