Commit 9e24c1f798

9e24c1f79844b329c023c7f26e8461c97d6ad313

parent: e1021181dd

Unsigned

Alicia Sykes <alicia@omg.lol> · 2026-10-10 21:07 UTC

Adds a check for GTM/trackers

Layout: unified · split

.github/CONTRIBUTING.md +1
@@ -307,6 +307,7 @@ Below is the full list of checks - it's basically the same as what is listed in
307 - 🟡 **Security policy** - Repo should have a security policy (SECURITY.md) and/or private vulnerability reporting enabled 307 - 🟡 **Security policy** - Repo should have a security policy (SECURITY.md) and/or private vulnerability reporting enabled
308 - 🟡 **Minimum stars** - Repo should have ≥100 stars 308 - 🟡 **Minimum stars** - Repo should have ≥100 stars
309 - 🟡 **Bus factor** - Flags if ≥96% of commits come from a single contributor (bots and AI excluded) 309 - 🟡 **Bus factor** - Flags if ≥96% of commits come from a single contributor (bots and AI excluded)
310 - 🟡 **Website trackers** - Website should not load privacy-invasive third-party trackers
310 - 🟡 **Trackers** - Android app should not have privacy-invasive trackers 311 - 🟡 **Trackers** - Android app should not have privacy-invasive trackers
311 - 🟡 **De-Googled** - Android app should not be broken without Google Play Services 312 - 🟡 **De-Googled** - Android app should not be broken without Google Play Services
312 - 🟡 **Privacy policy** - Privacy policy should not be graded poorly (via ToS;DR) 313 - 🟡 **Privacy policy** - Privacy policy should not be graded poorly (via ToS;DR)
api/README.md +1
@@ -27,6 +27,7 @@ Enrichment data
27- iOS app versioning, size, reviews and info 27- iOS app versioning, size, reviews and info
28- Docker container info 28- Docker container info
29- Website security and hosting summary 29- Website security and hosting summary
30- Third-party trackers loaded by a website (via DuckDuckGo's tracker blocklist)
30- Community overview, from Discord, Reddit and Mastadon 31- Community overview, from Discord, Reddit and Mastadon
31 32
32--- 33---
api/src/app.ts +7
@@ -21,6 +21,7 @@ import android from '@/routes/private/android'
21import discord from '@/routes/private/discord' 21import discord from '@/routes/private/discord'
22import reddit from '@/routes/private/reddit' 22import reddit from '@/routes/private/reddit'
23import website from '@/routes/private/website' 23import website from '@/routes/private/website'
24import trackers from '@/routes/private/trackers'
24import security from '@/routes/private/security' 25import security from '@/routes/private/security'
25import docker from '@/routes/private/docker' 26import docker from '@/routes/private/docker'
26 27
@@ -46,6 +47,7 @@ const buildPrivate = () => {
46 priv.route('/', discord) 47 priv.route('/', discord)
47 priv.route('/', reddit) 48 priv.route('/', reddit)
48 priv.route('/', website) 49 priv.route('/', website)
50 priv.route('/', trackers)
49 priv.route('/', security) 51 priv.route('/', security)
50 priv.route('/', docker) 52 priv.route('/', docker)
51 return priv 53 return priv
@@ -66,9 +68,13 @@ export const buildApp = () => {
66 // CORS everywhere. Public browse routes get the standard limit; enrich routes 68 // CORS everywhere. Public browse routes get the standard limit; enrich routes
67 // are public too, but anonymous callers hit a stricter limit while a valid 69 // are public too, but anonymous callers hit a stricter limit while a valid
68 // bearer token bypasses it. Edge caching stays off for enrich (below). 70 // bearer token bypasses it. Edge caching stays off for enrich (below).
71 // Trackers has its own bucket, so its page fetches never starve the other lookups.
69 app.use('*', cors({ origin: '*' })) 72 app.use('*', cors({ origin: '*' }))
70 const publicLimiter = rateLimit() 73 const publicLimiter = rateLimit()
71 const enrichLimiter = rateLimit((env) => env.ENRICH_RATE_LIMIT ?? env.RATE_LIMIT) 74 const enrichLimiter = rateLimit((env) => env.ENRICH_RATE_LIMIT ?? env.RATE_LIMIT)
75 const trackersLimiter = rateLimit(
76 (env) => env.TRACKERS_RATE_LIMIT ?? env.ENRICH_RATE_LIMIT ?? env.RATE_LIMIT,
77 )
72 app.use('/v1/*', (c, next) => { 78 app.use('/v1/*', (c, next) => {
73 if (!c.req.path.startsWith('/v1/enrich')) return publicLimiter(c, next) 79 if (!c.req.path.startsWith('/v1/enrich')) return publicLimiter(c, next)
74 const authed = hasValidToken(c.env.API_TOKEN, c.req.header('authorization')) 80 const authed = hasValidToken(c.env.API_TOKEN, c.req.header('authorization'))
@@ -76,6 +82,7 @@ export const buildApp = () => {
76 throw new ApiError('UNAUTHORIZED', 'Invalid or missing bearer token', 401) 82 throw new ApiError('UNAUTHORIZED', 'Invalid or missing bearer token', 401)
77 } 83 }
78 if (authed) return next() 84 if (authed) return next()
85 if (c.req.path.startsWith('/v1/enrich/trackers')) return trackersLimiter(c, next)
79 return enrichLimiter(c, next) 86 return enrichLimiter(c, next)
80 }) 87 })
81 app.use('/v1/*', async (c, next) => { 88 app.use('/v1/*', async (c, next) => {
api/src/lib/cache/freshness.ts +2
@@ -9,6 +9,8 @@ export const CACHE_DAYS = {
9 security: 14, 9 security: 14,
10 android: 60, 10 android: 60,
11 website: 60, 11 website: 60,
12 trackers: 30,
13 trackerBlocklist: 7, // Shared DuckDuckGo blocklist used by the trackers route
12 ios: 60, 14 ios: 60,
13 github: 7, 15 github: 7,
14 discord: 14, 16 discord: 14,
api/src/lib/env.ts +1
@@ -19,6 +19,7 @@ export const readEnv = (workersEnv?: Partial<AppEnv>): AppEnv => {
19 CACHE: workersEnv?.CACHE, 19 CACHE: workersEnv?.CACHE,
20 RATE_LIMIT: workersEnv?.RATE_LIMIT, 20 RATE_LIMIT: workersEnv?.RATE_LIMIT,
21 ENRICH_RATE_LIMIT: workersEnv?.ENRICH_RATE_LIMIT, 21 ENRICH_RATE_LIMIT: workersEnv?.ENRICH_RATE_LIMIT,
22 TRACKERS_RATE_LIMIT: workersEnv?.TRACKERS_RATE_LIMIT,
22 API_BASE: workersEnv?.API_BASE ?? env.API_BASE, 23 API_BASE: workersEnv?.API_BASE ?? env.API_BASE,
23 } 24 }
24} 25}
api/src/lib/fetch.ts +1
@@ -19,6 +19,7 @@ const ALLOWED_HOSTS = new Set([
19 'api.deps.dev', 19 'api.deps.dev',
20 'plexus.techlore.tech', 20 'plexus.techlore.tech',
21 'hub.docker.com', 21 'hub.docker.com',
22 'staticcdn.duckduckgo.com',
22]) 23])
23 24
24export interface FetchOpts { 25export interface FetchOpts {
api/src/lib/page.ts added +130
@@ -0,0 +1,130 @@
1/**
2 * Fetches the HTML of a public web page, for enrich routes that inspect websites.
3 * Unlike fetchJson the host is arbitrary, so IPs, local names, custom ports and
4 * hosts resolving to private addresses are refused, each redirect hop is
5 * re-checked, and the body is capped in size.
6 */
7
8import { ApiError } from '@/lib/errors'
9import { log } from '@/lib/log'
10
11const MAX_BYTES = 2_000_000
12const MAX_REDIRECTS = 5
13const TIMEOUT_MS = 10000
14const USER_AGENT =
15 'Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0'
16const LOCAL_SUFFIXES = ['.localhost', '.local', '.internal', '.lan', '.home.arpa']
17
18export interface Page {
19 // Where the page ended up, after any redirects
20 url: string
21 html: string
22}
23
24// Only plain http(s) on public hostnames and default ports, never IPs or local names
25export const isPublicUrl = (url: URL) => {
26 const host = url.hostname.toLowerCase().replace(/\.$/, '')
27 return (
28 ['http:', 'https:'].includes(url.protocol) &&
29 !url.port &&
30 !url.username &&
31 !url.password &&
32 host.includes('.') &&
33 !/^[\d.]+$/.test(host) &&
34 !host.startsWith('[') &&
35 !LOCAL_SUFFIXES.some((suffix) => host.endsWith(suffix))
36 )
37}
38
39// IPv4 blocks that are never public (RFC 6890): private, loopback, link-local,
40// shared CGNAT, benchmarking, multicast and reserved ranges
41const PRIVATE_V4: [string, number][] = [
42 ['0.0.0.0', 8],
43 ['10.0.0.0', 8],
44 ['100.64.0.0', 10],
45 ['127.0.0.0', 8],
46 ['169.254.0.0', 16],
47 ['172.16.0.0', 12],
48 ['192.0.0.0', 24],
49 ['192.168.0.0', 16],
50 ['198.18.0.0', 15],
51 ['224.0.0.0', 3],
52]
53
54const v4ToInt = (ip: string) =>
55 ip.split('.').reduce((n, part) => n * 256 + Number(part), 0)
56
57// Special IPv6 (anything under ::, unique-local, link-local, NAT64) or private IPv4
58export const isPrivateIp = (ip: string) => {
59 const addr = ip.toLowerCase()
60 if (addr.includes(':')) return /^(::|fc|fd|fe[89a-f]|64:ff9b:)/.test(addr)
61 return PRIVATE_V4.some(
62 ([base, bits]) => v4ToInt(addr) >>> (32 - bits) === v4ToInt(base) >>> (32 - bits),
63 )
64}
65
66// Workers can't reach private networks, elsewhere refuse hosts that resolve to them.
67// Fetch resolves again, so this blocks static records (like localtest.me), not fast rebinding.
68const resolvesPrivate = async (host: string) => {
69 if (globalThis.navigator?.userAgent === 'Cloudflare-Workers') return false
70 const { lookup } = await import('node:dns/promises')
71 const addresses = await lookup(host, { all: true })
72 return addresses.some(({ address }) => isPrivateIp(address))
73}
74
75// Read at most MAX_BYTES of the body, then stop downloading
76const readCapped = async (res: Response) => {
77 const reader = res.body?.getReader()
78 if (!reader) return ''
79 const decoder = new TextDecoder()
80 let html = ''
81 let size = 0
82 while (size < MAX_BYTES) {
83 const { done, value } = await reader.read()
84 if (done) break
85 const chunk = value.subarray(0, MAX_BYTES - size)
86 size += chunk.byteLength
87 html += decoder.decode(chunk, { stream: true })
88 }
89 await reader.cancel()
90 return html
91}
92
93export const fetchPage = async (target: string): Promise<Page> => {
94 const signal = AbortSignal.timeout(TIMEOUT_MS)
95 let url = new URL(target)
96 try {
97 for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
98 if (!isPublicUrl(url) || (await resolvesPrivate(url.hostname))) {
99 throw new ApiError('BAD_REQUEST', `URL not allowed: ${url.hostname}`, 400)
100 }
101 const res = await fetch(url, {
102 headers: { 'User-Agent': USER_AGENT, Accept: 'text/html' },
103 redirect: 'manual',
104 signal,
105 })
106 const location = res.headers.get('location')
107 if (res.status >= 300 && res.status < 400 && location) {
108 await res.body?.cancel()
109 url = new URL(location, url)
110 continue
111 }
112 if (!res.ok) {
113 throw new ApiError(
114 'UPSTREAM_ERROR',
115 `${url.hostname} returned ${res.status}`,
116 502,
117 )
118 }
119 if (!res.headers.get('content-type')?.includes('html')) {
120 throw new ApiError('UPSTREAM_ERROR', `${url.hostname} did not return HTML`, 502)
121 }
122 return { url: url.href, html: await readCapped(res) }
123 }
124 throw new ApiError('UPSTREAM_ERROR', `Too many redirects from ${target}`, 502)
125 } catch (caught) {
126 if (caught instanceof ApiError) throw caught
127 log.warn('page_fetch_failed', { host: url.hostname, err: (caught as Error).message })
128 throw new ApiError('UPSTREAM_ERROR', `Could not fetch ${url.hostname}`, 502)
129 }
130}
api/src/lib/trackers.ts added +149
@@ -0,0 +1,149 @@
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}
api/src/routes/private/trackers.ts added +63
@@ -0,0 +1,63 @@
1// Third-party trackers a web page loads, classified by DuckDuckGo's Tracker Blocklist
2import { createRoute, z } from '@hono/zod-openapi'
3import { fetchJson } from '@/lib/fetch'
4import { fetchPage } from '@/lib/page'
5import { BLOCKLIST_URL, findTrackers, slimBlocklist } from '@/lib/trackers'
6import { freshSeconds } from '@/lib/cache/freshness'
7import { newApp } from '@/lib/openapi'
8import { ErrorResponse, Ok, TrackersReportSchema } from '@/schemas'
9
10const app = newApp()
11
12const FRESH_TTL = freshSeconds('trackers')
13const BLOCKLIST_TTL = freshSeconds('trackerBlocklist')
14
15const route = createRoute({
16 method: 'get',
17 path: '/enrich/trackers',
18 tags: ['Enrichment'],
19 summary: 'Website trackers',
20 description:
21 "Third-party trackers a web page loads, as classified by DuckDuckGo's " +
22 'Tracker Blocklist (CC BY-NC-SA 4.0). Only the HTML is checked, so trackers ' +
23 'that other scripts load later are not seen.',
24 request: { query: z.object({ url: z.string().url() }) },
25 responses: {
26 200: Ok(TrackersReportSchema),
27 400: ErrorResponse,
28 401: ErrorResponse,
29 500: ErrorResponse,
30 502: ErrorResponse,
31 },
32})
33
34// Short fixed-length digest, as a full URL could exceed KV's 512-byte key limit
35const sha256 = async (text: string) => {
36 const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
37 return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('')
38}
39
40// Cache key is the host plus a hash of the full URL, the blocklist is shared by all pages
41app.openapi(route, async (c) => {
42 const { url } = c.req.valid('query')
43 const { hostname, origin, pathname, search } = new URL(url)
44 const data = await c.var.storage.fetch(
45 `trackers:${hostname}:${await sha256(origin + pathname + search)}`,
46 FRESH_TTL,
47 async () => {
48 const [page, blocklist] = await Promise.all([
49 fetchPage(url),
50 c.var.storage.fetch('trackers:blocklist', BLOCKLIST_TTL, async () =>
51 slimBlocklist(await fetchJson(BLOCKLIST_URL, { timeoutMs: 15000 })),
52 ),
53 ])
54 return {
55 finalUrl: page.url,
56 trackers: findTrackers(page.html, page.url, blocklist),
57 }
58 },
59 )
60 return c.json(data, 200)
61})
62
63export default app
api/src/schemas/index.ts +14
@@ -144,6 +144,20 @@ export const WebsiteReportSchema = z
144 .object({}) 144 .object({})
145 .openapi('WebsiteReport', { description: 'APIVoid url reputation report, passthrough' }) 145 .openapi('WebsiteReport', { description: 'APIVoid url reputation report, passthrough' })
146 146
147// Third-party trackers found on a web page, via DuckDuckGo's Tracker Blocklist
148export const TrackersReportSchema = z
149 .object({
150 finalUrl: z.string(),
151 trackers: z.array(
152 z.object({
153 domain: z.string(),
154 owner: z.string(),
155 categories: z.array(z.string()),
156 }),
157 ),
158 })
159 .openapi('TrackersReport')
160
147export const DockerInfoSchema = z.object({}).openapi('DockerInfo', { 161export const DockerInfoSchema = z.object({}).openapi('DockerInfo', {
148 description: 'Portainer template, Docker Hub metrics and generated run/compose usage', 162 description: 'Portainer template, Docker Hub metrics and generated run/compose usage',
149}) 163})
api/src/types.ts +1
@@ -66,6 +66,7 @@ export interface AppEnv {
66 CACHE?: KVNamespace 66 CACHE?: KVNamespace
67 RATE_LIMIT?: RateLimiter 67 RATE_LIMIT?: RateLimiter
68 ENRICH_RATE_LIMIT?: RateLimiter 68 ENRICH_RATE_LIMIT?: RateLimiter
69 TRACKERS_RATE_LIMIT?: RateLimiter
69 API_BASE?: string 70 API_BASE?: string
70} 71}
71 72
api/tests/app.test.ts +15
@@ -95,6 +95,21 @@ describe('enrich rate limiting', () => {
95 expect(calls.n).toBe(0) 95 expect(calls.n).toBe(0)
96 }) 96 })
97 97
98 it('trackers uses its own limit, not the shared enrich one', async () => {
99 const enrich = denyLimiter()
100 const trackers = denyLimiter()
101 const res = await app.fetch(
102 new Request('http://localhost/v1/enrich/trackers?url=https://example.com'),
103 {
104 API_TOKEN: 'test',
105 ENRICH_RATE_LIMIT: enrich.limiter,
106 TRACKERS_RATE_LIMIT: trackers.limiter,
107 },
108 )
109 expect(res.status).toBe(429)
110 expect([enrich.calls.n, trackers.calls.n]).toEqual([0, 1])
111 })
112
98 it('wrong token does not bypass the enrich rate limit', async () => { 113 it('wrong token does not bypass the enrich rate limit', async () => {
99 const { limiter, calls } = denyLimiter() 114 const { limiter, calls } = denyLimiter()
100 const res = await app.fetch( 115 const res = await app.fetch(
api/tests/trackers.test.ts added +389
@@ -0,0 +1,389 @@
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) =>
225 new Response(body, { 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 () =>
289 new Response('%PDF', { headers: { 'content-type': 'application/pdf' } }),
290 async () => Promise.reject(new TypeError('fetch failed')),
291 ]) {
292 vi.stubGlobal('fetch', vi.fn().mockImplementation(respond))
293 await expect(fetchPage('https://example.com')).rejects.toMatchObject({
294 status: 502,
295 })
296 }
297 })
298
299 it('stops reading after 2 MB, even mid-chunk', async () => {
300 const chunk = new Uint8Array(1_500_000).fill(97)
301 let pulled = 0
302 const body = new ReadableStream({
303 pull(controller) {
304 pulled++
305 controller.enqueue(chunk)
306 },
307 })
308 vi.stubGlobal('fetch', vi.fn().mockResolvedValue(html(body)))
309 const page = await fetchPage('https://example.com')
310 expect(page.html.length).toBe(2_000_000)
311 expect(pulled).toBeLessThan(4)
312 })
313})
314
315describe('GET /v1/enrich/trackers', () => {
316 const app = buildApp()
317 // A Map-backed stand-in for Workers KV
318 const kv = new Map<string, string>()
319 const CACHE = {
320 get: async (key: string) => (kv.has(key) ? JSON.parse(kv.get(key)!) : null),
321 put: async (key: string, value: string) => void kv.set(key, value),
322 }
323 const hit = (url: string) =>
324 app.fetch(
325 new Request(`http://localhost/v1/enrich/trackers?url=${encodeURIComponent(url)}`),
326 { CACHE },
327 )
328
329 afterEach(() => vi.unstubAllGlobals())
330
331 // Serve the blocklist and a page, recording which URLs were requested
332 const upstream = (page: Response | (() => Response)) => {
333 const calls: string[] = []
334 vi.stubGlobal(
335 'fetch',
336 vi.fn(async (input: string | URL) => {
337 const url = String(input)
338 calls.push(url)
339 if (url === BLOCKLIST_URL) return Response.json(tds)
340 return typeof page === 'function' ? page() : page
341 }),
342 )
343 return calls
344 }
345
346 it('returns the trackers a page loads, and caches the result', async () => {
347 const calls = upstream(() => html(GTM))
348 const res = await hit('https://route-test.example.com/page?utm=1')
349 expect(res.status).toBe(200)
350 expect(await res.json()).toEqual({
351 finalUrl: 'https://route-test.example.com/page?utm=1',
352 trackers: [
353 {
354 domain: 'googletagmanager.com',
355 owner: 'Google Ads',
356 categories: ['Tag Manager'],
357 },
358 ],
359 })
360 const again = await hit('https://route-test.example.com/page?utm=1#top')
361 expect(again.status).toBe(200)
362 expect(calls.filter((url) => url !== BLOCKLIST_URL)).toHaveLength(1)
363 })
364
365 it('caches each query string apart, under keys short enough for KV', async () => {
366 const calls = upstream(() => html(''))
367 const long = `https://route-keys.example.com/${'a'.repeat(1000)}`
368 for (const url of [`${long}?x=1`, `${long}?x=2`]) {
369 expect((await hit(url)).status).toBe(200)
370 }
371 expect(calls.filter((url) => url !== BLOCKLIST_URL)).toHaveLength(2)
372 expect([...kv.keys()].every((key) => key.length <= 512)).toBe(true)
373 })
374
375 it('rejects an invalid or private URL with the error envelope', async () => {
376 upstream(html(''))
377 expect((await hit('not a url')).status).toBe(400)
378 const res = await hit('http://127.0.0.1/')
379 expect(res.status).toBe(400)
380 expect(await res.json()).toMatchObject({ error: { code: 'BAD_REQUEST' } })
381 })
382
383 it('returns a 502 envelope when the page cannot be fetched', async () => {
384 upstream(new Response('down', { status: 503 }))
385 const res = await hit('https://route-down.example.com/')
386 expect(res.status).toBe(502)
387 expect(await res.json()).toMatchObject({ error: { code: 'UPSTREAM_ERROR' } })
388 })
389})
api/wrangler.toml +8
@@ -33,6 +33,14 @@ type = "ratelimit"
33namespace_id = "1002" 33namespace_id = "1002"
34simple = { limit = 10, period = 60 } 34simple = { limit = 10, period = 60 }
35 35
36# Own limit for anonymous /enrich/trackers requests, which each fetch a web page,
37# kept separate so they never use up the budget of the other enrich routes
38[[unsafe.bindings]]
39name = "TRACKERS_RATE_LIMIT"
40type = "ratelimit"
41namespace_id = "1003"
42simple = { limit = 10, period = 60 }
43
36# Scheduled cache warmer 44# Scheduled cache warmer
37[triggers] 45[triggers]
38crons = ["*/15 * * * *"] 46crons = ["*/15 * * * *"]
lib/checks/check-project.py +40 −1
@@ -6,6 +6,7 @@ import os
6import re 6import re
7import sys 7import sys
8from datetime import datetime, timedelta, timezone 8from datetime import datetime, timedelta, timezone
9from urllib.parse import urlparse
9 10
10import yaml 11import yaml
11 12
@@ -35,6 +36,11 @@ SPAM_WINDOW_DAYS = 2
35NEW_ACCOUNT_DAYS = 14 36NEW_ACCOUNT_DAYS = 14
36TRACKER_LIMIT = 2 37TRACKER_LIMIT = 2
37POOR_PRIVACY_GRADES = {"D", "E"} 38POOR_PRIVACY_GRADES = {"D", "E"}
39# The API fetches and scans the page itself, so allow it longer to respond
40TRACKERS_TIMEOUT = 30
41# Code hosts and app stores, whose trackers belong to the platform rather than the project
42PLATFORM_HOSTS = ("github.com", "gitlab.com", "codeberg.org", "play.google.com",
43 "apps.apple.com", "addons.mozilla.org", "chromewebstore.google.com")
38 44
39SESSION = utils.make_session(user_agent=USER_AGENT) 45SESSION = utils.make_session(user_agent=USER_AGENT)
40API_TOKEN = os.environ.get("API_TOKEN", "") 46API_TOKEN = os.environ.get("API_TOKEN", "")
@@ -119,6 +125,10 @@ PRIVACY_GRADE_MSG = (
119 "The privacy policy for this service is graded as poor by ToS;DR," 125 "The privacy policy for this service is graded as poor by ToS;DR,"
120 " indicating serious privacy concerns" 126 " indicating serious privacy concerns"
121) 127)
128WEB_TRACKERS_MSG = (
129 "The website appears to load third-party trackers ({}), according to"
130 " DuckDuckGo's tracker list. Please confirm these are justified"
131)
122 132
123 133
124def load_diff(path): 134def load_diff(path):
@@ -268,11 +278,40 @@ def check_privacy_grade(tosdr_id):
268 return None 278 return None
269 279
270 280
281def _is_platform(url):
282 """True if a URL is on a code host or app store, rather than the project's own site."""
283 host = (urlparse(url).hostname or "").lower()
284 return any(host == h or host.endswith(f".{h}") for h in PLATFORM_HOSTS)
285
286
287def check_website_trackers(url):
288 """Return WEB_TRACKERS_MSG naming the third-party trackers the website loads."""
289 try:
290 if _is_platform(url):
291 logger.info("Tracker check skipped for %s (not the project's own site)", url)
292 return None
293 report = utils.fetch_trackers(url, API_TOKEN, session=SESSION,
294 timeout=TRACKERS_TIMEOUT, label=url)
295 if not report:
296 return None
297 if _is_platform(report.get("finalUrl", "")):
298 logger.info("Tracker check skipped for %s (redirects to %s)", url, report["finalUrl"])
299 return None
300 domains = [t["domain"] for t in report.get("trackers", [])]
301 logger.info("Website trackers on %s: %s", url, ", ".join(domains) or "none found")
302 return WEB_TRACKERS_MSG.format(", ".join(domains)) if domains else None
303 except Exception as exc:
304 logger.warning("check_website_trackers error for %s: %s", url, exc)
305 return None
306
307
271def check_privacy_signals(diff): 308def check_privacy_signals(diff):
272 """Check trackers, de-Googled support and ToS;DR grade for added services.""" 309 """Check website trackers, Android trackers, de-Googled support and ToS;DR grade for additions."""
273 findings = [] 310 findings = []
274 for svc in get_services(diff, "added"): 311 for svc in get_services(diff, "added"):
275 fields = svc.get("fields", {}) 312 fields = svc.get("fields", {})
313 if fields.get("url"):
314 findings.append(check_website_trackers(fields["url"]))
276 if fields.get("androidApp"): 315 if fields.get("androidApp"):
277 findings.extend(check_android_app(fields["androidApp"])) 316 findings.extend(check_android_app(fields["androidApp"]))
278 if fields.get("tosdrId"): 317 if fields.get("tosdrId"):
lib/utils/__init__.py +2
@@ -15,6 +15,7 @@ try:
15 fetch_ios, 15 fetch_ios,
16 fetch_privacy, 16 fetch_privacy,
17 fetch_security_report, 17 fetch_security_report,
18 fetch_trackers,
18 ios_app_id, 19 ios_app_id,
19 ios_days_since_update, 20 ios_days_since_update,
20 ios_rating, 21 ios_rating,
@@ -58,6 +59,7 @@ __all__ = [
58 "fetch_privacy", 59 "fetch_privacy",
59 "fetch_repo", 60 "fetch_repo",
60 "fetch_security_report", 61 "fetch_security_report",
62 "fetch_trackers",
61 "gh_get", 63 "gh_get",
62 "has_security_contact", 64 "has_security_contact",
63 "ios_app_id", 65 "ios_app_id",
lib/utils/api.py +6
@@ -58,6 +58,12 @@ def fetch_privacy(tosdr_id, token, session=None, timeout=DEFAULT_TIMEOUT, label=
58 token=token, session=session, timeout=timeout, label=label) 58 token=token, session=session, timeout=timeout, label=label)
59 59
60 60
61def fetch_trackers(url, token, session=None, timeout=DEFAULT_TIMEOUT, label=None):
62 """Fetch the third-party trackers a web page loads from the unified API. Returns JSON or None."""
63 return enrich_get("trackers", params={"url": url},
64 token=token, session=session, timeout=timeout, label=label)
65
66
61def unpatched_advisories(report): 67def unpatched_advisories(report):
62 """Return (low_medium, high_critical) counts of open, unpatched advisories.""" 68 """Return (low_medium, high_critical) counts of open, unpatched advisories."""
63 items = (report.get("advisories") or {}).get("items") or [] if report else [] 69 items = (report.get("advisories") or {}).get("items") or [] if report else []
web/src/pages/api/index.astro +1
@@ -76,6 +76,7 @@ const endpoints = [
76 ['/v1/enrich/ios/{bundleId}', 'Version, size and reviews'], 76 ['/v1/enrich/ios/{bundleId}', 'Version, size and reviews'],
77 ['/v1/enrich/docker/{name}', 'Image tags and pull stats'], 77 ['/v1/enrich/docker/{name}', 'Image tags and pull stats'],
78 ['/v1/enrich/website', 'Hosting, DNS and security posture'], 78 ['/v1/enrich/website', 'Hosting, DNS and security posture'],
79 ['/v1/enrich/trackers', 'Third-party trackers a website loads'],
79 ['/v1/enrich/discord/{invite}', 'Server size and activity'], 80 ['/v1/enrich/discord/{invite}', 'Server size and activity'],
80 ], 81 ],
81 }, 82 },