Cookie scanner, phase 1: declarations, database lookup, review list
ipalKit({ cookieScanner }) (opt-in) adds the cookie-review collection, a
"Scan cookies" box above its list and GET/POST /api/ipal/cookie-scan. A scan
lists the cookies of every integration the project switches on (consent,
admin login, locale, stats, GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok,
Turnstile), the project's own declarations, and extra names looked up in the
bundled Open Cookie Database, as drafts. Editors accept (→ Cookie Settings →
Cookies, every locale, only empty text filled), edit or reject. A rescan never
deletes, never changes status and never overwrites edited text.
Everything is overridable (access, collectionOverrides, integrations,
declarations, databaseCategories, labels, syncAccepted) and the building
blocks are exported. Admin labels in en + pl. Docs: cookie-scanner.md,
consent.md, AGENT.md, ipal-reference, ipal-consent-check.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
ab45cf48be
commit
a0545b6716
@@ -9,6 +9,7 @@ export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.
|
||||
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'
|
||||
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
|
||||
export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'
|
||||
export { CookieScanButton } from '../modules/consent/scanner/CookieScanButton.js'
|
||||
export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'
|
||||
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
|
||||
export { MetaDescriptionCheck } from '../modules/seo/MetaDescriptionCheck.js'
|
||||
|
||||
@@ -136,7 +136,7 @@ export const cookieSettingsFields: Field[] = [
|
||||
type: 'array',
|
||||
admin: {
|
||||
description:
|
||||
'Cookies the site uses — shown on the cookie policy page (<CookieTable>) and per category in the detailed settings window. Fill it from a scan: ipal-consent-check → cookie-scan.',
|
||||
'Cookies the site uses — shown on the cookie policy page (<CookieTable>) and per category in the detailed settings window. Fill it from a scan: Cookie review → Scan cookies (cookieScanner option), or ipal-consent-check → cookie-scan.',
|
||||
initCollapsed: true,
|
||||
},
|
||||
fields: [
|
||||
|
||||
@@ -50,6 +50,44 @@ export {
|
||||
updateConsent,
|
||||
} from './modules/consent/index.js'
|
||||
export type { ConsentCategory, ConsentLogOptions, ConsentState, ConsentTexts, CookieTableRow } from './modules/consent/index.js'
|
||||
// Cookie scanner — review list, scan, declarations, Open Cookie Database lookup (docs/cookie-scanner.md).
|
||||
export {
|
||||
addToCookieList,
|
||||
applyCookieFindings,
|
||||
buildCookieReviewCollection,
|
||||
buildCookieScanEndpoints,
|
||||
collectCookieFindings,
|
||||
COOKIE_REVIEW_SLUG,
|
||||
COOKIE_SCAN_LABELS,
|
||||
COOKIE_SCAN_PATH,
|
||||
cookieNameMatches,
|
||||
cookieScanContext,
|
||||
DEFAULT_COOKIE_INTEGRATIONS,
|
||||
DEFAULT_DATABASE_CATEGORIES,
|
||||
indexCookieDatabase,
|
||||
loadCookieDatabase,
|
||||
lookupCookie,
|
||||
mergeCookieReview,
|
||||
mergeCookieScanLabels,
|
||||
parseCookieNames,
|
||||
runCookieScan,
|
||||
suggestionFor,
|
||||
} from './modules/consent/scanner/index.js'
|
||||
export type {
|
||||
CookieDatabaseIndex,
|
||||
CookieDeclaration,
|
||||
CookieFinding,
|
||||
CookieFindingSource,
|
||||
CookieIntegration,
|
||||
CookieReviewValues,
|
||||
CookieScanContext,
|
||||
CookieScanLabels,
|
||||
CookieScannerOptions,
|
||||
CookieScanSummary,
|
||||
CookieStorage,
|
||||
LocalizedText,
|
||||
OpenCookieCategory,
|
||||
} from './modules/consent/scanner/index.js'
|
||||
export { constructionNoticeHref, isPathAllowed, isPathVisibleIn } from './modules/construction/logic.js'
|
||||
export type { ConstructionMode } from './modules/construction/types.js'
|
||||
export { CONSTRUCTION_NOTICE_PARAM } from './modules/construction/types.js'
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
'use client'
|
||||
|
||||
import { 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 Status =
|
||||
| { kind: 'done'; summary: CookieScanSummary }
|
||||
| { kind: 'error' }
|
||||
| { kind: 'idle' }
|
||||
| { kind: 'scanning' }
|
||||
|
||||
/**
|
||||
* 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. Labels in the admin language
|
||||
* (`labels` from the collection config, English fallback).
|
||||
*/
|
||||
export function CookieScanButton({ labels = COOKIE_SCAN_LABELS }: { 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' })
|
||||
|
||||
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
|
||||
className="btn btn--style-primary"
|
||||
disabled={status.kind === 'scanning'}
|
||||
onClick={scan}
|
||||
style={{ margin: 0 }}
|
||||
type="button"
|
||||
>
|
||||
{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>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default CookieScanButton
|
||||
@@ -0,0 +1,178 @@
|
||||
import type { CollectionAfterChangeHook, CollectionBeforeChangeHook, CollectionConfig } from 'payload'
|
||||
|
||||
import type { CookieReviewValues } from './merge.js'
|
||||
import type { CookieScannerOptions } from './types.js'
|
||||
|
||||
import { userMeetsRole } from '../../access/predicates.js'
|
||||
import { CONSENT_CATEGORIES } from '../categories.js'
|
||||
import { type CookieScanLabels, labelFor, labelRecord, mergeCookieScanLabels } from './labels.js'
|
||||
import { addToCookieList } from './sync.js'
|
||||
|
||||
/**
|
||||
* Cookie review list — drafts from "Scan cookies" that an editor accepts,
|
||||
* edits or rejects. Accepting adds the cookie to Cookie Settings → Cookies
|
||||
* (the banner's detailed window and <CookieTable>). Opt-in:
|
||||
* `ipalKit({ cookieScanner: true })`.
|
||||
*/
|
||||
export const COOKIE_REVIEW_SLUG = 'cookie-review'
|
||||
|
||||
const setKey: CollectionBeforeChangeHook = ({ data, originalDoc }) => {
|
||||
const name = (data.name ?? originalDoc?.name)?.trim()
|
||||
const storage = data.storage ?? originalDoc?.storage ?? 'cookie'
|
||||
if (name) {
|
||||
data.name = name
|
||||
data.key = `${storage}:${name}`
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
function buildSyncHook(): CollectionAfterChangeHook {
|
||||
return async ({ context, doc, previousDoc, req }) => {
|
||||
if (context?.ipalCookieScan || doc.status !== 'accepted' || previousDoc?.status === 'accepted') {return doc}
|
||||
// Local API calls with `req` rewrite req.locale / req.fallbackLocale; the editor's own
|
||||
// save is still being read after this hook, so put them back.
|
||||
const { fallbackLocale, locale } = req
|
||||
try {
|
||||
const full = (await req.payload.findByID({
|
||||
id: doc.id,
|
||||
collection: COOKIE_REVIEW_SLUG as never,
|
||||
depth: 0,
|
||||
locale: (req.payload.config.localization ? 'all' : undefined) as never,
|
||||
overrideAccess: true,
|
||||
req,
|
||||
})) as unknown as { name: string } & CookieReviewValues
|
||||
const result = await addToCookieList({ entry: full, payload: req.payload, req })
|
||||
req.payload.logger.info(`[ipal] cookie review: "${full.name}" accepted → Cookie Settings (${result})`)
|
||||
if (!doc.listed) {
|
||||
await req.payload.update({
|
||||
id: doc.id,
|
||||
collection: COOKIE_REVIEW_SLUG as never,
|
||||
context: { ipalCookieScan: true },
|
||||
data: { listed: true } as never,
|
||||
overrideAccess: true,
|
||||
req,
|
||||
})
|
||||
}
|
||||
} finally {
|
||||
req.locale = locale
|
||||
req.fallbackLocale = fallbackLocale
|
||||
}
|
||||
return { ...doc, listed: true }
|
||||
}
|
||||
}
|
||||
|
||||
export function buildCookieReviewCollection(options: CookieScannerOptions = {}): CollectionConfig {
|
||||
const labels = mergeCookieScanLabels(options.labels)
|
||||
const L = (key: keyof CookieScanLabels) => labelRecord(labels, key)
|
||||
return {
|
||||
slug: COOKIE_REVIEW_SLUG,
|
||||
access: {
|
||||
// Written by editors (review) and by the scan (Local API); deleting is admin-only and never automatic.
|
||||
create: ({ req }) => userMeetsRole(req, 'editor'),
|
||||
delete: ({ req }) => userMeetsRole(req, 'admin'),
|
||||
read: ({ req }) => userMeetsRole(req, 'editor'),
|
||||
update: ({ req }) => userMeetsRole(req, 'editor'),
|
||||
},
|
||||
admin: {
|
||||
components: {
|
||||
beforeListTable: [{ clientProps: { labels }, path: '@intecion/ipal-kit/admin#CookieScanButton' }],
|
||||
},
|
||||
defaultColumns: ['name', 'vendor', 'category', 'status', 'source', 'listed'],
|
||||
description: L('collectionDescription'),
|
||||
group: 'Settings',
|
||||
listSearchableFields: ['name', 'vendor'],
|
||||
useAsTitle: 'name',
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
type: 'row',
|
||||
fields: [
|
||||
{ name: 'name', type: 'text', admin: { width: '50%' }, label: L('name'), required: true },
|
||||
{
|
||||
name: 'storage',
|
||||
type: 'select',
|
||||
admin: { width: '25%' },
|
||||
defaultValue: 'cookie',
|
||||
label: L('storage'),
|
||||
options: [
|
||||
{ label: L('cookie'), value: 'cookie' },
|
||||
{ label: L('localStorage'), value: 'localStorage' },
|
||||
{ label: L('sessionStorage'), value: 'sessionStorage' },
|
||||
],
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
name: 'category',
|
||||
type: 'select',
|
||||
admin: { width: '25%' },
|
||||
label: L('category'),
|
||||
options: CONSENT_CATEGORIES.map((c) => ({ label: L(c), value: c })),
|
||||
validate: (value: unknown, { req, siblingData }: { req: { i18n?: { language?: string } }; siblingData: { status?: string } }) =>
|
||||
siblingData?.status === 'accepted' && !value ? labelFor(labels, req.i18n?.language, 'categoryRequired') : true,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'row',
|
||||
fields: [
|
||||
{ name: 'vendor', type: 'text', admin: { width: '50%' }, label: L('vendor') },
|
||||
{ name: 'domain', type: 'text', admin: { width: '50%' }, label: L('domain') },
|
||||
],
|
||||
},
|
||||
{ name: 'purpose', type: 'textarea', label: L('purpose'), localized: true },
|
||||
{ name: 'retention', type: 'text', label: L('retention'), localized: true },
|
||||
{
|
||||
name: 'setBeforeConsent',
|
||||
type: 'checkbox',
|
||||
admin: { description: L('setBeforeConsentDescription') },
|
||||
label: L('setBeforeConsent'),
|
||||
},
|
||||
{
|
||||
name: 'status',
|
||||
type: 'select',
|
||||
admin: { description: L('statusDescription'), position: 'sidebar' },
|
||||
defaultValue: 'draft',
|
||||
index: true,
|
||||
label: L('status'),
|
||||
options: [
|
||||
{ label: L('draft'), value: 'draft' },
|
||||
{ label: L('accepted'), value: 'accepted' },
|
||||
{ label: L('rejected'), value: 'rejected' },
|
||||
],
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
name: 'source',
|
||||
type: 'select',
|
||||
admin: { position: 'sidebar', readOnly: true },
|
||||
defaultValue: 'manual',
|
||||
label: L('source'),
|
||||
options: [
|
||||
{ label: L('integration'), value: 'integration' },
|
||||
{ label: L('project'), value: 'project' },
|
||||
{ label: L('database'), value: 'database' },
|
||||
{ label: L('unknown'), value: 'unknown' },
|
||||
{ label: L('manual'), value: 'manual' },
|
||||
],
|
||||
},
|
||||
{ name: 'sourceDetail', type: 'text', admin: { position: 'sidebar', readOnly: true }, label: L('sourceDetail') },
|
||||
{
|
||||
name: 'listed',
|
||||
type: 'checkbox',
|
||||
admin: { description: L('listedDescription'), position: 'sidebar', readOnly: true },
|
||||
label: L('listed'),
|
||||
},
|
||||
{ name: 'lastScannedAt', type: 'date', admin: { position: 'sidebar', readOnly: true }, label: L('lastScannedAt') },
|
||||
// `storage:name`, one entry per cookie — what a rescan matches on.
|
||||
{ name: 'key', type: 'text', admin: { hidden: true }, index: true, unique: true },
|
||||
// The last scan's suggestion: a value still equal to it was not edited and may follow the next scan.
|
||||
{ name: 'suggested', type: 'json', admin: { hidden: true } },
|
||||
],
|
||||
hooks: {
|
||||
afterChange: options.syncAccepted === false ? [] : [buildSyncHook()],
|
||||
beforeChange: [setKey],
|
||||
},
|
||||
labels: { plural: L('plural'), singular: L('singular') },
|
||||
timestamps: true,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { ConsentCategory } from '../categories.js'
|
||||
import type { OpenCookieRow } from './data/openCookieDatabase.js'
|
||||
import type { CookieFinding, OpenCookieCategory } from './types.js'
|
||||
|
||||
/**
|
||||
* Lookup in the bundled Open Cookie Database (Apache-2.0,
|
||||
* github.com/jkwakman/Open-Cookie-Database; license in
|
||||
* docs/licenses/open-cookie-database-LICENSE.txt). Refreshed by
|
||||
* `scripts/refresh-cookie-database.mjs` — nothing is fetched at runtime. The
|
||||
* ~430 KB table is imported only when a scan needs it.
|
||||
*/
|
||||
|
||||
export const DEFAULT_DATABASE_CATEGORIES: Record<OpenCookieCategory, ConsentCategory> = {
|
||||
Analytics: 'analytics',
|
||||
// The database defines Functional as "technical, essential or strictly necessary", but
|
||||
// contributors file trackers there too (Hotjar's user id). An unchecked lookup must not
|
||||
// land as "no consent needed": it asks for consent until an editor says otherwise.
|
||||
Functional: 'functional',
|
||||
Marketing: 'marketing',
|
||||
Necessary: 'necessary',
|
||||
Personalization: 'functional',
|
||||
Security: 'necessary',
|
||||
}
|
||||
|
||||
/** An index over database rows: exact names, then prefixes (longest first). */
|
||||
export type CookieDatabaseIndex = {
|
||||
exact: Map<string, OpenCookieRow>
|
||||
prefixes: OpenCookieRow[]
|
||||
}
|
||||
|
||||
export function indexCookieDatabase(rows: readonly OpenCookieRow[]): CookieDatabaseIndex {
|
||||
const exact = new Map<string, OpenCookieRow>()
|
||||
const prefixes: OpenCookieRow[] = []
|
||||
for (const row of rows) {
|
||||
if (row[7] === 1) {prefixes.push(row)}
|
||||
else if (!exact.has(row[0])) {exact.set(row[0], row)}
|
||||
}
|
||||
prefixes.sort((a, b) => b[0].length - a[0].length)
|
||||
return { exact, prefixes }
|
||||
}
|
||||
|
||||
let bundled: CookieDatabaseIndex | null = null
|
||||
|
||||
/** The bundled database, indexed once per process. */
|
||||
export async function loadCookieDatabase(): Promise<CookieDatabaseIndex> {
|
||||
if (!bundled) {
|
||||
const { OPEN_COOKIE_DATABASE } = await import('./data/openCookieDatabase.js')
|
||||
bundled = indexCookieDatabase(OPEN_COOKIE_DATABASE)
|
||||
}
|
||||
return bundled
|
||||
}
|
||||
|
||||
/**
|
||||
* A cookie name looked up in the database: exact name first, then the longest
|
||||
* matching wildcard prefix (`_gac_` matches `_gac_UA-1`). Null when unknown.
|
||||
*/
|
||||
export function lookupCookie(
|
||||
index: CookieDatabaseIndex,
|
||||
name: string,
|
||||
categories: Partial<Record<OpenCookieCategory, ConsentCategory>> = {},
|
||||
): CookieFinding | null {
|
||||
const row = index.exact.get(name) ?? index.prefixes.find((r) => r[0] && name.startsWith(r[0]))
|
||||
if (!row) {return null}
|
||||
const [pattern, platform, category, domain, description, retention, controller, wildcard] = row
|
||||
const map = { ...DEFAULT_DATABASE_CATEGORIES, ...categories }
|
||||
const thirdParty = /\(3rd party\)/i.test(domain) ? domain.replace(/\s*\(3rd party\)/i, '').trim() : ''
|
||||
return {
|
||||
category: map[category as OpenCookieCategory],
|
||||
...(thirdParty ? { domain: thirdParty } : {}),
|
||||
name: wildcard === 1 && pattern !== name ? `${pattern}*` : name,
|
||||
...(description ? { purpose: description } : {}),
|
||||
...(retention ? { retention } : {}),
|
||||
source: 'database',
|
||||
sourceDetail: `Open Cookie Database: ${platform}${category ? ` (${category})` : ''}`,
|
||||
storage: 'cookie',
|
||||
vendor: controller || platform,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { Endpoint, PayloadRequest } from 'payload'
|
||||
|
||||
import type { CookieScanContext, CookieScannerOptions } from './types.js'
|
||||
|
||||
import { userMeetsRole } from '../../access/predicates.js'
|
||||
import { DEFAULT_COOKIE_INTEGRATIONS } from './integrations.js'
|
||||
import { cookieScanContext, enabledCookieIntegrations, parseCookieNames, runCookieScan } from './scan.js'
|
||||
|
||||
export const COOKIE_SCAN_PATH = '/ipal/cookie-scan'
|
||||
|
||||
/**
|
||||
* GET /api/ipal/cookie-scan → `{ integrations: [{ key, label }] }` — what a scan would cover.
|
||||
* POST /api/ipal/cookie-scan, body `{ names?: string[] | string }` → runs a scan,
|
||||
* `{ ok, summary: { created, updated, unchanged, unknown }, integrations }`.
|
||||
* Editors and up by default (`cookieScanner.access`).
|
||||
*/
|
||||
export function buildCookieScanEndpoints(options: CookieScannerOptions, plugin: CookieScanContext['plugin']): Endpoint[] {
|
||||
const allowed = async (req: PayloadRequest) =>
|
||||
options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
|
||||
const integrations = options.integrations ? options.integrations(DEFAULT_COOKIE_INTEGRATIONS) : DEFAULT_COOKIE_INTEGRATIONS
|
||||
const list = (items: { key: string; label: string }[]) => items.map(({ key, label }) => ({ key, label }))
|
||||
|
||||
return [
|
||||
{
|
||||
handler: async (req) => {
|
||||
if (!(await allowed(req))) {return Response.json({ ok: false }, { status: 403 })}
|
||||
const enabled = await enabledCookieIntegrations(integrations, await cookieScanContext(req.payload, plugin, req))
|
||||
return Response.json({ integrations: list(enabled), ok: true })
|
||||
},
|
||||
method: 'get',
|
||||
path: COOKIE_SCAN_PATH,
|
||||
},
|
||||
{
|
||||
handler: async (req) => {
|
||||
if (!(await allowed(req))) {return Response.json({ ok: false }, { status: 403 })}
|
||||
let body: { names?: unknown } = {}
|
||||
try {
|
||||
body = ((await (req as unknown as Request).json()) ?? {}) as { names?: unknown }
|
||||
} catch {
|
||||
// empty body = scan without extra names
|
||||
}
|
||||
try {
|
||||
const { enabled, summary } = await runCookieScan({ names: parseCookieNames(body.names), options, payload: req.payload, plugin, req })
|
||||
return Response.json({ integrations: list(enabled), ok: true, summary })
|
||||
} catch (err) {
|
||||
req.payload.logger.error(`[ipal] cookie scan failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
return Response.json({ ok: false }, { status: 500 })
|
||||
}
|
||||
},
|
||||
method: 'post',
|
||||
path: COOKIE_SCAN_PATH,
|
||||
},
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Cookie scanner — server-safe building blocks. The admin button is in /admin.
|
||||
export { buildCookieReviewCollection, COOKIE_REVIEW_SLUG } from './collection.js'
|
||||
export { DEFAULT_DATABASE_CATEGORIES, indexCookieDatabase, loadCookieDatabase, lookupCookie } from './cookieDatabase.js'
|
||||
export type { CookieDatabaseIndex } from './cookieDatabase.js'
|
||||
export { buildCookieScanEndpoints, COOKIE_SCAN_PATH } from './endpoint.js'
|
||||
export { cookieNameMatches, DEFAULT_COOKIE_INTEGRATIONS } from './integrations.js'
|
||||
export { COOKIE_SCAN_LABELS, mergeCookieScanLabels } from './labels.js'
|
||||
export type { CookieScanLabels } from './labels.js'
|
||||
export { mergeCookieReview, suggestionFor } from './merge.js'
|
||||
export type { CookieReviewValues } from './merge.js'
|
||||
export { applyCookieFindings, collectCookieFindings, cookieScanContext, parseCookieNames, runCookieScan } from './scan.js'
|
||||
export { addToCookieList } from './sync.js'
|
||||
export type {
|
||||
CookieDeclaration,
|
||||
CookieFinding,
|
||||
CookieFindingSource,
|
||||
CookieIntegration,
|
||||
CookieScanContext,
|
||||
CookieScannerOptions,
|
||||
CookieScanSummary,
|
||||
CookieStorage,
|
||||
LocalizedText,
|
||||
OpenCookieCategory,
|
||||
} from './types.js'
|
||||
@@ -0,0 +1,292 @@
|
||||
import type { CookieDeclaration, CookieIntegration, CookieScanContext } from './types.js'
|
||||
|
||||
import { validAnalyticsId } from '../../analytics/idFormats.js'
|
||||
import { LOCALE_COOKIE_NAME } from '../../i18n/negotiateLocale.js'
|
||||
import { getTurnstileConfig } from '../../turnstile/config.js'
|
||||
import { CONSENT_COOKIE } from '../storage.js'
|
||||
|
||||
/** A tag ID from Site Integrations is filled in and valid. */
|
||||
const hasId = (field: string) => (ctx: CookieScanContext) =>
|
||||
Boolean(validAnalyticsId(field as never, ctx.integrations[field]))
|
||||
|
||||
const T = (en: string, pl: string) => ({ en, pl })
|
||||
const SESSION = T('Session', 'Sesja')
|
||||
const days = (n: number) => T(`${n} days`, `${n} dni`)
|
||||
const months = (n: number) => T(`${n} months`, `${n} mies.`)
|
||||
const YEAR = T('1 year', '1 rok')
|
||||
const TWO_YEARS = T('2 years', '2 lata')
|
||||
const SITE = 'This site'
|
||||
|
||||
/**
|
||||
* Cookies of everything the plugin itself injects — one place per integration.
|
||||
* Each one is part of a scan only when this project switches it on (an ID in
|
||||
* Site Integrations, a plugin option). Change the list with
|
||||
* `cookieScanner.integrations: (defaults) => …`.
|
||||
*/
|
||||
export const DEFAULT_COOKIE_INTEGRATIONS: CookieIntegration[] = [
|
||||
{
|
||||
declarations: [
|
||||
{
|
||||
name: CONSENT_COOKIE,
|
||||
category: 'necessary',
|
||||
purpose: T('Stores your cookie consent decision.', 'Zapamiętuje Twoją decyzję w sprawie plików cookie.'),
|
||||
retention: months(6),
|
||||
setBeforeConsent: false,
|
||||
vendor: SITE,
|
||||
},
|
||||
],
|
||||
isEnabled: () => true,
|
||||
key: 'consent',
|
||||
label: 'Cookie banner',
|
||||
},
|
||||
{
|
||||
declarations: (ctx) => [
|
||||
{
|
||||
name: `${ctx.payload.config.cookiePrefix ?? 'payload'}-token`,
|
||||
category: 'necessary',
|
||||
purpose: T('Session of a logged-in editor (admin panel only).', 'Sesja zalogowanego redaktora (tylko panel administracyjny).'),
|
||||
retention: T('Until logout (2 hours by default)', 'Do wylogowania (domyślnie 2 godziny)'),
|
||||
setBeforeConsent: true,
|
||||
vendor: SITE,
|
||||
},
|
||||
],
|
||||
isEnabled: () => true,
|
||||
key: 'admin',
|
||||
label: 'Admin panel login',
|
||||
},
|
||||
{
|
||||
declarations: [
|
||||
{
|
||||
name: LOCALE_COOKIE_NAME,
|
||||
category: 'functional',
|
||||
purpose: T('Remembers the selected site language.', 'Zapamiętuje wybrany język strony.'),
|
||||
retention: SESSION,
|
||||
setBeforeConsent: false,
|
||||
vendor: SITE,
|
||||
},
|
||||
],
|
||||
isEnabled: (ctx) => ctx.plugin.localeCount > 1,
|
||||
key: 'locale',
|
||||
label: 'Language choice',
|
||||
},
|
||||
{
|
||||
declarations: [
|
||||
{
|
||||
name: 'ipal_vid', // VISITOR_COOKIE — that file is a client component
|
||||
category: 'analytics',
|
||||
purpose: T(
|
||||
'Built-in statistics: random visitor id that joins your visits across days. Set only with analytics consent.',
|
||||
'Wbudowane statystyki: losowy identyfikator łączący Twoje wizyty z różnych dni. Tylko po zgodzie na analitykę.',
|
||||
),
|
||||
retention: months(6),
|
||||
setBeforeConsent: false,
|
||||
vendor: SITE,
|
||||
},
|
||||
],
|
||||
isEnabled: (ctx) => ctx.plugin.stats,
|
||||
key: 'stats',
|
||||
label: 'Built-in statistics',
|
||||
},
|
||||
{
|
||||
declarations: [
|
||||
{
|
||||
name: '_ga',
|
||||
category: 'analytics',
|
||||
purpose: T('Google Analytics: distinguishes users in statistics.', 'Google Analytics: rozróżnia użytkowników w statystykach.'),
|
||||
retention: TWO_YEARS,
|
||||
setBeforeConsent: false,
|
||||
vendor: 'Google',
|
||||
},
|
||||
{
|
||||
name: '_ga_*',
|
||||
category: 'analytics',
|
||||
purpose: T('Google Analytics: keeps the session state.', 'Google Analytics: przechowuje stan sesji.'),
|
||||
retention: TWO_YEARS,
|
||||
setBeforeConsent: false,
|
||||
vendor: 'Google',
|
||||
},
|
||||
],
|
||||
isEnabled: hasId('ga4MeasurementId'),
|
||||
key: 'ga4',
|
||||
label: 'Google Analytics 4',
|
||||
},
|
||||
{
|
||||
// GTM itself sets no cookie; its tags do. The Conversion Linker (Google Ads)
|
||||
// is the usual one — anything else the container fires shows up in a crawl.
|
||||
declarations: [
|
||||
{
|
||||
name: '_gcl_*',
|
||||
category: 'marketing',
|
||||
purpose: T(
|
||||
'Google Ads (via Google Tag Manager): attributes conversions to ad clicks.',
|
||||
'Google Ads (przez Google Tag Manager): przypisuje konwersje do kliknięć reklam.',
|
||||
),
|
||||
retention: months(3),
|
||||
setBeforeConsent: false,
|
||||
vendor: 'Google',
|
||||
},
|
||||
],
|
||||
isEnabled: hasId('gtmContainerId'),
|
||||
key: 'gtm',
|
||||
label: 'Google Tag Manager',
|
||||
},
|
||||
{
|
||||
declarations: [
|
||||
{
|
||||
name: '_fbp',
|
||||
category: 'marketing',
|
||||
purpose: T('Meta Pixel: ad measurement and targeting.', 'Meta Pixel: pomiar i dopasowanie reklam.'),
|
||||
retention: months(3),
|
||||
setBeforeConsent: false,
|
||||
vendor: 'Meta',
|
||||
},
|
||||
{
|
||||
name: '_fbc',
|
||||
category: 'marketing',
|
||||
purpose: T('Meta Pixel: stores the last ad click.', 'Meta Pixel: zapamiętuje ostatnie kliknięcie reklamy.'),
|
||||
retention: months(3),
|
||||
setBeforeConsent: false,
|
||||
vendor: 'Meta',
|
||||
},
|
||||
],
|
||||
isEnabled: hasId('metaPixelId'),
|
||||
key: 'metaPixel',
|
||||
label: 'Meta Pixel',
|
||||
},
|
||||
{
|
||||
declarations: [
|
||||
{
|
||||
name: '_clck',
|
||||
category: 'analytics',
|
||||
purpose: T('Clarity: user id for behaviour analytics.', 'Clarity: identyfikator użytkownika w analizie zachowań.'),
|
||||
retention: YEAR,
|
||||
setBeforeConsent: false,
|
||||
vendor: 'Microsoft Clarity',
|
||||
},
|
||||
{
|
||||
name: '_clsk',
|
||||
category: 'analytics',
|
||||
purpose: T('Clarity: joins page views into one session.', 'Clarity: łączy odsłony w jedną sesję.'),
|
||||
retention: T('1 day', '1 dzień'),
|
||||
setBeforeConsent: false,
|
||||
vendor: 'Microsoft Clarity',
|
||||
},
|
||||
{
|
||||
name: 'CLID',
|
||||
category: 'analytics',
|
||||
domain: 'clarity.ms',
|
||||
purpose: T('Clarity: user id across sites using Clarity.', 'Clarity: identyfikator użytkownika między stronami z Clarity.'),
|
||||
retention: YEAR,
|
||||
setBeforeConsent: false,
|
||||
vendor: 'Microsoft Clarity',
|
||||
},
|
||||
{
|
||||
name: 'MUID',
|
||||
category: 'marketing',
|
||||
domain: 'clarity.ms',
|
||||
purpose: T('Microsoft: browser id used across Microsoft services and ads.', 'Microsoft: identyfikator przeglądarki w usługach i reklamach Microsoft.'),
|
||||
retention: YEAR,
|
||||
setBeforeConsent: false,
|
||||
vendor: 'Microsoft',
|
||||
},
|
||||
],
|
||||
isEnabled: hasId('clarityProjectId'),
|
||||
key: 'clarity',
|
||||
label: 'Microsoft Clarity',
|
||||
},
|
||||
{
|
||||
declarations: [
|
||||
{
|
||||
name: 'li_fat_id',
|
||||
category: 'marketing',
|
||||
purpose: T('LinkedIn Insight Tag: conversion attribution.', 'LinkedIn Insight Tag: przypisanie konwersji.'),
|
||||
retention: days(30),
|
||||
setBeforeConsent: false,
|
||||
vendor: 'LinkedIn',
|
||||
},
|
||||
{
|
||||
name: 'bcookie',
|
||||
category: 'marketing',
|
||||
domain: 'linkedin.com',
|
||||
purpose: T('LinkedIn: browser id.', 'LinkedIn: identyfikator przeglądarki.'),
|
||||
retention: YEAR,
|
||||
setBeforeConsent: false,
|
||||
vendor: 'LinkedIn',
|
||||
},
|
||||
{
|
||||
name: 'lidc',
|
||||
category: 'marketing',
|
||||
domain: 'linkedin.com',
|
||||
purpose: T('LinkedIn: data-centre routing.', 'LinkedIn: wybór centrum danych.'),
|
||||
retention: T('1 day', '1 dzień'),
|
||||
setBeforeConsent: false,
|
||||
vendor: 'LinkedIn',
|
||||
},
|
||||
{
|
||||
name: 'UserMatchHistory',
|
||||
category: 'marketing',
|
||||
domain: 'linkedin.com',
|
||||
purpose: T('LinkedIn Ads: id sync with ad partners.', 'LinkedIn Ads: synchronizacja identyfikatorów z partnerami reklamowymi.'),
|
||||
retention: days(30),
|
||||
setBeforeConsent: false,
|
||||
vendor: 'LinkedIn',
|
||||
},
|
||||
],
|
||||
isEnabled: hasId('linkedInPartnerId'),
|
||||
key: 'linkedIn',
|
||||
label: 'LinkedIn Insight Tag',
|
||||
},
|
||||
{
|
||||
declarations: [
|
||||
{
|
||||
name: '_ttp',
|
||||
category: 'marketing',
|
||||
purpose: T('TikTok Pixel: ad measurement.', 'TikTok Pixel: pomiar reklam.'),
|
||||
retention: months(13),
|
||||
setBeforeConsent: false,
|
||||
vendor: 'TikTok',
|
||||
},
|
||||
{
|
||||
name: '_tt_enable_cookie',
|
||||
category: 'marketing',
|
||||
purpose: T('TikTok Pixel: checks that cookies work.', 'TikTok Pixel: sprawdza, czy cookies działają.'),
|
||||
retention: months(13),
|
||||
setBeforeConsent: false,
|
||||
vendor: 'TikTok',
|
||||
},
|
||||
],
|
||||
isEnabled: hasId('tiktokPixelId'),
|
||||
key: 'tiktok',
|
||||
label: 'TikTok Pixel',
|
||||
},
|
||||
{
|
||||
// Turnstile hands back a one-time token; cf_clearance appears only when the
|
||||
// widget has pre-clearance switched on in the Cloudflare dashboard.
|
||||
declarations: [
|
||||
{
|
||||
name: 'cf_clearance',
|
||||
category: 'necessary',
|
||||
purpose: T(
|
||||
'Cloudflare Turnstile: proves the anti-spam check was passed (only with pre-clearance on).',
|
||||
'Cloudflare Turnstile: potwierdza przejście zabezpieczenia antyspamowego (tylko z włączonym pre-clearance).',
|
||||
),
|
||||
retention: T('30 minutes (set in Cloudflare)', '30 minut (ustawiane w Cloudflare)'),
|
||||
setBeforeConsent: true,
|
||||
vendor: 'Cloudflare',
|
||||
},
|
||||
],
|
||||
isEnabled: async (ctx) => (await getTurnstileConfig(ctx.payload)).enabled,
|
||||
key: 'turnstile',
|
||||
label: 'Cloudflare Turnstile',
|
||||
},
|
||||
]
|
||||
|
||||
/** An integration's declarations for this project. */
|
||||
export function declarationsOf(integration: CookieIntegration, ctx: CookieScanContext): CookieDeclaration[] {
|
||||
return typeof integration.declarations === 'function' ? integration.declarations(ctx) : integration.declarations
|
||||
}
|
||||
|
||||
/** True when `name` matches `pattern` (a trailing `*` = prefix). */
|
||||
export function cookieNameMatches(pattern: string, name: string): boolean {
|
||||
return pattern.endsWith('*') ? name.startsWith(pattern.slice(0, -1)) : name === pattern
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
/**
|
||||
* Admin labels of the cookie scanner, per admin language. Payload picks the
|
||||
* user's admin language from a `{ en, pl }` record; a language missing here falls
|
||||
* back to English. Projects add or change languages with `cookieScanner.labels`.
|
||||
*/
|
||||
export type CookieScanLabels = {
|
||||
accepted: string
|
||||
analytics: string
|
||||
category: string
|
||||
categoryRequired: string
|
||||
collectionDescription: string
|
||||
cookie: string
|
||||
database: string
|
||||
domain: string
|
||||
draft: string
|
||||
functional: string
|
||||
integration: string
|
||||
integrationsFound: string
|
||||
integrationsNone: string
|
||||
lastScannedAt: string
|
||||
listed: string
|
||||
listedDescription: string
|
||||
localStorage: string
|
||||
manual: string
|
||||
marketing: string
|
||||
name: string
|
||||
namesHint: string
|
||||
namesLabel: string
|
||||
necessary: string
|
||||
plural: string
|
||||
project: string
|
||||
purpose: string
|
||||
rejected: string
|
||||
retention: string
|
||||
scanButton: string
|
||||
scanError: string
|
||||
scanIntro: string
|
||||
scanning: string
|
||||
/** `{created}`, `{updated}`, `{unchanged}`, `{unknown}` are filled in. */
|
||||
scanResult: string
|
||||
sessionStorage: string
|
||||
setBeforeConsent: string
|
||||
setBeforeConsentDescription: string
|
||||
singular: string
|
||||
source: string
|
||||
sourceDetail: string
|
||||
status: string
|
||||
statusDescription: string
|
||||
storage: string
|
||||
unknown: string
|
||||
vendor: string
|
||||
}
|
||||
|
||||
export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
|
||||
en: {
|
||||
name: 'Name',
|
||||
accepted: 'Accepted',
|
||||
analytics: 'Analytics',
|
||||
category: 'Category',
|
||||
categoryRequired: 'Pick a category before accepting.',
|
||||
collectionDescription:
|
||||
'Cookies found by "Scan cookies". Check each draft, then set it to Accepted (it is added to Cookie Settings → Cookies) or Rejected. A scan never deletes entries and never changes text you edited.',
|
||||
cookie: 'Cookie',
|
||||
database: 'Open Cookie Database',
|
||||
domain: 'Domain',
|
||||
draft: 'Draft',
|
||||
functional: 'Functional',
|
||||
integration: 'Plugin integration',
|
||||
integrationsFound: 'Integrations in use',
|
||||
integrationsNone: 'No integration with cookies is switched on.',
|
||||
lastScannedAt: 'Last seen by a scan',
|
||||
listed: 'In the cookie list',
|
||||
listedDescription: 'Already in Cookie Settings → Cookies.',
|
||||
localStorage: 'Local storage',
|
||||
manual: 'Added by hand',
|
||||
marketing: 'Marketing',
|
||||
namesHint: 'Optional: cookie names seen in the browser (DevTools → Application → Cookies), one per line. They are looked up in the plugin and the Open Cookie Database.',
|
||||
namesLabel: 'More cookie names',
|
||||
necessary: 'Necessary',
|
||||
plural: 'Cookie review',
|
||||
project: 'Project declaration',
|
||||
purpose: 'Purpose',
|
||||
rejected: 'Rejected',
|
||||
retention: 'Retention',
|
||||
scanButton: 'Scan cookies',
|
||||
scanError: 'The scan failed.',
|
||||
scanIntro: 'Lists the cookies of the integrations switched on in this project as drafts to review.',
|
||||
scanning: 'Scanning…',
|
||||
scanResult: '{created} new, {updated} updated, {unchanged} unchanged, {unknown} unknown.',
|
||||
sessionStorage: 'Session storage',
|
||||
setBeforeConsent: 'Set before consent',
|
||||
setBeforeConsentDescription: 'May be set before the visitor decides. Only necessary cookies should be.',
|
||||
singular: 'Cookie review entry',
|
||||
source: 'Found by',
|
||||
sourceDetail: 'Source',
|
||||
status: 'Status',
|
||||
statusDescription: 'Accepted → added to Cookie Settings → Cookies. Rejecting never removes a row from that list.',
|
||||
storage: 'Stored in',
|
||||
unknown: 'Unknown — fill in',
|
||||
vendor: 'Provider',
|
||||
},
|
||||
pl: {
|
||||
name: 'Nazwa',
|
||||
accepted: 'Zaakceptowany',
|
||||
analytics: 'Analityczne',
|
||||
category: 'Kategoria',
|
||||
categoryRequired: 'Wybierz kategorię przed akceptacją.',
|
||||
collectionDescription:
|
||||
'Pliki cookie znalezione przez „Skanuj cookies”. Sprawdź każdy szkic i ustaw Zaakceptowany (trafi do Ustawień cookies → Cookies) albo Odrzucony. Skan nigdy nie usuwa wpisów ani nie zmienia poprawionych przez Ciebie tekstów.',
|
||||
cookie: 'Cookie',
|
||||
database: 'Open Cookie Database',
|
||||
domain: 'Domena',
|
||||
draft: 'Szkic',
|
||||
functional: 'Funkcjonalne',
|
||||
integration: 'Integracja wtyczki',
|
||||
integrationsFound: 'Używane integracje',
|
||||
integrationsNone: 'Żadna integracja z plikami cookie nie jest włączona.',
|
||||
lastScannedAt: 'Ostatnio widziany w skanie',
|
||||
listed: 'Na liście cookies',
|
||||
listedDescription: 'Już jest w Ustawieniach cookies → Cookies.',
|
||||
localStorage: 'Local storage',
|
||||
manual: 'Dodany ręcznie',
|
||||
marketing: 'Marketingowe',
|
||||
namesHint: 'Opcjonalnie: nazwy cookies widoczne w przeglądarce (DevTools → Application → Cookies), po jednej w wierszu. Zostaną wyszukane we wtyczce i w Open Cookie Database.',
|
||||
namesLabel: 'Dodatkowe nazwy cookies',
|
||||
necessary: 'Niezbędne',
|
||||
plural: 'Przegląd cookies',
|
||||
project: 'Deklaracja projektu',
|
||||
purpose: 'Cel',
|
||||
rejected: 'Odrzucony',
|
||||
retention: 'Czas przechowywania',
|
||||
scanButton: 'Skanuj cookies',
|
||||
scanError: 'Skan się nie powiódł.',
|
||||
scanIntro: 'Dodaje cookies integracji włączonych w tym projekcie jako szkice do przejrzenia.',
|
||||
scanning: 'Skanowanie…',
|
||||
scanResult: 'Nowe: {created}, zaktualizowane: {updated}, bez zmian: {unchanged}, nieznane: {unknown}.',
|
||||
sessionStorage: 'Session storage',
|
||||
setBeforeConsent: 'Ustawiany przed zgodą',
|
||||
setBeforeConsentDescription: 'Może powstać, zanim odwiedzający zdecyduje. Tylko niezbędne cookies powinny.',
|
||||
singular: 'Wpis przeglądu cookies',
|
||||
source: 'Źródło',
|
||||
sourceDetail: 'Skąd',
|
||||
status: 'Status',
|
||||
statusDescription: 'Zaakceptowany → trafia do Ustawień cookies → Cookies. Odrzucenie nigdy nie usuwa wiersza z tej listy.',
|
||||
storage: 'Przechowywany w',
|
||||
unknown: 'Nieznany — uzupełnij',
|
||||
vendor: 'Dostawca',
|
||||
},
|
||||
}
|
||||
|
||||
/** Plugin labels with the project's languages and changes merged over them. */
|
||||
export function mergeCookieScanLabels(overrides: Record<string, Partial<CookieScanLabels>> = {}): Record<string, CookieScanLabels> {
|
||||
const out: Record<string, CookieScanLabels> = { ...COOKIE_SCAN_LABELS }
|
||||
for (const [lang, labels] of Object.entries(overrides)) {
|
||||
out[lang] = { ...(out[lang] ?? COOKIE_SCAN_LABELS.en), ...labels }
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** One label as a Payload `{ en, pl, … }` record. */
|
||||
export function labelRecord(labels: Record<string, CookieScanLabels>, key: keyof CookieScanLabels): Record<string, string> {
|
||||
return Object.fromEntries(Object.entries(labels).map(([lang, l]) => [lang, l[key]]))
|
||||
}
|
||||
|
||||
/** One label in one language (English when the language is missing). */
|
||||
export function labelFor(labels: Record<string, CookieScanLabels>, lang: string | undefined, key: keyof CookieScanLabels): string {
|
||||
return (lang && labels[lang]?.[key]) || labels.en?.[key] || COOKIE_SCAN_LABELS.en[key]
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import type { ConsentCategory } from '../categories.js'
|
||||
import type { CookieFinding, LocalizedText } from './types.js'
|
||||
|
||||
/** The editable values of a review entry; `purpose` / `retention` per locale. */
|
||||
export type CookieReviewValues = {
|
||||
category?: ConsentCategory | null
|
||||
domain?: null | string
|
||||
purpose?: Record<string, null | string>
|
||||
retention?: Record<string, null | string>
|
||||
setBeforeConsent?: boolean | null
|
||||
vendor?: null | string
|
||||
}
|
||||
|
||||
const SCALARS = ['category', 'domain', 'setBeforeConsent', 'vendor'] as const
|
||||
const TEXTS = ['purpose', 'retention'] as const
|
||||
|
||||
/** Text for one locale: that language, else English, else the first one given. */
|
||||
export function textFor(text: LocalizedText | undefined, locale: string): string | undefined {
|
||||
if (text === undefined) {return undefined}
|
||||
if (typeof text === 'string') {return text}
|
||||
return text[locale] ?? text.en ?? Object.values(text)[0]
|
||||
}
|
||||
|
||||
/** What a scan suggests for an entry, resolved for the project's locales. */
|
||||
export function suggestionFor(finding: CookieFinding, locales: string[]): CookieReviewValues {
|
||||
const perLocale = (text: LocalizedText | undefined) => {
|
||||
if (text === undefined) {return undefined}
|
||||
return Object.fromEntries(locales.map((l) => [l, textFor(text, l) ?? null]))
|
||||
}
|
||||
const out: CookieReviewValues = {}
|
||||
if (finding.category) {out.category = finding.category}
|
||||
if (finding.domain) {out.domain = finding.domain}
|
||||
if (finding.vendor) {out.vendor = finding.vendor}
|
||||
if (typeof finding.setBeforeConsent === 'boolean') {out.setBeforeConsent = finding.setBeforeConsent}
|
||||
const purpose = perLocale(finding.purpose)
|
||||
const retention = perLocale(finding.retention)
|
||||
if (purpose) {out.purpose = purpose}
|
||||
if (retention) {out.retention = retention}
|
||||
return out
|
||||
}
|
||||
|
||||
const isEmpty = (v: unknown) => v === undefined || v === null || v === ''
|
||||
|
||||
/**
|
||||
* New values for an entry after a scan. A value takes the new suggestion only
|
||||
* while it is empty or still equal to what the previous scan suggested — once an
|
||||
* editor changed it, it is theirs and stays. Text is compared per locale.
|
||||
*/
|
||||
export function mergeCookieReview(
|
||||
current: CookieReviewValues,
|
||||
previous: CookieReviewValues | null | undefined,
|
||||
next: CookieReviewValues,
|
||||
): { changed: boolean; values: CookieReviewValues } {
|
||||
const prev = previous ?? {}
|
||||
const values: CookieReviewValues = { ...current }
|
||||
let changed = false
|
||||
const pick = <V>(cur: V, before: undefined | V, suggested: undefined | V): V => {
|
||||
if (suggested === undefined || isEmpty(suggested)) {return cur}
|
||||
if (isEmpty(cur) || cur === before) {return suggested}
|
||||
return cur
|
||||
}
|
||||
for (const key of SCALARS) {
|
||||
const v = pick(current[key], prev[key], next[key])
|
||||
if (v !== current[key]) {
|
||||
;(values as Record<string, unknown>)[key] = v
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
for (const key of TEXTS) {
|
||||
const cur = current[key] ?? {}
|
||||
const merged = { ...cur }
|
||||
for (const [locale, suggested] of Object.entries(next[key] ?? {})) {
|
||||
const v = pick(cur[locale], prev[key]?.[locale], suggested)
|
||||
if (v !== cur[locale]) {
|
||||
merged[locale] = v ?? null
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if (Object.keys(merged).length) {values[key] = merged}
|
||||
}
|
||||
return { changed, values }
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
import type { BasePayload, PayloadRequest } from 'payload'
|
||||
|
||||
import type { CookieReviewValues } from './merge.js'
|
||||
import type {
|
||||
CookieDeclaration,
|
||||
CookieFinding,
|
||||
CookieIntegration,
|
||||
CookieScanContext,
|
||||
CookieScannerOptions,
|
||||
CookieScanSummary,
|
||||
CookieStorage,
|
||||
} from './types.js'
|
||||
|
||||
import { COOKIE_REVIEW_SLUG } from './collection.js'
|
||||
import { loadCookieDatabase, lookupCookie } from './cookieDatabase.js'
|
||||
import { cookieNameMatches, declarationsOf, DEFAULT_COOKIE_INTEGRATIONS } from './integrations.js'
|
||||
import { mergeCookieReview, suggestionFor } from './merge.js'
|
||||
|
||||
/** Most names one scan looks up — the panel field is for a handful, not a dump. */
|
||||
export const MAX_SCAN_NAMES = 200
|
||||
|
||||
/** Cookie / storage key names as browsers allow them: no spaces, `;`, `,` or `=`. */
|
||||
const NAME = /^[^\s;,=]{1,200}$/
|
||||
|
||||
/** Names from the panel's text box: trimmed, de-duplicated, invalid ones dropped. */
|
||||
export function parseCookieNames(input: unknown): string[] {
|
||||
const list = Array.isArray(input) ? input : typeof input === 'string' ? input.split(/[\n,]/) : []
|
||||
const out = new Set<string>()
|
||||
for (const raw of list) {
|
||||
if (typeof raw !== 'string') {continue}
|
||||
const name = raw.trim()
|
||||
if (NAME.test(name)) {out.add(name)}
|
||||
if (out.size >= MAX_SCAN_NAMES) {break}
|
||||
}
|
||||
return [...out]
|
||||
}
|
||||
|
||||
const reviewKey = (storage: CookieStorage, name: string) => `${storage}:${name}`
|
||||
|
||||
function fromDeclaration(d: CookieDeclaration, source: 'integration' | 'project', sourceDetail: string): CookieFinding {
|
||||
return {
|
||||
category: d.category,
|
||||
...(d.domain ? { domain: d.domain } : {}),
|
||||
name: d.name,
|
||||
purpose: d.purpose,
|
||||
retention: d.retention,
|
||||
setBeforeConsent: d.setBeforeConsent,
|
||||
source,
|
||||
sourceDetail,
|
||||
storage: d.storage ?? 'cookie',
|
||||
vendor: d.vendor,
|
||||
}
|
||||
}
|
||||
|
||||
/** The integrations this project uses (a failing check counts as off and is logged). */
|
||||
export async function enabledCookieIntegrations(
|
||||
integrations: CookieIntegration[],
|
||||
ctx: CookieScanContext,
|
||||
): Promise<CookieIntegration[]> {
|
||||
const on: CookieIntegration[] = []
|
||||
for (const integration of integrations) {
|
||||
try {
|
||||
if (await integration.isEnabled(ctx)) {on.push(integration)}
|
||||
} catch (err) {
|
||||
ctx.payload.logger.warn(`[ipal] cookie scan: could not check "${integration.key}": ${err instanceof Error ? err.message : String(err)}`)
|
||||
}
|
||||
}
|
||||
return on
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything a scan reports, before anything is written: the cookies of the
|
||||
* enabled integrations, the project's declarations, and each extra name looked
|
||||
* up in the project's declarations, every built-in integration, then the Open
|
||||
* Cookie Database. A name nothing knows comes back with `source: 'unknown'`.
|
||||
*/
|
||||
export async function collectCookieFindings({
|
||||
ctx,
|
||||
database = true,
|
||||
databaseCategories,
|
||||
declarations = [],
|
||||
integrations = DEFAULT_COOKIE_INTEGRATIONS,
|
||||
names = [],
|
||||
}: {
|
||||
ctx: CookieScanContext
|
||||
database?: boolean
|
||||
databaseCategories?: CookieScannerOptions['databaseCategories']
|
||||
declarations?: CookieDeclaration[]
|
||||
integrations?: CookieIntegration[]
|
||||
names?: string[]
|
||||
}): Promise<{ enabled: CookieIntegration[]; findings: CookieFinding[] }> {
|
||||
const enabled = await enabledCookieIntegrations(integrations, ctx)
|
||||
const found = new Map<string, CookieFinding>()
|
||||
const add = (f: CookieFinding) => {
|
||||
const key = reviewKey(f.storage, f.name)
|
||||
if (!found.has(key)) {found.set(key, f)}
|
||||
}
|
||||
for (const d of declarations) {add(fromDeclaration(d, 'project', 'Project'))}
|
||||
for (const integration of enabled) {
|
||||
for (const d of declarationsOf(integration, ctx)) {add(fromDeclaration(d, 'integration', integration.label))}
|
||||
}
|
||||
|
||||
const known = [
|
||||
...declarations.map((d) => ({ d, detail: 'Project', source: 'project' as const })),
|
||||
...integrations.flatMap((i) => declarationsOf(i, ctx).map((d) => ({ d, detail: i.label, source: 'integration' as const }))),
|
||||
]
|
||||
const index = database ? await loadCookieDatabase() : null
|
||||
for (const name of names) {
|
||||
if ([...found.values()].some((f) => f.storage === 'cookie' && cookieNameMatches(f.name, name))) {continue}
|
||||
const declared = known.find((k) => (k.d.storage ?? 'cookie') === 'cookie' && cookieNameMatches(k.d.name, name))
|
||||
if (declared) {
|
||||
add(fromDeclaration(declared.d, declared.source, declared.detail))
|
||||
continue
|
||||
}
|
||||
const fromDb = index ? lookupCookie(index, name, databaseCategories) : null
|
||||
add(fromDb ?? { name, source: 'unknown', storage: 'cookie' })
|
||||
}
|
||||
return { enabled, findings: [...found.values()] }
|
||||
}
|
||||
|
||||
type ReviewDoc = {
|
||||
id: number | string
|
||||
listed?: boolean | null
|
||||
suggested?: CookieReviewValues | null
|
||||
} & CookieReviewValues
|
||||
|
||||
function localesOf(payload: BasePayload): { defaultLocale?: string; locales: (string | undefined)[] } {
|
||||
const l = payload.config.localization
|
||||
if (!l) {return { locales: [undefined] }}
|
||||
const codes = l.localeCodes ?? l.locales.map((x) => (typeof x === 'string' ? x : x.code))
|
||||
return { defaultLocale: l.defaultLocale, locales: [l.defaultLocale, ...codes.filter((c) => c !== l.defaultLocale)] }
|
||||
}
|
||||
|
||||
/** Names already in Cookie Settings → Cookies. */
|
||||
async function listedNames(payload: BasePayload, req?: PayloadRequest): Promise<Set<string>> {
|
||||
try {
|
||||
const g = (await payload.findGlobal({ slug: 'cookie-settings' as never, depth: 0, req })) as { cookies?: { name?: null | string }[] }
|
||||
return new Set((g.cookies ?? []).map((c) => c.name?.trim() ?? '').filter(Boolean))
|
||||
} catch {
|
||||
return new Set()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes findings to the review list as drafts. New names become drafts; an
|
||||
* existing entry gets the new suggestion only where an editor has not changed
|
||||
* the value (see mergeCookieReview). Status is never changed, nothing is
|
||||
* deleted and nothing is published — accepting stays the editor's step.
|
||||
*/
|
||||
export async function applyCookieFindings({
|
||||
collection = COOKIE_REVIEW_SLUG,
|
||||
findings,
|
||||
payload,
|
||||
req,
|
||||
}: {
|
||||
collection?: string
|
||||
findings: CookieFinding[]
|
||||
payload: BasePayload
|
||||
req?: PayloadRequest
|
||||
}): Promise<CookieScanSummary> {
|
||||
const { locales } = localesOf(payload)
|
||||
const codes = locales.filter((l): l is string => Boolean(l))
|
||||
const listed = await listedNames(payload, req)
|
||||
const summary: CookieScanSummary = { created: 0, unchanged: 0, unknown: 0, updated: 0 }
|
||||
const now = new Date().toISOString()
|
||||
const common = { collection: collection as never, context: { ipalCookieScan: true }, depth: 0, fallbackLocale: false as never, overrideAccess: true, req }
|
||||
|
||||
for (const finding of findings) {
|
||||
if (finding.source === 'unknown') {summary.unknown++}
|
||||
const key = reviewKey(finding.storage, finding.name)
|
||||
const next = suggestionFor(finding, codes.length ? codes : ['en'])
|
||||
const machine = {
|
||||
key,
|
||||
lastScannedAt: now,
|
||||
listed: listed.has(finding.name),
|
||||
source: finding.source,
|
||||
sourceDetail: finding.sourceDetail ?? null,
|
||||
suggested: next,
|
||||
}
|
||||
const found = await payload.find({ ...common, limit: 1, locale: (codes.length ? 'all' : undefined) as never, where: { key: { equals: key } } })
|
||||
const existing = found.docs[0] as ReviewDoc | undefined
|
||||
|
||||
const values = existing ? mergeCookieReview(existing, existing.suggested, next) : { changed: true, values: next }
|
||||
const { purpose, retention, ...scalars } = values.values
|
||||
const textIn = (locale: string | undefined) => ({
|
||||
...(purpose && locale ? { purpose: purpose[locale] ?? null } : {}),
|
||||
...(retention && locale ? { retention: retention[locale] ?? null } : {}),
|
||||
...(!locale && purpose ? { purpose: Object.values(purpose)[0] ?? null } : {}),
|
||||
...(!locale && retention ? { retention: Object.values(retention)[0] ?? null } : {}),
|
||||
})
|
||||
|
||||
let id = existing?.id
|
||||
for (const [i, locale] of locales.entries()) {
|
||||
const data = i === 0
|
||||
? { ...scalars, ...machine, ...textIn(locale), ...(existing ? {} : { name: finding.name, status: 'draft', storage: finding.storage }) }
|
||||
: textIn(locale)
|
||||
if (i > 0 && (!values.changed || !Object.keys(data).length)) {continue}
|
||||
if (id === undefined) {
|
||||
id = ((await payload.create({ ...common, data: data as never, locale: locale as never })) as { id: number | string }).id
|
||||
} else {
|
||||
await payload.update({ ...common, id, data: data as never, locale: locale as never })
|
||||
}
|
||||
}
|
||||
if (!existing) {summary.created++}
|
||||
else if (values.changed) {summary.updated++}
|
||||
else {summary.unchanged++}
|
||||
}
|
||||
return summary
|
||||
}
|
||||
|
||||
/** Scan context from a running Payload: SiteIntegrations + the plugin's module switches. */
|
||||
export async function cookieScanContext(
|
||||
payload: BasePayload,
|
||||
plugin: CookieScanContext['plugin'],
|
||||
req?: PayloadRequest,
|
||||
): Promise<CookieScanContext> {
|
||||
let integrations: Record<string, unknown> = {}
|
||||
try {
|
||||
integrations = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0, req })) as Record<string, unknown>
|
||||
} catch {
|
||||
// No such global (project replaced it) — integrations keyed on its IDs count as off.
|
||||
}
|
||||
return { integrations, payload, plugin }
|
||||
}
|
||||
|
||||
/**
|
||||
* One full scan: findings for this project, plus the names already in Cookie
|
||||
* Settings and the extra `names`, written to the review list.
|
||||
*/
|
||||
export async function runCookieScan({
|
||||
names = [],
|
||||
options = {},
|
||||
payload,
|
||||
plugin,
|
||||
req,
|
||||
}: {
|
||||
names?: string[]
|
||||
options?: CookieScannerOptions
|
||||
payload: BasePayload
|
||||
plugin: CookieScanContext['plugin']
|
||||
req?: PayloadRequest
|
||||
}): Promise<{ enabled: CookieIntegration[]; summary: CookieScanSummary }> {
|
||||
const ctx = await cookieScanContext(payload, plugin, req)
|
||||
const integrations = options.integrations ? options.integrations(DEFAULT_COOKIE_INTEGRATIONS) : DEFAULT_COOKIE_INTEGRATIONS
|
||||
const { enabled, findings } = await collectCookieFindings({
|
||||
ctx,
|
||||
database: options.database !== false,
|
||||
databaseCategories: options.databaseCategories,
|
||||
declarations: options.declarations,
|
||||
integrations,
|
||||
names: [...new Set([...(await listedNames(payload, req)), ...names])],
|
||||
})
|
||||
const summary = await applyCookieFindings({ findings, payload, req })
|
||||
return { enabled, summary }
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { BasePayload, PayloadRequest } from 'payload'
|
||||
|
||||
import type { CookieReviewValues } from './merge.js'
|
||||
|
||||
type Row = {
|
||||
category?: null | string
|
||||
duration?: null | string
|
||||
id?: string
|
||||
name?: null | string
|
||||
provider?: null | string
|
||||
purpose?: null | string
|
||||
}
|
||||
|
||||
type Entry = { name: string } & CookieReviewValues
|
||||
|
||||
const empty = (v: unknown) => v === undefined || v === null || (typeof v === 'string' && !v.trim())
|
||||
|
||||
/**
|
||||
* Adds an accepted review entry to Cookie Settings → Cookies, in every locale.
|
||||
* A missing row is added; an existing row (same name) gets only its EMPTY
|
||||
* provider, purpose and retention filled — text an editor wrote there stays,
|
||||
* and its category is never changed. Never removes a row.
|
||||
* Returns what happened, for the log.
|
||||
*/
|
||||
export async function addToCookieList({
|
||||
entry,
|
||||
payload,
|
||||
req,
|
||||
}: {
|
||||
entry: Entry
|
||||
payload: BasePayload
|
||||
req?: PayloadRequest
|
||||
}): Promise<'added' | 'filled' | 'unchanged'> {
|
||||
const l = payload.config.localization
|
||||
const codes = l ? (l.localeCodes ?? []) : []
|
||||
const defaultLocale = l ? l.defaultLocale : undefined
|
||||
const locales = l ? [defaultLocale!, ...codes.filter((c) => c !== defaultLocale)] : [undefined]
|
||||
const text = (map: Record<string, null | string> | undefined, locale: string | undefined) =>
|
||||
(locale ? map?.[locale] : map && Object.values(map)[0]) ?? null
|
||||
// fallbackLocale off for reads AND writes: an update in one locale otherwise reads the
|
||||
// stored rows with the default locale's text filled in and saves that text into it.
|
||||
const common = { slug: 'cookie-settings' as never, context: { ipalCookieScan: true }, depth: 0, fallbackLocale: false as never, overrideAccess: true, req }
|
||||
let result: 'added' | 'filled' | 'unchanged' = 'unchanged'
|
||||
|
||||
for (const [i, locale] of locales.entries()) {
|
||||
const g = (await payload.findGlobal({ ...common, locale: locale as never })) as { cookies?: Row[] }
|
||||
const rows = [...(g.cookies ?? [])]
|
||||
const row = rows.find((r) => r.name?.trim() === entry.name)
|
||||
let changed = false
|
||||
if (!row) {
|
||||
if (i > 0) {continue} // added in the default locale; Payload keeps the row in every locale
|
||||
rows.push({
|
||||
name: entry.name,
|
||||
category: entry.category ?? 'necessary',
|
||||
duration: text(entry.retention, locale),
|
||||
provider: entry.vendor ?? null,
|
||||
purpose: text(entry.purpose, locale),
|
||||
})
|
||||
changed = true
|
||||
result = 'added'
|
||||
} else {
|
||||
const fill = (key: 'duration' | 'provider' | 'purpose', value: null | string | undefined) => {
|
||||
if (empty(row[key]) && !empty(value)) {
|
||||
row[key] = value
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if (i === 0) {fill('provider', entry.vendor)}
|
||||
fill('purpose', text(entry.purpose, locale))
|
||||
fill('duration', text(entry.retention, locale))
|
||||
if (changed && result === 'unchanged') {result = 'filled'}
|
||||
}
|
||||
if (changed) {await payload.updateGlobal({ ...common, data: { cookies: rows } as never, locale: locale as never })}
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import type { BasePayload, PayloadRequest } from 'payload'
|
||||
|
||||
import type { CollectionOverride } from '../../shared/collectionOverride.js'
|
||||
import type { ConsentCategory } from '../categories.js'
|
||||
import type { CookieScanLabels } from './labels.js'
|
||||
|
||||
/** Text per admin/content language (`{ en, pl }`), or one string for every language. */
|
||||
export type LocalizedText = Record<string, string> | string
|
||||
|
||||
/** Where a key is kept in the browser. */
|
||||
export type CookieStorage = 'cookie' | 'localStorage' | 'sessionStorage'
|
||||
|
||||
/**
|
||||
* One cookie (or storage key) an integration sets — the single place its cookie
|
||||
* policy text lives. A trailing `*` in `name` matches every name with that prefix
|
||||
* (`_ga_*` → `_ga_ABC123`).
|
||||
*/
|
||||
export type CookieDeclaration = {
|
||||
category: ConsentCategory
|
||||
/** Third-party domain that sets it, e.g. `clarity.ms`. Omit for the site's own cookies. */
|
||||
domain?: string
|
||||
name: string
|
||||
purpose: LocalizedText
|
||||
retention: LocalizedText
|
||||
/** True when it may be set before the visitor decides (only `necessary` cookies should be). */
|
||||
setBeforeConsent: boolean
|
||||
/** Default `'cookie'`. */
|
||||
storage?: CookieStorage
|
||||
vendor: string
|
||||
}
|
||||
|
||||
/** What a scan knows about the project when it decides which integrations are on. */
|
||||
export type CookieScanContext = {
|
||||
/** SiteIntegrations (depth 0); `{}` when it can't be read. */
|
||||
integrations: Record<string, unknown>
|
||||
payload: BasePayload
|
||||
/** Plugin options that switch modules on. */
|
||||
plugin: { localeCount: number; stats: boolean }
|
||||
}
|
||||
|
||||
/**
|
||||
* A feature that sets cookies, with the check whether this project uses it.
|
||||
* Built-ins: DEFAULT_COOKIE_INTEGRATIONS. Projects add their own (custom embeds,
|
||||
* chat widgets) through `cookieScanner.integrations` or `cookieScanner.declarations`.
|
||||
*/
|
||||
export type CookieIntegration = {
|
||||
declarations: ((ctx: CookieScanContext) => CookieDeclaration[]) | CookieDeclaration[]
|
||||
/** Whether the project uses it — e.g. an ID is filled in Site Integrations. */
|
||||
isEnabled: (ctx: CookieScanContext) => boolean | Promise<boolean>
|
||||
/** Stable id, e.g. `ga4`. */
|
||||
key: string
|
||||
/** Shown in the panel, e.g. `Google Analytics 4`. */
|
||||
label: string
|
||||
}
|
||||
|
||||
/** Where a review entry's suggestion came from. `manual` = added by hand in the panel. */
|
||||
export type CookieFindingSource = 'database' | 'integration' | 'manual' | 'project' | 'unknown'
|
||||
|
||||
/** One cookie a scan found, before it is written to the review list. */
|
||||
export type CookieFinding = {
|
||||
category?: ConsentCategory
|
||||
domain?: string
|
||||
name: string
|
||||
purpose?: LocalizedText
|
||||
retention?: LocalizedText
|
||||
setBeforeConsent?: boolean
|
||||
source: CookieFindingSource
|
||||
/** e.g. `Google Analytics 4`, `Open Cookie Database: Hotjar`. */
|
||||
sourceDetail?: string
|
||||
storage: CookieStorage
|
||||
vendor?: string
|
||||
}
|
||||
|
||||
/** Open Cookie Database category names. */
|
||||
export type OpenCookieCategory = 'Analytics' | 'Functional' | 'Marketing' | 'Necessary' | 'Personalization' | 'Security'
|
||||
|
||||
/** Totals a scan reports back to the panel. */
|
||||
export type CookieScanSummary = {
|
||||
created: number
|
||||
unchanged: number
|
||||
/** Names nothing knew — the editor fills provider, purpose and category. */
|
||||
unknown: number
|
||||
updated: number
|
||||
}
|
||||
|
||||
/**
|
||||
* `ipalKit({ cookieScanner })` — the Cookie review list and the "Scan cookies"
|
||||
* action. Every key is optional.
|
||||
*/
|
||||
export type CookieScannerOptions = {
|
||||
/** Who may run a scan (GET/POST /api/ipal/cookie-scan). Default: `editor` and up. */
|
||||
access?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>
|
||||
/** Change the `cookie-review` collection (object merges, function takes over). */
|
||||
collectionOverrides?: CollectionOverride
|
||||
/** Look unknown names up in the bundled Open Cookie Database. Default true. */
|
||||
database?: boolean
|
||||
/**
|
||||
* How Open Cookie Database categories map to consent categories. Default:
|
||||
* Functional / Personalization → functional, Security / Necessary → necessary,
|
||||
* Analytics → analytics, Marketing → marketing. Functional is not mapped to
|
||||
* necessary on purpose: the database files some trackers there, and a lookup
|
||||
* nobody checked yet must not skip consent. `{ Functional: 'necessary' }` to change it.
|
||||
*/
|
||||
databaseCategories?: Partial<Record<OpenCookieCategory, ConsentCategory>>
|
||||
/** The project's own cookies (custom embeds, chat): always part of a scan. */
|
||||
declarations?: CookieDeclaration[]
|
||||
/**
|
||||
* Built-in integrations → the ones to use: filter, change or add.
|
||||
* `(defaults) => [...defaults, myChatWidget]`.
|
||||
*/
|
||||
integrations?: (defaults: CookieIntegration[]) => CookieIntegration[]
|
||||
/** Admin labels per language, merged over the plugin's `en` / `pl` (add `de: {…}`). */
|
||||
labels?: Record<string, Partial<CookieScanLabels>>
|
||||
/**
|
||||
* Accepting an entry adds it to Cookie Settings → Cookies (fills only empty
|
||||
* text of an existing row). Default true; `false` = the list is only a review aid.
|
||||
*/
|
||||
syncAccepted?: boolean
|
||||
}
|
||||
@@ -10,6 +10,8 @@ import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
|
||||
import { buildSiteSettings } from './globals/SiteSettings/index.js'
|
||||
import { adminOnly, adminOrSelf, injectRoles } from './modules/access/index.js'
|
||||
import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js'
|
||||
import { buildCookieReviewCollection } from './modules/consent/scanner/collection.js'
|
||||
import { buildCookieScanEndpoints } from './modules/consent/scanner/endpoint.js'
|
||||
import { buildConstructionFields } from './modules/construction/fields.js'
|
||||
import { buildArchiveFields } from './modules/content/index.js'
|
||||
import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js'
|
||||
@@ -311,6 +313,16 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
config.endpoints = [...(config.endpoints ?? []), buildConsentLogEndpoint(logOptions)]
|
||||
}
|
||||
|
||||
// --- cookie scanner: review list + "Scan cookies" (opt-in) ---
|
||||
if (options.cookieScanner) {
|
||||
const scannerOptions = options.cookieScanner === true ? {} : options.cookieScanner
|
||||
config.collections = [...(config.collections ?? []), applyCollectionOverride(buildCookieReviewCollection(scannerOptions), scannerOptions.collectionOverrides)]
|
||||
config.endpoints = [
|
||||
...(config.endpoints ?? []),
|
||||
...buildCookieScanEndpoints(scannerOptions, { localeCount: options.i18n.locales.length, stats: Boolean(options.stats) }),
|
||||
]
|
||||
}
|
||||
|
||||
// --- built-in statistics: cookieless visits + consented history (opt-in) ---
|
||||
if (options.stats) {
|
||||
const statsOptions = options.stats === true ? {} : options.stats
|
||||
|
||||
@@ -15,6 +15,7 @@ export type TotpPluginFactory = (options: {
|
||||
import type { GlobalOverrides } from './globals/overrides.js'
|
||||
import type { AccessOption } from './modules/access/types.js'
|
||||
import type { ConsentLogOptions } from './modules/consent/consentLog.js'
|
||||
import type { CookieScannerOptions } from './modules/consent/scanner/types.js'
|
||||
import type { ContentOption } from './modules/content/types.js'
|
||||
import type { FormsOption } from './modules/forms/types.js'
|
||||
import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js'
|
||||
@@ -63,6 +64,17 @@ export type IpalOptions = {
|
||||
*/
|
||||
content?: ContentOption
|
||||
|
||||
/**
|
||||
* Cookie scanner (docs/cookie-scanner.md): the `cookie-review` collection, a
|
||||
* "Scan cookies" action above its list and GET/POST /api/ipal/cookie-scan. A
|
||||
* scan lists the cookies of the integrations this project switches on, plus
|
||||
* names looked up in the bundled Open Cookie Database, as drafts an editor
|
||||
* accepts (→ Cookie Settings → Cookies), edits or rejects. Never deletes,
|
||||
* never overwrites edited text, never publishes by itself.
|
||||
* `true` or CookieScannerOptions. Default off.
|
||||
*/
|
||||
cookieScanner?: boolean | CookieScannerOptions
|
||||
|
||||
/**
|
||||
* `false` = plugin off without uninstalling: its collections, globals and
|
||||
* fields stay (DB schema and migrations unchanged), but it adds no endpoints,
|
||||
|
||||
Reference in New Issue
Block a user