SPB Git

Repository Public

URLSafety.swift 9.3 KB 182 lines swift

1import Foundation23/// Decision taken for a navigation, before WebKit is allowed to proceed.4enum NavigationVerdict: Equatable, Sendable {5    case allow6    /// Not a web scheme: may be handed to the system, but only after the user confirms.7    case external8    case block(String)9}1011enum URLSafety {12    static let webSchemes: Set<String> = ["http", "https", "about", "blob"]1314    /// - Parameters:15    ///   - isMainFrame: `false` for sub-frame navigations.16    ///   - typedByUser: the user typed or pasted the address, or chose a bookmark/history entry.17    ///   - sourceIsFile: the page requesting the navigation is itself a local file.18    static func verdict(for url: URL, isMainFrame: Bool, typedByUser: Bool, sourceIsFile: Bool = false) -> NavigationVerdict {19        guard let scheme = url.scheme?.lowercased(), !scheme.isEmpty else { return .block("missing scheme") }20        if webSchemes.contains(scheme) { return .allow }21        switch scheme {22        case SPSearchURL.scheme:23            // The app's own results page: only as a tab's main document, and only when the user asked for it.24            return isMainFrame && typedByUser ? .allow : .block("search pages are opened by the user only")25        case "javascript", "vbscript":26            return .block("script URLs are never navigated to")27        case "data":28            // Top-level data: navigations are a classic phishing vector; sub-frames (images, inline documents) are fine.29            return isMainFrame ? .block("top-level data: URLs are blocked") : .allow30        case "file":31            // Web content must not be able to open local files; the user (or another local file) may.32            return (typedByUser || sourceIsFile) ? .allow : .block("web pages cannot open local files")33        default:34            return isMainFrame ? .external : .block("sub-frames cannot open external applications")35        }36    }37}3839/// Something worth telling the user about an address. None of these prove a page is malicious;40/// they are signals surfaced in the address bar and the page-information panel.41enum URLWarning: String, Equatable, Sendable, CaseIterable {42    case embeddedCredentials43    case punycodeHost44    case mixedScriptHost45    case ipAddressHost46    case insecureTransport47    case excessiveSubdomains48    case nonStandardPort4950    var message: String {51        switch self {52        case .embeddedCredentials: return L("The address contains a user name before the site name, a common way to disguise the real destination.")53        case .punycodeHost: return L("The site name uses international characters that can imitate another name.")54        case .mixedScriptHost: return L("The site name mixes several alphabets, which can imitate another name.")55        case .ipAddressHost: return L("The site is identified by a numeric address instead of a name.")56        case .insecureTransport: return L("The connection is not encrypted. Do not enter passwords or card numbers.")57        case .excessiveSubdomains: return L("The address has many sub-levels; check the highlighted part to see the real site.")58        case .nonStandardPort: return L("The site uses an unusual port.")59        }60    }6162    /// Warnings that justify an explicit confirmation before following a link.63    var isDeceptive: Bool { self == .embeddedCredentials || self == .mixedScriptHost }64}6566enum URLInspector {67    static func warnings(for url: URL) -> [URLWarning] {68        guard let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https" else { return [] }69        var result: [URLWarning] = []70        let host = (url.host ?? "").lowercased()71        let kind = AddressResolver.classify(host: host)7273        if !(url.user ?? "").isEmpty || url.password != nil { result.append(.embeddedCredentials) }74        if host.split(separator: ".").contains(where: { $0.hasPrefix("xn--") }) { result.append(.punycodeHost) }75        if hasMixedScripts(host) { result.append(.mixedScriptHost) }76        let isIP = host.hasPrefix("[") || (host.split(separator: ".").count == 4 && host.allSatisfy { $0.isNumber || $0 == "." })77        if isIP && !isLoopback(host) { result.append(.ipAddressHost) }78        if scheme == "http" && kind != .local { result.append(.insecureTransport) }79        if !isIP && host.split(separator: ".").count >= 6 { result.append(.excessiveSubdomains) }80        if let port = url.port, kind != .local, ![80, 443, 8080, 8443].contains(port) { result.append(.nonStandardPort) }81        return result82    }8384    static func isLoopback(_ host: String) -> Bool {85        let h = host.lowercased()86        return h == "localhost" || h == "[::1]" || h == "::1" || h.hasPrefix("127.") || h.hasSuffix(".localhost")87    }8889    /// True when a single label mixes Latin letters with Cyrillic or Greek ones (the usual homograph trick).90    static func hasMixedScripts(_ host: String) -> Bool {91        for label in host.split(separator: ".") {92            var latin = false, other = false93            for scalar in label.unicodeScalars where scalar.properties.isAlphabetic {94                switch scalar.value {95                case 0x41...0x24F: latin = true96                case 0x370...0x3FF, 0x400...0x52F: other = true97                default: break98                }99            }100            if latin && other { return true }101        }102        return false103    }104105    /// Best-effort registrable domain ("example.co.uk" from "a.b.example.co.uk") used to emphasise106    /// the part of the address that identifies the site. Not a full Public Suffix List.107    static func registrableDomain(of host: String) -> String {108        let labels = host.lowercased().split(separator: ".").map(String.init)109        guard labels.count > 2 else { return host.lowercased() }110        if labels.allSatisfy({ $0.allSatisfy(\.isNumber) }) { return host }111        let secondLevel: Set<String> = ["co", "com", "org", "net", "gov", "gouv", "ac", "edu", "qc", "on", "bc", "ab", "or", "ne"]112        let tld = labels[labels.count - 1], sld = labels[labels.count - 2]113        let take = (tld.count == 2 && secondLevel.contains(sld)) ? 3 : 2114        return labels.suffix(take).joined(separator: ".")115    }116}117118enum DownloadRisk: Equatable, Sendable {119    case normal120    /// Can run code when opened (applications, installers, scripts).121    case executable122    /// May contain executables.123    case archive124}125126enum DownloadSafety {127    static let executableExtensions: Set<String> = [128        "app", "dmg", "pkg", "mpkg", "command", "tool", "sh", "zsh", "bash", "csh", "py", "rb", "pl", "php", "js",129        "jar", "scpt", "scptd", "applescript", "workflow", "action", "terminal", "inetloc", "webloc", "fileloc",130        "exe", "msi", "bat", "cmd", "com", "scr", "ps1", "vbs", "lnk", "dylib", "kext", "prefpane", "qlgenerator",131        "saver", "osax", "mobileconfig", "shortcut",132    ]133    static let archiveExtensions: Set<String> = ["zip", "tar", "gz", "tgz", "bz2", "xz", "7z", "rar", "iso", "xip", "cpgz", "zst"]134135    static func risk(forFilename name: String) -> DownloadRisk {136        let ext = (name as NSString).pathExtension.lowercased()137        if executableExtensions.contains(ext) { return .executable }138        if archiveExtensions.contains(ext) { return .archive }139        return .normal140    }141142    /// Produces a file name that is safe to create inside a directory: no path components, no control143    /// characters, no leading dot (hidden file), bounded length, never empty.144    static func sanitize(filename raw: String) -> String {145        var name = raw.precomposedStringWithCanonicalMapping146        name = name.replacingOccurrences(of: "\\", with: "/")147        name = name.split(separator: "/", omittingEmptySubsequences: true).last.map(String.init) ?? ""148        name = String(name.unicodeScalars.filter { scalar in149            !(scalar.value < 0x20 || scalar.value == 0x7F || scalar == ":" || (0x200B...0x200F).contains(scalar.value)150                || (0x202A...0x202E).contains(scalar.value) || (0x2066...0x2069).contains(scalar.value))151        }.map(Character.init))152        name = name.trimmingCharacters(in: .whitespaces)153        while name.hasPrefix(".") { name.removeFirst() }154        while name.hasSuffix(".") || name.hasSuffix(" ") { name.removeLast() }155        if name.isEmpty { return "download" }156        let limit = 200157        if name.utf8.count > limit {158            let ext = (name as NSString).pathExtension159            var stem = (name as NSString).deletingPathExtension160            let budget = limit - (ext.isEmpty ? 0 : ext.utf8.count + 1)161            while stem.utf8.count > max(budget, 1) { stem.removeLast() }162            name = ext.isEmpty || ext.utf8.count > 20 ? stem : stem + "." + ext163        }164        return name165    }166167    /// Returns a URL inside `directory` that does not collide with an existing file: "a.pdf", "a (2).pdf", …168    static func uniqueURL(in directory: URL, filename: String, exists: (URL) -> Bool = { FileManager.default.fileExists(atPath: $0.path) }) -> URL {169        let safe = sanitize(filename: filename)170        var candidate = directory.appendingPathComponent(safe, isDirectory: false)171        let ext = (safe as NSString).pathExtension172        let stem = (safe as NSString).deletingPathExtension173        var counter = 2174        while exists(candidate) && counter < 10_000 {175            let next = ext.isEmpty ? "\(stem) (\(counter))" : "\(stem) (\(counter)).\(ext)"176            candidate = directory.appendingPathComponent(next, isDirectory: false)177            counter += 1178        }179        return candidate180    }181}182
Files main
Menu

Theme