SPB Git

Repository Public

magic.ts 5.0 KB 68 lines typescript

1/**2 * File-type validation by content. An extension is a claim made by whoever named the file; what is accepted3 * is decided from the first bytes (magic numbers) or, for text formats, from the file being real UTF-8 text.4 * A file whose content does not match its extension is refused, whatever it is called.5 */6export type Kind = "mp4" | "mov" | "webm" | "mkv" | "pdf" | "zip" | "gzip" | "tar" | "png" | "jpeg" | "vtt" | "text" | "unknown";78const starts = (b: Buffer, bytes: number[], at = 0) => b.length >= at + bytes.length && bytes.every((v, i) => b[at + i] === v);910/** Identifies a file from its first bytes (give at least 512; 4096 is better for text detection). */11export function sniff(head: Buffer): Kind {12  if (head.length >= 12 && head.toString("latin1", 4, 8) === "ftyp") return head.toString("latin1", 8, 12) === "qt  " ? "mov" : "mp4";13  if (starts(head, [0x1a, 0x45, 0xdf, 0xa3])) return head.subarray(0, 64).includes("webm") ? "webm" : "mkv";14  if (starts(head, [0x25, 0x50, 0x44, 0x46, 0x2d])) return "pdf";15  if (starts(head, [0x50, 0x4b, 0x03, 0x04]) || starts(head, [0x50, 0x4b, 0x05, 0x06])) return "zip";16  if (starts(head, [0x1f, 0x8b])) return "gzip";17  if (starts(head, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return "png";18  if (starts(head, [0xff, 0xd8, 0xff])) return "jpeg";19  if (head.length >= 262 && head.toString("latin1", 257, 262) === "ustar") return "tar";20  if (!head.length || head.includes(0)) return "unknown";21  // Text: valid UTF-8 (the last few bytes may cut a character in two) and no control characters besides whitespace.22  let text: string | null = null;23  for (let cut = 0; cut < 4 && text === null; cut++) { try { text = new TextDecoder("utf-8", { fatal: true }).decode(head.subarray(0, head.length - cut)); } catch { /* try a shorter slice */ } }24  if (text === null || /[\u0001-\u0008\u000b\u000e-\u001f]/.test(text)) return "unknown";25  return /^?WEBVTT(?:[ \t\r\n]|$)/.test(text) ? "vtt" : "text";26}2728export const extOf = (filename: string): string => { const m = /\.(tar\.gz|[A-Za-z0-9]{1,8})$/.exec(filename.toLowerCase()); return m ? m[1]! : ""; };2930/** Keeps a file name harmless: no directory, ASCII letters, digits, dot, dash and underscore only. */31export function safeFilename(name: string): string {32  const base = name.split(/[\\/]/).pop() ?? "", m = /^(.*?)(?:\.(tar\.gz|[A-Za-z0-9]{1,8}))?$/s.exec(base)!;33  const stem = m[1]!.normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[^A-Za-z0-9._-]+/g, "-").replace(/-{2,}/g, "-").replace(/^[-.]+|[-.]+$/g, "").slice(0, 80).replace(/[-.]+$/, "") || "fichier";34  return m[2] ? `${stem}.${m[2].toLowerCase()}` : stem;35}3637export type Purpose = "master" | "resource" | "captions" | "transcript" | "archive" | "slides";3839const VIDEO: Record<string, Kind[]> = { mp4: ["mp4", "mov"], m4v: ["mp4", "mov"], mov: ["mov", "mp4"], webm: ["webm", "mkv"], mkv: ["mkv", "webm"] };40const TEXT_EXT = ["txt", "md", "tex", "bib", "csv", "tsv", "json", "yaml", "yml", "py", "ipynb", "r", "sql", "vtt", "srt"];41/** Extensions accepted for a downloadable resource, with the content each must have and the type it is served as. */42export const RESOURCE_TYPES: Record<string, { kinds: Kind[]; mime: string }> = {43  pdf: { kinds: ["pdf"], mime: "application/pdf" }, zip: { kinds: ["zip"], mime: "application/zip" },44  "tar.gz": { kinds: ["gzip"], mime: "application/gzip" }, tgz: { kinds: ["gzip"], mime: "application/gzip" }, tar: { kinds: ["tar"], mime: "application/x-tar" },45  png: { kinds: ["png"], mime: "image/png" }, jpg: { kinds: ["jpeg"], mime: "image/jpeg" }, jpeg: { kinds: ["jpeg"], mime: "image/jpeg" },46  ...Object.fromEntries(TEXT_EXT.map((e) => [e, { kinds: ["text", "vtt"] as Kind[], mime: e === "csv" ? "text/csv; charset=utf-8" : e === "json" || e === "ipynb" ? "application/json; charset=utf-8" : "text/plain; charset=utf-8" }])),47};48const ACCEPT: Record<Purpose, Record<string, Kind[]>> = {49  master: VIDEO,50  captions: { vtt: ["vtt"] },51  transcript: { vtt: ["vtt"], json: ["text"] },52  archive: { zip: ["zip"], "tar.gz": ["gzip"], tgz: ["gzip"] },53  slides: { "tar.gz": ["gzip"], tgz: ["gzip"] },54  resource: Object.fromEntries(Object.entries(RESOURCE_TYPES).map(([e, v]) => [e, v.kinds])),55};5657export const acceptedExtensions = (purpose: Purpose) => Object.keys(ACCEPT[purpose]);58export const extensionAccepted = (purpose: Purpose, filename: string) => extOf(filename) in ACCEPT[purpose];5960/** Null when the content matches what the extension claims for this purpose; otherwise the reason of the refusal. */61export function contentMismatch(purpose: Purpose, filename: string, head: Buffer): string | null {62  const ext = extOf(filename), expected = ACCEPT[purpose][ext];63  if (!expected) return `Type de fichier non accepté ici (.${ext || "?"}). Acceptés : ${acceptedExtensions(purpose).map((e) => `.${e}`).join(", ")}.`;64  const kind = sniff(head);65  if (expected.includes(kind)) return null;66  return `Le contenu du fichier ne correspond pas à son extension .${ext} (contenu reconnu : ${kind === "unknown" ? "binaire non reconnu" : kind}).`;67}68
Files main
Menu

Theme