SPB Git

Repository Public License

SHIELD.md 15.2 KB 218 lines markdown

1# PrivacyEngine — Shield, Ghost, permissions, data controls23`Packages/NavigatorKit/Sources/PrivacyEngine`. Pure logic: imports `NavigatorCore`, `Persistence`, `Diagnostics`,4`Foundation` and `CryptoKit`. It never imports WebKit: it produces rule lists as JSON strings, verdicts and5instructions; the web layer (WebRuntime) compiles, applies and reports back.67| File | What it is |8|---|---|9| `ShieldModel.swift` | Domains, rule model, list parser, built-in list loader |10| `ContentRuleLists.swift` | WebKit rule format, url-filter validator, generator |11| `ShieldService.swift` | Settings, user lists, compilation, statistics (actor) |12| `PermissionService.swift` | `PermissionProvider` implementation (actor) |13| `GhostSession.swift` | Private sessions (actors), `GhostPolicy` |14| `DataControls.swift` | Clear / retention / export façade |15| `URLHygiene.swift` | Tracking-parameter stripping, punycode, homograph heuristic |16| `PrivacyText.swift` | Keys and reference wording of the explanatory texts |17| `Resources/shield-builtin.txt` | The built-in list |1819## Shield2021### What it generates2223`ShieldService.compile(profile:)` (or `ContentRuleListGenerator.compile` directly) returns `ContentRuleList`s:24an identifier, the JSON, the rule count and a SHA-256 of the JSON. The web layer compiles each one with25`WKContentRuleListStore.compileContentRuleList(forIdentifier:encodedContentRuleList:)`, skips lists whose hash it26already compiled, and removes compiled lists whose identifier is no longer returned.2728One concern per list, because `ignore-previous-rules` only reaches back inside its own list:2930| Identifier | Rules |31|---|---|32| `orix.shield.https` | `make-https` on `^http://` (with `unless-domain` for sites the user allowed over HTTP), then `ignore-previous-rules` for local hosts: `localhost`, `*.localhost`, `*.local`, `*.internal`, single-label hosts, 127/8, 10/8, 172.16/12, 192.168/16, 169.254/16, IPv6 literals |33| `orix.shield.cookies` | `block-cookies` on third-party loads (option, off by default) |34| `orix.shield.trackers.N`, `orix.shield.ads.N`, `orix.shield.custom.N` | one `block` rule per domain: url-filter `^[^:]+://+([^:/]+\.)?domain[:/]`, `load-type: ["third-party"]`, `unless-domain` for the sites of the same owner |35| `orix.shield.cosmetic.N` | `css-display-none` with a validated selector, scoped by `if-domain` or `unless-domain` |3637Every list ends with one `ignore-previous-rules` rule with `if-domain` = the sites where the user chose38**"Shield off for this site"** (`ShieldService.setShield(enabled:onSite:profile:)`). On those sites nothing is39blocked, hidden or upgraded.4041Respecting WebKit's limits:4243- **Rule count.** A list never exceeds 50 000 rules (`ContentRuleListGenerator.maximumRulesPerList`); longer44  sets are split into numbered lists, each with its own trailing allow rule. Newer WebKit versions are reported45  to accept more; that was not verified here, so the long-standing value is used.46- **Regular expressions.** `ContentBlockerRegex.problem(in:)` accepts only the subset WebKit compiles (literals,47  `.`, classes and ranges, `* + ?`, groups, `^` at the start, `$` at the end, escaped punctuation) and refuses48  alternation, `{n,m}`, `(?…)`, `\d`-style escapes, non-ASCII and mid-pattern anchors. Every generated filter is49  checked; a refused rule is dropped with a diagnostic and never takes its list down.50- **Triggers.** `if-domain` and `unless-domain` are never combined in one trigger (WebKit refuses it). Domain51  conditions are lowercase ASCII (punycode) with the `*` prefix that also matches subdomains.52- **Selectors.** WebKit rejects a whole list for one selector it cannot parse, so `CosmeticRule.validate` is53  deliberately conservative (character allow-list, balanced brackets and quotes, 512 characters).5455A test (`WebKitCompilationTests`, macOS) compiles every generated list — built-in list, a user list, cosmetic56rules, IDN site exceptions — with the real `WKContentRuleListStore`, and checks that patterns the validator57refuses are indeed refused by WebKit.5859Relation with the web layer's own HTTPS upgrade: WebRuntime's navigation policy upgrades *top-level*60navigations and shows the interstitial when the secure load fails. The `make-https` rule additionally upgrades61sub-resources. `make-https` has no fallback: a sub-resource that does not exist over HTTPS simply fails. When62the user accepts HTTP for a site after a failed upgrade, call `ShieldService.allowHTTP(onSite:profile:)` so the63rule stops applying on that site.6465### The built-in list6667`Resources/shield-builtin.txt`, version in its header (`2026.11.25.1`), 292 domains in two sections68(`[trackers]`, `[ads]`).6970- **It is not EasyList, EasyPrivacy or any other community list, and nothing in it was copied from one.** It was71  written by hand for this project from general knowledge of which companies run advertising exchanges,72  analytics, session recording, data brokerage and marketing pixels.73- **Coverage is partial.** A few hundred domains against the tens of thousands of a maintained list. It will74  miss most regional and long-tail networks, anything served from a first-party subdomain (CNAME cloaking), and75  anything that needs a path or a pattern to be told apart from content.76- **What it deliberately leaves out:** anti-fraud and bot-detection services (blocking them breaks sign-in and77  payments), consent managers, tag managers other than Google's, A/B testing tools that hide the page until they78  load, error-reporting services, privacy-preserving analytics, and any domain that also serves content or79  sign-in (`facebook.com`, `facebook.net`, `google.com`, CDNs). A test pins a list of domains that must never80  appear.81- Rules apply to third-party requests only, so visiting a listed company's own site keeps working; `unless=`82  entries cover sister domains of the same owner.83- It has no cosmetic rules.84- Nobody has measured its effect on a corpus of real pages. Treat the list as a reasonable default, not as a85  tested blocker. The UI text `PrivacyText.shieldPartialCoverage` says so to the user.8687### User lists8889`ShieldService.importList(named:text:)` parses a text with `ShieldListParser` and stores the source (setting90`shield.user_lists`). The format is a deliberately small subset; anything else is **rejected with a line91number and a reason, never guessed**:9293| Line | Meaning |94|---|---|95| `! comment`, `# comment`, blank | ignored; `! title: …` and `! version: …` are read |96| `[trackers]`, `[ads]`, `[custom]` | category of the following domains; other `[…]` headers are ignored |97| `example.com` | block third-party requests to the domain and its subdomains |98| `example.com unless=a.com,b.com` | … except on pages of those sites |99| `||example.com^`, `||example.com^$third-party` | the same, Adblock-Plus syntax |100| `@@||example.com^` | never block this domain (also lifts a rule on a parent domain) |101| `0.0.0.0 example.com`, `127.0.0.1 example.com` | hosts-file lines |102| `##selector`, `a.com,b.com##selector` | hide matching elements everywhere / on those sites |103104Rejected: URL paths and wildcards (`||example.com/ads/*`), regular expressions, any other `$option`, `#@#`,105`#?#`, scriptlets, `~site` negation, invalid domains, risky selectors. Limits: 8 MB per list, 2 048 characters106per line, 500 diagnostics reported.107108### Statistics: only what is measurable109110**`WKContentRuleList` gives the app no callback.** WebKit applies the rules inside its networking code: the app111is not told that a request was blocked, a cookie stripped or an element hidden, and there is no public API to112ask. A "1 234 trackers blocked" counter cannot be computed honestly, so there is none.113114`ShieldCounters` holds three numbers, per profile, per site (host of the page) and per day:115116| Counter | Source | Exactness |117|---|---|---|118| `popupsBlocked` | the web layer refused to open a window (`record(.popupBlocked, …)`) | exact |119| `httpsUpgrades` | the web layer saw a main-frame navigation go from `http://` to `https://` because of the upgrade (`record(.httpsUpgraded, …)`) | exact for main frames; sub-resource upgrades are invisible |120| `likelyBlockedRequests` | a page script reported failed sub-resources whose host is on an active block list (`ingest(_:site:profile:)`) | **estimate**, shown as "likely blocked" |121122Reporting protocol for the optional page script (to be implemented by the web layer; not shipped by this123module): the script posts the message `shieldReport` with the body124`{ "failedHosts": { "<host>": <count>, … } }` — hosts of sub-resources that fired an `error` event or appear as a125zero-size `PerformanceResourceTiming` entry since the previous report. The web layer decodes it as126`ShieldPageReport` and calls `ingest`. The service counts only hosts that match an active block rule and are127third-party to the page, caps each host at 500 and each report at 200 hosts, and ignores reports from sites128where Shield is off. Limits stated in the code and to the user: a request can fail for another reason; some129blocked requests leave no trace in the page; a hostile page can post inflated numbers for listed hosts.130131Storage: one setting per profile and day, `shield.stats.<profile>.<yyyy-MM-dd>` → `{ site: counters }`, at most132400 sites per day (the rest goes to `(other)`), written in batches (every 25 events and on133`flushStatistics()`), kept 90 days (`pruneStatistics`). These rows name visited sites, so134`DataControls.clear` removes them with the history of the same period. They are only ever written for a135profile that exists in storage.136137## Permissions138139`PermissionService` implements `NavigatorCore.PermissionProvider` (`verdict(for:origin:profileID:)`,140`record(_:for:origin:profileID:)` = remember until revoked) and adds:141142- `decide(_:for:origin:profile:duration:)` with `PermissionDuration`: `once` (nothing kept), `session` (memory,143  until the app quits; it replaces a stored decision), `day` (stored with a 24 h expiry), `always` (stored).144- Defaults per kind (`builtInDefaults`): ask for camera, microphone, location, notifications, device motion and145  clipboard; deny for pop-ups and autoplay; ask for downloads the user did not start. User-configurable146  (`setDefaultVerdict`), except that camera, microphone and location cannot be allowed by default for all sites.147- Camera, microphone, location and device motion are **denied on insecure origins** whatever is stored, and148  cannot be allowed there (`PermissionError.insecureOrigin`). Loopback counts as secure.149- `revoke`, `revokeAll(origin:profile:)`, `purgeExpired`, `endSession`.150- Queries for the per-site panel: `sitePermissions(origin:profile:)` (every kind with its verdict and source:151  default / stored / session / policy) and `decidedSites(profile:)`.152- A storage failure answers `ask`, never `allow`.153154Decisions are scoped by profile + origin (scheme, host, port) + kind. In a private profile every decision,155including `always`, stays in memory and ends with the session.156157## Ghost (private windows)158159`GhostSessionManager.begin()` creates a `GhostSession`: a `Profile(kind: .ghost)` and one space, declared in160`database.ghosts`, with windows and tabs held in the actor. What that guarantees, and how:161162| Promise | Mechanism |163|---|---|164| No profile, space, window or tab row | the stores refuse ghost owners (`ghostWriteRejected`) and rows whose owner is not stored; `OrbitService` and `SessionOrchestrator` drop ghost changes before storage |165| No history, bookmarks-by-accident, downloads list | foreign keys to a profile that does not exist; WebRuntime does not call the history recorder for a ghost profile; `DownloadManager` keeps ghost downloads in memory |166| No permissions stored | `PermissionService` keeps them in memory |167| No Shield statistics or site exceptions stored | `ShieldService` keeps them in memory, and never writes site-naming rows for a profile that is not stored (covers events arriving after the session ended) |168| No cookies or site data on disk | WebRuntime gives a ghost profile a `.nonPersistent()` data store (its code, not this module's) |169| No memory indexing, no sync | `GhostPolicy.indexesMemory` / `.syncs` are `false`; those modules must check them — **not verified here**, they did not exist when this was written |170171The test `usingEveryServiceInAGhostContextWritesNothing` drives the session, the permission service and Shield172in a ghost context, tries every store directly, and compares the row count of **every table** before and after173(and after late events once the session ended): zero rows written, and the JSON export contains nothing of the174session.175176What private browsing does **not** hide is part of the product text (`PrivacyText.ghostLimitations`): the177network and the internet provider, the employer or school, the sites themselves, downloads and bookmarks the178user keeps, software on the device. The UI must show these when a private window opens.179180## Data controls181182`DataControls` (settings UI):183184- `clear(DataClearRequest(categories:range:profileID:))` — categories map to `UserDataType`s and are deleted in185  one transaction through `database.lifecycle`; session permissions and Shield statistics are cleared in their186  services. Cookies / site data and cache belong to WebKit: the report carries a `WebsiteDataInstruction`187  (profiles, kinds, `modifiedSince`) for WebRuntime to execute. WebKit only supports "modified since", so a188  custom range that does not end now removes website data from its start up to now.189- `clearEverything()` — everything the app stores, then compaction; Keychain items are not touched here.190- `historyRetentionDays()`, `setHistoryRetention(days:)`, `applyRetention()` (history, 90-day Shield191  statistics, expired permissions).192- `exportJSON(profile:)`, `export(to:profile:)` — the `UserDataBundle` of Persistence: no cookies, no site193  data, no secrets, no WebKit session state.194195## URL hygiene196197- `TrackingParameterStripper.strip(_:)` removes known tracking parameters (`utm_*`, `fbclid`, `gclid`, `msclkid`,198  `mc_eid`, … — the lists are in the source) from a URL the user **copies or shares**. Never applied to199  navigation. Opt-in (`privacy.strip_tracking_parameters`, off by default). The other parameters, their order200  and encoding, and the fragment are left byte for byte.201- `HomographDetector.assess(host:)` flags, for the address bar: labels mixing scripts that are not written202  together (Latin + Cyrillic, Latin + Greek…; Japanese, Korean and Chinese combinations are allowed), whole203  labels made of Cyrillic or Greek look-alikes of Latin letters under a top-level domain where that script is204  not the norm, invisible and direction-changing characters, and malformed punycode. When suspicious,205  `displayHost` is the punycode form. It is a heuristic with coarse script ranges, not a complete confusables206  table: a name can pass and still be deceptive.207208## Not verified209210- Rule lists were compiled by WebKit in a test, but **never attached to a web view and loaded against real211  pages**: that blocking, cookie stripping, upgrades and site exceptions behave as intended at run time is not212  verified. In particular, whether `unless-domain` on the `make-https` rule exempts a top-level navigation to213  the allowed site itself was not checked.214- Compilation was only run on macOS; iOS was compiled (the module), not executed.215- The page script of the reporting protocol does not exist yet.216- No measurement of the built-in list's coverage or breakage.217- `GhostPolicy.indexesMemory` and `.syncs` are flags: nothing enforces them in MemoryEngine and SyncEngine yet.218
Files main
Menu

Theme