SPB Git

Repository Public

http.ts 8.6 KB 201 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : KA Maps Engine8 * File             : server/km-maps/lib/http.ts9 * Module           : server10 * Repository       : https://git.spboucher.ai/ka-maps-engine11 * Created          : 2026-12-0112 * Last Modified    : 2026-12-0113 *14 * Author           : Simon-Pierre Boucher15 * Position         : Professor of Finance16 * Institution      : Université du Québec en Outaouais (UQO)17 * Organization     : SP Boucher18 * Website          : https://spboucher.ai19 * Git              : https://git.spboucher.ai20 *21 * Preferred Contact: support@spboucher.ai22 * Development      : dev@spboucher.ai23 * Support          : support@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// Outils HTTP communs (service de manifeste et Studio) : réponses, ETag, compression, adresse du43// client derrière la passerelle, limitation de débit en mémoire.44import { createHash } from 'node:crypto';45import type { IncomingMessage, ServerResponse } from 'node:http';46import { brotliCompressSync, gzipSync, constants as zc } from 'node:zlib';4748export const sha256hex = (s: string | Uint8Array) => createHash('sha256').update(s).digest('hex');49export const etagOf = (s: string | Uint8Array) => `"${createHash('sha256').update(s).digest('base64url').slice(0, 27)}"`;5051const TRUSTED = new Set((process.env.KM_TRUSTED_PROXIES ?? '127.0.0.1,::1,10.67.0.1').split(',').map((s) => s.trim()));5253/** Adresse du client : celle de la connexion, ou la dernière entrée de X-Forwarded-For quand la54 *  connexion vient de la passerelle. Sert uniquement à la limitation de débit (en mémoire) et au55 *  journal d'audit des administrateurs ; jamais journalisée pour le public. */56export function clientIp(req: IncomingMessage): string {57  const peer = (req.socket.remoteAddress ?? '').replace(/^::ffff:/, '');58  if (TRUSTED.has(peer)) {59    const xff = String(req.headers['x-forwarded-for'] ?? '').split(',').map((s) => s.trim()).filter(Boolean);60    if (xff.length) return xff[xff.length - 1];61  }62  return peer;63}6465export class RateLimiter {66  private buckets = new Map<string, { tokens: number; at: number }>();67  private perMinute: number;68  private burst: number;69  constructor(perMinute: number, burst: number) {70    this.perMinute = perMinute;71    this.burst = burst;72    setInterval(() => this.sweep(), 60_000).unref();73  }74  take(key: string, cost = 1): boolean {75    const now = Date.now();76    const b = this.buckets.get(key) ?? { tokens: this.burst, at: now };77    b.tokens = Math.min(this.burst, b.tokens + ((now - b.at) / 60_000) * this.perMinute);78    b.at = now;79    const ok = b.tokens >= cost;80    if (ok) b.tokens -= cost;81    this.buckets.set(key, b);82    return ok;83  }84  private sweep() {85    const now = Date.now();86    for (const [k, b] of this.buckets) if (now - b.at > 10 * 60_000) this.buckets.delete(k);87  }88}8990export type Reply = { status?: number; headers?: Record<string, string>; body?: string | Buffer; type?: string };9192const COMPRESSIBLE = /^(text\/|application\/(json|javascript|wasm|xml|manifest\+json)|image\/svg)/;9394/** Envoie une réponse : ETag conditionnel (304), compression négociée (br, gzip) si utile. */95export function send(req: IncomingMessage, res: ServerResponse, r: Reply, opts: { precompressed?: { br?: Buffer; gzip?: Buffer } } = {}): number {96  const status = r.status ?? 200;97  const headers: Record<string, string> = { ...(r.headers ?? {}) };98  let body: Buffer = typeof r.body === 'string' ? Buffer.from(r.body) : (r.body ?? Buffer.alloc(0));99  if (r.type) headers['Content-Type'] = r.type;100  const etag = headers['ETag'];101  if (etag && status === 200 && matches(req.headers['if-none-match'], etag)) {102    for (const k of ['Content-Type', 'Content-Length', 'Content-Encoding']) delete headers[k];103    res.writeHead(304, headers);104    res.end();105    return 304;106  }107  const type = headers['Content-Type'] ?? '';108  if (status === 200 && body.length > 1024 && COMPRESSIBLE.test(type)) {109    const accept = String(req.headers['accept-encoding'] ?? '');110    headers['Vary'] = headers['Vary'] ? `${headers['Vary']}, Accept-Encoding` : 'Accept-Encoding';111    if (/\bbr\b/.test(accept)) {112      body = opts.precompressed?.br ?? brotliCompressSync(body, { params: { [zc.BROTLI_PARAM_QUALITY]: 5 } });113      headers['Content-Encoding'] = 'br';114    } else if (/\bgzip\b/.test(accept)) {115      body = opts.precompressed?.gzip ?? gzipSync(body, { level: 6 });116      headers['Content-Encoding'] = 'gzip';117    }118  }119  headers['Content-Length'] = String(body.length);120  res.writeHead(status, headers);121  res.end(req.method === 'HEAD' ? undefined : body);122  return status;123}124125function matches(header: string | string[] | undefined, etag: string): boolean {126  if (!header) return false;127  const list = String(header).split(',').map((s) => s.trim().replace(/^W\//, ''));128  return list.includes(etag) || list.includes('*');129}130131export const json = (value: unknown, extra: Partial<Reply> = {}): Reply => ({ type: 'application/json; charset=utf-8', body: JSON.stringify(value), ...extra });132export const problem = (status: number, error: string, detail?: unknown): Reply =>133  json({ error, ...(detail !== undefined ? { detail } : {}) }, { status, headers: { 'Cache-Control': 'no-store' } });134135/** Lit un corps JSON borné. */136export function readJson(req: IncomingMessage, limit = 2_000_000): Promise<any> {137  return new Promise((resolve, reject) => {138    const chunks: Buffer[] = [];139    let size = 0;140    req.on('data', (c: Buffer) => {141      size += c.length;142      if (size > limit) {143        reject(Object.assign(new Error('corps trop volumineux'), { status: 413 }));144        req.destroy();145      } else chunks.push(c);146    });147    req.on('end', () => {148      if (size === 0) return resolve({});149      try {150        resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')));151      } catch {152        reject(Object.assign(new Error('JSON invalide'), { status: 400 }));153      }154    });155    req.on('error', reject);156  });157}158159/** Compteurs et histogrammes au format Prometheus (texte). */160export class Metrics {161  private counters = new Map<string, number>();162  private hist = new Map<string, { buckets: number[]; sum: number; count: number }>();163  static BOUNDS = [1, 2.5, 5, 10, 25, 50, 100, 250, 1000, 5000];164  private prefix: string;165  constructor(prefix: string) {166    this.prefix = prefix;167  }168  inc(name: string, labels: Record<string, string> = {}, by = 1) {169    const k = this.key(name, labels);170    this.counters.set(k, (this.counters.get(k) ?? 0) + by);171  }172  observe(name: string, labels: Record<string, string>, ms: number) {173    const k = `${name}|${JSON.stringify(labels)}`;174    const h = this.hist.get(k) ?? { buckets: Metrics.BOUNDS.map(() => 0), sum: 0, count: 0 };175    Metrics.BOUNDS.forEach((b, i) => {176      if (ms <= b) h.buckets[i]++;177    });178    h.sum += ms;179    h.count++;180    this.hist.set(k, h);181  }182  private key(name: string, labels: Record<string, string>) {183    const l = Object.entries(labels).map(([k, v]) => `${k}="${String(v).replace(/["\\\n]/g, '_')}"`).join(',');184    return `${this.prefix}_${name}${l ? `{${l}}` : ''}`;185  }186  render(extra: Record<string, number> = {}): string {187    const lines: string[] = [];188    for (const [k, v] of Object.entries(extra)) lines.push(`${this.prefix}_${k} ${v}`);189    for (const [k, v] of [...this.counters].sort()) lines.push(`${k} ${v}`);190    for (const [k, h] of [...this.hist].sort()) {191      const [name, lj] = k.split('|');192      const labels = JSON.parse(lj) as Record<string, string>;193      Metrics.BOUNDS.forEach((b, i) => lines.push(`${this.key(`${name}_bucket`, { ...labels, le: String(b) })} ${h.buckets[i]}`));194      lines.push(`${this.key(`${name}_bucket`, { ...labels, le: '+Inf' })} ${h.count}`);195      lines.push(`${this.key(`${name}_sum`, labels)} ${h.sum.toFixed(3)}`);196      lines.push(`${this.key(`${name}_count`, labels)} ${h.count}`);197    }198    return lines.join('\n') + '\n';199  }200}201
Files main
Menu

Theme