SPB Git

Repository Public

BlockerRules.swift 9.3 KB 176 lines swift

1import Foundation23/// Builds `WKContentRuleList` JSON from plain domain lists.4/// Only network-level blocking of third-party requests is generated: no cosmetic filtering and no script injection.5enum BlockerRuleBuilder {6    /// WebKit refuses rule lists above 150 000 rules; staying well below keeps compilation fast.7    static let maxDomains = 40_00089    struct Options: Equatable, Sendable {10        var trackers = true11        var ads = true12        var extraDomains: [String] = []13        /// Hosts (and their sub-domains) on which nothing is blocked.14        var disabledHosts: [String] = []15    }1617    static func domains(for options: Options) -> [String] {18        var set = Set<String>()19        if options.trackers { set.formUnion(BuiltInBlockList.trackers) }20        if options.ads { set.formUnion(BuiltInBlockList.ads) }21        set.formUnion(options.extraDomains.filter(isValidDomain))22        return Array(set.sorted().prefix(maxDomains))23    }2425    static func rules(for options: Options) -> [[String: Any]] {26        var rules: [[String: Any]] = domains(for: options).map { domain in27            [28                "trigger": ["url-filter": urlFilter(forDomain: domain), "load-type": ["third-party"]] as [String: Any],29                "action": ["type": "block"],30            ]31        }32        let disabled = options.disabledHosts.map { $0.lowercased() }.filter(isValidDomain).sorted()33        if !disabled.isEmpty {34            // Later rules win: on these sites every earlier rule is ignored.35            rules.append([36                "trigger": ["url-filter": ".*", "if-top-url": disabled.map(urlFilter(forDomain:))] as [String: Any],37                "action": ["type": "ignore-previous-rules"],38            ])39        }40        return rules41    }4243    static func json(for options: Options) -> String {44        let rules = rules(for: options)45        guard !rules.isEmpty, let data = try? JSONSerialization.data(withJSONObject: rules, options: [.sortedKeys]),46              let text = String(data: data, encoding: .utf8) else { return "[]" }47        return text48    }4950    /// A stable identifier for a given rule set, so an unchanged list is not recompiled.51    static func identifier(for options: Options) -> String {52        var hash: UInt64 = 0xcbf29ce48422232553        for byte in json(for: options).utf8 { hash = (hash ^ UInt64(byte)) &* 0x100000001b3 }54        return "spbrowser-blocker-" + String(hash, radix: 16)55    }5657    /// Matches the domain itself and any sub-domain, over http(s) or ws(s), anchored so "notexample.com" is not caught.58    static func urlFilter(forDomain domain: String) -> String {59        "^[^:]+://+([^:/]+\\.)?" + NSRegularExpression.escapedPattern(for: domain.lowercased()) + "[:/]"60    }6162    static func isValidDomain(_ domain: String) -> Bool {63        let d = domain.lowercased()64        guard d.count <= 253, d.unicodeScalars.allSatisfy({ $0.isASCII }) else { return false }65        return AddressResolver.classify(host: d) == .remote66    }67}6869/// Extracts blockable domains from the two common list formats:70/// hosts files (`0.0.0.0 tracker.example`) and Adblock-style domain rules (`||tracker.example^`).71/// Anything more specific (paths, cosmetic rules, exceptions, regexes) is ignored rather than approximated.72enum BlockListParser {73    static func domains(from text: String) -> [String] {74        var result = Set<String>()75        for rawLine in text.split(whereSeparator: \.isNewline) {76            var line = rawLine.trimmingCharacters(in: .whitespaces)77            if line.isEmpty || line.hasPrefix("!") || line.hasPrefix("#") || line.hasPrefix("[") || line.hasPrefix("@@") { continue }78            if line.contains("##") || line.contains("#@#") || line.contains("#?#") { continue }7980            if line.hasPrefix("||") {81                line.removeFirst(2)82                var optionsPart = ""83                if let dollar = line.firstIndex(of: "$") {84                    optionsPart = String(line[line.index(after: dollar)...])85                    line = String(line[..<dollar])86                }87                guard line.hasSuffix("^") else { continue }88                line.removeLast()89                // Only plain "block this domain" rules; skip rules narrowed to resource types or specific sites.90                let options = optionsPart.split(separator: ",").map { $0.lowercased() }91                guard options.allSatisfy({ $0 == "third-party" || $0 == "3p" || $0 == "all" }) else { continue }92                if BlockerRuleBuilder.isValidDomain(line) { result.insert(line.lowercased()) }93                continue94            }9596            if let hash = line.firstIndex(of: "#") { line = String(line[..<hash]).trimmingCharacters(in: .whitespaces) }97            let fields = line.split(whereSeparator: { $0 == " " || $0 == "\t" }).map(String.init)98            let candidate: String?99            switch fields.count {100            case 1: candidate = fields[0]101            case 2 where ["0.0.0.0", "127.0.0.1", "::", "::1"].contains(fields[0]): candidate = fields[1]102            default: candidate = nil103            }104            if let candidate, candidate != "localhost", BlockerRuleBuilder.isValidDomain(candidate) {105                result.insert(candidate.lowercased())106            }107        }108        return result.sorted()109    }110}111112/// A user-configured remote list. It is only fetched when the user asks for an update.113struct BlockListSource: Codable, Equatable, Identifiable, Sendable {114    var id: UUID = UUID()115    var name: String116    var url: String117    var enabled = true118    var lastUpdated: Date?119    var domainCount = 0120121    /// Lists offered as one-click additions. Both are published for use in blockers; fetching is always user-initiated.122    static let suggested: [BlockListSource] = [123        BlockListSource(name: "Peter Lowe's Ad and tracking server list",124                        url: "https://pgl.yoyo.org/adservers/serverlist.php?hostformat=hosts&showintro=0&mimetype=plaintext"),125        BlockListSource(name: "EasyPrivacy (domain rules only)", url: "https://easylist.to/easylist/easyprivacy.txt"),126    ]127128    var isFetchable: Bool {129        guard let u = URL(string: url), u.scheme?.lowercased() == "https", !(u.host ?? "").isEmpty else { return false }130        return true131    }132}133134/// Persisted state of the remote lists: their configuration and the domains extracted at the last update.135struct BlockListState: Codable, Equatable, Sendable {136    var sources: [BlockListSource] = []137    var domainsBySource: [String: [String]] = [:]138139    var activeDomains: [String] {140        sources.filter(\.enabled).flatMap { domainsBySource[$0.id.uuidString] ?? [] }141    }142}143144/// A short, hand-maintained list of widely known third-party tracking and advertising hosts.145/// It gives useful protection out of the box without any network fetch; larger lists are opt-in.146enum BuiltInBlockList {147    static let trackers: [String] = [148        "google-analytics.com", "googletagmanager.com", "googletagservices.com", "analytics.google.com",149        "stats.g.doubleclick.net", "connect.facebook.net", "pixel.facebook.com", "analytics.tiktok.com",150        "analytics.twitter.com", "ads-twitter.com", "static.ads-twitter.com", "bat.bing.com", "clarity.ms",151        "hotjar.com", "hotjar.io", "mixpanel.com", "segment.io", "segment.com", "cdn.segment.com", "amplitude.com",152        "cdn.amplitude.com", "fullstory.com", "mouseflow.com", "crazyegg.com", "optimizely.com", "newrelic.com",153        "nr-data.net", "scorecardresearch.com", "quantserve.com", "quantcount.com", "chartbeat.com", "chartbeat.net",154        "parsely.com", "parse.ly", "branch.io", "app.link", "appsflyer.com", "adjust.com", "kochava.com",155        "bugsnag.com", "matomo.cloud", "statcounter.com", "histats.com", "yandex.ru", "mc.yandex.ru",156        "snap.licdn.com", "px.ads.linkedin.com", "ct.pinterest.com", "sc-static.net", "tr.snapchat.com",157        "demdex.net", "omtrdc.net", "2o7.net", "everesttech.net", "bluekai.com", "krxd.net", "exelator.com",158        "rlcdn.com", "agkn.com", "adsrvr.org", "mathtag.com", "crwdcntrl.net", "tapad.com", "id5-sync.com",159        "liveintent.com", "liadm.com", "permutive.com", "permutive.app", "heapanalytics.com", "heap.io",160        "inspectlet.com", "luckyorange.com", "smartlook.com", "logrocket.com", "lr-ingest.io", "sentry-cdn.com",161        "cloudflareinsights.com", "plausible.io", "onesignal.com", "pushcrew.com", "braze.com", "iterable.com",162    ]163164    static let ads: [String] = [165        "doubleclick.net", "googlesyndication.com", "googleadservices.com", "adservice.google.com", "2mdn.net",166        "adnxs.com", "adsystem.com", "amazon-adsystem.com", "advertising.com", "adform.net", "adroll.com",167        "criteo.com", "criteo.net", "outbrain.com", "taboola.com", "rubiconproject.com", "pubmatic.com",168        "openx.net", "casalemedia.com", "indexww.com", "smartadserver.com", "moatads.com", "adsafeprotected.com",169        "doubleverify.com", "teads.tv", "sharethrough.com", "triplelift.com", "3lift.com", "yieldmo.com",170        "bidswitch.net", "contextweb.com", "lijit.com", "sovrn.com", "gumgum.com", "media.net", "zedo.com",171        "revcontent.com", "mgid.com", "popads.net", "propellerads.com", "adcolony.com", "applovin.com",172        "unityads.unity3d.com", "inmobi.com", "smaato.net", "spotxchange.com", "spotx.tv", "springserve.com",173        "serving-sys.com", "flashtalking.com", "adtechus.com", "yieldlab.net", "improvedigital.com", "33across.com",174    ]175}176
Files main
Menu

Theme