SPB Git

Repository Public License

URLHygiene.swift 14.6 KB 290 lines swift

1import Foundation2import NavigatorCore3import Persistence45public enum PrivacySettings {6    /// Remove known tracking parameters from links the user copies or shares. Off by default (opt-in).7    public static let stripTrackingParameters = SettingKey<Bool>("privacy.strip_tracking_parameters", default: false)8}910// MARK: - Tracking parameters1112/// Removes well-known tracking parameters from a URL the user copies or shares. Never applied to navigation:13/// the page the user is on keeps its URL; only the copy handed to the pasteboard or the share sheet is cleaned.14public enum TrackingParameterStripper {15    /// Parameters removed whatever the site.16    public static let exactNames: Set<String> = [17        // Google Ads / Analytics18        "gclid", "gclsrc", "dclid", "gbraid", "wbraid", "gad_source", "_ga", "_gl", "srsltid",19        // Meta20        "fbclid", "igshid", "igsh", "mibextid",21        // Microsoft, Twitter/X, TikTok, LinkedIn, Yandex, others22        "msclkid", "twclid", "ttclid", "li_fat_id", "yclid", "ysclid", "rb_clickid", "s_cid", "wickedid", "oly_anon_id", "oly_enc_id",23        // E-mail and marketing tools24        "mc_cid", "mc_eid", "_hsenc", "_hsmi", "__hssc", "__hstc", "__hsfp", "hsctatracking", "mkt_tok", "vero_id", "vero_conv",25        "_openstat", "ml_subscriber", "ml_subscriber_hash", "oft_id", "oft_k", "oft_lk", "oft_d", "oft_c", "oft_ck", "oft_ids", "oft_sk",26        "_branch_match_id", "_bta_tid", "_bta_c", "trk_contact", "trk_msg", "trk_module", "trk_sid", "si_campaign",27    ]2829    /// Parameters removed by prefix.30    public static let prefixes: [String] = ["utm_", "pk_", "piwik_", "mtm_", "matomo_", "hsa_", "stm_"]3132    /// Whether a query parameter name is a known tracking parameter (case-insensitive).33    public static func isTracking(_ name: String) -> Bool {34        let lowered = name.lowercased()35        return exactNames.contains(lowered) || prefixes.contains { lowered.hasPrefix($0) }36    }3738    /// The URL without its tracking parameters, and the names removed. Everything else is left byte for byte:39    /// order, encoding and empty values of the other parameters, the path and the fragment. Only `http` and40    /// `https` URLs are touched.41    public static func strip(_ url: URL) -> (url: URL, removed: [String]) {42        guard let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https",43              var components = URLComponents(url: url, resolvingAgainstBaseURL: false),44              let query = components.percentEncodedQuery, !query.isEmpty else { return (url, []) }45        var kept: [Substring] = []46        var removed: [String] = []47        // Split by hand: `URLQueryItem` would re-encode the values that stay.48        for pair in query.split(separator: "&", omittingEmptySubsequences: false) {49            let rawName = pair.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false).first.map(String.init) ?? ""50            let name = rawName.removingPercentEncoding ?? rawName51            if !name.isEmpty, isTracking(name) { removed.append(name) } else { kept.append(pair) }52        }53        guard !removed.isEmpty else { return (url, []) }54        components.percentEncodedQuery = kept.isEmpty ? nil : kept.joined(separator: "&")55        return (components.url ?? url, removed)56    }5758    /// Applies the user's setting: the cleaned URL when the option is on, the URL itself otherwise.59    public static func urlForSharing(_ url: URL, database: NavigatorDatabase) async -> URL {60        let enabled = (try? await database.settings.value(PrivacySettings.stripTrackingParameters)) ?? false61        return enabled ? strip(url).url : url62    }63}6465// MARK: - Punycode6667/// RFC 3492 decoder, for showing and inspecting internationalised host names. Decoding only: Foundation68/// already encodes (`URLComponents.encodedHost`).69public enum Punycode {70    private static let base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700, initialBias = 72, initialN = 1287172    private static func adapt(_ delta: Int, _ count: Int, first: Bool) -> Int {73        var delta = first ? delta / damp : delta / 274        delta += delta / count75        var k = 076        while delta > ((base - tMin) * tMax) / 2 {77            delta /= base - tMin78            k += base79        }80        return k + (base - tMin + 1) * delta / (delta + skew)81    }8283    /// Decodes the part after `xn--`. `nil` for invalid input (bad digit, overflow, invalid code point).84    public static func decode(_ input: String) -> String? {85        let bytes = Array(input.utf8)86        guard bytes.allSatisfy({ $0 < 0x80 }) else { return nil }87        var output: [UInt32] = []88        var start = 089        if let delimiter = bytes.lastIndex(of: 0x2D) {90            output = bytes[..<delimiter].map(UInt32.init)91            start = delimiter + 192        }93        var n = initialN, i = 0, bias = initialBias94        var index = start95        while index < bytes.count {96            let oldI = i97            var weight = 198            var k = base99            while true {100                guard index < bytes.count else { return nil }101                let byte = bytes[index]102                index += 1103                let digit: Int104                switch byte {105                case 0x30...0x39: digit = Int(byte) - 0x30 + 26106                case 0x41...0x5A: digit = Int(byte) - 0x41107                case 0x61...0x7A: digit = Int(byte) - 0x61108                default: return nil109                }110                guard digit <= (Int(Int32.max) - i) / weight else { return nil }111                i += digit * weight112                let threshold = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias)113                if digit < threshold { break }114                guard weight <= Int(Int32.max) / (base - threshold) else { return nil }115                weight *= base - threshold116                k += base117            }118            bias = adapt(i - oldI, output.count + 1, first: oldI == 0)119            guard i / (output.count + 1) <= Int(Int32.max) - n else { return nil }120            n += i / (output.count + 1)121            i %= output.count + 1122            guard n <= 0x10FFFF, Unicode.Scalar(UInt32(n)) != nil else { return nil }123            output.insert(UInt32(n), at: i)124            i += 1125        }126        var result = String.UnicodeScalarView()127        for value in output {128            guard let scalar = Unicode.Scalar(value) else { return nil }129            result.append(scalar)130        }131        return String(result)132    }133134    /// Unicode form of a host: every `xn--` label decoded. Labels that do not decode are left as they are.135    public static func unicodeHost(_ host: String) -> String {136        host.split(separator: ".", omittingEmptySubsequences: false).map { label -> String in137            let lowered = label.lowercased()138            guard lowered.hasPrefix("xn--"), let decoded = decode(String(lowered.dropFirst(4))) else { return String(label) }139            return decoded140        }.joined(separator: ".")141    }142}143144// MARK: - Homograph heuristic145146/// Writing systems the heuristic tells apart. Coarse on purpose: block ranges, not the full Unicode script147/// property (which the Swift standard library does not expose).148public enum HostScript: String, Sendable, Codable, CaseIterable {149    case latin, greek, cyrillic, armenian, hebrew, arabic, devanagari, thai, georgian, hangul, hiragana, katakana, han, bopomofo150    /// Any other letter.151    case other152153    static func of(_ scalar: Unicode.Scalar) -> HostScript? {154        switch scalar.value {155        case 0x30...0x39, 0x2D, 0x2E, 0x5F: return nil   // digits, hyphen, dot: common to every script156        case 0x41...0x5A, 0x61...0x7A, 0xC0...0x24F, 0x1E00...0x1EFF: return .latin157        case 0x370...0x3FF, 0x1F00...0x1FFF: return .greek158        case 0x400...0x52F, 0x1C80...0x1C8F, 0x2DE0...0x2DFF, 0xA640...0xA69F: return .cyrillic159        case 0x530...0x58F: return .armenian160        case 0x590...0x5FF: return .hebrew161        case 0x600...0x6FF, 0x750...0x77F, 0x8A0...0x8FF: return .arabic162        case 0x900...0x97F: return .devanagari163        case 0xE00...0xE7F: return .thai164        case 0x10A0...0x10FF: return .georgian165        case 0x1100...0x11FF, 0x3130...0x318F, 0xAC00...0xD7AF: return .hangul166        case 0x3040...0x309F: return .hiragana167        case 0x30A0...0x30FF, 0x31F0...0x31FF: return .katakana168        case 0x3400...0x4DBF, 0x4E00...0x9FFF, 0x20000...0x2A6DF, 0x3005, 0x3007: return .han169        case 0x3100...0x312F: return .bopomofo170        default: return scalar.properties.isAlphabetic ? .other : nil171        }172    }173}174175public enum HostWarning: Sendable, Hashable {176    /// A label mixes scripts that are not normally written together (e.g. Latin and Cyrillic).177    case mixedScripts(label: String, scripts: [HostScript])178    /// A label is written entirely in Cyrillic or Greek letters that look like Latin letters, under a Latin179    /// top-level domain: it can imitate a Latin name exactly.180    case latinLookalike(label: String)181    /// Invisible or direction-changing characters (zero-width, bidi controls, soft hyphen…).182    case invisibleCharacters183    /// An `xn--` label that is not valid punycode.184    case malformedPunycode(label: String)185}186187public struct HostAssessment: Sendable, Hashable {188    /// ASCII form (punycode), lowercase.189    public var asciiHost: String190    /// Unicode form.191    public var unicodeHost: String192    public var warnings: [HostWarning]193194    public var isSuspicious: Bool { !warnings.isEmpty }195    /// What the address bar should show: the Unicode form when nothing is suspicious, the punycode form when196    /// something is, so a look-alike cannot pass for the real name.197    public var displayHost: String { isSuspicious ? asciiHost : unicodeHost }198}199200/// Heuristic warning for internationalised host names that may imitate another name (IDN homograph attack).201///202/// It is a heuristic: it flags the well-known patterns — scripts mixed inside one label, whole labels made of203/// Latin look-alikes from Cyrillic or Greek, invisible characters — and has no table of every confusable pair204/// in Unicode. A name can pass it and still be deceptive (e.g. `rn` for `m`, or an all-Cyrillic name under a205/// Cyrillic top-level domain that resembles a brand).206public enum HomographDetector {207    /// Script combinations that are normal inside one label.208    private static let allowedCombinations: [Set<HostScript>] = [209        [.latin, .han, .hiragana, .katakana],   // Japanese210        [.latin, .han, .hangul],                // Korean211        [.latin, .han, .bopomofo],              // Chinese212    ]213214    /// Cyrillic and Greek letters that are (near-)identical to a lowercase Latin letter. Kept strict on215    /// purpose: letters that merely resemble a Latin one (к, м, н, т, в…) are left out, otherwise ordinary216    /// words would be flagged.217    private static let cyrillicLookalikes: Set<Unicode.Scalar> = [218        "а", "с", "е", "о", "р", "х", "у", "ѕ", "і", "ј", "һ", "ԁ", "ԛ", "ԝ", "ӏ", "ѵ",219    ]220    private static let greekLookalikes: Set<Unicode.Scalar> = ["ο", "ν", "α", "ρ", "ι", "κ", "τ", "υ", "χ"]221    /// Country-code domains where a name written entirely in that script is the norm, not an imitation.222    private static let cyrillicTLDs: Set<String> = ["ru", "su", "by", "bg", "kz", "ua", "rs", "mk", "mn", "kg", "tj"]223    private static let greekTLDs: Set<String> = ["gr", "cy"]224225    private static func isInvisible(_ scalar: Unicode.Scalar) -> Bool {226        switch scalar.value {227        case 0xAD, 0x34F, 0x61C, 0x115F, 0x1160, 0x17B4, 0x17B5, 0x180B...0x180E, 0x200B...0x200F, 0x202A...0x202E,228             0x2060...0x2064, 0x2066...0x206F, 0x3164, 0xFE00...0xFE0F, 0xFEFF, 0xFFA0, 0xE0000...0xE0FFF:229            return true230        default:231            return scalar.properties.generalCategory == .format || scalar.properties.generalCategory == .control232        }233    }234235    /// Assesses a host as typed, pasted or taken from a URL (Unicode or punycode, any case).236    public static func assess(host: String) -> HostAssessment {237        let trimmed = host.trimmingCharacters(in: .whitespaces)238        var warnings: [HostWarning] = []239        var asciiLabels: [String] = [], unicodeLabels: [String] = []240        var sawInvisible = false241242        for rawLabel in trimmed.split(separator: ".", omittingEmptySubsequences: false) {243            let label = String(rawLabel)244            let lowered = label.lowercased()245            var unicode = lowered246            if lowered.hasPrefix("xn--") {247                if let decoded = Punycode.decode(String(lowered.dropFirst(4))), !decoded.isEmpty { unicode = decoded } else {248                    warnings.append(.malformedPunycode(label: lowered))249                }250                asciiLabels.append(lowered)251            } else if lowered.unicodeScalars.allSatisfy(\.isASCII) {252                asciiLabels.append(lowered)253            } else {254                var components = URLComponents()255                components.scheme = "https"256                components.host = lowered257                asciiLabels.append(components.encodedHost?.lowercased() ?? lowered)258            }259            unicodeLabels.append(unicode)260            if unicode.unicodeScalars.contains(where: isInvisible) { sawInvisible = true }261            let scripts = Set(unicode.unicodeScalars.compactMap(HostScript.of))262            if scripts.count > 1, !allowedCombinations.contains(where: scripts.isSubset(of:)) {263                warnings.append(.mixedScripts(label: unicode, scripts: scripts.sorted { $0.rawValue < $1.rawValue }))264            }265        }266        if sawInvisible { warnings.append(.invisibleCharacters) }267268        // Whole-label look-alikes only matter under a Latin (ASCII) top-level domain: `xn--80ak6aa92e.com`.269        if let tld = unicodeLabels.last, tld.unicodeScalars.allSatisfy(\.isASCII), unicodeLabels.count >= 2 {270            for label in unicodeLabels.dropLast() {271                let letters = label.unicodeScalars.filter { HostScript.of($0) != nil }272                guard !letters.isEmpty else { continue }273                let scripts = Set(letters.compactMap(HostScript.of))274                if scripts == [.cyrillic], !cyrillicTLDs.contains(tld), letters.allSatisfy(cyrillicLookalikes.contains) {275                    warnings.append(.latinLookalike(label: label))276                }277                if scripts == [.greek], !greekTLDs.contains(tld), letters.allSatisfy(greekLookalikes.contains) {278                    warnings.append(.latinLookalike(label: label))279                }280            }281        }282        return HostAssessment(asciiHost: asciiLabels.joined(separator: "."), unicodeHost: unicodeLabels.joined(separator: "."),283                              warnings: warnings)284    }285286    public static func assess(_ url: URL) -> HostAssessment? {287        URLComponents(url: url, resolvingAgainstBaseURL: true)?.encodedHost.map(assess(host:))288    }289}290
Files main
Menu

Theme