api/src/routes/private/trackers.ts
63 lines · 2248 bytes
5 symbols in this file
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