api/tests/trackers.test.ts
390 lines · 14007 bytes
1// Unit tests for website tracker detection, the guarded page fetcher and the route
2import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest'
3import { lookup } from 'node:dns/promises'
4import { buildApp } from '../src/app'
5import { fetchPage, isPrivateIp, isPublicUrl } from '@/lib/page'
6import { BLOCKLIST_URL, findTrackers, pageUrls, slimBlocklist } from '@/lib/trackers'
7
8// Every hostname resolves to a public address unless a test says otherwise
9vi.mock('node:dns/promises', () => ({ lookup: vi.fn() }))
10const publicDns = [{ address: '93.184.215.14', family: 4 }]
11beforeEach(() => {
12 vi.mocked(lookup).mockResolvedValue(publicDns as never)
13})
14
15const tds = {
16 trackers: {
17 'googletagmanager.com': {
18 default: 'block',
19 owner: { name: 'Google Ads' },
20 categories: ['Tag Manager'],
21 },
22 'facebook.net': {
23 default: 'ignore',
24 owner: { name: 'Facebook, Inc.' },
25 rules: [{ rule: 'facebook\\.net/.*/fbevents\\.js' }],
26 },
27 'stripe.com': { default: 'ignore', owner: { name: 'Stripe, Inc.' } },
28 'hotjar.com': {
29 default: 'block',
30 owner: { name: 'Hotjar Ltd' },
31 rules: [{ rule: 'hotjar\\.com/allowed', action: 'ignore' }, { rule: '([' }],
32 },
33 'excdn.net': { default: 'block', owner: { name: 'Example Corp' } },
34 'reddit.com': { default: 'block', owner: { name: 'Reddit Inc.' } },
35 },
36 domains: { 'example-corp.com': 'Example Corp', 'excdn.net': 'Example Corp' },
37}
38const list = slimBlocklist(tds)
39const found = (html: string, page = 'https://example.com/') =>
40 findTrackers(html, page, list).map((t) => t.domain)
41
42const GTM =
43 "<script>j.src='https://www.googletagmanager.com/gtm.js?id='+i;" +
44 "})(window,document,'script','dataLayer','GTM-AB12');</script>"
45
46describe('slimBlocklist', () => {
47 it('keeps owner, categories, default and rules, plus domain owners', () => {
48 expect(list.entities['excdn.net']).toBe('Example Corp')
49 expect(list.trackers['googletagmanager.com']).toEqual({
50 owner: 'Google Ads',
51 categories: ['Tag Manager'],
52 block: true,
53 rules: [],
54 })
55 })
56
57 it('rejects a blocklist with no trackers', () => {
58 expect(() => slimBlocklist({})).toThrow('Tracker blocklist was empty')
59 })
60})
61
62describe('pageUrls', () => {
63 const urls = (html: string) => pageUrls(html, 'https://example.com/').map(String)
64
65 it('collects tag sources, quoted or not, and URLs in inline scripts', () => {
66 const html =
67 '<img src="/a.png"><iframe src="https://x.com/f"></iframe>' +
68 '<script src=https://cdn.z.com/t.js async></script>' +
69 '<script>load("//cdn.y.com/s.js")</script>'
70 expect(urls(html)).toEqual([
71 'https://example.com/a.png',
72 'https://x.com/f',
73 'https://cdn.z.com/t.js',
74 'https://cdn.y.com/s.js',
75 ])
76 })
77
78 it('ignores page text, JSON blocks, prefetch hints and comments', () => {
79 const html =
80 '<p>We block https://www.googletagmanager.com for you</p>' +
81 '<script type="application/json">{"u":"https://www.googletagmanager.com/gtm.js"}</script>' +
82 '<link rel="dns-prefetch" href="https://www.googletagmanager.com">' +
83 '<!-- <script src="https://www.googletagmanager.com/gtm.js"></script> -->'
84 expect(urls(html)).toEqual([])
85 })
86
87 it('skips inline mentions of linked pages, but keeps loads', () => {
88 const html =
89 '<a href="https://www.reddit.com/r/example/">Reddit</a>' +
90 '<script type="application/ld+json">{"sameAs":["https://x.com/me"]}</script>' +
91 '<script>self.__next_f.push(["https://reddit.com/r/example","https://x.com/me"]);' +
92 's.src="https://www.redditstatic.com/ads/pixel.js"</script>'
93 expect(urls(html)).toEqual(['https://www.redditstatic.com/ads/pixel.js'])
94 })
95})
96
97describe('findTrackers', () => {
98 it('finds a tracker loaded by an inline snippet', () => {
99 expect(findTrackers(GTM, 'https://example.com/', list)).toEqual([
100 {
101 domain: 'googletagmanager.com',
102 owner: 'Google Ads',
103 categories: ['Tag Manager'],
104 },
105 ])
106 })
107
108 it('uses rules before the default', () => {
109 const pixel = '<script src="https://connect.facebook.net/en_US/fbevents.js"></script>'
110 const sdk = '<script src="https://connect.facebook.net/en_US/sdk.js"></script>'
111 const allowed = '<script src="https://static.hotjar.com/allowed.js"></script>'
112 expect(found(pixel)).toEqual(['facebook.net'])
113 expect(found(sdk)).toEqual([])
114 expect(found(allowed)).toEqual([])
115 })
116
117 it('skips ignored and unlisted domains, and survives a broken rule', () => {
118 const html =
119 '<script src="https://js.stripe.com/v3/"></script>' +
120 '<script src="https://plausible.io/js/script.js"></script>' +
121 '<script src="https://static.hotjar.com/c/hotjar-1.js"></script>'
122 expect(found(html)).toEqual(['hotjar.com'])
123 })
124
125 it('treats the tracker on its own site as first party', () => {
126 expect(found(GTM, 'https://tagmanager.googletagmanager.com/')).toEqual([])
127 })
128
129 it("treats a company's own tracker domains as first party", () => {
130 const html = '<script src="https://cdn.excdn.net/t.js"></script>'
131 expect(found(html, 'https://www.example-corp.com/')).toEqual([])
132 expect(found(html)).toEqual(['excdn.net'])
133 })
134
135 it('never matches built-in object keys as domains', () => {
136 const html =
137 '<script src="https://a.__proto__/x.js"></script><img src="//b.constructor/p">'
138 expect(found(html, 'https://c.hasownproperty/')).toEqual([])
139 })
140
141 it('ignores inline mentions of pages the site links to, like social profiles', () => {
142 const link = '<a href="https://www.reddit.com/r/example">Reddit</a>'
143 const data =
144 '<script>self.__next_f.push(["https://www.reddit.com/r/example"])</script>'
145 expect(found(link + data)).toEqual([])
146 expect(found(data)).toEqual(['reddit.com'])
147 expect(found(link + '<img src="https://www.reddit.com/r/example">')).toEqual([
148 'reddit.com',
149 ])
150 })
151
152 it('reports each domain once, sorted', () => {
153 const html = GTM + GTM + '<script src="https://static.hotjar.com/c/h.js"></script>'
154 expect(found(html)).toEqual(['googletagmanager.com', 'hotjar.com'])
155 })
156
157 it('ignores relative and malformed URLs', () => {
158 expect(found('<script src="/gtm.js"></script><img src="http://[bad">')).toEqual([])
159 })
160})
161
162describe('isPublicUrl', () => {
163 const ok = (url: string) => isPublicUrl(new URL(url))
164
165 it('allows public http(s) hosts', () => {
166 expect(ok('https://example.com/path?q=1')).toBe(true)
167 expect(ok('http://sub.example.org')).toBe(true)
168 })
169
170 it('refuses IPs, local names, custom ports, credentials and other schemes', () => {
171 for (const url of [
172 'http://127.0.0.1',
173 'http://169.254.169.254/latest/meta-data',
174 'http://0x7f.1',
175 'http://[::1]/',
176 'http://localhost',
177 'http://localhost.',
178 'http://app.localhost',
179 'http://metadata.google.internal',
180 'http://printer.local',
181 'http://router.lan',
182 'https://example.com:8443',
183 'https://user:pass@example.com',
184 'ftp://example.com',
185 'file:///etc/passwd',
186 ]) {
187 expect(ok(url), url).toBe(false)
188 }
189 })
190})
191
192describe('isPrivateIp', () => {
193 it('flags private, loopback, link-local and mapped addresses', () => {
194 for (const ip of [
195 '10.1.2.3',
196 '172.16.0.1',
197 '172.31.255.255',
198 '192.168.1.1',
199 '127.0.0.1',
200 '169.254.169.254',
201 '100.64.0.1',
202 '0.0.0.0',
203 '224.0.0.1',
204 '255.255.255.255',
205 '::1',
206 '::',
207 'fd12:3456::1',
208 'fe80::1',
209 '::ffff:127.0.0.1',
210 '::127.0.0.1',
211 '64:ff9b::a00:1',
212 ]) {
213 expect(isPrivateIp(ip), ip).toBe(true)
214 }
215 })
216
217 it('allows public addresses', () => {
218 for (const ip of ['93.184.215.14', '1.1.1.1', '172.32.0.1', '2606:4700::6810:84e5']) {
219 expect(isPrivateIp(ip), ip).toBe(false)
220 }
221 })
222})
223
224const html = (body: BodyInit, status = 200) =>
225 new Response(body, { status, headers: { 'content-type': 'text/html' } })
226const redirect = (location: string) =>
227 new Response(null, { status: 301, headers: { location } })
228
229describe('fetchPage', () => {
230 afterEach(() => vi.unstubAllGlobals())
231
232 it('follows public redirects by hand and reports the final URL', async () => {
233 const fetchMock = vi
234 .fn()
235 .mockResolvedValueOnce(redirect('/en/'))
236 .mockResolvedValueOnce(html('<p>hi</p>'))
237 vi.stubGlobal('fetch', fetchMock)
238 expect(await fetchPage('https://example.com')).toEqual({
239 url: 'https://example.com/en/',
240 html: '<p>hi</p>',
241 })
242 expect(fetchMock.mock.calls[0][1]).toMatchObject({ redirect: 'manual' })
243 })
244
245 it('refuses a redirect to a private address', async () => {
246 const fetchMock = vi.fn().mockResolvedValue(redirect('http://127.0.0.1/admin'))
247 vi.stubGlobal('fetch', fetchMock)
248 await expect(fetchPage('https://example.com')).rejects.toMatchObject({ status: 400 })
249 expect(fetchMock).toHaveBeenCalledTimes(1)
250 })
251
252 it('refuses a public name that resolves to a private address', async () => {
253 vi.mocked(lookup).mockResolvedValue([{ address: '::1', family: 6 }] as never)
254 const fetchMock = vi.fn()
255 vi.stubGlobal('fetch', fetchMock)
256 await expect(fetchPage('http://localtest.me/')).rejects.toMatchObject({ status: 400 })
257 expect(fetchMock).not.toHaveBeenCalled()
258 })
259
260 it('treats a failed DNS lookup as unreachable', async () => {
261 vi.mocked(lookup).mockRejectedValue(new Error('ENOTFOUND'))
262 vi.stubGlobal('fetch', vi.fn())
263 await expect(fetchPage('https://nope.example.com')).rejects.toMatchObject({
264 status: 502,
265 })
266 })
267
268 it('refuses a private URL without fetching it', async () => {
269 const fetchMock = vi.fn()
270 vi.stubGlobal('fetch', fetchMock)
271 await expect(fetchPage('http://localhost/')).rejects.toMatchObject({ status: 400 })
272 expect(fetchMock).not.toHaveBeenCalled()
273 })
274
275 it('gives up after too many redirects', async () => {
276 vi.stubGlobal(
277 'fetch',
278 vi.fn().mockImplementation(async () => redirect('/loop')),
279 )
280 await expect(fetchPage('https://example.com')).rejects.toMatchObject({
281 message: expect.stringContaining('Too many redirects'),
282 })
283 })
284
285 it('rejects error statuses, non-HTML and network failures as 502', async () => {
286 for (const respond of [
287 async () => new Response('nope', { status: 404 }),
288 async () => html('<p>hi</p>', 202),
289 async () =>
290 new Response('%PDF', { headers: { 'content-type': 'application/pdf' } }),
291 async () => Promise.reject(new TypeError('fetch failed')),
292 ]) {
293 vi.stubGlobal('fetch', vi.fn().mockImplementation(respond))
294 await expect(fetchPage('https://example.com')).rejects.toMatchObject({
295 status: 502,
296 })
297 }
298 })
299
300 it('stops reading after 2 MB, even mid-chunk', async () => {
301 const chunk = new Uint8Array(1_500_000).fill(97)
302 let pulled = 0
303 const body = new ReadableStream({
304 pull(controller) {
305 pulled++
306 controller.enqueue(chunk)
307 },
308 })
309 vi.stubGlobal('fetch', vi.fn().mockResolvedValue(html(body)))
310 const page = await fetchPage('https://example.com')
311 expect(page.html.length).toBe(2_000_000)
312 expect(pulled).toBeLessThan(4)
313 })
314})
315
316describe('GET /v1/enrich/trackers', () => {
317 const app = buildApp()
318 // A Map-backed stand-in for Workers KV
319 const kv = new Map<string, string>()
320 const CACHE = {
321 get: async (key: string) => (kv.has(key) ? JSON.parse(kv.get(key)!) : null),
322 put: async (key: string, value: string) => void kv.set(key, value),
323 }
324 const hit = (url: string) =>
325 app.fetch(
326 new Request(`http://localhost/v1/enrich/trackers?url=${encodeURIComponent(url)}`),
327 { CACHE },
328 )
329
330 afterEach(() => vi.unstubAllGlobals())
331
332 // Serve the blocklist and a page, recording which URLs were requested
333 const upstream = (page: Response | (() => Response)) => {
334 const calls: string[] = []
335 vi.stubGlobal(
336 'fetch',
337 vi.fn(async (input: string | URL) => {
338 const url = String(input)
339 calls.push(url)
340 if (url === BLOCKLIST_URL) return Response.json(tds)
341 return typeof page === 'function' ? page() : page
342 }),
343 )
344 return calls
345 }
346
347 it('returns the trackers a page loads, and caches the result', async () => {
348 const calls = upstream(() => html(GTM))
349 const res = await hit('https://route-test.example.com/page?utm=1')
350 expect(res.status).toBe(200)
351 expect(await res.json()).toEqual({
352 finalUrl: 'https://route-test.example.com/page?utm=1',
353 trackers: [
354 {
355 domain: 'googletagmanager.com',
356 owner: 'Google Ads',
357 categories: ['Tag Manager'],
358 },
359 ],
360 })
361 const again = await hit('https://route-test.example.com/page?utm=1#top')
362 expect(again.status).toBe(200)
363 expect(calls.filter((url) => url !== BLOCKLIST_URL)).toHaveLength(1)
364 })
365
366 it('caches each query string apart, under keys short enough for KV', async () => {
367 const calls = upstream(() => html(''))
368 const long = `https://route-keys.example.com/${'a'.repeat(1000)}`
369 for (const url of [`${long}?x=1`, `${long}?x=2`]) {
370 expect((await hit(url)).status).toBe(200)
371 }
372 expect(calls.filter((url) => url !== BLOCKLIST_URL)).toHaveLength(2)
373 expect([...kv.keys()].every((key) => key.length <= 512)).toBe(true)
374 })
375
376 it('rejects an invalid or private URL with the error envelope', async () => {
377 upstream(html(''))
378 expect((await hit('not a url')).status).toBe(400)
379 const res = await hit('http://127.0.0.1/')
380 expect(res.status).toBe(400)
381 expect(await res.json()).toMatchObject({ error: { code: 'BAD_REQUEST' } })
382 })
383
384 it('returns a 502 envelope when the page cannot be fetched', async () => {
385 upstream(new Response('down', { status: 503 }))
386 const res = await hit('https://route-down.example.com/')
387 expect(res.status).toBe(502)
388 expect(await res.json()).toMatchObject({ error: { code: 'UPSTREAM_ERROR' } })
389 })
390})