Files
ipal-kit/services/cookie-crawler/lib.mjs
T
Radosław SmolińskiandClaude Opus 5.5 4bb9c663fd Cookie scanner, phase 2: browser crawl through a shared scanner service
cookieScanner.crawl (opt-in) adds "Crawl site" to the Cookie review box. The
site asks the shared scanner service (services/cookie-crawler: Node +
Playwright, Dockerfile, deployed once on Coolify) to crawl its sitemap pages
twice, with no consent and after "Accept all". The service posts cookies,
storage keys and third-party hosts back to POST /api/ipal/cookie-crawl/results
(bearer token, running job only). No browser in the site.

Findings land as drafts through the same merge rules. Anything stored before
consent that is not necessary, and tracker requests before consent, are
violations, flagged on the review entries from the latest crawl only. The
cookie-crawl global keeps the latest result (no history). A dashboard warning
(CookieCrawlAlert) and an opt-in e-mail through the project's mail adapter
follow a crawl with violations or new unknown cookies. Scheduled crawls: a
Coolify scheduled task with the token. ipalEnvRules({ cookieCrawl: true }).

Also: the six older real-Payload tests no longer leave an orphaned
payload generate:types process (typescript.autoGenerate: false).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 15:14:01 +01:00

108 lines
4.5 KiB
JavaScript

// Pure helpers of the ipal 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(/<loc>\s*([^<\s]+)\s*<\/loc>/g)].map((m) => m[1].replace(/&amp;/g, '&'))
let xml = await text(`${origin}/sitemap.xml`)
if (/<sitemapindex/i.test(xml)) {
const children = locs(xml).filter((u) => 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()] }
}