Files
ipal-kit/src/modules/consent/consentLog.ts
T
Radosław SmolińskiandClaude Opus 5.5 0bfc509102 Run stats and consent-log retention purges off the request
The daily purge was awaited inside the visitor's request via payload.delete,
which loads and deletes expired documents one by one. It now runs as one
db.deleteMany in the background; failures are logged and retried.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:04:09 +02:00

104 lines
3.9 KiB
TypeScript

import type { CollectionConfig, Endpoint, PayloadRequest } from 'payload'
import { isAdmin } 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 `<ConsentProvider logEndpoint="/api/ipal/consent">`.
* 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: { user } }) => isAdmin(user),
read: ({ req: { user } }) => isAdmin(user),
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<string, unknown>; 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',
}
}