Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Core/Security/FileValidator.swift3// Description: Validates imported files on their real bytes (same rules as the server) before any upload, plus log redaction.4import Foundation56/// Mirror of `src/lib/files.ts` on the server: a file is accepted for what its bytes are, never for its extension alone.7public enum FileValidator {8 public enum Rejection: Error, Equatable, Sendable, CustomStringConvertible {9 case empty(String), tooLarge(String, limitMb: Int), unsupported(String), unreadable(String), tooMany(limit: Int)10 public var description: String {11 switch self {12 case .empty(let n): "\(n) est vide."13 case .tooLarge(let n, let mb): "\(n) dépasse \(mb) Mo."14 case .unsupported(let n): "\(n) : format non pris en charge. Formats acceptés : \(FileValidator.formatsHelp)"15 case .unreadable(let n): "\(n) : lecture impossible."16 case .tooMany(let l): "\(l) fichiers au maximum par envoi."17 }18 }19 }2021 public static let formatsHelp = "images (PNG, JPEG, WebP, GIF, HEIC converti), PDF, DOCX, XLSX, CSV, TXT, Markdown, JSON, audio (MP3, M4A, WAV, OGG, WebM)."22 public static let maxFilesPerUpload = 102324 static let textExtensions: [String: String] = [25 "txt": "text/plain", "md": "text/markdown", "markdown": "text/markdown", "csv": "text/csv", "json": "application/json", "log": "text/plain", "yaml": "text/plain", "yml": "text/plain",26 "ts": "text/plain", "tsx": "text/plain", "js": "text/plain", "jsx": "text/plain", "py": "text/plain", "sql": "text/plain", "tex": "text/plain", "r": "text/plain",27 "html": "text/plain", "htm": "text/plain", "xml": "text/plain", "css": "text/plain", "swift": "text/plain",28 ]2930 private static func ascii(_ d: Data, _ start: Int, _ s: String) -> Bool {31 let bytes = Array(s.utf8)32 guard d.count >= start + bytes.count else { return false }33 return d.subdata(in: (d.startIndex + start)..<(d.startIndex + start + bytes.count)).elementsEqual(bytes)34 }3536 /// Canonical MIME type of the content, or nil when the bytes do not match an accepted format.37 public static func sniffMime(_ data: Data, filename: String) -> String? {38 let ext = (filename as NSString).pathExtension.lowercased()39 let b = [UInt8](data.prefix(16))40 if ascii(data, 0, "%PDF-") { return "application/pdf" }41 if b.count > 8, b[0] == 0x89, ascii(data, 1, "PNG") { return "image/png" }42 if b.count > 3, b[0] == 0xff, b[1] == 0xd8, b[2] == 0xff { return "image/jpeg" }43 if ascii(data, 0, "GIF87a") || ascii(data, 0, "GIF89a") { return "image/gif" }44 if ascii(data, 0, "RIFF"), ascii(data, 8, "WEBP") { return "image/webp" }45 if ascii(data, 0, "RIFF"), ascii(data, 8, "WAVE") { return "audio/wav" }46 if ascii(data, 0, "OggS") { return "audio/ogg" }47 if ascii(data, 0, "ID3") || (b.count > 2 && b[0] == 0xff && (b[1] & 0xe0) == 0xe0 && ext == "mp3") { return "audio/mpeg" }48 if b.count > 4, b[0] == 0x1a, b[1] == 0x45, b[2] == 0xdf, b[3] == 0xa3 { return "audio/webm" }49 if ascii(data, 4, "ftyp") {50 let brand = String(decoding: data.subdata(in: (data.startIndex + 8)..<(data.startIndex + min(12, data.count))), as: UTF8.self)51 if ["M4A ", "mp42", "isom", "M4B ", "iso2", "mp41", "dash"].contains(where: brand.hasPrefix), ["m4a", "mp4", "aac", "m4b"].contains(ext) { return "audio/mp4" }52 if ["heic", "heix", "heif", "mif1", "msf1", "hevc"].contains(where: brand.hasPrefix) { return "image/heic" } // converted to JPEG before upload53 return nil54 }55 if b.count > 4, b[0] == 0x50, b[1] == 0x4b, b[2] == 0x03 || b[2] == 0x05 {56 let head = String(decoding: data.prefix(8192), as: Unicode.ASCII.self)57 let tail = String(decoding: data.suffix(65_536), as: Unicode.ASCII.self)58 let has = { (s: String) in head.contains(s) || tail.contains(s) }59 if has("word/document.xml") || (has("[Content_Types].xml") && has("word/")) { return "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }60 if has("xl/workbook.xml") || (has("[Content_Types].xml") && has("xl/")) { return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }61 return nil62 }63 if let mime = textExtensions[ext] {64 let sample = data.prefix(65_536)65 if sample.contains(0) { return nil }66 // a multi-byte character may be cut at the sample boundary: tolerate up to 3 trailing bytes67 let candidates = sample.count == data.count ? [sample] : [sample, sample.dropLast(1), sample.dropLast(2), sample.dropLast(3)]68 guard candidates.contains(where: { String(data: Data($0), encoding: .utf8) != nil }) else { return nil }69 return mime70 }71 return nil72 }7374 /// Checks one file before it is read into an upload. Returns the sniffed MIME type.75 public static func validate(data: Data, filename: String, maxUploadMb: Int) -> Result<String, Rejection> {76 if data.isEmpty { return .failure(.empty(filename)) }77 if data.count > maxUploadMb * 1024 * 1024 { return .failure(.tooLarge(filename, limitMb: maxUploadMb)) }78 guard let mime = sniffMime(data, filename: filename) else { return .failure(.unsupported(filename)) }79 return .success(mime)80 }8182 /// File names are shown and sent as-is, minus control characters and path separators.83 public static func sanitizedName(_ name: String) -> String {84 let cleaned = name.unicodeScalars.filter { !CharacterSet.controlCharacters.contains($0) && $0 != "/" && $0 != "\\" && $0 != "\"" }85 let s = String(String.UnicodeScalarView(cleaned)).trimmingCharacters(in: .whitespaces)86 return s.isEmpty ? "fichier" : String(s.prefix(150))87 }88}8990/// Removes anything that looks like a credential before a string reaches a log line.91public enum Redactor {92 private static let patterns: [NSRegularExpression] = [93 #"(?i)(cookie|authorization|set-cookie)\s*[:=]\s*[^\n]+"#,94 #"(?i)(csa_session|csa_ceremony|csa_setup)=[A-Za-z0-9_\-\.]+"#,95 #"\b[A-Za-z0-9_-]{43}\b"#, // session / setup tokens (base64url of 32 bytes)96 #"\b(sk|xai|pk)-[A-Za-z0-9_\-]{16,}\b"#, // provider API keys97 #"\b[0-9A-HJKMNP-TV-Z]{4}(-[0-9A-HJKMNP-TV-Z]{4}){4}\b"#, // bootstrap / recovery codes98 ].compactMap { try? NSRegularExpression(pattern: $0) }99100 public static func redact(_ s: String) -> String {101 var out = s102 for re in patterns { out = re.stringByReplacingMatches(in: out, range: NSRange(out.startIndex..., in: out), withTemplate: "‹redacted›") }103 return out104 }105}106