// Pure helpers of the IAPL cookie crawler (no browser, no network) — tested in // test/cookieCrawler.test.ts. Wire format: src/modules/consent/scanner/crawl/result.ts. import { createHash, timingSafeEqual } from 'node:crypto' /** `acme.pl=TOKEN,shop.example.com=TOKEN2` → [{ host, token }]. Tokens shorter than 16 chars are refused. */ export function parseSites(value = '') { const sites = [] for (const pair of value.split(/[,\n]/)) { const i = pair.indexOf('=') if (i < 1) {continue} const host = pair.slice(0, i).trim().toLowerCase().replace(/^www\./, '') const token = pair.slice(i + 1).trim() if (host && token.length >= 16) {sites.push({ host, token })} } return sites } /** Host without `www.`, lower case. */ export const bareHost = (url) => new URL(url).hostname.toLowerCase().replace(/^www\./, '') function sameToken(a, b) { const x = createHash('sha256').update(String(a)).digest() const y = createHash('sha256').update(String(b)).digest() return timingSafeEqual(x, y) } /** * Checks a crawl request: the site must be listed, the bearer token must be that * site's token, the callback must be on the same origin as the site, and only * https (http only when allowHttp — local tests). Returns an error string or null. */ export function checkCrawlRequest({ allowHttp = false, authorization, body, sites }) { if (!body || typeof body !== 'object') {return 'bad_request'} const { callbackUrl, jobId, siteUrl } = body if (typeof jobId !== 'string' || !/^[0-9a-f]{16,64}$/.test(jobId)) {return 'bad_job_id'} let site, callback try { site = new URL(siteUrl) callback = new URL(callbackUrl) } catch { return 'bad_url' } const protocols = allowHttp ? ['https:', 'http:'] : ['https:'] if (!protocols.includes(site.protocol)) {return 'https_only'} if (callback.origin !== site.origin) {return 'callback_not_on_site'} const entry = sites.find((s) => s.host === bareHost(site.href)) if (!entry) {return 'site_not_allowed'} const token = typeof authorization === 'string' && authorization.startsWith('Bearer ') ? authorization.slice(7).trim() : '' if (!token || !sameToken(token, entry.token)) {return 'unauthorized'} return null } /** * Pages to visit: the site URL, then up to `max` same-origin URLs from * /sitemap.xml (one level of sitemap index followed). Never throws. */ export async function discoverPages(siteUrl, max, fetchImpl = fetch) { const origin = new URL(siteUrl).origin const pages = [new URL(siteUrl).href] const text = async (url) => { try { const res = await fetchImpl(url, { signal: AbortSignal.timeout(15_000) }) return res.ok ? await res.text() : '' } catch { return '' } } const locs = (xml) => [...xml.matchAll(/\s*([^<\s]+)\s*<\/loc>/g)].map((m) => m[1].replace(/&/g, '&')) let xml = await text(`${origin}/sitemap.xml`) if (/ u.startsWith(origin)).slice(0, 5) xml = (await Promise.all(children.map(text))).join('\n') } for (const url of locs(xml)) { if (pages.length > max) {break} if (url.startsWith(`${origin}/`) && !pages.includes(url)) {pages.push(url)} } return pages } /** True for the site's own host and its subdomains. */ export function isFirstParty(host, siteHost) { const h = host.toLowerCase().replace(/^www\./, '') return h === siteHost || h.endsWith(`.${siteHost}`) } /** * Two runs (no consent / accept all) → the wire format's observations and * requests. A run: { cookies: [{ name, domain, page }], storage: [{ name, storage, page }], * requests: [{ host, page }] } — first sighting per page. */ export function mergeRuns(before, after) { const obs = new Map() const reqs = new Map() const add = (map, key, base, flag, page) => { const entry = map.get(key) ?? { ...base, after: false, before: false, pages: [] } entry[flag] = true if (page && entry.pages.length < 5 && !entry.pages.includes(page)) {entry.pages.push(page)} map.set(key, entry) } for (const [run, flag] of [[before, 'before'], [after, 'after']]) { for (const c of run.cookies) {add(obs, `cookie:${c.name}`, { domain: c.domain.replace(/^\./, ''), name: c.name, storage: 'cookie' }, flag, c.page)} for (const s of run.storage) {add(obs, `${s.storage}:${s.name}`, { name: s.name, storage: s.storage }, flag, s.page)} for (const r of run.requests) {add(reqs, r.host, { host: r.host }, flag, r.page)} } return { observations: [...obs.values()], requests: [...reqs.values()] } }