api/src/lib/trackers.ts

149 lines · 5026 bytes

22 symbols in this file
  1/**
  2 * Finds the third-party trackers a web page loads
  3 * Using DuckDuckGo's Tracker Blocklist (CC BY-NC-SA 4.0)
  4 * Script, iframe and image sources, plus URLs in inline scripts
  5 */
  6
  7import { ApiError } from '@/lib/errors'
  8
  9export const BLOCKLIST_URL =
 10  'https://staticcdn.duckduckgo.com/trackerblocking/v5/current/extension-tds.json'
 11
 12interface Rule {
 13  rule: string
 14  action?: string
 15}
 16
 17interface TdsTracker {
 18  default?: string
 19  owner?: { name?: string }
 20  categories?: string[]
 21  rules?: Rule[]
 22}
 23
 24interface Tds {
 25  trackers?: Record<string, TdsTracker>
 26  domains?: Record<string, string>
 27}
 28
 29// Slimmed blocklist entry, keyed by tracker domain
 30export interface Tracker {
 31  owner: string
 32  categories: string[]
 33  block: boolean
 34  rules: Rule[]
 35}
 36
 37export interface Blocklist {
 38  trackers: Record<string, Tracker>
 39  // Domain to owning company, so a company's own domains count as first party
 40  entities: Record<string, string>
 41}
 42
 43export interface FoundTracker {
 44  domain: string
 45  owner: string
 46  categories: string[]
 47}
 48
 49const COMMENT_RE = /<!--[\s\S]*?-->/g
 50const SCRIPT_RE = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi
 51const SRC_RE = /<(?:script|iframe|img)\b[^>]*?\bsrc\s*=\s*["']?([^"'\s>]+)/gi
 52const HREF_RE = /<a\b[^>]*?\bhref\s*=\s*["']?([^"'\s>]+)/gi
 53const JSON_TYPE_RE = /(?:^|\s)type\s*=\s*["']?[^"'\s>]*json/i
 54const URL_RE = /(?:https?:)?\/\/[a-z0-9.-]+\.[a-z]{2,}[^\s"'`<>()\\]*/gi
 55
 56// Keep only the fields we match on, so the cached copy stays small
 57export const slimBlocklist = (tds: Tds): Blocklist => {
 58  if (!tds?.trackers) {
 59    throw new ApiError('UPSTREAM_ERROR', 'Tracker blocklist was empty', 502)
 60  }
 61  const trackers: Record<string, Tracker> = {}
 62  for (const [domain, entry] of Object.entries(tds.trackers)) {
 63    trackers[domain] = {
 64      owner: entry.owner?.name ?? '',
 65      categories: entry.categories ?? [],
 66      block: entry.default === 'block',
 67      rules: (entry.rules ?? []).map(({ rule, action }) => ({ rule, action })),
 68    }
 69  }
 70  return { trackers, entities: tds.domains ?? {} }
 71}
 72
 73const toUrl = (raw: string, base: string) => {
 74  try {
 75    return new URL(raw, base)
 76  } catch {
 77    return null
 78  }
 79}
 80
 81const toUrls = (raws: string[], base: string) =>
 82  raws.map((raw) => toUrl(raw, base)).filter((url): url is URL => url !== null)
 83
 84// Host and path, so a link and a mention of the same page compare equal
 85const pageOf = (url: URL) =>
 86  url.hostname.replace(/^www\./, '') + url.pathname.replace(/\/$/, '')
 87
 88// Tag sources plus URLs inside inline scripts, so mentions in text or JSON don't count.
 89// Inline mentions of pages the site links to (like social profiles in framework data)
 90// are links rather than loads, so are skipped, as is anything commented out.
 91export const pageUrls = (html: string, base: string) => {
 92  const live = html.replace(COMMENT_RE, '')
 93  const links = [...live.matchAll(HREF_RE)].map((match) => match[1])
 94  const inline: string[] = []
 95  for (const [, attrs, body] of live.matchAll(SCRIPT_RE)) {
 96    const target = JSON_TYPE_RE.test(attrs) ? links : inline
 97    target.push(...(body.match(URL_RE) ?? []))
 98  }
 99  const linked = new Set(toUrls(links, base).map(pageOf))
100  const loaded = toUrls(
101    [...live.matchAll(SRC_RE)].map((match) => match[1]),
102    base,
103  )
104  return [...loaded, ...toUrls(inline, base).filter((url) => !linked.has(pageOf(url)))]
105}
106
107// The entry for a host or its nearest listed parent domain
108const nearest = <T>(host: string, map: Record<string, T>) => {
109  const labels = host.split('.')
110  for (let i = 0; i < labels.length - 1; i++) {
111    const domain = labels.slice(i).join('.')
112    if (Object.hasOwn(map, domain)) return { domain, value: map[domain] }
113  }
114  return null
115}
116
117const ruleMatches = (rule: string, url: string) => {
118  try {
119    return new RegExp(rule, 'i').test(url)
120  } catch {
121    return false
122  }
123}
124
125// DuckDuckGo's verdict, the first matching rule wins, else the domain's default
126const isBlocked = (url: string, tracker: Tracker) => {
127  const rule = tracker.rules.find((r) => ruleMatches(r.rule, url))
128  return rule ? rule.action !== 'ignore' : tracker.block
129}
130
131// Blocked third-party trackers on a page, one per tracker domain
132export const findTrackers = (html: string, pageUrl: string, list: Blocklist) => {
133  const pageHost = new URL(pageUrl).hostname
134  const pageEntity = nearest(pageHost, list.entities)?.value
135  const found = new Map<string, FoundTracker>()
136  for (const url of pageUrls(html, pageUrl)) {
137    const match = nearest(url.hostname, list.trackers)
138    if (!match || found.has(match.domain)) continue
139    const sameEntity =
140      pageEntity !== undefined &&
141      nearest(match.domain, list.entities)?.value === pageEntity
142    const firstParty =
143      sameEntity || pageHost === match.domain || pageHost.endsWith(`.${match.domain}`)
144    if (firstParty || !isBlocked(url.href, match.value)) continue
145    const { owner, categories } = match.value
146    found.set(match.domain, { domain: match.domain, owner, categories })
147  }
148  return [...found.values()].sort((a, b) => a.domain.localeCompare(b.domain))
149}