Admin API and screens: dashboard and setup checklist, template and style, pages and blocks, ministries, leadership, media library with the storage limit, publish and history. Pending changes with who and when, discard one, one Publish, restore any version (each version keeps the working copy's rows, never sent to visitors). Preview on the site's own addresses with a bar (widths, back, publish); shared preview links for 7 days or until revoked. Roles checked, same-origin changes only. Publish refreshes the public pages at once (WEBSITE_CONTENT_CACHE_SECONDS). E2E on a production build: the admin's flows and axe on every screen. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
49 lines
2.1 KiB
TypeScript
49 lines
2.1 KiB
TypeScript
/**
|
|
* Shared bits for the API: errors as `{ error: { code, message, fields? } }` (as Accounts and
|
|
* Events' /api/v2), async handlers, and a same-origin check on everything that changes something.
|
|
*/
|
|
import type { Request, RequestHandler, Response } from 'express';
|
|
|
|
export class ApiError extends Error {
|
|
constructor(public status: number, public code: string, message: string, public fields?: Record<string, string>) {
|
|
super(message);
|
|
}
|
|
}
|
|
|
|
/** Known errors carry a status and code; anything else is a 500. */
|
|
export function sendError(res: Response, e: unknown) {
|
|
if (e instanceof ApiError) {
|
|
return res.status(e.status).json({ error: { code: e.code, message: e.message, ...(e.fields ? { fields: e.fields } : {}) } });
|
|
}
|
|
console.error('[api]', e);
|
|
return res.status(500).json({ error: { code: 'INTERNAL', message: 'Something went wrong. Please try again.' } });
|
|
}
|
|
|
|
/** A handler whose result is sent as JSON; an error (thrown or rejected) as `{ error }`. */
|
|
export const handle = (fn: (req: Request, res: Response) => unknown): RequestHandler => (req, res) => {
|
|
Promise.resolve().then(() => fn(req, res)).then((out) => {
|
|
if (out !== undefined && !res.headersSent) res.json(out);
|
|
}).catch((e) => sendError(res, e));
|
|
};
|
|
|
|
/**
|
|
* Changes only from the site itself: an `Origin` (or `Referer`) on the site's own address, as
|
|
* Accounts' http.ts. With SameSite=Lax cookies this stops another site posting on someone's behalf.
|
|
*/
|
|
export function sameOrigin(publicUrl: string, production: boolean): RequestHandler {
|
|
const own = new URL(publicUrl).origin;
|
|
return (req, res, next) => {
|
|
if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();
|
|
let origin = req.get('origin') ?? null;
|
|
if (!origin && req.get('referer')) {
|
|
try {
|
|
origin = new URL(req.get('referer')!).origin;
|
|
} catch {
|
|
origin = null;
|
|
}
|
|
}
|
|
if (origin === own || (!production && origin && /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(origin))) return next();
|
|
return res.status(403).json({ error: { code: 'FORBIDDEN', message: 'That request didn\'t come from this site.' } });
|
|
};
|
|
}
|