Consent version only goes up (owner's decision Q2, 1.17.2)
A stored consent counts only under the version it was given for, so a lower Cookies →
Consent version made consent given under an older policy valid again. A save through access
control (panel, REST, GraphQL) with a lower number is now refused with a message (English and
Polish); the same or a higher number and saves without it pass; the Local API with
overrideAccess may still lower it. iapl({ cookieSettings: { allowLowerPolicyVersion: true } })
keeps the old behaviour. Building blocks exported: policyVersionNeverDown,
buildCookieSettingsFields, buildCookieSettings. No schema change.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
fc70a34f3e
commit
27ddbc3b41
@@ -1217,6 +1217,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
|
||||
| Rich-text links: one rule for every stored URL — `link`, `autolink` (also marked internal) and the Markdown output (`lexicalToMarkdown`) drop `javascript:` / `data:` targets | `safeLinks={false}` (trusted content only) | `sanitizeRichTextLinks`, `safeHref` |
|
||||
| Locales: no stand-in — `resolveRoute` (page route, `/md/…`, MCP `get_page`) answers `null` for a locale the site does not have (`xx`, `all`); a 404 page that is a draft is not shown (built-in view instead) | — | `isSiteLocale(payload, locale)`; verify: `curl -i <site>/md/xx` → 404 |
|
||||
| Site integrations versions (when a project turns them on) are read by admins only (`readVersions`) | — | `globalOverrides: { 'site-integrations': { access: { readVersions } } }` |
|
||||
| Consent version only goes up (1.17.2): a save through access control with a lower Cookies → *Consent version* is refused with a message (old consent would count again); the Local API with `overrideAccess` may still | `iapl({ cookieSettings: { allowLowerPolicyVersion: true } })` | `policyVersionNeverDown`, `buildCookieSettingsFields` (type `CookieSettingsFieldOptions`), `buildCookieSettings(options)`; verify: lower it in the panel → the error under the field |
|
||||
| Consent log on (since 1.17.0; Postgres / SQLite: a migration in the same deploy) | `consentLog: false`; one layout: `logEndpoint={false}` | `consentLog: { retentionDays, collectionOverrides }`; `buildConsentLogCollection` / `buildConsentLogEndpoint`, `CONSENT_LOG_PATH` |
|
||||
| Global Privacy Control honoured: no banner, analytics and marketing off, no Google request also in Consent Mode `advanced`; a grant made without the signal is switched off when it appears | `gpc={false}` (doctor warns) | `gpc="ask"`; `resolveConsent`, `gpcFromHeaders`, `consentBannerScript({ gpc })` |
|
||||
| "Reject" styled like "Accept all" (`equalChoice`) | `equalChoice={false}` (doctor warns) | `classNames.rejectButton` |
|
||||
|
||||
@@ -542,6 +542,13 @@ to add the hook to a config. Nothing to migrate.
|
||||
- **New consent after a policy change:** Cookies → *Consent version* (sidebar). Raise it by 1
|
||||
after adding a tool or changing the policy — every visitor will see the banner again.
|
||||
`getConsentTexts` passes the version to `<ConsentProvider texts>` automatically.
|
||||
- **The consent version only goes up (1.17.2).** A stored consent counts only under the version it was given for,
|
||||
so a lower number would make consent given under an older policy valid again. Saving Cookies with a lower
|
||||
*Consent version* through the panel, REST or GraphQL is refused: "The consent version cannot go down: it is 3
|
||||
now…" (Polish in a Polish panel). The same number, a higher one, or a save without it pass. A script an admin runs
|
||||
with the Local API and `overrideAccess` may still lower it. Turn the rule off: `iapl({ cookieSettings:
|
||||
{ allowLowerPolicyVersion: true } })`. Building blocks: `policyVersionNeverDown` (the field hook),
|
||||
`buildCookieSettingsFields({ allowLowerPolicyVersion })`, `buildCookieSettings(options)`.
|
||||
- **Withdrawing consent deletes the tools' cookies** (`_ga`, `_ga_*`, `_gid`, `_fbp`, `_gcl_*`, Clarity,
|
||||
LinkedIn, TikTok, Hotjar…) — also on the parent domain (`.client.com`), where GA stores them.
|
||||
The project's own cookies: `<ConsentProvider cookieMap={{ marketing: ['_my*'] }}>` (added to the
|
||||
|
||||
@@ -1,8 +1,44 @@
|
||||
import type { Field } from 'payload'
|
||||
import type { Field, FieldHook, NumberField } from 'payload'
|
||||
|
||||
import { ValidationError } from 'payload'
|
||||
|
||||
import { iaplT } from '../../modules/admin-i18n/t.js'
|
||||
import { rowLabel } from '../../modules/admin-ui/index.js'
|
||||
import { consentCategoryOptions } from '../../modules/consent/categoryLabels.js'
|
||||
|
||||
/**
|
||||
* Cookie settings → Consent version only goes up (1.17.2). A stored consent counts only under the version it was
|
||||
* given for, so a LOWER number would make old consent cookies valid again — consent given under an older policy.
|
||||
* A save through access control (the panel, REST, GraphQL) with a lower number is refused with a message; the
|
||||
* Local API with `overrideAccess` (a script an admin runs) may still lower it. `iapl({ cookieSettings:
|
||||
* { allowLowerPolicyVersion: true } })` leaves the field free, as before.
|
||||
*/
|
||||
export const policyVersionNeverDown: FieldHook = ({ global, originalDoc, overrideAccess, path, req, siblingData, value }) => {
|
||||
if (overrideAccess === true) {return value}
|
||||
const stored = Number((originalDoc as { policyVersion?: unknown } | undefined)?.policyVersion)
|
||||
// what the save SENT: Payload passes the stored value for a field that was not sent
|
||||
const sent = siblingData && 'policyVersion' in siblingData ? Number((siblingData as { policyVersion?: unknown }).policyVersion) : NaN
|
||||
if (!Number.isFinite(stored) || !Number.isFinite(sent) || sent >= stored) {return value}
|
||||
const vars = { stored }
|
||||
const message = req?.t ? iaplT(req.t as never, 'policyVersionDown', vars) : `The consent version cannot go down: it is ${stored} now.`
|
||||
throw new ValidationError({ errors: [{ message, path: path.join('.') }], global: global?.slug }, req?.t)
|
||||
}
|
||||
|
||||
export type CookieSettingsFieldOptions = {
|
||||
/** `true` = an editor may lower the consent version, as before 1.17.2. Default false. */
|
||||
allowLowerPolicyVersion?: boolean
|
||||
}
|
||||
|
||||
/** The Cookie settings fields, with the consent-version rule unless it is turned off. */
|
||||
export function buildCookieSettingsFields({ allowLowerPolicyVersion = false }: CookieSettingsFieldOptions = {}): Field[] {
|
||||
if (allowLowerPolicyVersion) {return cookieSettingsFields}
|
||||
return cookieSettingsFields.map((field) =>
|
||||
'name' in field && field.name === 'policyVersion'
|
||||
? ({ ...field, hooks: { ...(field as NumberField).hooks, beforeValidate: [policyVersionNeverDown, ...((field as NumberField).hooks?.beforeValidate ?? [])] } } as Field)
|
||||
: field,
|
||||
)
|
||||
}
|
||||
|
||||
const DEFAULT_HINT = { en: 'Leave empty to use the default.', pl: 'Zostaw puste, aby użyć domyślnej wartości.' }
|
||||
const HIDDEN_HINT = { en: 'Leave empty to hide it.', pl: 'Zostaw puste, aby go nie pokazywać.' }
|
||||
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import type { GlobalConfig } from 'payload'
|
||||
|
||||
import { userMeetsRole } from '../../modules/access/index.js'
|
||||
import { cookieSettingsFields } from './fields.js'
|
||||
import { buildCookieSettingsFields, type CookieSettingsFieldOptions } from './fields.js'
|
||||
|
||||
/**
|
||||
* Builds the CookieSettings global ("Cookies" in the admin) — consent banner copy and the
|
||||
* cookie list, managed by editors. With the cookie scanner it also carries its tabs.
|
||||
* Public read (the banner needs it on the frontend for anonymous visitors).
|
||||
*/
|
||||
export function buildCookieSettings(): GlobalConfig {
|
||||
export function buildCookieSettings(options: CookieSettingsFieldOptions = {}): GlobalConfig {
|
||||
return {
|
||||
slug: 'cookie-settings',
|
||||
access: {
|
||||
@@ -18,7 +18,7 @@ export function buildCookieSettings(): GlobalConfig {
|
||||
admin: {
|
||||
group: { en: 'Privacy', pl: 'Prywatność' },
|
||||
},
|
||||
fields: cookieSettingsFields,
|
||||
fields: buildCookieSettingsFields(options),
|
||||
label: { en: 'Cookies', pl: 'Cookies' },
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
export { buildCookieSettingsFields, policyVersionNeverDown } from './globals/CookieSettings/fields.js'
|
||||
export type { CookieSettingsFieldOptions } from './globals/CookieSettings/fields.js'
|
||||
export { buildCookieSettings } from './globals/CookieSettings/index.js'
|
||||
export { lightboxNotificationFields } from './globals/Notifications/fields.js'
|
||||
export { applyGlobalOverrides } from './globals/overrides.js'
|
||||
export type { GlobalOverride, GlobalOverrides, IaplGlobalSlug, IpalGlobalSlug } from './globals/overrides.js'
|
||||
|
||||
@@ -9,6 +9,7 @@ export const consentTexts = defineTexts({
|
||||
cookieIntegrationStats: 'Built-in statistics',
|
||||
cookieIntegrationTheme: 'Theme choice',
|
||||
cookieSourceProject: 'Project',
|
||||
policyVersionDown: 'The consent version cannot go down: it is {{stored}} now. Raise it to ask every visitor again, or leave it as it is.',
|
||||
},
|
||||
pl: {
|
||||
cookieIntegrationAdmin: 'Logowanie do panelu',
|
||||
@@ -17,5 +18,6 @@ export const consentTexts = defineTexts({
|
||||
cookieIntegrationStats: 'Wbudowane statystyki',
|
||||
cookieIntegrationTheme: 'Wybór motywu',
|
||||
cookieSourceProject: 'Projekt',
|
||||
policyVersionDown: 'Wersji zgody nie można obniżyć: teraz wynosi {{stored}}. Podnieś ją, aby ponownie zapytać odwiedzających, albo zostaw bez zmian.',
|
||||
},
|
||||
})
|
||||
|
||||
+1
-1
@@ -766,7 +766,7 @@ export const iapl = (options: IaplOptions): Plugin => {
|
||||
reenterSecretOnChange: options.secrets?.reenterOnChange !== false,
|
||||
writeOnlySecrets: options.secrets?.writeOnly !== false,
|
||||
}),
|
||||
withFillLocales('global', buildCookieSettings(), fillLocales['cookie-settings']),
|
||||
withFillLocales('global', buildCookieSettings(options.cookieSettings), fillLocales['cookie-settings']),
|
||||
buildNotifications({ lightbox: options.lightbox === true }),
|
||||
]
|
||||
// A global feeds every page's layout — revalidate the site on save.
|
||||
|
||||
@@ -119,6 +119,13 @@ export type IaplOptions = {
|
||||
*/
|
||||
cookieScanner?: boolean | CookieScannerOptions
|
||||
|
||||
/**
|
||||
* Cookie settings (the global). `allowLowerPolicyVersion: true` lets an editor LOWER the consent version, as
|
||||
* before 1.17.2 — a lower number makes consent given under an older policy valid again, so by default a save
|
||||
* through access control with a lower number is refused (the Local API with `overrideAccess` may still).
|
||||
*/
|
||||
cookieSettings?: { allowLowerPolicyVersion?: boolean }
|
||||
|
||||
/**
|
||||
* Forms — form-builder collections (forms, form-submissions) plus the
|
||||
* callable submitForm (Turnstile + persistence + SMTP-from-panel email).
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Cookie settings → Consent version only goes up (owner's decision Q2, 1.17.2). A stored consent counts only under
|
||||
* the version it was given for: a LOWER number made old consent cookies valid again. A save through access control
|
||||
* with a lower number is refused with a message; the Local API with `overrideAccess` may still lower it;
|
||||
* `cookieSettings: { allowLowerPolicyVersion: true }` keeps the old behaviour.
|
||||
* Real HTTP; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI.
|
||||
*/
|
||||
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
import { testDatabase } from './http/db.js'
|
||||
import { startPayloadServer } from './http/server.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
const PASSWORD = 'a-long-test-password-1'
|
||||
|
||||
async function site(name: string, cookieSettings?: { allowLowerPolicyVersion?: boolean }) {
|
||||
const config = buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), `iapl-${name}`) } }],
|
||||
db: testDatabase(name),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [iapl({ access: { authCollection: 'users' }, ...(cookieSettings ? { cookieSettings } : {}), i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, mail: { relay: false }, twoFactor: false })],
|
||||
secret: `${name}-0123456789-0123456789`,
|
||||
telemetry: false,
|
||||
})
|
||||
const payload = await getPayload({ config })
|
||||
const server = await startPayloadServer(config)
|
||||
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'] } as never })
|
||||
const { token } = (await (await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: '[email protected]', password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })).json()) as { token: string }
|
||||
await payload.updateGlobal({ slug: 'cookie-settings' as never, data: { policyVersion: 3 } as never })
|
||||
const save = (data: Record<string, unknown>) =>
|
||||
fetch(`${server.url}/api/globals/cookie-settings`, { body: JSON.stringify(data), headers: { authorization: `JWT ${token}`, 'content-type': 'application/json' }, method: 'POST' })
|
||||
const gql = (query: string) =>
|
||||
fetch(`${server.url}/api/graphql`, { body: JSON.stringify({ query }), headers: { authorization: `JWT ${token}`, 'content-type': 'application/json' }, method: 'POST' }).then((r) => r.json() as Promise<{ errors?: { message: string }[] }>)
|
||||
const stored = async () => ((await payload.findGlobal({ slug: 'cookie-settings' as never })) as { policyVersion?: number }).policyVersion
|
||||
return { gql, payload, save, server, stored }
|
||||
}
|
||||
|
||||
describe('by default the consent version only goes up', () => {
|
||||
let s: Awaited<ReturnType<typeof site>>
|
||||
beforeAll(async () => {
|
||||
s = await site('policy_rising')
|
||||
}, 120_000)
|
||||
afterAll(async () => {
|
||||
await s?.server.close()
|
||||
await s?.payload.destroy?.()
|
||||
})
|
||||
|
||||
test('a lower number is refused with the message, and the stored one stays', async () => {
|
||||
const res = await s.save({ policyVersion: 1 })
|
||||
expect(res.status).toBe(400)
|
||||
expect(JSON.stringify(await res.json())).toContain('The consent version cannot go down: it is 3 now')
|
||||
expect(await s.stored()).toBe(3)
|
||||
})
|
||||
|
||||
test('over GraphQL too', async () => {
|
||||
const res = await s.gql('mutation { updateCookieSetting(data: { policyVersion: 2 }) { policyVersion } }')
|
||||
expect(res.errors?.[0]?.message ?? '').toMatch(/invalid|cannot go down/i)
|
||||
expect(await s.stored()).toBe(3)
|
||||
})
|
||||
|
||||
test('the same number, a higher one, and a save that does not send it all pass', async () => {
|
||||
expect((await s.save({ policyVersion: 3 })).status).toBe(200)
|
||||
expect((await s.save({ title: 'Cookies' })).status).toBe(200)
|
||||
expect((await s.save({ policyVersion: 4 })).status).toBe(200)
|
||||
expect(await s.stored()).toBe(4)
|
||||
})
|
||||
|
||||
test('the Local API with access control off may lower it (a script an admin runs)', async () => {
|
||||
await s.payload.updateGlobal({ slug: 'cookie-settings' as never, data: { policyVersion: 2 } as never })
|
||||
expect(await s.stored()).toBe(2)
|
||||
})
|
||||
|
||||
test('the Polish text exists', async () => {
|
||||
const { adminTexts } = await import('../src/modules/admin-i18n/texts/index.js')
|
||||
expect(JSON.stringify(adminTexts)).toContain('Wersji zgody nie można obniżyć')
|
||||
})
|
||||
})
|
||||
|
||||
describe('cookieSettings: { allowLowerPolicyVersion: true } keeps the old behaviour', () => {
|
||||
test('the field has no consent-version rule then, and has it by default', async () => {
|
||||
const { buildCookieSettings } = await import('../src/globals/CookieSettings/index.js')
|
||||
const { policyVersionNeverDown } = await import('../src/globals/CookieSettings/fields.js')
|
||||
const hooksOf = (g: { fields: unknown[] }) =>
|
||||
((g.fields as { hooks?: { beforeValidate?: unknown[] }; name?: string }[]).find((f) => f.name === 'policyVersion')?.hooks?.beforeValidate ?? [])
|
||||
expect(hooksOf(buildCookieSettings())).toContain(policyVersionNeverDown)
|
||||
expect(hooksOf(buildCookieSettings({ allowLowerPolicyVersion: true }))).not.toContain(policyVersionNeverDown)
|
||||
})
|
||||
|
||||
test('iapl() passes the option through', async () => {
|
||||
const { buildConfig } = await import('payload')
|
||||
const { policyVersionNeverDown } = await import('../src/globals/CookieSettings/fields.js')
|
||||
const config = await iapl({ cookieSettings: { allowLowerPolicyVersion: true }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, mail: { relay: false }, twoFactor: false })({ collections: [], secret: 'x' } as never)
|
||||
void buildConfig
|
||||
const g = config.globals!.find((x) => x.slug === 'cookie-settings') as { fields: { hooks?: { beforeValidate?: unknown[] }; name?: string }[] }
|
||||
expect(g.fields.find((f) => f.name === 'policyVersion')?.hooks?.beforeValidate ?? []).not.toContain(policyVersionNeverDown)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user