Files
ipal-kit/src/modules/consent/scanner/crawl/endpoints.ts
T
Radosław SmolińskiandClaude Opus 5.5 6b46bc0c14 Admin panel in English and Polish, reworded per docs/dev/admin-ux.md
- admin-i18n module: AdminText { en, pl }, component texts under the ipal
  namespace (project translations win), en + pl admin languages when the
  project sets none (project's supportedLanguages wins)
- every plugin label, description, option, tab and group as { en, pl };
  explicit labels instead of auto-labels; sentence case; glossary terms
- visible renames (slugs, names, data unchanged): Cookie banner, Form
  messages, Privacy group, Search engines, Maintenance, Spam protection,
  E-mail sending, stats nav link Overview (hidden without access)
- Polish visitor defaults by page locale: cookie banner, form messages,
  validators, lightbox, accessibility widget; {field} uses the label
- fixes: e-mail status banner used Turnstile wording; developer words and
  env var names out of editor messages; stats numbers/dates in the admin
  language; test e-mail no longer says ipal-kit
- test/adminUx.test.ts: length limits, en + pl present, no developer words

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

167 lines
7.6 KiB
TypeScript

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 {
COOKIE_CRAWL_PATH,
COOKIE_CRAWL_RESULTS_PATH,
COOKIE_CRAWL_SLUG,
COOKIE_SCAN_TOKEN_ENV,
COOKIE_SCAN_URL_ENV,
CRAWL_TIMEOUT_MS,
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<string, null | number>
}
/** 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<string, CookieScanLabels>
options: CookieScannerOptions
plugin: CookieScanContext['plugin']
}): Endpoint[] {
const crawl: CookieCrawlOptions = typeof options.crawl === 'object' ? options.crawl : {}
const isStaff = async (req: PayloadRequest) =>
options.access ? Boolean(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<CrawlDoc>) =>
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 ? [] : [COOKIE_SCAN_URL_ENV]),
...(config.token ? [] : [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(`[ipal] 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({ 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(`[ipal] 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,
},
]
}