import type { Endpoint, PayloadRequest } from 'payload' import { createHash, randomBytes, timingSafeEqual } from 'node:crypto' import type { CookieScanLabels } from '../labels.js' import type { CookieCrawlOptions, CookieScanContext, CookieScannerOptions } from '../types.js' import { userMeetsRole } from '../../../access/predicates.js' import { secondFactorPassed } from '../../../security/totp/secondFactor.js' import { accessAllowed } from '../../../shared/accessAnswer.js' import { COOKIE_CRAWL_PATH, COOKIE_CRAWL_RESULTS_PATH, COOKIE_CRAWL_SLUG, CRAWL_TIMEOUT_MS, IAPL_COOKIE_SCAN_TOKEN_ENV, IAPL_COOKIE_SCAN_URL_ENV, resolveCrawlConfig, } from './config.js' import { finishCrawl, ingestCrawlResult } from './ingest.js' import { parseCrawlResult } from './result.js' type CrawlDoc = { error?: null | string finishedAt?: null | string jobId?: null | string startedAt?: null | string startedBy?: null | string status?: 'done' | 'failed' | 'idle' | 'running' | null summary?: null | Record } /** Constant-time comparison of a bearer token with the configured one. */ export function bearerMatches(header: null | string | undefined, token: null | string): boolean { if (!token || !header?.startsWith('Bearer ')) {return false} const a = createHash('sha256').update(header.slice(7).trim()).digest() const b = createHash('sha256').update(token).digest() return timingSafeEqual(a, b) } const isStale = (doc: CrawlDoc, now = Date.now()) => doc.status === 'running' && (!doc.startedAt || now - new Date(doc.startedAt).getTime() > CRAWL_TIMEOUT_MS) /** * GET /api/ipal/cookie-crawl → `{ configured, missing, status, startedAt, finishedAt, summary, error }` * POST /api/ipal/cookie-crawl → asks the scanner service to crawl this site (editor, or the bearer token * — for a Coolify scheduled task); `202`, `409` while one runs, `503` when not configured * POST /api/ipal/cookie-crawl/results → the service's callback, bearer token only; refuses any job but the running one */ export function buildCookieCrawlEndpoints({ fetchImpl = fetch, labels, options, plugin, }: { /** For tests. */ fetchImpl?: typeof fetch labels: Record options: CookieScannerOptions plugin: CookieScanContext['plugin'] }): Endpoint[] { const crawl: CookieCrawlOptions = typeof options.crawl === 'object' ? options.crawl : {} const isStaff = async (req: PayloadRequest) => options.access ? secondFactorPassed(req) && accessAllowed('cookieScanner.access', await options.access({ req })) : userMeetsRole(req, 'editor') const read = async (req: PayloadRequest) => (await req.payload.findGlobal({ slug: COOKIE_CRAWL_SLUG as never, depth: 0, overrideAccess: true, req })) as CrawlDoc const write = (req: PayloadRequest, data: Partial) => req.payload.updateGlobal({ slug: COOKIE_CRAWL_SLUG as never, context: { ipalCookieScan: true }, data: data as never, depth: 0, overrideAccess: true, req }) return [ { handler: async (req) => { if (!(await isStaff(req))) {return Response.json({ ok: false }, { status: 403 })} const config = resolveCrawlConfig(crawl, req.payload) const doc = await read(req) const stale = isStale(doc) return Response.json({ configured: Boolean(config.serviceUrl && config.token && config.siteUrl), error: stale ? 'Timed out — the scanner service never reported back.' : (doc.error ?? null), finishedAt: doc.finishedAt ?? null, missing: [ ...(config.serviceUrl ? [] : [IAPL_COOKIE_SCAN_URL_ENV]), ...(config.token ? [] : [IAPL_COOKIE_SCAN_TOKEN_ENV]), ...(config.siteUrl ? [] : ['serverURL / NEXT_PUBLIC_SERVER_URL']), ], ok: true, startedAt: doc.startedAt ?? null, status: stale ? 'failed' : (doc.status ?? 'idle'), summary: doc.summary ?? null, }) }, method: 'get', path: COOKIE_CRAWL_PATH, }, { handler: async (req) => { const config = resolveCrawlConfig(crawl, req.payload) const byToken = bearerMatches(req.headers.get('authorization'), config.token) if (!byToken && !(await isStaff(req))) {return Response.json({ ok: false }, { status: 403 })} if (!config.serviceUrl || !config.token || !config.siteUrl) { return Response.json({ error: 'not_configured', ok: false }, { status: 503 }) } const doc = await read(req) if (doc.status === 'running' && !isStale(doc)) {return Response.json({ error: 'running', ok: false }, { status: 409 })} const jobId = randomBytes(16).toString('hex') const user = req.user as { email?: string } | null | undefined await write(req, { error: null, finishedAt: null, jobId, startedAt: new Date().toISOString(), startedBy: byToken ? 'schedule' : (user?.email ?? 'editor'), status: 'running' }) const api = req.payload.config.routes?.api ?? '/api' try { const res = await fetchImpl(`${config.serviceUrl}/crawl`, { body: JSON.stringify({ acceptSelector: config.acceptSelector, callbackUrl: `${config.siteUrl}${api}${COOKIE_CRAWL_RESULTS_PATH}`, jobId, maxPages: config.maxPages, siteUrl: config.siteUrl, }), headers: { Authorization: `Bearer ${config.token}`, 'Content-Type': 'application/json' }, method: 'POST', signal: AbortSignal.timeout(15_000), }) if (!res.ok) {throw new Error(`scanner service answered HTTP ${res.status}`)} } catch (err) { const message = err instanceof Error ? err.message : String(err) req.payload.logger.error(`[iapl] cookie crawl: could not start — ${message}`) await write(req, { error: 'The checking service could not be reached. Please try again later.', finishedAt: new Date().toISOString(), jobId: null, status: 'failed' }) return Response.json({ error: 'service_unreachable', ok: false }, { status: 502 }) } return Response.json({ ok: true, status: 'running' }, { status: 202 }) }, method: 'post', path: COOKIE_CRAWL_PATH, }, { handler: async (req) => { const config = resolveCrawlConfig(crawl, req.payload) if (!bearerMatches(req.headers.get('authorization'), config.token)) {return Response.json({ ok: false }, { status: 401 })} let body: unknown try { body = await (req as unknown as Request).json() } catch { return Response.json({ ok: false }, { status: 400 }) } const result = parseCrawlResult(body) if (!result) {return Response.json({ ok: false }, { status: 400 })} const doc = await read(req) if (doc.status !== 'running' || !doc.jobId || doc.jobId !== result.jobId) { return Response.json({ error: 'unknown_job', ok: false }, { status: 409 }) } try { const summary = result.ok ? await ingestCrawlResult({ config, labels, options, payload: req.payload, plugin, req, result }) : undefined await finishCrawl({ approval: options.approval !== false, labels, payload: req.payload, req, result, siteUrl: config.siteUrl, summary }) return Response.json({ ok: true }) } catch (err) { const message = err instanceof Error ? err.message : String(err) req.payload.logger.error(`[iapl] cookie crawl: saving the result failed — ${message}`) await write(req, { error: 'The result could not be saved. Please run the check again.', finishedAt: new Date().toISOString(), jobId: null, status: 'failed' }) return Response.json({ ok: false }, { status: 500 }) } }, method: 'post', path: COOKIE_CRAWL_RESULTS_PATH, }, ] }