SPB Git

Repository Public License

SHIELD.md 15.2 KB

# PrivacyEngine — Shield, Ghost, permissions, data controls

Packages/NavigatorKit/Sources/PrivacyEngine. Pure logic: imports NavigatorCore, Persistence, Diagnostics, Foundation and CryptoKit. It never imports WebKit: it produces rule lists as JSON strings, verdicts and instructions; the web layer (WebRuntime) compiles, applies and reports back.

File What it is
ShieldModel.swift Domains, rule model, list parser, built-in list loader
ContentRuleLists.swift WebKit rule format, url-filter validator, generator
ShieldService.swift Settings, user lists, compilation, statistics (actor)
PermissionService.swift PermissionProvider implementation (actor)
GhostSession.swift Private sessions (actors), GhostPolicy
DataControls.swift Clear / retention / export façade
URLHygiene.swift Tracking-parameter stripping, punycode, homograph heuristic
PrivacyText.swift Keys and reference wording of the explanatory texts
Resources/shield-builtin.txt The built-in list

# Shield

# What it generates

ShieldService.compile(profile:) (or ContentRuleListGenerator.compile directly) returns ContentRuleLists: an identifier, the JSON, the rule count and a SHA-256 of the JSON. The web layer compiles each one with WKContentRuleListStore.compileContentRuleList(forIdentifier:encodedContentRuleList:), skips lists whose hash it already compiled, and removes compiled lists whose identifier is no longer returned.

One concern per list, because ignore-previous-rules only reaches back inside its own list:

Identifier Rules
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
orix.shield.cookies block-cookies on third-party loads (option, off by default)
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
orix.shield.cosmetic.N css-display-none with a validated selector, scoped by if-domain or unless-domain

Every list ends with one ignore-previous-rules rule with if-domain = the sites where the user chose "Shield off for this site" (ShieldService.setShield(enabled:onSite:profile:)). On those sites nothing is blocked, hidden or upgraded.

Respecting WebKit's limits:

  • Rule count. A list never exceeds 50 000 rules (ContentRuleListGenerator.maximumRulesPerList); longer sets are split into numbered lists, each with its own trailing allow rule. Newer WebKit versions are reported to accept more; that was not verified here, so the long-standing value is used.
  • Regular expressions. ContentBlockerRegex.problem(in:) accepts only the subset WebKit compiles (literals, ., classes and ranges, * + ?, groups, ^ at the start, $ at the end, escaped punctuation) and refuses alternation, {n,m}, (?…), \d-style escapes, non-ASCII and mid-pattern anchors. Every generated filter is checked; a refused rule is dropped with a diagnostic and never takes its list down.
  • Triggers. if-domain and unless-domain are never combined in one trigger (WebKit refuses it). Domain conditions are lowercase ASCII (punycode) with the * prefix that also matches subdomains.
  • Selectors. WebKit rejects a whole list for one selector it cannot parse, so CosmeticRule.validate is deliberately conservative (character allow-list, balanced brackets and quotes, 512 characters).

A test (WebKitCompilationTests, macOS) compiles every generated list — built-in list, a user list, cosmetic rules, IDN site exceptions — with the real WKContentRuleListStore, and checks that patterns the validator refuses are indeed refused by WebKit.

Relation with the web layer's own HTTPS upgrade: WebRuntime's navigation policy upgrades top-level navigations and shows the interstitial when the secure load fails. The make-https rule additionally upgrades sub-resources. make-https has no fallback: a sub-resource that does not exist over HTTPS simply fails. When the user accepts HTTP for a site after a failed upgrade, call ShieldService.allowHTTP(onSite:profile:) so the rule stops applying on that site.

# The built-in list

Resources/shield-builtin.txt, version in its header (2026.11.25.1), 292 domains in two sections ([trackers], [ads]).

  • It is not EasyList, EasyPrivacy or any other community list, and nothing in it was copied from one. It was written by hand for this project from general knowledge of which companies run advertising exchanges, analytics, session recording, data brokerage and marketing pixels.
  • Coverage is partial. A few hundred domains against the tens of thousands of a maintained list. It will miss most regional and long-tail networks, anything served from a first-party subdomain (CNAME cloaking), and anything that needs a path or a pattern to be told apart from content.
  • What it deliberately leaves out: anti-fraud and bot-detection services (blocking them breaks sign-in and payments), consent managers, tag managers other than Google's, A/B testing tools that hide the page until they load, error-reporting services, privacy-preserving analytics, and any domain that also serves content or sign-in (facebook.com, facebook.net, google.com, CDNs). A test pins a list of domains that must never appear.
  • Rules apply to third-party requests only, so visiting a listed company's own site keeps working; unless= entries cover sister domains of the same owner.
  • It has no cosmetic rules.
  • Nobody has measured its effect on a corpus of real pages. Treat the list as a reasonable default, not as a tested blocker. The UI text PrivacyText.shieldPartialCoverage says so to the user.

# User lists

ShieldService.importList(named:text:) parses a text with ShieldListParser and stores the source (setting shield.user_lists). The format is a deliberately small subset; anything else is rejected with a line number and a reason, never guessed:

Line Meaning
! comment, # comment, blank ignored; ! title: … and ! version: … are read
[trackers], [ads], [custom] category of the following domains; other […] headers are ignored
example.com block third-party requests to the domain and its subdomains
example.com unless=a.com,b.com … except on pages of those sites
`
`@@
0.0.0.0 example.com, 127.0.0.1 example.com hosts-file lines
##selector, a.com,b.com##selector hide matching elements everywhere / on those sites

Rejected: URL paths and wildcards (||example.com/ads/*), regular expressions, any other $option, #@#, #?#, scriptlets, ~site negation, invalid domains, risky selectors. Limits: 8 MB per list, 2 048 characters per line, 500 diagnostics reported.

# Statistics: only what is measurable

WKContentRuleList gives the app no callback. WebKit applies the rules inside its networking code: the app is not told that a request was blocked, a cookie stripped or an element hidden, and there is no public API to ask. A "1 234 trackers blocked" counter cannot be computed honestly, so there is none.

ShieldCounters holds three numbers, per profile, per site (host of the page) and per day:

Counter Source Exactness
popupsBlocked the web layer refused to open a window (record(.popupBlocked, …)) exact
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
likelyBlockedRequests a page script reported failed sub-resources whose host is on an active block list (ingest(_:site:profile:)) estimate, shown as "likely blocked"

Reporting protocol for the optional page script (to be implemented by the web layer; not shipped by this module): the script posts the message shieldReport with the body { "failedHosts": { "<host>": <count>, … } } — hosts of sub-resources that fired an error event or appear as a zero-size PerformanceResourceTiming entry since the previous report. The web layer decodes it as ShieldPageReport and calls ingest. The service counts only hosts that match an active block rule and are third-party to the page, caps each host at 500 and each report at 200 hosts, and ignores reports from sites where Shield is off. Limits stated in the code and to the user: a request can fail for another reason; some blocked requests leave no trace in the page; a hostile page can post inflated numbers for listed hosts.

Storage: one setting per profile and day, shield.stats.<profile>.<yyyy-MM-dd> → { site: counters }, at most 400 sites per day (the rest goes to (other)), written in batches (every 25 events and on flushStatistics()), kept 90 days (pruneStatistics). These rows name visited sites, so DataControls.clear removes them with the history of the same period. They are only ever written for a profile that exists in storage.

# Permissions

PermissionService implements NavigatorCore.PermissionProvider (verdict(for:origin:profileID:), record(_:for:origin:profileID:) = remember until revoked) and adds:

  • decide(_:for:origin:profile:duration:) with PermissionDuration: once (nothing kept), session (memory, until the app quits; it replaces a stored decision), day (stored with a 24 h expiry), always (stored).
  • Defaults per kind (builtInDefaults): ask for camera, microphone, location, notifications, device motion and clipboard; deny for pop-ups and autoplay; ask for downloads the user did not start. User-configurable (setDefaultVerdict), except that camera, microphone and location cannot be allowed by default for all sites.
  • Camera, microphone, location and device motion are denied on insecure origins whatever is stored, and cannot be allowed there (PermissionError.insecureOrigin). Loopback counts as secure.
  • revoke, revokeAll(origin:profile:), purgeExpired, endSession.
  • Queries for the per-site panel: sitePermissions(origin:profile:) (every kind with its verdict and source: default / stored / session / policy) and decidedSites(profile:).
  • A storage failure answers ask, never allow.

Decisions are scoped by profile + origin (scheme, host, port) + kind. In a private profile every decision, including always, stays in memory and ends with the session.

# Ghost (private windows)

GhostSessionManager.begin() creates a GhostSession: a Profile(kind: .ghost) and one space, declared in database.ghosts, with windows and tabs held in the actor. What that guarantees, and how:

Promise Mechanism
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
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
No permissions stored PermissionService keeps them in memory
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)
No cookies or site data on disk WebRuntime gives a ghost profile a .nonPersistent() data store (its code, not this module's)
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

The test usingEveryServiceInAGhostContextWritesNothing drives the session, the permission service and Shield in a ghost context, tries every store directly, and compares the row count of every table before and after (and after late events once the session ended): zero rows written, and the JSON export contains nothing of the session.

What private browsing does not hide is part of the product text (PrivacyText.ghostLimitations): the network and the internet provider, the employer or school, the sites themselves, downloads and bookmarks the user keeps, software on the device. The UI must show these when a private window opens.

# Data controls

DataControls (settings UI):

  • clear(DataClearRequest(categories:range:profileID:)) — categories map to UserDataTypes and are deleted in one transaction through database.lifecycle; session permissions and Shield statistics are cleared in their services. Cookies / site data and cache belong to WebKit: the report carries a WebsiteDataInstruction (profiles, kinds, modifiedSince) for WebRuntime to execute. WebKit only supports "modified since", so a custom range that does not end now removes website data from its start up to now.
  • clearEverything() — everything the app stores, then compaction; Keychain items are not touched here.
  • historyRetentionDays(), setHistoryRetention(days:), applyRetention() (history, 90-day Shield statistics, expired permissions).
  • exportJSON(profile:), export(to:profile:) — the UserDataBundle of Persistence: no cookies, no site data, no secrets, no WebKit session state.

# URL hygiene

  • TrackingParameterStripper.strip(_:) removes known tracking parameters (utm_*, fbclid, gclid, msclkid, mc_eid, … — the lists are in the source) from a URL the user copies or shares. Never applied to navigation. Opt-in (privacy.strip_tracking_parameters, off by default). The other parameters, their order and encoding, and the fragment are left byte for byte.
  • HomographDetector.assess(host:) flags, for the address bar: labels mixing scripts that are not written together (Latin + Cyrillic, Latin + Greek…; Japanese, Korean and Chinese combinations are allowed), whole labels made of Cyrillic or Greek look-alikes of Latin letters under a top-level domain where that script is not the norm, invisible and direction-changing characters, and malformed punycode. When suspicious, displayHost is the punycode form. It is a heuristic with coarse script ranges, not a complete confusables table: a name can pass and still be deceptive.

# Not verified

  • Rule lists were compiled by WebKit in a test, but never attached to a web view and loaded against real pages: that blocking, cookie stripping, upgrades and site exceptions behave as intended at run time is not verified. In particular, whether unless-domain on the make-https rule exempts a top-level navigation to the allowed site itself was not checked.
  • Compilation was only run on macOS; iOS was compiled (the module), not executed.
  • The page script of the reporting protocol does not exist yet.
  • No measurement of the built-in list's coverage or breakage.
  • GhostPolicy.indexesMemory and .syncs are flags: nothing enforces them in MemoryEngine and SyncEngine yet.
Files main
Menu

Theme