Files
ipal-kit/src/modules/consent/consentLog.ts
T

189 lines
9.0 KiB
TypeScript

import type { CollectionConfig, Endpoint, PayloadRequest } from 'payload'
import { TTL_FIELD } from '../shared/ttl.js'
import type { CollectionOverride } from '../shared/collectionOverride.js'
import { userMeetsRole } from '../access/predicates.js'
import { createDailyPurge } from '../shared/purge.js'
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
import { readCappedBody as readCapped } from '../shared/readCappedBody.js'
import { CONSENT_CATEGORIES } from './categories.js'
import { CONSENT_CATEGORY_LABELS } from './categoryLabels.js'
import { CONSENT_VERSION } from './storage.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.
*
* On by default since 1.17.0 (`iapl({ consentLog: false })` turns it off): adds the collection and the endpoint
* POST /api/ipal/consent. <SiteProviders> posts there by itself (the site shell knows the path); a layout with its
* own <ConsentProvider> passes `logEndpoint="/api/ipal/consent"`. Postgres / SQLite: the collection is a table, so
* the deploy that brings it needs a migration — until it exists a write answers 503 and logs one line; the page and
* the banner never notice. Records older than `retentionDays` (default 3 years) are purged automatically.
*/
export const CONSENT_LOG_SLUG = 'consent-records'
/** The endpoint's path under the API route (`/api` + this). */
export const CONSENT_LOG_PATH = '/ipal/consent'
/** A database error that means the collection's table is not there (a SQL project without the migration). */
export function isMissingTableError(err: unknown): boolean {
const text = err instanceof Error ? `${err.message} ${(err as { cause?: { message?: string } }).cause?.message ?? ''}` : String(err)
return /relation "?[\w.]*consent_records"? does not exist|no such table:? *"?[\w.]*consent_records|consent_records.*does(?: not|n't) exist/i.test(text)
}
export type ConsentLogOptions = {
/**
* Change the `consent-records` collection: an object merges over it
* (`access` / `admin` / `hooks` key by key, your keys win), a function gets it
* and returns the one to use. E.g. narrow who reads the records in a project
* without roles: `{ access: { read: ({ req }) => req.user?.email === '[email protected]' } }`.
*/
collectionOverrides?: CollectionOverride
/** Days a record is kept. Default 1095 (3 years). */
retentionDays?: number
/**
* MongoDB: a TTL index deletes records older than `retentionDays` by itself, also when no new record comes
* (1.18.0; shared/ttl.ts). Default true; `false` drops the index at the next start — the purge after a new record
* stays. Postgres / SQLite: not used.
*/
ttlIndex?: boolean
}
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: {
en: 'Proof of each cookie banner choice, stored with a random ID and no personal data.',
pl: 'Dowód każdego wyboru na banerze cookies, zapisany z losowym identyfikatorem, bez danych osobowych.',
},
group: { en: 'Privacy', pl: 'Prywatność' },
useAsTitle: 'consentId',
},
fields: [
{ name: 'consentId', type: 'text', index: true, label: { en: 'Consent ID', pl: 'Identyfikator zgody' }, required: true },
{ name: 'version', type: 'number', label: { en: 'Consent version', pl: 'Wersja zgody' }, required: true },
{
name: 'choices',
type: 'group',
fields: CONSENT_CATEGORIES.map((c) => ({ name: c, type: 'checkbox' as const, label: CONSENT_CATEGORY_LABELS[c] })),
label: { en: 'Choices', pl: 'Wybór' },
},
],
labels: {
plural: { en: 'Consent records', pl: 'Rejestr zgód' },
singular: { en: 'Consent record', pl: 'Zapis zgody' },
},
timestamps: true,
}
}
const purge = createDailyPurge(CONSENT_LOG_SLUG)
/** The missing-table line is logged once per Payload instance, not on every visitor's click. */
const missingTableLogged = new WeakSet<object>()
/** Largest body the endpoint reads. A decision is about 200 bytes; anything near this is not one. */
export const CONSENT_LOG_MAX_BYTES = 4096
/** The request body as text, or null when it is larger than `max` bytes (shared/readCappedBody.ts). */
export function readCappedBody(request: Request, max: number = CONSENT_LOG_MAX_BYTES): Promise<null | string> {
return readCapped(request, max)
}
/** Cookie Settings → Policy version per Payload instance, cached for a minute. */
const policyCache = new WeakMap<object, { at: number; version: number }>()
async function currentPolicyVersion(req: PayloadRequest, fresh = false): Promise<number> {
const cached = policyCache.get(req.payload)
if (!fresh && cached && Date.now() - cached.at < 60_000) {return cached.version}
let version = CONSENT_VERSION
try {
const g = (await req.payload.findGlobal({ slug: 'cookie-settings' as never, depth: 0 })) as { policyVersion?: unknown }
if (typeof g.policyVersion === 'number' && g.policyVersion >= 1) {version = Math.trunc(g.policyVersion)}
} catch {
// global missing — the default version applies
}
policyCache.set(req.payload, { at: Date.now(), version })
return version
}
/**
* A decision is made under the site's policy version or an earlier one (a page rendered before an editor raised
* it). A version above the current one is refused; when the cache says lower, it is read again once — the editor
* may have just raised it.
*/
async function versionAllowed(req: PayloadRequest, version: number): Promise<boolean> {
if (version <= (await currentPolicyVersion(req))) {return true}
return version <= (await currentPolicyVersion(req, true))
}
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 })}
const text = await readCappedBody(req as unknown as Request).catch(() => null)
if (text === null) {return Response.json({ ok: false }, { status: 413 })}
let body: unknown
try {
body = JSON.parse(text)
} catch {
return Response.json({ ok: false }, { status: 400 })
}
// `gpc` (Global Privacy Control at the time of the choice) may come with the body; the record does not store it.
const b = body as { gpc?: unknown; 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 || !(await versionAllowed(req, b.version as number))) {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,
[TTL_FIELD]: new Date().toISOString(), // MongoDB TTL counts from here (dropped where the field is not there)
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) {
if (isMissingTableError(err)) {
if (!missingTableLogged.has(req.payload)) {
missingTableLogged.add(req.payload)
req.payload.logger.error(
"[iapl] consent log: the consent-records table does not exist — create and apply a migration (pnpm payload migrate:create consent-log, commit, migrate at container start) or set iapl({ consentLog: false }). Banner choices are not recorded until then; the site works.",
)
}
return Response.json({ ok: false }, { status: 503 })
}
req.payload.logger.error(`[iapl] consent log write failed: ${err instanceof Error ? err.message : String(err)}`)
return Response.json({ ok: false }, { status: 500 })
}
},
method: 'post',
path: CONSENT_LOG_PATH,
}
}