- The admin box uses Payload's Button (plain <button class="btn"> rendered
unstyled), shows "Never run" before the first crawl and the note on a
finished crawl (e.g. "Accept all" not found).
- The dashboard warning puts its link on its own line.
- Dev sandbox: cookieScanner { crawl: true } and the regenerated import map.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
176 lines
7.5 KiB
TypeScript
176 lines
7.5 KiB
TypeScript
'use client'
|
|
|
|
import { Button, useConfig, useTranslation } from '@payloadcms/ui'
|
|
import { useRouter } from 'next/navigation.js'
|
|
import { useEffect, useState } from 'react'
|
|
|
|
import type { CookieScanLabels } from './labels.js'
|
|
import type { CookieScanSummary } from './types.js'
|
|
|
|
import { COOKIE_SCAN_LABELS } from './labels.js'
|
|
|
|
type CrawlState = {
|
|
configured: boolean
|
|
error: null | string
|
|
finishedAt: null | string
|
|
missing: string[]
|
|
startedAt: null | string
|
|
status: 'done' | 'failed' | 'idle' | 'running'
|
|
summary: { newUnknown?: null | number; pages?: null | number; violations?: null | number } | null
|
|
}
|
|
|
|
type Status =
|
|
| { kind: 'done'; summary: CookieScanSummary }
|
|
| { kind: 'error' }
|
|
| { kind: 'idle' }
|
|
| { kind: 'scanning' }
|
|
|
|
const fill = (template: string, values: Record<string, null | number | string>) =>
|
|
template.replace(/\{(\w+)\}/g, (_, k: string) => String(values[k] ?? ''))
|
|
|
|
/**
|
|
* Admin UI above the Cookie review list (beforeListTable): shows which
|
|
* integrations a scan covers, takes optional extra cookie names, runs
|
|
* POST /api/ipal/cookie-scan and reloads the list. With `crawl`, also "Crawl
|
|
* site" (POST /api/ipal/cookie-crawl) and the latest crawl's status, polled
|
|
* while it runs. Labels in the admin language (`labels` from the collection
|
|
* config, English fallback).
|
|
*/
|
|
export function CookieScanButton({ crawl = false, labels = COOKIE_SCAN_LABELS }: { crawl?: boolean; labels?: Record<string, CookieScanLabels> }) {
|
|
const { i18n } = useTranslation()
|
|
const { config } = useConfig()
|
|
const router = useRouter()
|
|
const t = labels[i18n.language] ?? labels.en ?? COOKIE_SCAN_LABELS.en
|
|
const endpoint = `${config.serverURL ?? ''}${config.routes?.api ?? '/api'}/ipal/cookie-scan`
|
|
const [names, setNames] = useState('')
|
|
const [integrations, setIntegrations] = useState<{ key: string; label: string }[] | null>(null)
|
|
const [status, setStatus] = useState<Status>({ kind: 'idle' })
|
|
const [crawlState, setCrawlState] = useState<CrawlState | null>(null)
|
|
const [crawlStarting, setCrawlStarting] = useState(false)
|
|
const crawlEndpoint = endpoint.replace(/cookie-scan$/, 'cookie-crawl')
|
|
const when = (iso: null | string) => (iso ? new Date(iso).toLocaleString(i18n.language) : '')
|
|
|
|
useEffect(() => {
|
|
if (!crawl) {return}
|
|
let stopped = false
|
|
let wasRunning = false
|
|
const poll = async () => {
|
|
try {
|
|
const res = await fetch(crawlEndpoint, { credentials: 'include' })
|
|
const data = res.ok ? ((await res.json()) as CrawlState) : null
|
|
if (stopped || !data) {return}
|
|
setCrawlState(data)
|
|
if (wasRunning && data.status !== 'running') {router.refresh()}
|
|
wasRunning = data.status === 'running'
|
|
} catch {
|
|
// offline — try again on the next tick
|
|
}
|
|
}
|
|
void poll()
|
|
const timer = setInterval(() => void poll(), 3000)
|
|
return () => {
|
|
stopped = true
|
|
clearInterval(timer)
|
|
}
|
|
}, [crawl, crawlEndpoint, router])
|
|
|
|
const startCrawl = async () => {
|
|
setCrawlStarting(true)
|
|
try {
|
|
await fetch(crawlEndpoint, { credentials: 'include', method: 'POST' })
|
|
const res = await fetch(crawlEndpoint, { credentials: 'include' })
|
|
if (res.ok) {setCrawlState((await res.json()) as CrawlState)}
|
|
} finally {
|
|
setCrawlStarting(false)
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
fetch(endpoint, { credentials: 'include' })
|
|
.then((r) => (r.ok ? r.json() : null))
|
|
.then((data: { integrations?: { key: string; label: string }[] } | null) => setIntegrations(data?.integrations ?? []))
|
|
.catch(() => setIntegrations([]))
|
|
}, [endpoint])
|
|
|
|
const scan = async () => {
|
|
setStatus({ kind: 'scanning' })
|
|
try {
|
|
const res = await fetch(endpoint, {
|
|
body: JSON.stringify({ names: names.split('\n') }),
|
|
credentials: 'include',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
method: 'POST',
|
|
})
|
|
const data = (await res.json()) as { ok?: boolean; summary?: CookieScanSummary }
|
|
if (!res.ok || !data.ok || !data.summary) {throw new Error('scan failed')}
|
|
setStatus({ kind: 'done', summary: data.summary })
|
|
router.refresh()
|
|
} catch {
|
|
setStatus({ kind: 'error' })
|
|
}
|
|
}
|
|
|
|
const result = (s: CookieScanSummary) =>
|
|
t.scanResult.replace(/\{(\w+)\}/g, (_, k: string) => String(s[k as keyof CookieScanSummary] ?? ''))
|
|
|
|
return (
|
|
<div className="ipal-cookie-scan" data-ipal="cookie-scan" style={{ marginBottom: '1.5rem' }}>
|
|
<p style={{ marginTop: 0 }}>{t.scanIntro}</p>
|
|
{integrations ? (
|
|
<p style={{ fontSize: '.85rem', opacity: 0.8 }}>
|
|
{integrations.length ? `${t.integrationsFound}: ${integrations.map((i) => i.label).join(', ')}` : t.integrationsNone}
|
|
</p>
|
|
) : null}
|
|
<label className="field-label" htmlFor="ipal-cookie-scan-names">{t.namesLabel}</label>
|
|
<p style={{ fontSize: '.85rem', marginTop: 0, opacity: 0.7 }}>{t.namesHint}</p>
|
|
<textarea
|
|
aria-label={t.namesLabel}
|
|
id="ipal-cookie-scan-names"
|
|
onChange={(e) => setNames(e.target.value)}
|
|
placeholder={'_hjSessionUser_123\nintercom-id-abc'}
|
|
rows={3}
|
|
style={{ fontFamily: 'monospace', marginBottom: '.5rem', width: '100%' }}
|
|
value={names}
|
|
/>
|
|
<div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '1rem' }}>
|
|
<Button buttonStyle="primary" disabled={status.kind === 'scanning'} margin={false} onClick={() => void scan()} size="medium">
|
|
{status.kind === 'scanning' ? t.scanning : t.scanButton}
|
|
</Button>
|
|
{status.kind === 'done' ? <span role="status">✓ {result(status.summary)}</span> : null}
|
|
{status.kind === 'error' ? (
|
|
<span role="alert" style={{ color: 'var(--theme-error-500, crimson)' }}>✗ {t.scanError}</span>
|
|
) : null}
|
|
</div>
|
|
{crawl ? (
|
|
<div data-ipal="cookie-crawl" style={{ borderTop: '1px solid var(--theme-elevation-150, #ddd)', marginTop: '1.25rem', paddingTop: '1rem' }}>
|
|
<p style={{ marginTop: 0 }}>{t.crawlIntro}</p>
|
|
<div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '1rem' }}>
|
|
<Button
|
|
buttonStyle="secondary"
|
|
disabled={!crawlState?.configured || crawlState.status === 'running' || crawlStarting}
|
|
margin={false}
|
|
onClick={() => void startCrawl()}
|
|
size="medium"
|
|
>
|
|
{t.crawlButton}
|
|
</Button>
|
|
<span role="status">
|
|
{crawlState && !crawlState.configured ? `${t.crawlNotConfigured} (${crawlState.missing.join(', ')})` : null}
|
|
{crawlState?.configured && crawlState.status === 'running' ? fill(t.crawlRunning, { startedAt: when(crawlState.startedAt) }) : null}
|
|
{crawlState?.configured && crawlState.status === 'done'
|
|
? fill(t.crawlDone, { finishedAt: when(crawlState.finishedAt), newUnknown: crawlState.summary?.newUnknown ?? 0, pages: crawlState.summary?.pages ?? 0, violations: crawlState.summary?.violations ?? 0 })
|
|
: null}
|
|
{/* a finished crawl can still carry a note, e.g. "Accept all" not found */}
|
|
{crawlState?.configured && crawlState.status === 'done' && crawlState.error ? ` ⚠ ${crawlState.error}` : null}
|
|
{crawlState?.configured && crawlState.status === 'idle' ? t.crawlIdle : null}
|
|
{crawlState?.configured && crawlState.status === 'failed' ? fill(t.crawlFailed, { error: crawlState.error ?? '' }) : null}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
) : null}
|
|
</div>
|
|
)
|
|
}
|
|
|
|
export default CookieScanButton
|