SPB Git

Repository Public

media.ts 5.2 KB 108 lines typescript

1import crypto from "node:crypto";2import fs from "node:fs";3import path from "node:path";4import sharp from "sharp";5import { dataDir, getDb } from "./db";67/**8 * Médiathèque : téléversement sécurisé d'images.9 *  - type réel vérifié par la signature binaire (pas l'extension ni le Content-Type déclaré) ;10 *  - SVG et tout autre format refusés ; taille maximale 8 Mo ; limite de pixels ;11 *  - l'image est TOUJOURS ré-encodée en WebP (métadonnées EXIF/GPS supprimées, contenu parasite éliminé) ;12 *  - nom de fichier généré côté serveur (aucun chemin fourni par l'utilisateur).13 */14export const MAX_UPLOAD_BYTES = 8 * 1024 * 1024;15export const MEDIA_FILE_RE = /^[a-f0-9]{12}(-800)?\.webp$/;1617export interface MediaRow {18  id: string;19  filename: string;20  original_name: string;21  mime: string;22  size: number;23  width: number;24  height: number;25  alt: string;26  sha256: string;27  created_at: number;28}2930export function mediaDir(): string {31  const dir = path.join(dataDir(), "media");32  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });33  return dir;34}3536export function sniffImage(buf: Buffer): "image/jpeg" | "image/png" | "image/webp" | "image/gif" | "image/avif" | null {37  if (buf.length < 12) return null;38  if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return "image/jpeg";39  if (buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return "image/png";40  if (buf.subarray(0, 4).toString("latin1") === "RIFF" && buf.subarray(8, 12).toString("latin1") === "WEBP") return "image/webp";41  if (buf.subarray(0, 6).toString("latin1") === "GIF87a" || buf.subarray(0, 6).toString("latin1") === "GIF89a") return "image/gif";42  if (buf.subarray(4, 8).toString("latin1") === "ftyp" && /avif|avis/.test(buf.subarray(8, 12).toString("latin1"))) return "image/avif";43  return null;44}4546export type UploadResult = { ok: true; media: MediaRow } | { ok: false; error: string; status: number };4748export async function saveUpload(buf: Buffer, originalName: string, alt: string, userId: number | null): Promise<UploadResult> {49  if (buf.length === 0) return { ok: false, error: "Fichier vide.", status: 400 };50  if (buf.length > MAX_UPLOAD_BYTES) return { ok: false, error: "Fichier trop volumineux (8 Mo maximum).", status: 413 };51  const mime = sniffImage(buf);52  if (!mime) return { ok: false, error: "Format non accepté. Formats permis : JPEG, PNG, WebP, GIF, AVIF.", status: 415 };53  let main: Buffer, small: Buffer, width: number, height: number;54  try {55    const base = sharp(buf, { limitInputPixels: 50_000_000, failOn: "error" }).rotate();56    const out = await base.clone().resize({ width: 1600, height: 1600, fit: "inside", withoutEnlargement: true }).webp({ quality: 82 }).toBuffer({ resolveWithObject: true });57    main = out.data;58    width = out.info.width;59    height = out.info.height;60    small = await base.clone().resize({ width: 800, height: 800, fit: "inside", withoutEnlargement: true }).webp({ quality: 78 }).toBuffer();61  } catch {62    return { ok: false, error: "Image illisible ou corrompue.", status: 415 };63  }64  const id = crypto.randomBytes(6).toString("hex");65  const filename = `${id}.webp`;66  fs.writeFileSync(path.join(mediaDir(), filename), main, { mode: 0o600 });67  fs.writeFileSync(path.join(mediaDir(), `${id}-800.webp`), small, { mode: 0o600 });68  const safeName = path.basename(originalName).replace(/[^\p{L}\p{N}._ -]/gu, "").slice(0, 120) || "image";69  getDb()70    .prepare("INSERT INTO media (id, filename, original_name, mime, size, width, height, alt, sha256, created_at, user_id) VALUES (?,?,?,?,?,?,?,?,?,?,?)")71    .run(id, filename, safeName, "image/webp", main.length, width, height, alt.trim().slice(0, 300), crypto.createHash("sha256").update(main).digest("hex"), Date.now(), userId);72  return { ok: true, media: getMedia(id)! };73}7475export function getMedia(id: string): MediaRow | undefined {76  return getDb().prepare("SELECT * FROM media WHERE id = ?").get(id) as MediaRow | undefined;77}78export function listMedia(): MediaRow[] {79  return getDb().prepare("SELECT * FROM media ORDER BY created_at DESC").all() as unknown as MediaRow[];80}81export function updateAlt(id: string, alt: string) {82  getDb().prepare("UPDATE media SET alt = ? WHERE id = ?").run(alt.trim().slice(0, 300), id);83}8485/** Documents (brouillon ou publié) qui référencent ce fichier. */86export function mediaUsage(id: string): string[] {87  if (!/^[a-f0-9]{12}$/.test(id)) return [];88  const needle = `%/media/${id}.webp%`;89  return (getDb().prepare("SELECT key FROM documents WHERE deleted = 0 AND (draft_json LIKE ? OR published_json LIKE ?)").all(needle, needle) as { key: string }[]).map((r) => r.key);90}9192export function deleteMedia(id: string): { ok: true } | { ok: false; usedBy: string[] } {93  const usedBy = mediaUsage(id);94  if (usedBy.length) return { ok: false, usedBy };95  const m = getMedia(id);96  if (m) {97    for (const f of [m.filename, m.filename.replace(".webp", "-800.webp")]) fs.rmSync(path.join(mediaDir(), f), { force: true });98    getDb().prepare("DELETE FROM media WHERE id = ?").run(id);99  }100  return { ok: true };101}102103export function readMediaFile(file: string): Buffer | null {104  if (!MEDIA_FILE_RE.test(file)) return null;105  const p = path.join(mediaDir(), file);106  return fs.existsSync(p) ? fs.readFileSync(p) : null;107}108
Files main
Menu

Theme