Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : ORIX App Universe8 * File : src/lib/security/http.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/orix-spboucher-ai11 * Project Website : https://www.orixlab.dev12 * Created : 2026-11-2113 * Last Modified : 2026-11-2114 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243import { env } from "../env";4445export class ApiError extends Error {46 constructor(public status: number, public code: string, message?: string, public extra?: Record<string, unknown>) { super(message ?? code); }47}4849export const json = (body: unknown, init?: ResponseInit) =>50 Response.json(body, { ...init, headers: { "Cache-Control": "no-store", ...(init?.headers ?? {}) } });5152/** The gateway (Caddy on BHS64) sets X-Forwarded-For; the node itself is not reachable from the Internet. */53export function clientIp(req: Request): string {54 return (req.headers.get("x-forwarded-for") ?? "").split(",")[0].trim() || "local";55}5657export function assertSameOrigin(req: Request): void {58 const o = req.headers.get("origin");59 if (o && o !== new URL(env.appUrl).origin) throw new ApiError(403, "bad_origin", "Cross-origin request refused");60 const site = req.headers.get("sec-fetch-site");61 if (site && site !== "same-origin" && site !== "none") throw new ApiError(403, "bad_origin", "Cross-site request refused");62}6364/** Wraps a route handler: typed errors become JSON answers, anything else a bare 500 (no internals leaked). */65export function route<A extends unknown[]>(fn: (req: Request, ...a: A) => Promise<Response> | Response) {66 return async (req: Request, ...a: A): Promise<Response> => {67 try { return await fn(req, ...a); }68 catch (e) {69 if (e instanceof ApiError) {70 const headers: Record<string, string> = {};71 if (e.status === 429 && typeof e.extra?.retryAfterSeconds === "number") headers["Retry-After"] = String(e.extra.retryAfterSeconds);72 return json({ error: { code: e.code, message: e.message, ...e.extra } }, { status: e.status, headers });73 }74 console.error("[api]", req.method, new URL(req.url).pathname, e instanceof Error ? e.message : e);75 return json({ error: { code: "internal", message: "Internal error" } }, { status: 500 });76 }77 };78}7980export async function readJson<T>(req: Request, maxBytes = 512_000): Promise<T> {81 const raw = await req.text();82 if (raw.length > maxBytes) throw new ApiError(413, "too_large", "Request body too large");83 try { return JSON.parse(raw) as T; } catch { throw new ApiError(400, "bad_json", "Malformed JSON"); }84}85