Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Security/NameRules.swift3// Description: Naming rules shared with the server (sanitised names, uniqueness key, free-name search, conflict-copy names) and path-traversal guards for anything written on disk.4import Foundation56public enum NameRules {7 public static let maxNameBytes = 2558 private static let reserved: Set<String> = ["con", "prn", "aux", "nul", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9"]910 private static func isBad(_ u: Unicode.Scalar) -> Bool {11 switch u.value {12 case 0x00...0x1F, 0x7F...0x9F: return true13 case 0x202A...0x202E, 0x2066...0x2069, 0x200B...0x200F, 0xFEFF: return true14 default: return "/\\:*?\"<>|".unicodeScalars.contains(u)15 }16 }17 /// "archive.tar.gz" → ("archive", ".tar.gz"); a leading dot belongs to the stem.18 public static func splitExtension(_ name: String) -> (stem: String, ext: String) {19 guard let r = name.range(of: #"^(.+?)((?:\.tar)?\.[A-Za-z0-9]{1,10})$"#, options: .regularExpression), r == name.startIndex..<name.endIndex else { return (name, "") }20 // find the split: shortest stem such that the remainder matches the extension pattern21 var idx = name.index(after: name.startIndex)22 while idx < name.endIndex {23 let tail = String(name[idx...])24 if tail.range(of: #"^(?:\.tar)?\.[A-Za-z0-9]{1,10}$"#, options: .regularExpression) != nil { return (String(name[..<idx]), tail) }25 idx = name.index(after: idx)26 }27 return (name, "")28 }29 /// Lower-case extension without the dot ("" when none).30 public static func fileExtension(_ name: String) -> String {31 let e = splitExtension(name).ext32 guard let dot = e.lastIndex(of: ".") else { return "" }33 return String(e[e.index(after: dot)...]).lowercased()34 }35 private static func truncate(_ s: String, toBytes max: Int) -> String {36 var out = "", n = 037 for ch in s { let l = String(ch).utf8.count; if n + l > max { break }; out.append(ch); n += l }38 return out39 }40 /// The name the server will store for a client-supplied name: never a path, never empty, never "." or "..".41 public static func sanitize(_ raw: String, fallback: String = "sans-nom") -> String {42 var s = String(String.UnicodeScalarView(raw.precomposedStringWithCanonicalMapping.unicodeScalars.map { isBad($0) ? "_" : $0 }))43 s = s.replacingOccurrences(of: #"\s+"#, with: " ", options: .regularExpression).trimmingCharacters(in: .whitespaces)44 s = s.replacingOccurrences(of: #"^\.+"#, with: "", options: .regularExpression).replacingOccurrences(of: #"[. ]+$"#, with: "", options: .regularExpression).trimmingCharacters(in: .whitespaces)45 if s.isEmpty { s = fallback }46 if reserved.contains(splitExtension(s).stem.lowercased()) { s = "_" + s }47 if s.utf8.count > maxNameBytes {48 let (st, ex) = splitExtension(s)49 let keep = ex.utf8.count <= 20 ? ex : ""50 s = truncate(st, toBytes: maxNameBytes - keep.utf8.count) + keep51 }52 return s.isEmpty ? fallback : s53 }54 /// Uniqueness key inside a folder: case- and normalisation-insensitive.55 public static func key(_ name: String) -> String { name.precomposedStringWithCanonicalMapping.lowercased() }56 /// Key used by the local search index: also accent-insensitive.57 public static func searchKey(_ name: String) -> String {58 name.folding(options: [.diacriticInsensitive, .caseInsensitive, .widthInsensitive], locale: Locale(identifier: "en_US_POSIX")).lowercased()59 }60 /// "rapport.pdf" → "rapport (2).pdf" → "rapport (3).pdf" …61 public static func nextFree(_ name: String, taken: (String) -> Bool) -> String {62 if !taken(key(name)) { return name }63 let (stem0, ext) = splitExtension(name)64 var stem = stem0, start = 265 if let m = stem0.range(of: #" \((\d+)\)$"#, options: .regularExpression) {66 let digits = stem0[m].dropFirst(2).dropLast()67 stem = String(stem0[..<m.lowerBound]); start = (Int(digits) ?? 1) + 168 }69 for i in start..<100_000 {70 let candidate = sanitize("\(truncate(stem, toBytes: maxNameBytes - ext.utf8.count - 12)) (\(i))\(ext)")71 if !taken(key(candidate)) { return candidate }72 }73 return sanitize("\(stem) \(UUID().uuidString.prefix(8))\(ext)")74 }75 /// Name of the copy kept when the same file was changed on two devices: "rapport (conflit Mac de SP 2026-11-18 14.35).pdf".76 public static func conflictCopyName(_ name: String, device: String, at date: Date = Date(), timeZone: TimeZone = .current) -> String {77 let f = DateFormatter(); f.locale = Locale(identifier: "en_US_POSIX"); f.timeZone = timeZone; f.dateFormat = "yyyy-MM-dd HH.mm"78 let (stem, ext) = splitExtension(name)79 let who = sanitize(device, fallback: "appareil").prefix(40)80 let suffix = " (conflit \(who) \(f.string(from: date)))"81 return sanitize(truncate(stem, toBytes: maxNameBytes - ext.utf8.count - suffix.utf8.count) + suffix + ext)82 }83}8485public enum PathSafety {86 public struct Violation: Error, Sendable { public let path: String }87 /// A single path component that can be appended to a directory without leaving it.88 public static func isSafeComponent(_ c: String) -> Bool {89 !c.isEmpty && c != "." && c != ".." && !c.contains("/") && !c.contains("\0") && c.utf8.count <= NameRules.maxNameBytes90 }91 /// `base/component`, refusing anything that would land outside `base` (after resolving symbolic links of what exists).92 public static func child(of base: URL, named component: String) throws -> URL {93 guard isSafeComponent(component) else { throw Violation(path: component) }94 let url = base.appendingPathComponent(component, isDirectory: false)95 guard contains(base, url) else { throw Violation(path: url.path) }96 return url97 }98 /// True when `url` is `base` or lies below it. Resolves the existing ancestors so a symbolic link cannot lead outside.99 public static func contains(_ base: URL, _ url: URL) -> Bool {100 let b = realPath(base), u = realPath(url)101 return u == b || u.hasPrefix(b.hasSuffix("/") ? b : b + "/")102 }103 /// realpath of the deepest existing ancestor, plus the remaining components (which may not exist yet).104 public static func realPath(_ url: URL) -> String {105 var existing = url.standardizedFileURL, rest: [String] = []106 while !FileManager.default.fileExists(atPath: existing.path), existing.path != "/" { rest.insert(existing.lastPathComponent, at: 0); existing.deleteLastPathComponent() }107 let resolved = existing.path.withCString { p -> String in108 guard let r = realpath(p, nil) else { return existing.path }109 defer { free(r) }110 return String(cString: r)111 }112 return rest.reduce(resolved) { ($0 == "/" ? "" : $0) + "/" + $1 }113 }114}115