import type { CollectionConfig, Endpoint, PayloadRequest } from 'payload' import { userMeetsRole } from '../access/predicates.js' import { createDailyPurge } from '../shared/purge.js' import { clientIp, consumeRateLimit } from '../shared/rateLimit.js' import { CONSENT_CATEGORIES } from './categories.js' /** * Consent log — proof of consent (GDPR Art. 7(1): the controller must be able * to demonstrate it). Each banner decision is stored as: random consent id (the * same one kept in the visitor's cookie), the choices, the policy version and * the time. NO IP address, user agent or other personal data — the id alone * links a record to the browser that holds the cookie. * * Opt-in: `ipalKit({ consentLog: true })` adds the collection and the endpoint * POST /api/ipal/consent; the layout passes ``. * Records older than `retentionDays` (default 3 years) are purged automatically. */ export const CONSENT_LOG_SLUG = 'consent-records' export type ConsentLogOptions = { /** Days a record is kept. Default 1095 (3 years). */ retentionDays?: number } export function buildConsentLogCollection(): CollectionConfig { return { slug: CONSENT_LOG_SLUG, access: { // Written only by the endpoint (Local API); read and pruned by admins. create: () => false, delete: ({ req }) => userMeetsRole(req, 'admin'), read: ({ req }) => userMeetsRole(req, 'admin'), update: () => false, }, admin: { defaultColumns: ['consentId', 'version', 'createdAt'], description: 'Proof of cookie consent: random id (also in the visitor cookie), choices, policy version, time. No personal data.', group: 'Settings', useAsTitle: 'consentId', }, fields: [ { name: 'consentId', type: 'text', index: true, required: true }, { name: 'version', type: 'number', required: true }, { name: 'choices', type: 'group', fields: CONSENT_CATEGORIES.map((c) => ({ name: c, type: 'checkbox' as const })), }, ], labels: { plural: 'Consent records', singular: 'Consent record' }, timestamps: true, } } const purge = createDailyPurge(CONSENT_LOG_SLUG) export function buildConsentLogEndpoint({ retentionDays = 1095 }: ConsentLogOptions = {}): Endpoint { return { handler: async (req: PayloadRequest) => { const limit = await consumeRateLimit({ key: clientIp(req as unknown as Request), max: 20, scope: 'consent' }) if (!limit.ok) {return Response.json({ ok: false }, { status: 429 })} let body: unknown try { body = await (req as unknown as Request).json() } catch { return Response.json({ ok: false }, { status: 400 }) } const b = body as { id?: unknown; state?: Record; version?: unknown } const valid = typeof b.id === 'string' && /^[0-9a-f]{16,64}$/.test(b.id) && typeof b.version === 'number' && Number.isInteger(b.version) && b.version >= 1 && b.state !== null && typeof b.state === 'object' && CONSENT_CATEGORIES.every((c) => typeof b.state![c] === 'boolean') if (!valid) {return Response.json({ ok: false }, { status: 400 })} try { await req.payload.create({ collection: CONSENT_LOG_SLUG as never, data: { choices: Object.fromEntries(CONSENT_CATEGORIES.map((c) => [c, b.state![c] === true])), consentId: b.id, version: b.version, } as never, overrideAccess: true, }) purge(req.payload, { createdAt: { less_than: new Date(Date.now() - retentionDays * 86_400_000).toISOString() } }) return Response.json({ ok: true }, { status: 201 }) } catch (err) { req.payload.logger.error(`[ipal] consent log write failed: ${err instanceof Error ? err.message : String(err)}`) return Response.json({ ok: false }, { status: 500 }) } }, method: 'post', path: '/ipal/consent', } }