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]>
This commit is contained in:
Radosław Smoliński
2026-10-27 15:14:01 +01:00
co-authored by Claude Opus 5.5
parent 4f69f6ed20
commit 4bb9c663fd
44 changed files with 2165 additions and 36 deletions
+3
View File
@@ -0,0 +1,3 @@
node_modules
npm-debug.log
*.md
+17
View File
@@ -0,0 +1,17 @@
# ipal cookie crawler — one shared service for all sites (docs/cookie-scanner.md → Coolify).
# The Playwright image ships Chromium and its system libraries; the npm package
# version must match the image tag.
FROM mcr.microsoft.com/playwright:v1.64.0-noble
WORKDIR /app
ENV NODE_ENV=production
COPY package.json package-lock.json ./
RUN npm ci --omit=dev --no-audit --no-fund
COPY lib.mjs crawl.mjs server.mjs cli.mjs ./
# The image's non-root user; Chromium runs sandboxed as this user.
USER pwuser
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s \
CMD node -e "fetch('http://127.0.0.1:'+(process.env.PORT||3000)+'/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
CMD ["node", "server.mjs"]
+11
View File
@@ -0,0 +1,11 @@
# ipal cookie crawler
The browser half of ipal-kit's cookie scanner: one shared service that crawls a site twice (no
consent / after "Accept all") and posts cookies, storage keys and third-party hosts back to the
site. Sites never run a browser.
Setup, Coolify deploy, env and network notes: `docs/cookie-scanner.md` → "Browser crawl" in the
ipal-kit repository (also shipped in `node_modules/@intecion/ipal-kit/docs/`).
- `node server.mjs` — the service (`IPAL_CRAWLER_SITES="acme.pl=TOKEN"`).
- `node cli.mjs https://acme.pl --pages 10` — the same crawl from a laptop or CI, JSON on stdout.
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env node
// Same crawl as the service, from a laptop or CI — prints the result as JSON.
// node cli.mjs <siteUrl> [--pages 20] [--accept '[data-ipal="accept"]'] [--wait 3000]
// Exit code: 0 = nothing stored before consent but the consent cookie, 1 = something else was, 2 = setup problem.
// The verdict per cookie needs the site's categories: the panel's "Crawl site" does that.
import { crawlSite } from './crawl.mjs'
const args = process.argv.slice(2)
const opt = (name, def) => (args.includes(`--${name}`) ? args[args.indexOf(`--${name}`) + 1] : def)
if (!args[0] || args[0].startsWith('--')) {
console.error('Usage: node cli.mjs <siteUrl> [--pages N] [--accept selector] [--wait ms]')
process.exit(2)
}
let chromium
try {
;({ chromium } = await import('playwright'))
} catch {
console.error('Playwright not found: npm install (in services/cookie-crawler) && npx playwright install chromium')
process.exit(2)
}
const result = await crawlSite({
acceptSelector: opt('accept', '[data-ipal="accept"]'),
chromium,
maxPages: Number(opt('pages', 20)),
siteUrl: args[0],
waitMs: Number(opt('wait', 3000)),
})
console.log(JSON.stringify(result, null, 2))
const early = result.observations.filter((o) => o.before && o.name !== 'cookie-consent')
if (early.length) {console.error(`Stored before consent: ${early.map((o) => o.name).join(', ')} — classify them in the panel.`)}
process.exit(early.length ? 1 : 0)
+76
View File
@@ -0,0 +1,76 @@
// The crawl itself: two fresh browser profiles over the same pages — one with
// no consent decision, one after clicking "Accept all". Records cookies,
// localStorage / sessionStorage keys and third-party request hosts per page.
import { bareHost, discoverPages, isFirstParty, mergeRuns } from './lib.mjs'
async function run(browser, pages, { accept, acceptSelector, pageTimeoutMs, siteHost, waitMs }) {
const context = await browser.newContext()
const result = { accepted: false, cookies: [], requests: [], storage: [] }
let current = '/'
const seen = new Set()
const once = (key) => (seen.has(key) ? false : (seen.add(key), true))
context.on('request', (request) => {
let host
try {
host = new URL(request.url()).hostname.toLowerCase()
} catch {
return
}
if (!host || isFirstParty(host, siteHost) || !once(`r:${host}:${current}`)) {return}
result.requests.push({ host, page: current })
})
try {
const page = await context.newPage()
await page.setExtraHTTPHeaders({ 'X-Ipal-Cookie-Crawler': '1' })
for (const [i, url] of pages.entries()) {
current = new URL(url).pathname
await page.goto(url, { timeout: pageTimeoutMs, waitUntil: 'load' }).catch(() => {})
if (accept && i === 0) {
const button = page.locator(acceptSelector).first()
if (await button.count().catch(() => 0)) {
await button.click({ timeout: 5_000 }).then(() => (result.accepted = true)).catch(() => {})
}
}
await page.waitForTimeout(waitMs)
const keys = await page
.evaluate(() => ({ localStorage: Object.keys(localStorage), sessionStorage: Object.keys(sessionStorage) }))
.catch(() => ({ localStorage: [], sessionStorage: [] }))
for (const [storage, names] of Object.entries(keys)) {
for (const name of names) {if (once(`s:${storage}:${name}:${current}`)) {result.storage.push({ name, page: current, storage })}}
}
for (const c of await context.cookies()) {
if (once(`c:${c.name}:${current}`)) {result.cookies.push({ domain: c.domain, name: c.name, page: current })}
}
}
} finally {
await context.close()
}
return result
}
/**
* Crawls a site and returns the wire format (without jobId):
* `{ ok: true, pages, observations, requests, accepted }`. `chromium` is
* Playwright's (injected — the caller decides how it is installed).
*/
export async function crawlSite({
acceptSelector = '[data-ipal="accept"]',
chromium,
fetchImpl = fetch,
maxPages = 20,
pageTimeoutMs = 30_000,
siteUrl,
waitMs = 3_000,
}) {
const pages = await discoverPages(siteUrl, Math.min(100, Math.max(0, maxPages)), fetchImpl)
const siteHost = bareHost(siteUrl)
const browser = await chromium.launch()
try {
const options = { acceptSelector, pageTimeoutMs, siteHost, waitMs }
const before = await run(browser, pages, { ...options, accept: false })
const after = await run(browser, pages, { ...options, accept: true })
return { accepted: after.accepted, ok: true, pages: pages.map((p) => new URL(p).pathname), ...mergeRuns(before, after) }
} finally {
await browser.close()
}
}
+107
View File
@@ -0,0 +1,107 @@
// 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()] }
}
+46
View File
@@ -0,0 +1,46 @@
{
"name": "@intecion/ipal-cookie-crawler",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@intecion/ipal-cookie-crawler",
"version": "1.0.0",
"license": "MIT",
"dependencies": {
"playwright": "1.64.0"
},
"engines": {
"node": ">=20"
}
},
"node_modules/playwright": {
"version": "1.64.0",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.0.tgz",
"integrity": "sha512-kVzTnYFYEyQ9RGzBjNCd2+yEqWmVbxl3AHPynv3qQ6JTjv4a+kwRcnqQwIpuP3NnrnIrE/Q6wWAIAvMfIE2/Yg==",
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.64.0"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/playwright-core": {
"version": "1.64.0",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.0.tgz",
"integrity": "sha512-T9r+MZkTECl2+oUcZ26YgZzTrYidTsIhYYkJix+6iDOymOb1FB2RLLSOxRGnZGv5DStt+aduIVbt+E8WygXYpg==",
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=20"
}
}
}
}
+18
View File
@@ -0,0 +1,18 @@
{
"name": "@intecion/ipal-cookie-crawler",
"version": "1.0.0",
"private": true,
"description": "Headless-browser cookie crawler for ipal-kit sites (Cookie review → Crawl site). Runs as one shared service, never inside a site.",
"license": "MIT",
"type": "module",
"scripts": {
"crawl": "node cli.mjs",
"start": "node server.mjs"
},
"dependencies": {
"playwright": "1.64.0"
},
"engines": {
"node": ">=20"
}
}
+163
View File
@@ -0,0 +1,163 @@
// ipal cookie crawler — HTTP service (deploy: docs/cookie-scanner.md → "Scanner service on Coolify").
//
// GET /health → { ok, running, queued }
// POST /crawl → Authorization: Bearer <the site's token>
// { jobId, siteUrl, callbackUrl, maxPages?, acceptSelector? } → 202 { ok, queued }
// The crawl runs in the background; the result is POSTed to callbackUrl with the
// same bearer token.
//
// Env: IPAL_CRAWLER_SITES="acme.pl=TOKEN,shop.example.com=TOKEN2" (required), PORT (3000),
// CRAWLER_CONCURRENCY (1), CRAWLER_QUEUE_MAX (20), CRAWLER_JOB_TIMEOUT_MS (600000),
// CRAWLER_WAIT_MS (3000), CRAWLER_ALLOW_HTTP (unset; "1" only for local tests).
import { createServer } from 'node:http'
import { pathToFileURL } from 'node:url'
import { checkCrawlRequest, parseSites } from './lib.mjs'
const MAX_BODY = 64 * 1024
function readJson(req) {
return new Promise((resolve) => {
let size = 0
const chunks = []
req.on('data', (c) => {
size += c.length
if (size > MAX_BODY) {req.destroy()}
else {chunks.push(c)}
})
req.on('end', () => {
try {
resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))
} catch {
resolve(null)
}
})
req.on('error', () => resolve(null))
})
}
const send = (res, status, body) => {
res.writeHead(status, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(body))
}
/** POST the result to the site; 3 tries (0 s, 5 s, 30 s). */
async function deliver({ callbackUrl, fetchImpl, log, result, token }, delays = [0, 5_000, 30_000]) {
for (const delay of delays) {
if (delay) {await new Promise((r) => setTimeout(r, delay))}
try {
const res = await fetchImpl(callbackUrl, {
body: JSON.stringify(result),
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
method: 'POST',
signal: AbortSignal.timeout(60_000),
})
if (res.ok || (res.status >= 400 && res.status < 500)) {
log(`result for ${result.jobId} → ${callbackUrl}: HTTP ${res.status}`)
return res.status
}
} catch (err) {
log(`result for ${result.jobId} → ${callbackUrl} failed: ${err?.message ?? err}`)
}
}
return 0
}
/**
* The service as a function of its parts, so tests can inject `crawl` and
* `fetchImpl`. `crawl(job) → wire result without jobId`.
*/
export function createCrawlerServer({
allowHttp = false,
concurrency = 1,
crawl,
deliveryDelays,
fetchImpl = fetch,
jobTimeoutMs = 600_000,
log = (m) => console.log(`[crawler] ${m}`),
queueMax = 20,
sites,
}) {
const queue = []
let running = 0
const idle = []
const pump = () => {
while (running < concurrency && queue.length) {
const job = queue.shift()
running++
void (async () => {
let result
let timer
try {
result = await Promise.race([
crawl(job),
new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`crawl took longer than ${jobTimeoutMs} ms`)), jobTimeoutMs)
}),
])
result = { ...result, jobId: job.jobId }
} catch (err) {
result = { error: String(err?.message ?? err).slice(0, 300), jobId: job.jobId, ok: false }
} finally {
clearTimeout(timer)
}
log(`crawled ${job.siteUrl} (${job.jobId}): ${result.ok ? `${result.pages.length} pages` : result.error}`)
await deliver({ callbackUrl: job.callbackUrl, fetchImpl, log, result, token: job.token }, deliveryDelays)
running--
if (!running && !queue.length) {idle.splice(0).forEach((r) => r())}
pump()
})()
}
}
const server = createServer(async (req, res) => {
const url = new URL(req.url ?? '/', 'http://x')
if (req.method === 'GET' && url.pathname === '/health') {return send(res, 200, { ok: true, queued: queue.length, running })}
if (req.method !== 'POST' || url.pathname !== '/crawl') {return send(res, 404, { ok: false })}
const body = await readJson(req)
const error = checkCrawlRequest({ allowHttp, authorization: req.headers.authorization, body, sites })
if (error) {return send(res, error === 'unauthorized' || error === 'site_not_allowed' ? 401 : 400, { error, ok: false })}
if (queue.length >= queueMax) {return send(res, 429, { error: 'queue_full', ok: false })}
const token = req.headers.authorization.slice(7).trim()
queue.push({
acceptSelector: typeof body.acceptSelector === 'string' ? body.acceptSelector.slice(0, 200) : undefined,
callbackUrl: body.callbackUrl,
jobId: body.jobId,
maxPages: Number.isFinite(body.maxPages) ? body.maxPages : 20,
siteUrl: body.siteUrl,
token,
})
send(res, 202, { ok: true, queued: queue.length + running })
pump()
})
/** Resolves when nothing is queued or running (tests). */
server.whenIdle = () => (running || queue.length ? new Promise((r) => idle.push(r)) : Promise.resolve())
return server
}
// Run directly: `node server.mjs`
if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
const sites = parseSites(process.env.IPAL_CRAWLER_SITES)
if (!sites.length) {
console.error('[crawler] IPAL_CRAWLER_SITES is empty — set "host=token" pairs (token ≥ 16 chars).')
process.exit(1)
}
const { chromium } = await import('playwright')
const { crawlSite } = await import('./crawl.mjs')
const waitMs = Number(process.env.CRAWLER_WAIT_MS) || 3_000
const server = createCrawlerServer({
allowHttp: process.env.CRAWLER_ALLOW_HTTP === '1',
concurrency: Number(process.env.CRAWLER_CONCURRENCY) || 1,
crawl: (job) => crawlSite({ acceptSelector: job.acceptSelector, chromium, maxPages: job.maxPages, siteUrl: job.siteUrl, waitMs }),
jobTimeoutMs: Number(process.env.CRAWLER_JOB_TIMEOUT_MS) || 600_000,
queueMax: Number(process.env.CRAWLER_QUEUE_MAX) || 20,
sites,
})
const port = Number(process.env.PORT) || 3000
server.listen(port, () => console.log(`[crawler] listening on :${port} for ${sites.map((s) => s.host).join(', ')}`))
const stop = () => server.close(() => process.exit(0))
process.on('SIGTERM', stop)
process.on('SIGINT', stop)
}