Cotton code
92 lines · 4.4 KB · SwiftRaw
// Trackers blocked by WebKit itself (DECISIONS.md question 7: "On iPhone, WebKit blocks them itself, and Sites never// sees an address"; CONTRACT.md Trackers row).//// The core answers `sites.trackers { key, id }` with `{ on, hosts[], ios_rules[] }`: `ios_rules` is Apple's content// blocker JSON, one third-party block per tracker host (`cotton-core/src/sites_trackers.txt`). It is compiled ONCE per// list into a `WKContentRuleList` (kept by WebKit across launches under an identifier made from the rules, so an// unchanged list is looked up, not compiled again) and added to each site's web view while the site's own switch is on.//// Why a content rule list and no other hook: WebKit applies it inside the web content process to every request,// subresources included, before any connection is made; a navigation delegate never sees subresources, a URL scheme// handler cannot take http(s), and a proxy would see every address, which the decision forbids.import CryptoKitimport Foundationimport osimport WebKit@MainActorenum SitesTrackers {    /// The compiled list, once ready; nil until then, or when WebKit refused the rules (nothing is then claimed blocked    /// by this phone: the log says why).    private(set) static var list: WKContentRuleList?    private static var making: Task<WKContentRuleList?, Never>?    private static let log = Logger(subsystem: "com.cottondb.sites", category: "trackers")    /// The list for the core's `ios_rules`, compiled or looked up once; later calls wait on the same work.    static func prepare(rules: [JSONValue]) async -> WKContentRuleList? {        if let list { return list }        if let making { return await making.value }        let task = Task<WKContentRuleList?, Never> { await compile(rules) }        making = task        let made = await task.value        list = made        making = nil        return made    }    /// The identifier WebKit keeps the list under: the rules' own digest, so a changed list is a new identifier and the    /// old one is removed.    static func identifier(for source: String) -> String {        let digest = SHA256.hash(data: Data(source.utf8)).prefix(8).map { String(format: "%02x", $0) }.joined()        return "sites-trackers-\(digest)"    }    private static func compile(_ rules: [JSONValue]) async -> WKContentRuleList? {        guard !rules.isEmpty, let store = WKContentRuleListStore.default(),              let data = try? JSONEncoder().encode(JSONValue.array(rules)) else { return nil }        let source = String(decoding: data, as: UTF8.self)        let id = identifier(for: source)        if let kept = await lookUp(id, in: store) { return kept }        let made: WKContentRuleList? = await withCheckedContinuation { done in            store.compileContentRuleList(forIdentifier: id, encodedContentRuleList: source) { list, error in                if let error { log.error("trackers: WebKit refused the rules: \(error.localizedDescription, privacy: .public)") }                done.resume(returning: list)            }        }        if made != nil { removeOthers(than: id, in: store) }        log.log("trackers: \(rules.count, privacy: .public) rules \(made == nil ? "not compiled" : "compiled", privacy: .public) as \(id, privacy: .public)")        return made    }    private static func lookUp(_ id: String, in store: WKContentRuleListStore) async -> WKContentRuleList? {        await withCheckedContinuation { done in            store.lookUpContentRuleList(forIdentifier: id) { list, _ in done.resume(returning: list) }        }    }    private static func removeOthers(than id: String, in store: WKContentRuleListStore) {        store.getAvailableContentRuleListIdentifiers { ids in            for old in ids ?? [] where old.hasPrefix("sites-trackers-") && old != id {                store.removeContentRuleList(forIdentifier: old) { _ in }            }        }    }}/// `sites.trackers`' answer: the site's switch and the rules WebKit compiles.struct SitesTrackersAnswer: Decodable, Sendable {    var on: Bool    var rules: [JSONValue]    enum CodingKeys: String, CodingKey {        case on        case rules = "ios_rules"    }    init(from decoder: Decoder) throws {        let c = try decoder.container(keyedBy: CodingKeys.self)        on = try c.decodeIfPresent(Bool.self, forKey: .on) ?? true        rules = try c.decodeIfPresent([JSONValue].self, forKey: .rules) ?? []    }}