/** * 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) { 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.' } }); }; }