Files
crosscode-platform/apps/accounts/backend/src/http.ts
T
joshuaandClaude Opus 5.5 069b66fd30 Accounts 1.0.0 backend: OIDC provider, sign-in steps, account and admin API
oidc-provider 9.13.3 with PKCE, ES256, crosscode.identity/1 claims and
back-channel logout; clients are the linked products (Connect). Sign-in
steps (password, sign-up, email check, 2FA and its setup, privacy notice,
news question, password reset) survive to the product. Account page and
admin API, church profile, export and deletion fan-out, Hub v2 client,
jobs. End-to-end tests with a test product on openid-client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:33:49 +02:00

54 lines
2.5 KiB
TypeScript

/**
* 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<string, string>) {
super(message);
}
}
type Fielded = { status?: number; code?: string; fields?: Record<string, string>; 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<unknown>): 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.' } }),
});