SPB Git

Repository Public License

ShieldService.swift 21.3 KB 427 lines swift

1import Diagnostics2import Foundation3import NavigatorCore4import Persistence56// MARK: - Statistics78/// What Shield can honestly count for a site on a day.9///10/// WebKit applies content rule lists inside its networking code and gives the app **no callback** when a rule11/// blocks a request, strips a cookie or hides an element. There is therefore no true "trackers blocked"12/// number. These counters hold only what the web layer observes itself:13public struct ShieldCounters: Sendable, Hashable, Codable {14    /// Pop-up windows the web layer refused to open (it makes that decision, so the count is exact).15    public var popupsBlocked: Int16    /// Main-frame navigations the web layer saw change from `http://` to `https://` because of the upgrade17    /// rule (it compares the requested and the committed URL, so the count is exact for main frames only).18    public var httpsUpgrades: Int19    /// Sub-resources whose host is on an active block list and that the page reported as failed to load.20    /// This is an inference made by a script inside the page: it cannot tell a blocked request from one that21    /// failed for another reason, it misses requests that leave no trace in the page (fetch keep-alive,22    /// beacons, CSS-initiated loads), and a hostile page can inflate it. Shown as "likely blocked", never as fact.23    public var likelyBlockedRequests: Int2425    public init(popupsBlocked: Int = 0, httpsUpgrades: Int = 0, likelyBlockedRequests: Int = 0) {26        self.popupsBlocked = popupsBlocked; self.httpsUpgrades = httpsUpgrades; self.likelyBlockedRequests = likelyBlockedRequests27    }2829    public var isZero: Bool { popupsBlocked == 0 && httpsUpgrades == 0 && likelyBlockedRequests == 0 }3031    public static func + (lhs: Self, rhs: Self) -> Self {32        Self(popupsBlocked: lhs.popupsBlocked + rhs.popupsBlocked, httpsUpgrades: lhs.httpsUpgrades + rhs.httpsUpgrades,33             likelyBlockedRequests: lhs.likelyBlockedRequests + rhs.likelyBlockedRequests)34    }35}3637/// An exact event observed by the web layer.38public enum ShieldEvent: String, Sendable, Codable { case popupBlocked, httpsUpgraded }3940/// Body of the `shieldReport` message a page script may post (reporting protocol, see docs/SHIELD.md):41/// `{ "failedHosts": { "tracker.example": 3, … } }` — hosts of sub-resources that fired an `error` event or42/// show a zero-size `PerformanceResourceTiming` entry, with counts, since the previous report.43public struct ShieldPageReport: Sendable, Hashable, Codable {44    public var failedHosts: [String: Int]4546    public init(failedHosts: [String: Int]) { self.failedHosts = failedHosts }4748    public static let maximumHosts = 20049    public static let maximumCountPerHost = 50050}5152public struct ShieldDailyCounters: Sendable, Hashable {53    /// Calendar day, `yyyy-MM-dd` in the service's time zone.54    public var day: String55    public var counters: ShieldCounters56}5758// MARK: - User lists5960public struct ShieldUserList: Sendable, Hashable, Codable, Identifiable {61    public var id: UUID62    public var name: String63    public var isEnabled: Bool64    public var importedAt: Date65    /// The text as imported; parsed again at every compilation so parser fixes apply to existing lists.66    public var source: String6768    public init(id: UUID = UUID(), name: String, isEnabled: Bool = true, importedAt: Date, source: String) {69        self.id = id; self.name = name; self.isEnabled = isEnabled; self.importedAt = importedAt; self.source = source70    }71}7273public struct ShieldImportResult: Sendable, Hashable {74    /// `nil` when nothing usable was found: the list is not stored.75    public var list: ShieldUserList?76    public var acceptedLines: Int77    public var diagnostics: [ShieldListDiagnostic]78}7980public enum ShieldKeys {81    public static let settings = SettingKey<ShieldSettings>("shield.settings", default: ShieldSettings())82    public static let userLists = SettingKey<[ShieldUserList]>("shield.user_lists", default: [])83    static let statisticsPrefix = "shield.stats."84    static func statistics(profile: ProfileID, day: String) -> SettingKey<[String: ShieldCounters]> {85        SettingKey("\(statisticsPrefix)\(profile.string).\(day)", default: [:])86    }87}8889/// Shield: settings, user lists, rule-list generation and measurable statistics.90///91/// Settings and lists are global to the app. In a private (ghost) profile, "Shield off for this site" and all92/// statistics stay in memory and disappear with the session.93public actor ShieldService {94    public static let statisticsRetentionDays = 9095    /// Sites kept per profile and day; beyond it, events are added to the `other` bucket.96    public static let maximumSitesPerDay = 40097    public static let otherSitesBucket = "(other)"9899    private let database: NavigatorDatabase100    private let builtIn: ShieldList101    private let now: @Sendable () -> Date102    private let calendar: Calendar103104    private var ghostDisabledSites: [ProfileID: Set<String>] = [:]105    private var ghostCounters: [ProfileID: [String: [String: ShieldCounters]]] = [:]106    /// Counters not written yet: profile → day → site.107    private var pending: [ProfileID: [String: [String: ShieldCounters]]] = [:]108    private var pendingEvents = 0109    private var blockedCache: (signature: Int, domains: Set<String>)?110111    public init(database: NavigatorDatabase, builtIn: ShieldList = .builtIn, timeZone: TimeZone = .current,112                now: @escaping @Sendable () -> Date = { .now }) {113        self.database = database114        self.builtIn = builtIn115        self.now = now116        var calendar = Calendar(identifier: .gregorian)117        calendar.timeZone = timeZone118        self.calendar = calendar119    }120121    private func isGhost(_ profile: ProfileID) -> Bool { database.ghosts.contains(profile.raw) }122123    // MARK: Settings124125    public func settings() async throws -> ShieldSettings { try await database.settings.value(ShieldKeys.settings) }126127    public func update(_ settings: ShieldSettings) async throws {128        var cleaned = settings129        cleaned.disabledSites = Array(Set(settings.disabledSites.compactMap(ShieldDomain.normalize))).sorted()130        cleaned.httpAllowedSites = Array(Set(settings.httpAllowedSites.compactMap(ShieldDomain.normalize))).sorted()131        try await database.settings.set(ShieldKeys.settings, to: cleaned, at: now())132        blockedCache = nil133    }134135    /// Settings as they apply to a profile: for a private profile, with its in-memory site exceptions added.136    public func effectiveSettings(profile: ProfileID) async throws -> ShieldSettings {137        var settings = try await settings()138        if let extra = ghostDisabledSites[profile] {139            settings.disabledSites = Array(Set(settings.disabledSites).union(extra)).sorted()140        }141        return settings142    }143144    /// Whether Shield acts on pages of `site` (a host; its parent domains are checked too).145    public func isActive(onSite site: String, profile: ProfileID) async throws -> Bool {146        let settings = try await effectiveSettings(profile: profile)147        guard settings.isEnabled, let host = ShieldDomain.normalize(site) else { return settings.isEnabled }148        let disabled = Set(settings.disabledSites)149        return !ShieldDomain.selfAndParents(of: host).contains(where: disabled.contains)150    }151152    /// "Shield off for this site" / back on. Stored, except in a private profile where it lasts for the session.153    /// Throws `ShieldError.invalidSite` for something that is not a host name.154    public func setShield(enabled: Bool, onSite site: String, profile: ProfileID) async throws {155        guard let host = ShieldDomain.normalize(site) else { throw ShieldError.invalidSite }156        if isGhost(profile) {157            if enabled { ghostDisabledSites[profile]?.remove(host) } else { ghostDisabledSites[profile, default: []].insert(host) }158            return159        }160        try await requireStoredProfile(profile)161        var settings = try await settings()162        var sites = Set(settings.disabledSites)163        if enabled { sites.remove(host) } else { sites.insert(host) }164        settings.disabledSites = sites.sorted()165        try await update(settings)166    }167168    /// Remembers that the user accepted plain HTTP for a site after an upgrade failed (never stored for a169    /// private profile: there the web layer keeps the exception for the tab).170    public func allowHTTP(onSite site: String, profile: ProfileID) async throws {171        guard let host = ShieldDomain.normalize(site) else { throw ShieldError.invalidSite }172        guard !isGhost(profile) else { return }173        try await requireStoredProfile(profile)174        var settings = try await settings()175        settings.httpAllowedSites = Array(Set(settings.httpAllowedSites).union([host])).sorted()176        try await update(settings)177    }178179    /// Site exceptions and statistics name sites the user visited. They are only ever written for a profile180    /// that exists in storage: an event arriving late for a private session that already ended (its registry181    /// entry is gone) must not be mistaken for a normal profile's.182    private func requireStoredProfile(_ profile: ProfileID) async throws {183        guard try await database.profiles.profile(profile) != nil else { throw ShieldError.unknownProfile }184    }185186    // MARK: User lists187188    public func userLists() async throws -> [ShieldUserList] { try await database.settings.value(ShieldKeys.userLists) }189190    /// Parses and stores a list the user imported. Lines the parser does not support are reported, never guessed.191    public func importList(named name: String, text: String) async throws -> ShieldImportResult {192        let parsed = ShieldListParser.parse(text)193        guard parsed.acceptedLines > 0 else {194            return ShieldImportResult(list: nil, acceptedLines: 0, diagnostics: parsed.diagnostics)195        }196        let cleanedName = name.trimmingCharacters(in: .whitespacesAndNewlines)197        let title = cleanedName.isEmpty ? (parsed.list.title.isEmpty ? "Imported list" : parsed.list.title) : cleanedName198        let list = ShieldUserList(name: String(title.prefix(80)), importedAt: now(), source: text)199        var lists = try await userLists()200        lists.append(list)201        try await database.settings.set(ShieldKeys.userLists, to: lists, at: now())202        blockedCache = nil203        return ShieldImportResult(list: list, acceptedLines: parsed.acceptedLines, diagnostics: parsed.diagnostics)204    }205206    public func setUserList(_ id: UUID, enabled: Bool) async throws {207        var lists = try await userLists()208        guard let index = lists.firstIndex(where: { $0.id == id }) else { return }209        lists[index].isEnabled = enabled210        try await database.settings.set(ShieldKeys.userLists, to: lists, at: now())211        blockedCache = nil212    }213214    public func removeUserList(_ id: UUID) async throws {215        let lists = try await userLists().filter { $0.id != id }216        try await database.settings.set(ShieldKeys.userLists, to: lists, at: now())217        blockedCache = nil218    }219220    private func activeUserLists() async throws -> [ShieldList] {221        try await userLists().filter(\.isEnabled).map { ShieldListParser.parse($0.source).list }222    }223224    // MARK: Rule lists225226    /// The rule lists to install for a profile's web views.227    public func compile(profile: ProfileID) async throws -> ShieldCompilation {228        let settings = try await effectiveSettings(profile: profile)229        return ContentRuleListGenerator.compile(settings: settings, builtIn: builtIn, userLists: try await activeUserLists())230    }231232    /// Domains blocked by the active lists (categories that are switched on).233    public func blockedDomains() async throws -> Set<String> {234        let settings = try await settings()235        let lists = try await activeUserLists()236        var hasher = Hasher()237        hasher.combine(settings); hasher.combine(lists)238        let signature = hasher.finalize()239        if let blockedCache, blockedCache.signature == signature { return blockedCache.domains }240        var domains = Set<String>()241        if settings.isEnabled {242            let unblocked = Set(([builtIn] + lists).flatMap(\.unblocked))243            for entry in ([builtIn] + lists).flatMap(\.blocked) {244                switch entry.category {245                case .trackers where !settings.blockTrackers, .ads where !settings.blockAds: continue246                default: break247                }248                if !unblocked.contains(where: { ShieldDomain.host(entry.domain, isWithin: $0) || ShieldDomain.host($0, isWithin: entry.domain) }) {249                    domains.insert(entry.domain)250                }251            }252        }253        blockedCache = (signature, domains)254        return domains255    }256257    /// Whether a third-party request to `host` matches an active block rule.258    public func isListed(host: String) async throws -> Bool {259        guard let normalized = ShieldDomain.normalize(host) else { return false }260        let domains = try await blockedDomains()261        return ShieldDomain.selfAndParents(of: normalized).contains(where: domains.contains)262    }263264    // MARK: Statistics265266    func dayString(_ date: Date) -> String {267        let parts = calendar.dateComponents([.year, .month, .day], from: date)268        return String(format: "%04d-%02d-%02d", parts.year ?? 0, parts.month ?? 0, parts.day ?? 0)269    }270271    private func add(_ counters: ShieldCounters, site: String, profile: ProfileID) async {272        guard !counters.isZero else { return }273        // Statistics are keyed by the page's host; anything that is not a host name goes to the catch-all.274        let key = ShieldDomain.normalize(site) ?? Self.otherSitesBucket275        let day = dayString(now())276        if isGhost(profile) {277            ghostCounters[profile, default: [:]][day, default: [:]][key, default: ShieldCounters()] = (ghostCounters[profile]?[day]?[key] ?? ShieldCounters()) + counters278            return279        }280        pending[profile, default: [:]][day, default: [:]][key] = (pending[profile]?[day]?[key] ?? ShieldCounters()) + counters281        pendingEvents += 1282        if pendingEvents >= 25 { try? await flushStatistics() }283    }284285    /// Records an exact event observed by the web layer on a page of `site`.286    public func record(_ event: ShieldEvent, site: String, profile: ProfileID) async {287        switch event {288        case .popupBlocked: await add(ShieldCounters(popupsBlocked: 1), site: site, profile: profile)289        case .httpsUpgraded: await add(ShieldCounters(httpsUpgrades: 1), site: site, profile: profile)290        }291    }292293    /// Takes a report posted by the page script. Only hosts on an active block list are counted, counts are294    /// capped, and nothing is recorded when Shield is off for the site. Returns the number added to295    /// `likelyBlockedRequests`.296    @discardableResult297    public func ingest(_ report: ShieldPageReport, site: String, profile: ProfileID) async throws -> Int {298        guard try await isActive(onSite: site, profile: profile) else { return 0 }299        let domains = try await blockedDomains()300        let pageHost = ShieldDomain.normalize(site)301        var total = 0302        for (host, count) in report.failedHosts.sorted(by: { $0.key < $1.key }).prefix(ShieldPageReport.maximumHosts) {303            guard count > 0, let normalized = ShieldDomain.normalize(host),304                  let listed = ShieldDomain.selfAndParents(of: normalized).first(where: domains.contains) else { continue }305            // Rules only block third-party loads: a listed domain failing on one of its own pages was not306            // blocked by Shield.307            if let pageHost, ShieldDomain.host(pageHost, isWithin: listed) { continue }308            total += min(count, ShieldPageReport.maximumCountPerHost)309        }310        await add(ShieldCounters(likelyBlockedRequests: total), site: site, profile: profile)311        return total312    }313314    /// Writes pending counters. Called automatically every 25 events; call it when the app goes to the315    /// background and before quitting.316    public func flushStatistics() async throws {317        let batch = pending318        pending = [:]319        pendingEvents = 0320        for (profile, days) in batch {321            guard try await database.profiles.profile(profile) != nil else { continue }322            for (day, sites) in days {323                let key = ShieldKeys.statistics(profile: profile, day: day)324                var stored = try await database.settings.value(key)325                for (site, counters) in sites {326                    let bucket = stored[site] != nil || stored.count < Self.maximumSitesPerDay ? site : Self.otherSitesBucket327                    stored[bucket] = (stored[bucket] ?? ShieldCounters()) + counters328                }329                try await database.settings.set(key, to: stored, at: now())330            }331        }332    }333334    private func stored(profile: ProfileID, day: String) async throws -> [String: ShieldCounters] {335        if isGhost(profile) { return ghostCounters[profile]?[day] ?? [:] }336        var result = try await database.settings.value(ShieldKeys.statistics(profile: profile, day: day))337        for (site, counters) in pending[profile]?[day] ?? [:] { result[site] = (result[site] ?? ShieldCounters()) + counters }338        return result339    }340341    private func days(last count: Int) -> [String] {342        let today = now()343        return (0..<max(count, 1)).compactMap { calendar.date(byAdding: .day, value: -$0, to: today) }.map(dayString).reversed()344    }345346    /// Totals for a profile over the last `days` days (today included), for one site or all sites.347    public func counters(profile: ProfileID, site: String? = nil, days: Int = 7) async throws -> ShieldCounters {348        try await daily(profile: profile, site: site, days: days).reduce(ShieldCounters()) { $0 + $1.counters }349    }350351    /// One entry per day, oldest first, zero-filled.352    public func daily(profile: ProfileID, site: String? = nil, days: Int = 7) async throws -> [ShieldDailyCounters] {353        let host = site.flatMap(ShieldDomain.normalize)354        if site != nil, host == nil { return [] }355        var result: [ShieldDailyCounters] = []356        for day in self.days(last: days) {357            let sites = try await stored(profile: profile, day: day)358            let total = host.map { sites[$0] ?? ShieldCounters() } ?? sites.values.reduce(ShieldCounters(), +)359            result.append(ShieldDailyCounters(day: day, counters: total))360        }361        return result362    }363364    /// Sites with the most activity over the period, highest first (ties by name).365    public func topSites(profile: ProfileID, days: Int = 7, limit: Int = 20) async throws -> [(site: String, counters: ShieldCounters)] {366        var totals: [String: ShieldCounters] = [:]367        for day in self.days(last: days) {368            for (site, counters) in try await stored(profile: profile, day: day) { totals[site] = (totals[site] ?? ShieldCounters()) + counters }369        }370        func weight(_ counters: ShieldCounters) -> Int { counters.popupsBlocked + counters.httpsUpgrades + counters.likelyBlockedRequests }371        return totals.sorted { weight($0.value) != weight($1.value) ? weight($0.value) > weight($1.value) : $0.key < $1.key }372            .prefix(limit).map { (site: $0.key, counters: $0.value) }373    }374375    /// Deletes statistics: of one profile or all, for days inside `range` or all days. Statistics name the376    /// sites the user visited, so "clear history" clears them too (`DataControls` does it).377    @discardableResult378    public func clearStatistics(profile: ProfileID? = nil, range: DateInterval? = nil) async throws -> Int {379        func matches(_ day: String) -> Bool {380            guard let range else { return true }381            return day >= dayString(range.start) && day <= dayString(range.end.addingTimeInterval(-0.001))382        }383        for key in Array(pending.keys) where profile == nil || key == profile {384            pending[key] = pending[key]?.filter { !matches($0.key) }385        }386        for key in Array(ghostCounters.keys) where profile == nil || key == profile {387            ghostCounters[key] = ghostCounters[key]?.filter { !matches($0.key) }388        }389        var removed = 0390        for name in try await database.settings.allRaw().keys where name.hasPrefix(ShieldKeys.statisticsPrefix) {391            let parts = name.dropFirst(ShieldKeys.statisticsPrefix.count).split(separator: ".")392            guard parts.count == 2 else { continue }393            if let profile, String(parts[0]) != profile.string { continue }394            guard matches(String(parts[1])) else { continue }395            try await database.settings.remove(name)396            removed += 1397        }398        return removed399    }400401    /// Drops statistics older than the retention period. Call at launch.402    @discardableResult403    public func pruneStatistics() async throws -> Int {404        guard let cutoff = calendar.date(byAdding: .day, value: -Self.statisticsRetentionDays, to: now()) else { return 0 }405        let oldest = dayString(cutoff)406        var removed = 0407        for name in try await database.settings.allRaw().keys where name.hasPrefix(ShieldKeys.statisticsPrefix) {408            guard let day = name.split(separator: ".").last, String(day) < oldest else { continue }409            try await database.settings.remove(name)410            removed += 1411        }412        return removed413    }414415    /// Forgets everything kept in memory for a private profile.416    public func forgetGhost(profile: ProfileID) {417        ghostDisabledSites[profile] = nil418        ghostCounters[profile] = nil419    }420}421422public enum ShieldError: Error, Sendable, Equatable {423    case invalidSite424    /// The profile is neither stored nor a declared private profile.425    case unknownProfile426}427
Files main
Menu

Theme