Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : agentilab-web8 * File : lib/security/headers.ts9 * Module : Security10 * Repository : https://git.spboucher.ai/agentilab-web11 * Project Website : Not specified12 * Created : 2026-12-0513 * Last Modified : 2026-12-0514 *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: contact@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 : Proprietary34 *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 */4243export interface Header {44 key: string;45 value: string;46}4748/**49 * Politique de sécurité du contenu.50 *51 * Les pages sont générées statiquement : Next.js y inscrit des scripts en ligne52 * (charge utile RSC) qui ne peuvent pas porter de nonce sans rendu dynamique.53 * `script-src` accepte donc 'unsafe-inline' ; tout le reste est fermé : aucune54 * origine tierce, aucun objet, aucun cadre, aucune soumission de formulaire55 * externe. Le compromis est documenté dans docs/SECURITY.md.56 */57export function contentSecurityPolicy(dev = false): string {58 const directives: Record<string, string[]> = {59 'default-src': ["'self'"],60 'script-src': ["'self'", "'unsafe-inline'", ...(dev ? ["'unsafe-eval'"] : [])],61 'style-src': ["'self'", "'unsafe-inline'"],62 'img-src': ["'self'", 'data:'],63 'font-src': ["'self'"],64 'connect-src': ["'self'", ...(dev ? ['ws:'] : [])],65 'manifest-src': ["'self'"],66 'object-src': ["'none'"],67 'base-uri': ["'self'"],68 'form-action': ["'self'"],69 'frame-ancestors': ["'none'"],70 };71 return Object.entries(directives)72 .map(([name, values]) => `${name} ${values.join(' ')}`)73 .join('; ');74}7576/** En-têtes invariants, posés par next.config.ts sur toutes les réponses. */77export function staticSecurityHeaders(dev = false): Header[] {78 return [79 { key: 'Content-Security-Policy', value: contentSecurityPolicy(dev) },80 { key: 'X-Content-Type-Options', value: 'nosniff' },81 { key: 'X-Frame-Options', value: 'DENY' },82 { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },83 {84 key: 'Permissions-Policy',85 value: 'accelerometer=(), camera=(), geolocation=(), gyroscope=(), microphone=(), payment=(), usb=(), browsing-topics=()',86 },87 { key: 'Cross-Origin-Opener-Policy', value: 'same-origin' },88 ];89}9091/**92 * HSTS progressif : valeur fournie à l'exécution, jamais includeSubDomains ni93 * preload tant que tous les sous-domaines n'ont pas été audités.94 */95export function hstsHeader(maxAge: string | undefined): Header | null {96 const seconds = Number(maxAge ?? 0);97 if (!Number.isInteger(seconds) || seconds <= 0) return null;98 return { key: 'Strict-Transport-Security', value: `max-age=${seconds}` };99}100101/** Comparaison en temps constant de deux chaînes (authentification du staging). */102export function safeEqual(a: string, b: string): boolean {103 const ea = new TextEncoder().encode(a);104 const eb = new TextEncoder().encode(b);105 let diff = ea.length ^ eb.length;106 for (let i = 0; i < Math.max(ea.length, eb.length); i++) diff |= (ea[i] ?? 0) ^ (eb[i] ?? 0);107 return diff === 0;108}109110export function basicAuthOk(header: string | null, user: string, password: string): boolean {111 if (!header?.startsWith('Basic ')) return false;112 let decoded: string;113 try {114 decoded = atob(header.slice(6));115 } catch {116 return false;117 }118 const sep = decoded.indexOf(':');119 if (sep < 0) return false;120 return safeEqual(decoded.slice(0, sep), user) && safeEqual(decoded.slice(sep + 1), password);121}122