Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Vision8 * File : server/src/httpx.ts9 * Module : server10 * Repository : https://git.spboucher.ai/maclustr-vision11 * Project Website : https://camera.spboucher.ai12 * Created : 2026-11-3013 * Last Modified : 2026-11-3014 *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: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Petits outils HTTP : routage, lecture JSON bornée, en-têtes de sécurité, service de fichiers avec Range.43import fs from 'node:fs';44import type http from 'node:http';45import path from 'node:path';4647export class HttpError extends Error {48 status: number;49 code: string;50 extra?: Record<string, unknown>;51 constructor(status: number, code: string, message?: string, extra?: Record<string, unknown>) {52 super(message || code);53 this.status = status;54 this.code = code;55 this.extra = extra;56 }57}5859export const SECURITY_HEADERS: Record<string, string> = {60 'Content-Security-Policy':61 "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' blob: data:; media-src 'self' blob:; connect-src 'self'; worker-src 'self'; manifest-src 'self'; font-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'",62 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains',63 'Referrer-Policy': 'no-referrer',64 'X-Content-Type-Options': 'nosniff',65 'X-Frame-Options': 'DENY',66 'Cross-Origin-Opener-Policy': 'same-origin',67 'Cross-Origin-Resource-Policy': 'same-origin',68 'Permissions-Policy': 'camera=(), microphone=(), geolocation=(), payment=(), usb=()',69 'X-Robots-Tag': 'noindex, nofollow, noarchive',70};7172export function applySecurity(res: http.ServerResponse): void {73 for (const [k, v] of Object.entries(SECURITY_HEADERS)) res.setHeader(k, v);74}7576export function sendJson(res: http.ServerResponse, status: number, body: unknown, headers: Record<string, string | string[]> = {}): void {77 const data = Buffer.from(JSON.stringify(body));78 res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': data.length, 'Cache-Control': 'no-store', ...headers });79 res.end(data);80}8182export async function readJson(req: http.IncomingMessage, limit = 16 * 1024): Promise<any> {83 const ct = String(req.headers['content-type'] || '');84 if (!ct.toLowerCase().startsWith('application/json')) throw new HttpError(415, 'unsupported_media_type', 'JSON attendu');85 const chunks: Buffer[] = [];86 let size = 0;87 for await (const c of req) {88 size += c.length;89 if (size > limit) throw new HttpError(413, 'payload_too_large');90 chunks.push(c);91 }92 if (!size) return {};93 try {94 const v = JSON.parse(Buffer.concat(chunks).toString('utf8'));95 if (v === null || typeof v !== 'object' || Array.isArray(v)) throw new Error('objet attendu');96 return v;97 } catch {98 throw new HttpError(400, 'invalid_json');99 }100}101102export function parseCookies(header: string | undefined): Record<string, string> {103 const out: Record<string, string> = {};104 for (const part of (header || '').split(';')) {105 const i = part.indexOf('=');106 if (i > 0) out[part.slice(0, i).trim()] = part.slice(i + 1).trim();107 }108 return out;109}110111export function intParam(v: string | null, name: string, opts: { min?: number; max?: number; def?: number } = {}): number {112 if (v === null || v === '') {113 if (opts.def !== undefined) return opts.def;114 throw new HttpError(400, 'invalid_parameter', `${name} requis`);115 }116 if (!/^-?\d{1,16}$/.test(v)) throw new HttpError(400, 'invalid_parameter', `${name} invalide`);117 const n = Number(v);118 if ((opts.min !== undefined && n < opts.min) || (opts.max !== undefined && n > opts.max)) throw new HttpError(400, 'invalid_parameter', `${name} hors bornes`);119 return n;120}121122const MIME: Record<string, string> = {123 '.html': 'text/html; charset=utf-8',124 '.js': 'text/javascript; charset=utf-8',125 '.css': 'text/css; charset=utf-8',126 '.json': 'application/json; charset=utf-8',127 '.webmanifest': 'application/manifest+json; charset=utf-8',128 '.svg': 'image/svg+xml',129 '.png': 'image/png',130 '.ico': 'image/x-icon',131 '.woff2': 'font/woff2',132 '.txt': 'text/plain; charset=utf-8',133 '.mp4': 'video/mp4',134};135136/** Sert un fichier avec prise en charge de Range (lecture vidéo, reprise de téléchargement). */137export function serveFile(req: http.IncomingMessage, res: http.ServerResponse, file: string, opts: { contentType?: string; cacheControl: string; downloadName?: string } ): void {138 let st: fs.Stats;139 try {140 st = fs.statSync(file);141 if (!st.isFile()) throw new Error('not a file');142 } catch {143 throw new HttpError(404, 'not_found');144 }145 const type = opts.contentType || MIME[path.extname(file).toLowerCase()] || 'application/octet-stream';146 const headers: Record<string, string | number> = { 'Content-Type': type, 'Cache-Control': opts.cacheControl, 'Accept-Ranges': 'bytes', 'Last-Modified': st.mtime.toUTCString() };147 if (opts.downloadName) headers['Content-Disposition'] = `attachment; filename="${opts.downloadName.replace(/[^A-Za-z0-9._-]/g, '_')}"`;148 const range = /^bytes=(\d*)-(\d*)$/.exec(String(req.headers.range || ''));149 let start = 0;150 let end = st.size - 1;151 let status = 200;152 if (range && (range[1] || range[2])) {153 if (range[1]) {154 start = Number(range[1]);155 if (range[2]) end = Math.min(end, Number(range[2]));156 } else {157 start = Math.max(0, st.size - Number(range[2]));158 }159 if (start > end || start >= st.size) {160 res.writeHead(416, { 'Content-Range': `bytes */${st.size}`, 'Cache-Control': 'no-store' });161 res.end();162 return;163 }164 status = 206;165 headers['Content-Range'] = `bytes ${start}-${end}/${st.size}`;166 }167 headers['Content-Length'] = end - start + 1;168 res.writeHead(status, headers);169 if (req.method === 'HEAD' || st.size === 0) {170 res.end();171 return;172 }173 const stream = fs.createReadStream(file, { start, end });174 stream.on('error', () => res.destroy());175 res.on('close', () => stream.destroy());176 stream.pipe(res);177}178179export function mimeFor(file: string): string {180 return MIME[path.extname(file).toLowerCase()] || 'application/octet-stream';181}182