Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Social Engine & Remote Navigator8 * File : packages/media-engine/src/index.ts9 * Module : media-engine10 * Repository : https://git.spboucher.ai/maclustr-social11 * Project Website : https://social.spboucher.ai12 * Created : 2026-12-0113 * Last Modified : 2026-12-0114 *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// Media engine: validates what a file really is (magic bytes, not its name), re-encodes it without43// EXIF/GPS/ICC comments, and returns the SHA-256 of the cleaned bytes. Nothing here trusts the upload.44import sharp from 'sharp';45import { createHash, createHmac, timingSafeEqual } from 'node:crypto';4647export const MAX_BYTES = 15 * 1024 * 1024;48export const LIMITS = { minSide: 200, maxSide: 8192, maxPixels: 40_000_000 };49export type CleanMedia = { bytes: Buffer; sha256: string; mime: 'image/jpeg' | 'image/png' | 'image/webp'; ext: 'jpg' | 'png' | 'webp'; width: number; height: number; strippedMetadata: string[] };50export class MediaError extends Error { constructor(public code: string, msg?: string) { super(msg ?? code); } }5152export function sniff(buf: Buffer): 'jpeg' | 'png' | 'webp' | null {53 if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return 'jpeg';54 if (buf.length >= 8 && buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'png';55 if (buf.length >= 12 && buf.subarray(0, 4).toString('latin1') === 'RIFF' && buf.subarray(8, 12).toString('latin1') === 'WEBP') return 'webp';56 return null;57}58export async function cleanImage(input: Buffer): Promise<CleanMedia> {59 if (input.length === 0) throw new MediaError('empty');60 if (input.length > MAX_BYTES) throw new MediaError('too_large');61 const kind = sniff(input);62 if (!kind) throw new MediaError('unsupported_format', 'Formats acceptés : JPEG, PNG, WebP (contenu réel vérifié).');63 let meta;64 try { meta = await sharp(input, { limitInputPixels: LIMITS.maxPixels, failOn: 'error' }).metadata(); } catch { throw new MediaError('corrupt_image'); }65 if (meta.format !== kind) throw new MediaError('format_mismatch');66 if ((meta.pages ?? 1) > 1) throw new MediaError('animated_not_supported');67 const stripped = ['exif', 'icc', 'iptc', 'xmp'].filter((k) => (meta as any)[k]);68 // rotate() bakes the EXIF orientation in before the tag is dropped; sharp writes no metadata unless asked.69 let img = sharp(input, { limitInputPixels: LIMITS.maxPixels }).rotate().toColourspace('srgb');70 const out = kind === 'jpeg' ? await img.jpeg({ quality: 90, mozjpeg: true }).toBuffer({ resolveWithObject: true })71 : kind === 'png' ? await img.png({ compressionLevel: 9 }).toBuffer({ resolveWithObject: true })72 : await img.webp({ quality: 90 }).toBuffer({ resolveWithObject: true });73 const { width, height } = out.info;74 if (Math.min(width, height) < LIMITS.minSide) throw new MediaError('too_small', `Côté minimal ${LIMITS.minSide} px.`);75 if (Math.max(width, height) > LIMITS.maxSide) throw new MediaError('too_big_dimensions');76 const map = { jpeg: ['image/jpeg', 'jpg'], png: ['image/png', 'png'], webp: ['image/webp', 'webp'] } as const;77 return { bytes: out.data, sha256: createHash('sha256').update(out.data).digest('hex'), mime: map[kind][0], ext: map[kind][1], width, height, strippedMetadata: stripped };78}79export async function hasMetadata(buf: Buffer): Promise<boolean> {80 const m = await sharp(buf).metadata();81 return !!(m.exif || m.iptc || m.xmp);82}83export async function svgToPng(svg: string, width: number): Promise<Buffer> {84 return sharp(Buffer.from(svg), { density: 144 }).resize({ width }).png().toBuffer();85}8687/* Short-lived signed URLs: HMAC over (id, expiry, audience). */88export function signMediaUrl(key: Buffer, id: string, audience: string, ttlSeconds: number, now = Date.now()): string {89 const exp = Math.floor(now / 1000) + ttlSeconds;90 const sig = createHmac('sha256', key).update(`${id}.${exp}.${audience}`).digest('base64url');91 return `/media/s/${id}?exp=${exp}&aud=${encodeURIComponent(audience)}&sig=${sig}`;92}93export function verifyMediaSig(key: Buffer, id: string, exp: string, audience: string, sig: string, now = Date.now()): boolean {94 if (!/^\d{1,12}$/.test(exp) || Number(exp) * 1000 < now) return false;95 const want = createHmac('sha256', key).update(`${id}.${exp}.${audience}`).digest();96 let got: Buffer; try { got = Buffer.from(sig, 'base64url'); } catch { return false; }97 return got.length === want.length && timingSafeEqual(got, want);98}99