SPB Git

Repository Public License

ContentRuleLists.swift 19.8 KB 370 lines swift

1import CryptoKit2import Foundation3import NavigatorCore45// MARK: - WebKit content-blocker rule format67/// One rule of a `WKContentRuleList`, exactly as WebKit's JSON format spells it.8public struct ContentRule: Sendable, Hashable, Codable {9    public struct Trigger: Sendable, Hashable, Codable {10        public var urlFilter: String11        public var ifDomain: [String]?12        public var unlessDomain: [String]?13        public var loadType: [String]?14        public var resourceType: [String]?1516        enum CodingKeys: String, CodingKey {17            case urlFilter = "url-filter", ifDomain = "if-domain", unlessDomain = "unless-domain"18            case loadType = "load-type", resourceType = "resource-type"19        }2021        public init(urlFilter: String, ifDomain: [String]? = nil, unlessDomain: [String]? = nil,22                    loadType: [String]? = nil, resourceType: [String]? = nil) {23            self.urlFilter = urlFilter; self.ifDomain = ifDomain; self.unlessDomain = unlessDomain24            self.loadType = loadType; self.resourceType = resourceType25        }26    }2728    public struct Action: Sendable, Hashable, Codable {29        public enum Kind: String, Sendable, Codable {30            case block31            case blockCookies = "block-cookies"32            case cssDisplayNone = "css-display-none"33            case ignorePreviousRules = "ignore-previous-rules"34            case makeHTTPS = "make-https"35        }36        public var type: Kind37        public var selector: String?3839        public init(type: Kind, selector: String? = nil) { self.type = type; self.selector = selector }40    }4142    public var trigger: Trigger43    public var action: Action4445    public init(trigger: Trigger, action: Action) { self.trigger = trigger; self.action = action }46}4748/// Checks a `url-filter` against the regular-expression subset WebKit content blockers accept.49///50/// WebKit compiles url-filters to finite automata and supports only: literal characters, `.`, character51/// classes and ranges `[a-z]` / `[^…]`, the quantifiers `*`, `+`, `?`, groups `( )`, `^` at the very start,52/// `$` at the very end, and `\` to escape a punctuation character. A pattern using anything else makes53/// WebKit reject the entire list, so this validator refuses: non-ASCII characters, alternation `|`, counted54/// repetition `{n,m}`, `(?…)` groups (look-around, non-capturing), escapes of letters or digits (`\d`, `\w`,55/// `\b`, back-references), anchors in the middle of the pattern, a quantifier with nothing to repeat, and56/// unbalanced groups or classes.57public enum ContentBlockerRegex {58    public static let maximumLength = 1_0245960    /// `nil` when the pattern is acceptable, else the reason it is not.61    public static func problem(in pattern: String) -> String? {62        guard !pattern.isEmpty else { return "empty pattern" }63        let scalars = Array(pattern.unicodeScalars)64        guard scalars.count <= maximumLength else { return "pattern longer than \(maximumLength) characters" }65        guard scalars.allSatisfy({ $0.isASCII && $0.value >= 0x20 && $0.value != 0x7F }) else { return "non-ASCII or control character" }66        var depth = 067        var index = 068        var canQuantify = false69        while index < scalars.count {70            let scalar = scalars[index]71            switch scalar {72            case "\\":73                guard index + 1 < scalars.count else { return "trailing backslash" }74                let next = scalars[index + 1]75                if CharacterSet.alphanumerics.contains(next) { return "unsupported escape \\\(next)" }76                index += 177                canQuantify = true78            case "[":79                var cursor = index + 180                if cursor < scalars.count, scalars[cursor] == "^" { cursor += 1 }81                var closed = false, empty = true82                while cursor < scalars.count {83                    if scalars[cursor] == "\\" {84                        guard cursor + 1 < scalars.count else { return "trailing backslash" }85                        if CharacterSet.alphanumerics.contains(scalars[cursor + 1]) { return "unsupported escape in character class" }86                        cursor += 2; empty = false87                        continue88                    }89                    if scalars[cursor] == "]" { closed = true; break }90                    if scalars[cursor] == "[" { return "nested character class" }91                    cursor += 1; empty = false92                }93                guard closed else { return "unterminated character class" }94                guard !empty else { return "empty character class" }95                index = cursor96                canQuantify = true97            case "]": return "unbalanced ]"98            case "(":99                if index + 1 < scalars.count, scalars[index + 1] == "?" { return "(?…) groups are not supported" }100                depth += 1101                canQuantify = false102            case ")":103                guard depth > 0 else { return "unbalanced )" }104                guard index > 0, scalars[index - 1] != "(" else { return "empty group" }105                depth -= 1106                canQuantify = true107            case "|": return "alternation (|) is not supported"108            case "{", "}": return "counted repetition ({n,m}) is not supported"109            case "*", "+", "?":110                guard canQuantify else { return "quantifier with nothing to repeat" }111                canQuantify = false112            case "^":113                guard index == 0 else { return "^ is only supported at the start" }114                canQuantify = false115            case "$":116                guard index == scalars.count - 1 else { return "$ is only supported at the end" }117                canQuantify = false118            default:119                canQuantify = true120            }121            index += 1122        }123        guard depth == 0 else { return "unbalanced (" }124        return nil125    }126127    /// Escapes text so it matches literally inside a url-filter.128    public static func escape(_ literal: String) -> String {129        var result = ""130        for character in literal {131            if "\\.[](){}*+?^$|".contains(character) { result.append("\\") }132            result.append(character)133        }134        return result135    }136137    /// The url-filter matching any URL whose host is `domain` or one of its subdomains, on any scheme.138    public static func hostFilter(for domain: String) -> String {139        "^[^:]+://+([^:/]+\\.)?" + escape(domain) + "[:/]"140    }141}142143// MARK: - Output144145/// One rule list ready for `WKContentRuleListStore.compileContentRuleList(forIdentifier:encodedContentRuleList:)`.146public struct ContentRuleList: Sendable, Hashable, Identifiable {147    public enum Kind: String, Sendable, Codable, CaseIterable { case https, cookies, trackers, ads, custom, cosmetic }148149    /// Stable identifier (`orix.shield.trackers.0`…). The web layer compiles under this name.150    public var identifier: String151    public var kind: Kind152    public var json: String153    public var ruleCount: Int154    /// SHA-256 of `json`, hex. Unchanged hash = the compiled list on disk is still valid.155    public var contentHash: String156157    public var id: String { identifier }158}159160public struct ShieldCompilation: Sendable, Hashable {161    /// Lists to install, in a stable order. Empty when Shield is off.162    public var lists: [ContentRuleList]163    /// Rules that were dropped and why (invalid selector, invalid site…). A dropped rule never blocks the rest.164    public var diagnostics: [String]165    public var totalRuleCount: Int { lists.reduce(0) { $0 + $1.ruleCount } }166    /// Identifiers in use: the web layer removes compiled lists whose identifier is not in this set.167    public var identifiers: Set<String> { Set(lists.map(\.identifier)) }168}169170/// What the user chose. Stored as one setting.171public struct ShieldSettings: Sendable, Hashable, Codable {172    public var isEnabled: Bool173    public var blockTrackers: Bool174    public var blockAds: Bool175    /// Adds a `block-cookies` rule for every third-party request. Off by default: it breaks embedded sign-in176    /// and payment frames on some sites, and WebKit applies its own tracking prevention regardless.177    public var blockThirdPartyCookies: Bool178    public var upgradeToHTTPS: Bool179    public var hideElements: Bool180    /// "Shield off for this site": nothing is blocked, hidden or upgraded on pages of these sites.181    public var disabledSites: [String]182    /// Sites the user chose to keep loading over HTTP after an upgrade failed.183    public var httpAllowedSites: [String]184185    public init(isEnabled: Bool = true, blockTrackers: Bool = true, blockAds: Bool = true, blockThirdPartyCookies: Bool = false,186                upgradeToHTTPS: Bool = true, hideElements: Bool = true, disabledSites: [String] = [], httpAllowedSites: [String] = []) {187        self.isEnabled = isEnabled; self.blockTrackers = blockTrackers; self.blockAds = blockAds188        self.blockThirdPartyCookies = blockThirdPartyCookies; self.upgradeToHTTPS = upgradeToHTTPS189        self.hideElements = hideElements; self.disabledSites = disabledSites; self.httpAllowedSites = httpAllowedSites190    }191192    // Tolerant decoding: a setting written by an older build without a newer field keeps working.193    public init(from decoder: any Decoder) throws {194        let container = try decoder.container(keyedBy: CodingKeys.self)195        let defaults = ShieldSettings()196        isEnabled = try container.decodeIfPresent(Bool.self, forKey: .isEnabled) ?? defaults.isEnabled197        blockTrackers = try container.decodeIfPresent(Bool.self, forKey: .blockTrackers) ?? defaults.blockTrackers198        blockAds = try container.decodeIfPresent(Bool.self, forKey: .blockAds) ?? defaults.blockAds199        blockThirdPartyCookies = try container.decodeIfPresent(Bool.self, forKey: .blockThirdPartyCookies) ?? defaults.blockThirdPartyCookies200        upgradeToHTTPS = try container.decodeIfPresent(Bool.self, forKey: .upgradeToHTTPS) ?? defaults.upgradeToHTTPS201        hideElements = try container.decodeIfPresent(Bool.self, forKey: .hideElements) ?? defaults.hideElements202        disabledSites = try container.decodeIfPresent([String].self, forKey: .disabledSites) ?? []203        httpAllowedSites = try container.decodeIfPresent([String].self, forKey: .httpAllowedSites) ?? []204    }205}206207// MARK: - Generator208209/// Turns Shield settings and lists into WebKit content rule lists (JSON strings). Nothing is compiled here.210///211/// Layout — one concern per list, because `ignore-previous-rules` only reaches back inside its own list:212/// - `orix.shield.https`: `make-https` for every `http://` URL, then exemptions for local hosts.213/// - `orix.shield.cookies`: `block-cookies` on third-party loads.214/// - `orix.shield.trackers.N`, `orix.shield.ads.N`, `orix.shield.custom.N`: one `block` rule per domain,215///   third-party loads only, `unless-domain` for the domain's own sites.216/// - `orix.shield.cosmetic.N`: `css-display-none` rules.217///218/// Every list ends with one `ignore-previous-rules` rule scoped by `if-domain` to the sites where the user219/// turned Shield off. A list never exceeds `maximumRulesPerList`; longer sets are split into numbered lists.220public enum ContentRuleListGenerator {221    /// WebKit's long-standing per-list limit. Newer WebKit versions are reported to accept more; that was not222    /// verified for this project, so the conservative value is used. Smaller lists also compile faster and a223    /// compile failure stays local to one list.224    public static let maximumRulesPerList = 50_000225    public static let identifierPrefix = "orix.shield."226227    /// Hosts that must keep working over plain HTTP: this machine, link-local names and private networks,228    /// where a certificate is usually impossible. Each is a url-filter for an `ignore-previous-rules` rule.229    static let localHTTPFilters: [String] = [230        "^http://localhost[:/]",231        "^http://[^/:]+\\.localhost[:/]",232        "^http://[^/:]+\\.local[:/]",233        "^http://[^/:]+\\.internal[:/]",234        "^http://[^/:.]+[:/]",                                   // single-label intranet hosts235        "^http://127\\.[0-9]+\\.[0-9]+\\.[0-9]+[:/]",236        "^http://10\\.[0-9]+\\.[0-9]+\\.[0-9]+[:/]",237        "^http://192\\.168\\.[0-9]+\\.[0-9]+[:/]",238        "^http://172\\.1[6-9]\\.[0-9]+\\.[0-9]+[:/]",239        "^http://172\\.2[0-9]\\.[0-9]+\\.[0-9]+[:/]",240        "^http://172\\.3[01]\\.[0-9]+\\.[0-9]+[:/]",241        "^http://169\\.254\\.[0-9]+\\.[0-9]+[:/]",242        "^http://\\[",                                           // IPv6 literals243    ]244245    public static func compile(settings: ShieldSettings, builtIn: ShieldList = .builtIn, userLists: [ShieldList] = [],246                               maximumRulesPerList: Int = maximumRulesPerList) -> ShieldCompilation {247        guard settings.isEnabled else { return ShieldCompilation(lists: [], diagnostics: []) }248        var diagnostics: [String] = []249        let limit = max(maximumRulesPerList, 2)250251        func sites(_ raw: [String], _ what: String) -> [String] {252            var seen = Set<String>(), result: [String] = []253            for entry in raw {254                guard let site = ShieldDomain.normalize(entry) else { diagnostics.append("\(what): invalid site “\(entry.prefix(80))” ignored"); continue }255                if seen.insert(site).inserted { result.append("*" + site) }256            }257            return result.sorted()258        }259        let disabled = sites(settings.disabledSites, "Shield off")260        let allowRule: ContentRule? = disabled.isEmpty ? nil261            : ContentRule(trigger: .init(urlFilter: ".*", ifDomain: disabled), action: .init(type: .ignorePreviousRules))262263        var lists: [ContentRuleList] = []264        func emit(_ kind: ContentRuleList.Kind, _ rules: [ContentRule], numbered: Bool) {265            guard !rules.isEmpty else { return }266            let room = limit - (allowRule == nil ? 0 : 1)267            var chunkIndex = 0268            var start = 0269            while start < rules.count {270                var chunk = Array(rules[start..<min(start + room, rules.count)])271                start += chunk.count272                if let allowRule { chunk.append(allowRule) }273                let bad = chunk.compactMap { rule in ContentBlockerRegex.problem(in: rule.trigger.urlFilter).map { "\(rule.trigger.urlFilter): \($0)" } }274                if !bad.isEmpty {275                    // Cannot happen with generated filters; if it ever does, drop the rules, never the list.276                    diagnostics.append(contentsOf: bad.prefix(20).map { "dropped rule with unsupported url-filter \($0)" })277                    chunk.removeAll { ContentBlockerRegex.problem(in: $0.trigger.urlFilter) != nil }278                }279                let identifier = identifierPrefix + kind.rawValue + (numbered ? ".\(chunkIndex)" : "")280                let json = encode(chunk)281                lists.append(ContentRuleList(identifier: identifier, kind: kind, json: json, ruleCount: chunk.count, contentHash: hash(json)))282                chunkIndex += 1283            }284        }285286        if settings.upgradeToHTTPS {287            let allowed = sites(settings.httpAllowedSites, "HTTP allowed")288            var rules = [ContentRule(trigger: .init(urlFilter: "^http://", unlessDomain: allowed.isEmpty ? nil : allowed),289                                     action: .init(type: .makeHTTPS))]290            rules += localHTTPFilters.map { ContentRule(trigger: .init(urlFilter: $0), action: .init(type: .ignorePreviousRules)) }291            emit(.https, rules, numbered: false)292        }293        if settings.blockThirdPartyCookies {294            emit(.cookies, [ContentRule(trigger: .init(urlFilter: ".*", loadType: ["third-party"]), action: .init(type: .blockCookies))],295                 numbered: false)296        }297298        // Domains: built-in first, then user lists; a domain keeps the first category it was seen with.299        let all = [builtIn] + userLists300        let unblocked = Set(all.flatMap(\.unblocked).compactMap(ShieldDomain.normalize))301        var byCategory: [ShieldCategory: [BlockedDomain]] = [:]302        var seen = Set<String>()303        for list in all {304            for entry in list.blocked {305                guard let domain = ShieldDomain.normalize(entry.domain) else {306                    diagnostics.append("invalid domain “\(entry.domain.prefix(80))” ignored"); continue307                }308                // An exception for a domain also lifts rules on its subdomains and on its parents' wildcards.309                guard !unblocked.contains(where: { ShieldDomain.host(domain, isWithin: $0) || ShieldDomain.host($0, isWithin: domain) }),310                      seen.insert(domain).inserted else { continue }311                byCategory[entry.category, default: []].append(BlockedDomain(domain: domain, category: entry.category,312                                                                             exceptOnSites: entry.exceptOnSites))313            }314        }315        func blockRules(_ category: ShieldCategory) -> [ContentRule] {316            (byCategory[category] ?? []).sorted { $0.domain < $1.domain }.map { entry in317                let exceptions = entry.exceptOnSites.compactMap(ShieldDomain.normalize).map { "*" + $0 }.sorted()318                return ContentRule(trigger: .init(urlFilter: ContentBlockerRegex.hostFilter(for: entry.domain),319                                                  unlessDomain: exceptions.isEmpty ? nil : exceptions, loadType: ["third-party"]),320                                   action: .init(type: .block))321            }322        }323        if settings.blockTrackers { emit(.trackers, blockRules(.trackers), numbered: true) }324        if settings.blockAds { emit(.ads, blockRules(.ads), numbered: true) }325        // Imported lists are the user's explicit choice: active whenever Shield is on.326        emit(.custom, blockRules(.custom), numbered: true)327328        if settings.hideElements {329            var rules: [ContentRule] = []330            var seenRules = Set<CosmeticRule>()331            for rule in all.flatMap(\.cosmetic) where seenRules.insert(rule).inserted {332                if let problem = CosmeticRule.validate(selector: rule.selector) {333                    diagnostics.append("cosmetic rule dropped (\(problem))"); continue334                }335                let selector = rule.selector.trimmingCharacters(in: .whitespaces)336                switch rule.scope {337                case .everywhere(let except):338                    let exceptions = sites(except, "cosmetic rule")339                    rules.append(ContentRule(trigger: .init(urlFilter: ".*", unlessDomain: exceptions.isEmpty ? nil : exceptions),340                                             action: .init(type: .cssDisplayNone, selector: selector)))341                case .only(let only):342                    let scoped = sites(only, "cosmetic rule")343                    guard !scoped.isEmpty else { diagnostics.append("cosmetic rule dropped (no valid site)"); continue }344                    rules.append(ContentRule(trigger: .init(urlFilter: ".*", ifDomain: scoped),345                                             action: .init(type: .cssDisplayNone, selector: selector)))346                }347            }348            emit(.cosmetic, rules, numbered: true)349        }350        return ShieldCompilation(lists: lists, diagnostics: diagnostics)351    }352353    static func encode(_ rules: [ContentRule]) -> String {354        let encoder = JSONEncoder()355        // Sorted keys: the same rules always give the same bytes, hence the same hash.356        encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]357        // The model is plain strings and arrays: encoding cannot fail.358        return (try? encoder.encode(rules)).map { String(decoding: $0, as: UTF8.self) } ?? "[]"359    }360361    static func hash(_ json: String) -> String {362        SHA256.hash(data: Data(json.utf8)).map { String(format: "%02x", $0) }.joined()363    }364365    /// Decodes a generated list back into rules (tests, diagnostics screens).366    public static func decode(_ json: String) throws -> [ContentRule] {367        try JSONDecoder().decode([ContentRule].self, from: Data(json.utf8))368    }369}370
Files main
Menu

Theme