import type { ConsentCategory } from '../categories.js' import type { OpenCookieRow } from './data/openCookieDatabase.js' import type { CookieFinding, OpenCookieCategory } from './types.js' /** * Lookup in the bundled Open Cookie Database (Apache-2.0, * github.com/jkwakman/Open-Cookie-Database; license in * docs/licenses/open-cookie-database-LICENSE.txt). Refreshed by * `scripts/refresh-cookie-database.mjs` — nothing is fetched at runtime. The * ~430 KB table is imported only when a scan needs it. */ export const DEFAULT_DATABASE_CATEGORIES: Record = { Analytics: 'analytics', // The database defines Functional as "technical, essential or strictly necessary", but // contributors file trackers there too (Hotjar's user id). An unchecked lookup must not // land as "no consent needed": it asks for consent until an editor says otherwise. Functional: 'functional', Marketing: 'marketing', Necessary: 'necessary', Personalization: 'functional', Security: 'necessary', } /** An index over database rows: exact names, then prefixes (longest first). */ export type CookieDatabaseIndex = { exact: Map prefixes: OpenCookieRow[] } export function indexCookieDatabase(rows: readonly OpenCookieRow[]): CookieDatabaseIndex { const exact = new Map() const prefixes: OpenCookieRow[] = [] for (const row of rows) { if (row[7] === 1) {prefixes.push(row)} else if (!exact.has(row[0])) {exact.set(row[0], row)} } prefixes.sort((a, b) => b[0].length - a[0].length) return { exact, prefixes } } let bundled: CookieDatabaseIndex | null = null /** The bundled database, indexed once per process. */ export async function loadCookieDatabase(): Promise { if (!bundled) { const { OPEN_COOKIE_DATABASE } = await import('./data/openCookieDatabase.js') bundled = indexCookieDatabase(OPEN_COOKIE_DATABASE) } return bundled } /** * A cookie name looked up in the database: exact name first, then the longest * matching wildcard prefix (`_gac_` matches `_gac_UA-1`). Null when unknown. */ export function lookupCookie( index: CookieDatabaseIndex, name: string, categories: Partial> = {}, ): CookieFinding | null { const row = index.exact.get(name) ?? index.prefixes.find((r) => r[0] && name.startsWith(r[0])) if (!row) {return null} const [pattern, platform, category, domain, description, retention, controller, wildcard] = row const map = { ...DEFAULT_DATABASE_CATEGORIES, ...categories } const thirdParty = /\(3rd party\)/i.test(domain) ? domain.replace(/\s*\(3rd party\)/i, '').trim() : '' return { category: map[category as OpenCookieCategory], ...(thirdParty ? { domain: thirdParty } : {}), name: wildcard === 1 && pattern !== name ? `${pattern}*` : name, ...(description ? { purpose: description } : {}), ...(retention ? { retention } : {}), source: 'database', sourceDetail: `Open Cookie Database: ${platform}${category ? ` (${category})` : ''}`, storage: 'cookie', vendor: controller || platform, } }