// Unit tests for website tracker detection, the guarded page fetcher and the route
import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest'
import { lookup } from 'node:dns/promises'
import { buildApp } from '../src/app'
import { fetchPage, isPrivateIp, isPublicUrl } from '@/lib/page'
import { BLOCKLIST_URL, findTrackers, pageUrls, slimBlocklist } from '@/lib/trackers'
// Every hostname resolves to a public address unless a test says otherwise
vi.mock('node:dns/promises', () => ({ lookup: vi.fn() }))
const publicDns = [{ address: '93.184.215.14', family: 4 }]
beforeEach(() => {
vi.mocked(lookup).mockResolvedValue(publicDns as never)
})
const tds = {
trackers: {
'googletagmanager.com': {
default: 'block',
owner: { name: 'Google Ads' },
categories: ['Tag Manager'],
},
'facebook.net': {
default: 'ignore',
owner: { name: 'Facebook, Inc.' },
rules: [{ rule: 'facebook\\.net/.*/fbevents\\.js' }],
},
'stripe.com': { default: 'ignore', owner: { name: 'Stripe, Inc.' } },
'hotjar.com': {
default: 'block',
owner: { name: 'Hotjar Ltd' },
rules: [{ rule: 'hotjar\\.com/allowed', action: 'ignore' }, { rule: '([' }],
},
'excdn.net': { default: 'block', owner: { name: 'Example Corp' } },
'reddit.com': { default: 'block', owner: { name: 'Reddit Inc.' } },
},
domains: { 'example-corp.com': 'Example Corp', 'excdn.net': 'Example Corp' },
}
const list = slimBlocklist(tds)
const found = (html: string, page = 'https://example.com/') =>
findTrackers(html, page, list).map((t) => t.domain)
const GTM =
""
describe('slimBlocklist', () => {
it('keeps owner, categories, default and rules, plus domain owners', () => {
expect(list.entities['excdn.net']).toBe('Example Corp')
expect(list.trackers['googletagmanager.com']).toEqual({
owner: 'Google Ads',
categories: ['Tag Manager'],
block: true,
rules: [],
})
})
it('rejects a blocklist with no trackers', () => {
expect(() => slimBlocklist({})).toThrow('Tracker blocklist was empty')
})
})
describe('pageUrls', () => {
const urls = (html: string) => pageUrls(html, 'https://example.com/').map(String)
it('collects tag sources, quoted or not, and URLs in inline scripts', () => {
const html =
'
' +
'' +
''
expect(urls(html)).toEqual([
'https://example.com/a.png',
'https://x.com/f',
'https://cdn.z.com/t.js',
'https://cdn.y.com/s.js',
])
})
it('ignores page text, JSON blocks, prefetch hints and comments', () => {
const html =
'
We block https://www.googletagmanager.com for you
' + '' + '' + '' expect(urls(html)).toEqual([]) }) it('skips inline mentions of linked pages, but keeps loads', () => { const html = 'Reddit' + '' + '' expect(urls(html)).toEqual(['https://www.redditstatic.com/ads/pixel.js']) }) }) describe('findTrackers', () => { it('finds a tracker loaded by an inline snippet', () => { expect(findTrackers(GTM, 'https://example.com/', list)).toEqual([ { domain: 'googletagmanager.com', owner: 'Google Ads', categories: ['Tag Manager'], }, ]) }) it('uses rules before the default', () => { const pixel = '' const sdk = '' const allowed = '' expect(found(pixel)).toEqual(['facebook.net']) expect(found(sdk)).toEqual([]) expect(found(allowed)).toEqual([]) }) it('skips ignored and unlisted domains, and survives a broken rule', () => { const html = '' + '' + '' expect(found(html)).toEqual(['hotjar.com']) }) it('treats the tracker on its own site as first party', () => { expect(found(GTM, 'https://tagmanager.googletagmanager.com/')).toEqual([]) }) it("treats a company's own tracker domains as first party", () => { const html = '' expect(found(html, 'https://www.example-corp.com/')).toEqual([]) expect(found(html)).toEqual(['excdn.net']) }) it('never matches built-in object keys as domains', () => { const html = 'hi
')) vi.stubGlobal('fetch', fetchMock) expect(await fetchPage('https://example.com')).toEqual({ url: 'https://example.com/en/', html: 'hi
', }) expect(fetchMock.mock.calls[0][1]).toMatchObject({ redirect: 'manual' }) }) it('refuses a redirect to a private address', async () => { const fetchMock = vi.fn().mockResolvedValue(redirect('http://127.0.0.1/admin')) vi.stubGlobal('fetch', fetchMock) await expect(fetchPage('https://example.com')).rejects.toMatchObject({ status: 400 }) expect(fetchMock).toHaveBeenCalledTimes(1) }) it('refuses a public name that resolves to a private address', async () => { vi.mocked(lookup).mockResolvedValue([{ address: '::1', family: 6 }] as never) const fetchMock = vi.fn() vi.stubGlobal('fetch', fetchMock) await expect(fetchPage('http://localtest.me/')).rejects.toMatchObject({ status: 400 }) expect(fetchMock).not.toHaveBeenCalled() }) it('treats a failed DNS lookup as unreachable', async () => { vi.mocked(lookup).mockRejectedValue(new Error('ENOTFOUND')) vi.stubGlobal('fetch', vi.fn()) await expect(fetchPage('https://nope.example.com')).rejects.toMatchObject({ status: 502, }) }) it('refuses a private URL without fetching it', async () => { const fetchMock = vi.fn() vi.stubGlobal('fetch', fetchMock) await expect(fetchPage('http://localhost/')).rejects.toMatchObject({ status: 400 }) expect(fetchMock).not.toHaveBeenCalled() }) it('gives up after too many redirects', async () => { vi.stubGlobal( 'fetch', vi.fn().mockImplementation(async () => redirect('/loop')), ) await expect(fetchPage('https://example.com')).rejects.toMatchObject({ message: expect.stringContaining('Too many redirects'), }) }) it('rejects error statuses, non-HTML and network failures as 502', async () => { for (const respond of [ async () => new Response('nope', { status: 404 }), async () => html('hi
', 202), async () => new Response('%PDF', { headers: { 'content-type': 'application/pdf' } }), async () => Promise.reject(new TypeError('fetch failed')), ]) { vi.stubGlobal('fetch', vi.fn().mockImplementation(respond)) await expect(fetchPage('https://example.com')).rejects.toMatchObject({ status: 502, }) } }) it('stops reading after 2 MB, even mid-chunk', async () => { const chunk = new Uint8Array(1_500_000).fill(97) let pulled = 0 const body = new ReadableStream({ pull(controller) { pulled++ controller.enqueue(chunk) }, }) vi.stubGlobal('fetch', vi.fn().mockResolvedValue(html(body))) const page = await fetchPage('https://example.com') expect(page.html.length).toBe(2_000_000) expect(pulled).toBeLessThan(4) }) }) describe('GET /v1/enrich/trackers', () => { const app = buildApp() // A Map-backed stand-in for Workers KV const kv = new Map