/** * Shared bits for the API: errors as `{ error: { code, message, fields? } }` (as Events' /api/v2), * async handlers, a same-origin check on everything that changes something, and rate limits. */ import type { NextFunction, Request, RequestHandler, Response } from 'express'; import rateLimit from 'express-rate-limit'; import type { Ctx } from './context.js'; export class ApiError extends Error { constructor(public status: number, public code: string, message: string, public fields?: Record) { super(message); } } type Fielded = { status?: number; code?: string; fields?: Record; message: string }; /** Known errors from the services carry a status and code; anything else is a 500. */ export function sendError(res: Response, e: unknown) { const err = e as Fielded; if (e instanceof ApiError || (typeof err?.status === 'number' && typeof err?.code === 'string')) { return res.status(err.status!).json({ error: { code: err.code, message: err.message, ...(err.fields ? { fields: err.fields } : {}) } }); } console.error('[api]', e); return res.status(500).json({ error: { code: 'INTERNAL', message: 'Something went wrong. Please try again.' } }); } export const handle = (fn: (req: Request, res: Response) => Promise): RequestHandler => (req, res) => { 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. With * SameSite=Lax cookies this stops another site posting on someone's behalf. */ export function sameOrigin(ctx: Ctx): RequestHandler { const own = new URL(ctx.config.publicUrl).origin; return (req: Request, res: Response, next: NextFunction) => { if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next(); const origin = req.get('origin') || (req.get('referer') ? new URL(req.get('referer')!).origin : null); if (origin === own || (!ctx.config.production && origin && /^https?:\/\/localhost(:\d+)?$/.test(origin))) return next(); return res.status(403).json({ error: { code: 'FORBIDDEN', message: 'That request didn\'t come from this site.' } }); }; } export const limit = (max: number, minutes = 15): RequestHandler => rateLimit({ windowMs: minutes * 60e3, limit: max, standardHeaders: true, legacyHeaders: false, handler: (_req, res) => res.status(429).json({ error: { code: 'RATE_LIMITED', message: 'Too many tries. Please wait a few minutes.' } }), });