Files
ipal-kit/services/cookie-crawler/server.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

164 lines
6.3 KiB
JavaScript

// IAPL 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: IAPL_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.IAPL_CRAWLER_SITES?.trim() ? process.env.IAPL_CRAWLER_SITES : process.env.IPAL_CRAWLER_SITES) // IPAL_CRAWLER_SITES: the name before 1.17.0, still read
if (!sites.length) {
console.error('[crawler] IAPL_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)
}