Files
ipal-kit/services/cookie-crawler/lib.mjs
T
Radosław SmolińskiandClaude Fable 5.2 425fac14fb IAPL rename: the old names keep working, and a second cookie name and counter key for new sites
- exports: ipalKit, IpalOptions, ipalEnvRules, IpalEnvFeatures, ipalT, ipalVar, IPAL_TOKENS,
  IPAL_BREAKPOINTS, IpalTokenName, IpalGlobalSlug are aliases of the iapl names
- env: IAPL_* is read first, IPAL_* as fallback (readEnv; EnvRule.aliases for assertEnv);
  the crawler service reads IPAL_CRAWLER_SITES too
- doctor: reads ipal-doctor.json when it is the only one, the old pointer block, ipal-audit-skip
  and old skill folders; new rule legacy-names (info) and storage-names (warning)
- iapl-skills: installs iapl-*, removes the 16 old folders by exact name, rewrites the old
  pointer block in place; a project's own ipal-* skill stays
- storageNames: 'ipal' (default) | 'iapl': the cookie the scanner declares and the 2FA counter's
  kv prefix; <PageStats visitorCookie>, IAPL_VISITOR_COOKIE, verifyLimit.keyPrefix
- test/legacyNames.test.ts: 24 tests for all of the above

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 17:31:13 +01:00

108 lines
4.5 KiB
JavaScript

// 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(/<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()] }
}