@simmalugnt-se/payload-consent 0.6.11 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.0
4
+
5
+ - Built on c15t 3.2.2 (`@c15t/react`, and `@c15t/integrations` in place of `@c15t/scripts`). A project
6
+ installs `@c15t/react@3.2.2` and removes `@c15t/scripts`. Other integrations it passes in `scripts`
7
+ import from `@c15t/integrations`.
8
+ - c15t now does what the plugin did by hand: it asks again when the policy version changes or the
9
+ choice expires, and it deletes a denied category's listed cookies and localStorage keys, also on a
10
+ page load while the category is denied. Visitors' existing choices still apply until they expire.
11
+ - The cookie `c15t-policy` is gone. c15t adds `c15t-sid` (the visitor's random ID) and `c15t-vendors`,
12
+ and the cookie table lists them. Check that the site's cookie page says so.
13
+ - The settings dialog closes on Escape by c15t's own handling, and a click on the backdrop no longer
14
+ closes it, which is c15t's behaviour.
15
+ - Add to service preselects a category only when the Open Cookie Database suggests one. Before,
16
+ Necessary was preselected, so one click could put a tracker in order.
17
+ - Allowing a category from `ConsentFrame` keeps the banner open until the visitor has answered for the
18
+ other categories.
19
+
3
20
  ## 0.6.11
4
21
 
5
22
  - A scan judges findings by the Cookie services and their categories again, as in 0.6.9. The rules
package/README.md CHANGED
@@ -1,13 +1,13 @@
1
1
  # Payload consent
2
2
 
3
3
  A cookie banner for Payload sites, with its texts and the site's cookie services edited in Admin
4
- like other content. Built on [c15t](https://c15t.com) 2.2.1: no external consent script, nothing
4
+ like other content. Built on [c15t](https://c15t.com) 3.2.2: no external consent script, nothing
5
5
  loaded from a third party. Consent records and scans by our own scanner; see `docs/plans/consent.md` in the repository.
6
6
 
7
7
  ## Install
8
8
 
9
9
  ```sh
10
- pnpm add @simmalugnt-se/payload-consent @c15t/react@2.2.1
10
+ pnpm add @simmalugnt-se/payload-consent @c15t/react@3.2.2
11
11
  ```
12
12
 
13
13
  ```ts
@@ -79,10 +79,8 @@ collects (pages visited, the IP address, an identifier), not only why the site u
79
79
  ### How long a choice lasts
80
80
 
81
81
  A choice is kept for twelve months, then the banner asks again (`consentMonths` changes it).
82
- Visitors can change or withdraw it at any time through `ConsentSettingsLink`. c15t keeps the choice
83
- in a cookie and in localStorage and restores an expired cookie from localStorage, so the plugin
84
- forgets a choice older than `consentMonths`, or made under another policy version, before c15t reads
85
- it.
82
+ Visitors can change or withdraw it at any time through `ConsentSettingsLink`. The lifetime and the
83
+ policy version are part of the c15t policy rule the plugin passes, so c15t itself asks again.
86
84
 
87
85
  ## Consent records
88
86
 
@@ -100,16 +98,17 @@ legal basis is a legal obligation (art. 6(1)(c)), and records are deleted after
100
98
  period. Three years is a judgement, not a rule; `docs/research/consent-legal-questions.md` in the
101
99
  repository has the reasoning.
102
100
 
103
- When a visitor withdraws a category, c15t reloads the page and the plugin removes the cookies
104
- and localStorage keys the category's services list as their own (not third-party), so list the
105
- names a service stores, with `*` for a family such as `_ga_*`.
101
+ When a visitor withdraws a category, c15t reloads the page and deletes the cookies and localStorage
102
+ keys the category's services list (its `clearOnRevocation`), so list the names a service stores, with
103
+ `*` for a family such as `_ga_*`. c15t also deletes them on a page load while the category is denied.
106
104
 
107
105
  The policy version is a hash of the categories and each service's cookies and storage keys. When
108
106
  it changes, for example because a service gains a cookie, visitors are asked again. Rewording a
109
107
  text does not change it.
110
108
 
111
- The site keeps c15t in offline mode: the banner works without the server, and a record that cannot
112
- be posted only leaves the log without that entry.
109
+ The site runs c15t in `local()` mode and keeps its own record through the `onChoiceRecorded` callback,
110
+ as c15t documents for such a site: the banner works without the server, and a record that cannot be
111
+ posted only leaves the log without that entry.
113
112
 
114
113
  ## Scans
115
114
 
@@ -267,7 +266,7 @@ The services picked in Admin load on their own. Other c15t integrations go in `s
267
266
 
268
267
  ```tsx
269
268
  'use client'
270
- import { googleTagManager } from '@c15t/scripts/google-tag-manager'
269
+ import { googleTagManager } from '@c15t/integrations/google-tag-manager'
271
270
 
272
271
  <ConsentProvider
273
272
  config={consent}
@@ -299,8 +298,8 @@ import { CookieTable } from '@simmalugnt-se/payload-consent/client'
299
298
  ```
300
299
 
301
300
  It lists the services by category, each with its purpose, policy link and storage, and the
302
- banner's own consent storage first: `c15t`, a cookie and a localStorage key, and the cookie
303
- `c15t-policy` with the policy version the visitor chose under, all kept for `consentMonths`.
301
+ banner's own consent storage first: `c15t` (the choice), `c15t-sid` (the visitor's random ID) and
302
+ `c15t-vendors`, each a cookie and a localStorage key, kept for `consentMonths`.
304
303
 
305
304
  The global and the services are public to read by default (`access.read`), since the site shows
306
305
  them to everyone. `access.manage` says who works with cookies in Admin: changing the texts and
@@ -490,7 +490,8 @@ export function ScanPanel() {
490
490
  function FindingRow({ api, copy, finding, language, locale, onAdded, }) {
491
491
  const suggestion = finding.suggestion;
492
492
  const [service, setService] = useState(suggestion?.platform ?? (finding.kind === "host" ? finding.name : ""));
493
- const [category, setCategory] = useState(suggestion?.category ?? "necessary");
493
+ // Without a suggestion nothing is preselected: one click must not make a tracker Necessary.
494
+ const [category, setCategory] = useState(suggestion?.category);
494
495
  const [busy, setBusy] = useState(false);
495
496
  const [error, setError] = useState();
496
497
  async function add() {
@@ -550,11 +551,11 @@ function FindingRow({ api, copy, finding, language, locale, onAdded, }) {
550
551
  if (event.key !== "Enter")
551
552
  return;
552
553
  event.preventDefault();
553
- if (!busy && service.trim())
554
+ if (!busy && service.trim() && category)
554
555
  add();
555
556
  }, path: `${path}-service`, readOnly: busy, value: service }), _jsx(SelectInput, { isClearable: false, label: copy.category, name: `${path}-category`, onChange: (selected) => {
556
557
  const option = Array.isArray(selected) ? selected[0] : selected;
557
558
  if (option && typeof option === "object" && "value" in option)
558
559
  setCategory(option.value);
559
- }, options: CATEGORIES.map((value) => ({ label: copy.categories[value], value })), path: `${path}-category`, readOnly: busy, value: category }), _jsx(Button, { buttonStyle: "secondary", disabled: busy || !service.trim(), margin: false, onClick: add, size: "large", children: busy ? copy.adding : copy.add }), error ? (_jsx("p", { className: "consent-scan__error", role: "alert", children: error })) : null] })) : null] }));
560
+ }, options: CATEGORIES.map((value) => ({ label: copy.categories[value], value })), path: `${path}-category`, readOnly: busy, value: category }), _jsx(Button, { buttonStyle: "secondary", disabled: busy || !service.trim() || !category, margin: false, onClick: add, size: "large", children: busy ? copy.adding : copy.add }), error ? (_jsx("p", { className: "consent-scan__error", role: "alert", children: error })) : null] })) : null] }));
560
561
  }
package/dist/evaluate.js CHANGED
@@ -24,7 +24,7 @@ export function scanProblems(args) {
24
24
  return problems.slice(0, 20).map((problem) => problem.slice(0, 300));
25
25
  }
26
26
  /** The banner's own storage; always necessary. */
27
- const OWN_STORAGE = /^c15t(-policy|-storage-test-key)?$/;
27
+ const OWN_STORAGE = /^c15t(-sid|-vendors|-policy|-storage-test-key)?$/;
28
28
  /** `_ga_*` matches `_ga_ABC`; anything else must be equal. */
29
29
  export function matchesName(pattern, name) {
30
30
  return pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : pattern === name;
@@ -1,10 +1,10 @@
1
- import { type ConsentManagerOptions } from "@c15t/react";
1
+ import { type ConsentProviderOptions } from "@c15t/react";
2
2
  import { type ReactNode } from "react";
3
3
  import type { Category } from "../defaults.ts";
4
4
  import type { ConsentConfig, CookieTableData } from "../site-config.ts";
5
5
  /** A button that opens the settings dialog, for the site's footer. Render it inside `ConsentProvider`. */
6
6
  export { ConsentDialogLink as ConsentSettingsLink } from "@c15t/react";
7
- type Script = NonNullable<ConsentManagerOptions["scripts"]>[number];
7
+ type Script = NonNullable<ConsentProviderOptions["scripts"]>[number];
8
8
  /**
9
9
  * The services the plugin loads, each in its service's category. Nothing loads before consent,
10
10
  * including tags c15t would otherwise load at once in a denied state (Google Consent Mode's
@@ -15,7 +15,7 @@ type Props = {
15
15
  /** From `getConsentConfig` on the server. */
16
16
  config: ConsentConfig;
17
17
  /** More c15t script integrations, created on the client, besides the services the plugin loads. */
18
- scripts?: ConsentManagerOptions["scripts"];
18
+ scripts?: ConsentProviderOptions["scripts"];
19
19
  children: ReactNode;
20
20
  };
21
21
  /** The banner, the settings dialog and c15t's consent state around the site. */
@@ -1,18 +1,16 @@
1
1
  "use client";
2
2
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
- import { ConsentDialog as C15tDialog, ConsentBanner, ConsentManagerProvider, Frame, useConsentManager, } from "@c15t/react";
4
- import { gtag } from "@c15t/scripts/google-tag";
5
- import { googleTagManager } from "@c15t/scripts/google-tag-manager";
6
- import { hotjar } from "@c15t/scripts/hotjar";
7
- import { linkedinInsights } from "@c15t/scripts/linkedin-insights";
8
- import { metaPixel } from "@c15t/scripts/meta-pixel";
9
- import { clarity } from "@c15t/scripts/microsoft-clarity";
10
- import { microsoftUet } from "@c15t/scripts/microsoft-uet";
11
- import { tiktokPixel } from "@c15t/scripts/tiktok-pixel";
12
- import { createContext, useContext, useEffect, useRef, } from "react";
13
- import { isChoiceCurrent, savedAtFromCookie, savedAtFromStorage } from "../renewal.js";
14
- import { POLICY_COOKIE } from "../types.js";
15
- import { cookieDomains, matchesStorageName, subjectIdFromCookie, withdrawnStorage, } from "../withdrawal.js";
3
+ import { gtag } from "@c15t/integrations/google-tag";
4
+ import { googleTagManager } from "@c15t/integrations/google-tag-manager";
5
+ import { hotjar } from "@c15t/integrations/hotjar";
6
+ import { linkedinInsights } from "@c15t/integrations/linkedin-insights";
7
+ import { metaPixel } from "@c15t/integrations/meta-pixel";
8
+ import { clarity } from "@c15t/integrations/microsoft-clarity";
9
+ import { microsoftUet } from "@c15t/integrations/microsoft-uet";
10
+ import { tiktokPixel } from "@c15t/integrations/tiktok-pixel";
11
+ import { ConsentProvider as C15tProvider, ConsentBanner, ConsentDialog, ConsentGate, local, useSaveConsents, } from "@c15t/react";
12
+ import { createContext, useContext } from "react";
13
+ import { clearOnRevocation } from "../withdrawal.js";
16
14
  /** A button that opens the settings dialog, for the site's footer. Render it inside `ConsentProvider`. */
17
15
  export { ConsentDialogLink as ConsentSettingsLink } from "@c15t/react";
18
16
  /** Class names for c15t's unstyled parts, styled by `styles.css`. */
@@ -57,33 +55,66 @@ const factories = {
57
55
  * advanced mode), which sends data about the visit before the visitor has chosen.
58
56
  */
59
57
  export function integrationScripts(config) {
60
- return config.integrations.flatMap(({ key, id, category }) => {
61
- // One integration c15t refuses must not take the site's layout down with it.
62
- try {
63
- return [{ ...factories[key](id, category), category, alwaysLoad: false }];
64
- }
65
- catch (error) {
66
- console.error(`payload-consent: the ${key} integration could not be loaded`, error);
67
- return [];
68
- }
69
- });
58
+ return config.integrations.map(({ key, id, category }) => ({
59
+ ...factories[key](id, category),
60
+ category,
61
+ alwaysLoad: false,
62
+ }));
70
63
  }
71
64
  const ConfigContext = createContext(null);
65
+ /**
66
+ * Everyone gets the same opt-in rule: the site has no way to know the visitor's location. A new
67
+ * `copyRevision`, a changed scope or an expired choice makes c15t ask again.
68
+ */
69
+ function policyRule(config) {
70
+ return {
71
+ id: "site",
72
+ match: { isDefault: true, fallback: true },
73
+ model: "opt-in",
74
+ prompt: "choice",
75
+ categories: config.categories,
76
+ scopeMode: "strict",
77
+ copyRevision: config.policyVersion,
78
+ validity: { choiceDays: config.consentDays },
79
+ };
80
+ }
81
+ /** Posts a saved choice to the site's consent records, with its policy version. */
82
+ function recordChoice(config, subjectId, choice) {
83
+ if (!config.recordUrl || !subjectId || config.categories.length === 1)
84
+ return;
85
+ const choices = Object.fromEntries(config.categories.map((category) => [
86
+ category,
87
+ category === "necessary" || Boolean(choice[category]?.value),
88
+ ]));
89
+ // keepalive: a withdrawal posts this just before c15t reloads the page.
90
+ fetch(config.recordUrl, {
91
+ method: "POST",
92
+ headers: { "Content-Type": "application/json" },
93
+ keepalive: true,
94
+ body: JSON.stringify({
95
+ subjectId,
96
+ choices,
97
+ policyVersion: config.policyVersion,
98
+ locale: config.locale,
99
+ path: window.location.pathname,
100
+ }),
101
+ }).catch(() => {
102
+ // The choice still applies in the browser; only the record is missing.
103
+ });
104
+ }
72
105
  /** The banner, the settings dialog and c15t's consent state around the site. */
73
106
  export function ConsentProvider({ config, scripts, children }) {
74
107
  if (!config.enabled)
75
108
  return _jsx(_Fragment, { children: children });
76
- forgetOutdatedConsent(config);
77
- clearAfterWithdrawal(config);
78
109
  const options = {
79
- mode: "offline",
80
- overrides: { country: "SE" },
110
+ // Choices stay in the browser; the plugin keeps the record through `onChoiceRecorded`.
111
+ mode: local({ policyRules: [policyRule(config)], acknowledgeNoRecords: true }),
81
112
  consentCategories: config.categories,
82
113
  storageConfig: { defaultExpiryDays: config.consentDays },
83
114
  scripts: [...integrationScripts(config), ...(scripts ?? [])],
115
+ clearOnRevocation: clearOnRevocation(config.storage ?? []),
84
116
  legalLinks: config.legalLinks,
85
117
  noStyle: true,
86
- scrollLock: true,
87
118
  theme: { slots },
88
119
  i18n: {
89
120
  locale: config.locale,
@@ -91,196 +122,13 @@ export function ConsentProvider({ config, scripts, children }) {
91
122
  messages: { [config.locale]: config.messages },
92
123
  },
93
124
  callbacks: {
94
- // c15t reloads the page when a category is withdrawn. ConsentRecorder usually records the
95
- // choice first, but nothing waits for it: record here too (once, see recordChoice) and
96
- // clear the withdrawn services' storage.
97
- onBeforeConsentRevocationReload: ({ preferences }) => {
98
- const consents = preferences;
99
- writePolicy(config);
100
- recordChoice(config, subjectIdFromCookie(document.cookie), consents);
101
- clearWithdrawnStorage(config, consents);
102
- // A tag still running while the page unloads can write its cookie again: clear once more
103
- // after the reload (see clearAfterWithdrawal).
104
- try {
105
- window.sessionStorage.setItem(WITHDRAWN_KEY, JSON.stringify(consents));
106
- }
107
- catch {
108
- // Without session storage the cleanup above is all there is.
109
- }
110
- },
125
+ onChoiceRecorded: ({ snapshot }) => recordChoice(config, snapshot.subject?.subjectId, snapshot.explicitChoice?.categories ?? {}),
111
126
  },
112
127
  };
113
128
  // With only necessary storage there is nothing to consent to, so no banner: the settings link
114
129
  // still opens the dialog, which says the site only uses necessary storage.
115
130
  const necessaryOnly = config.categories.length === 1;
116
- return (_jsx(ConfigContext.Provider, { value: config, children: _jsxs(ConsentManagerProvider, { options: options, children: [children, necessaryOnly ? null : _jsx(ConsentBanner, { hideBranding: true }), _jsx(SettingsDialog, {}), _jsx(ConsentRecorder, { config: config })] }) }));
117
- }
118
- /** Set by a withdrawal just before c15t reloads the page; read once by the next page load. */
119
- const WITHDRAWN_KEY = "c15t-withdrawn";
120
- let checkedWithdrawal = false;
121
- /**
122
- * Clears what the withdrawn categories' services stored once more, on the page load that follows a
123
- * withdrawal. Only then: a fresh visitor, or a scanner, never has the marker.
124
- */
125
- function clearAfterWithdrawal(config) {
126
- if (typeof window === "undefined" || checkedWithdrawal)
127
- return;
128
- checkedWithdrawal = true;
129
- try {
130
- const saved = window.sessionStorage.getItem(WITHDRAWN_KEY);
131
- if (!saved)
132
- return;
133
- window.sessionStorage.removeItem(WITHDRAWN_KEY);
134
- clearWithdrawnStorage(config, JSON.parse(saved));
135
- }
136
- catch {
137
- // Without session storage there is no marker to act on.
138
- }
139
- }
140
- function readPolicy() {
141
- const match = document.cookie.match(new RegExp(`(?:^|; )${POLICY_COOKIE}=([^;]*)`));
142
- return match ? decodeURIComponent(match[1] ?? "") : null;
143
- }
144
- const checkedPolicies = new Set();
145
- function readStoredChoice() {
146
- try {
147
- return window.localStorage.getItem("c15t");
148
- }
149
- catch {
150
- return null;
151
- }
152
- }
153
- /**
154
- * Removes a choice made under another policy version, or older than the consent lifetime, before
155
- * c15t reads it, so nothing it allowed loads before the visitor is asked again. c15t keeps its
156
- * choice in localStorage too and restores an expired cookie from it, so both are checked. Runs
157
- * once per page load and version: a choice saved on this page writes the new version itself.
158
- */
159
- function forgetOutdatedConsent(config) {
160
- const version = config.policyVersion;
161
- if (typeof document === "undefined" || checkedPolicies.has(version))
162
- return;
163
- checkedPolicies.add(version);
164
- const stored = readStoredChoice();
165
- const hasCookie = /(?:^|; )c15t=/.test(document.cookie);
166
- if (!hasCookie && !stored)
167
- return;
168
- const current = isChoiceCurrent({
169
- savedAt: savedAtFromCookie(document.cookie) ?? savedAtFromStorage(stored),
170
- policyVersion: readPolicy(),
171
- }, { policyVersion: version, consentDays: config.consentDays, now: Date.now() });
172
- if (current)
173
- return;
174
- document.cookie = "c15t=; Path=/; Max-Age=0";
175
- try {
176
- window.localStorage.removeItem("c15t");
177
- }
178
- catch {
179
- // Without storage access there is nothing stored to remove.
180
- }
181
- }
182
- function writePolicy(config) {
183
- const secure = window.location.protocol === "https:" ? "; Secure" : "";
184
- document.cookie = `${POLICY_COOKIE}=${encodeURIComponent(config.policyVersion)}; Path=/; Max-Age=${config.consentDays * 24 * 60 * 60}; SameSite=Lax${secure}`;
185
- }
186
- /** The last choice posted from this page: a withdrawal reaches both the callback and the effect. */
187
- let lastRecorded;
188
- /**
189
- * Posts a saved choice to the site's consent records, with its policy version, once. Not when the
190
- * site only uses necessary storage: there is no consent to show.
191
- */
192
- function recordChoice(config, subjectId, consents) {
193
- if (!config.recordUrl || !subjectId || config.categories.length === 1)
194
- return;
195
- const choices = Object.fromEntries(config.categories.map((category) => [category, Boolean(consents[category])]));
196
- const key = JSON.stringify([subjectId, choices]);
197
- if (key === lastRecorded)
198
- return;
199
- lastRecorded = key;
200
- // keepalive: a withdrawal posts this just before the page reloads.
201
- fetch(config.recordUrl, {
202
- method: "POST",
203
- headers: { "Content-Type": "application/json" },
204
- keepalive: true,
205
- body: JSON.stringify({
206
- subjectId,
207
- choices,
208
- policyVersion: config.policyVersion,
209
- locale: config.locale,
210
- path: window.location.pathname,
211
- }),
212
- }).catch(() => {
213
- // The choice still applies in the browser; only the record is missing.
214
- });
215
- }
216
- /**
217
- * Removes the cookies and localStorage keys the Cookie services list for the categories the
218
- * visitor withdrew, such as `_ga` and `_ga_*`. Only on a withdrawal, never on an ordinary page
219
- * load: a scan must still see a service that stores something it should not.
220
- */
221
- function clearWithdrawnStorage(config, consents) {
222
- const items = withdrawnStorage(config.storage ?? [], consents);
223
- if (!items.length)
224
- return;
225
- const cookieNames = document.cookie
226
- .split("; ")
227
- .map((pair) => pair.slice(0, pair.indexOf("=")))
228
- .filter(Boolean);
229
- for (const item of items) {
230
- if (item.type === "cookie") {
231
- for (const name of cookieNames.filter((cookie) => matchesStorageName(item.name, cookie)))
232
- for (const domain of cookieDomains(window.location.hostname))
233
- document.cookie = `${name}=; Path=/; Max-Age=0${domain ? `; Domain=${domain}` : ""}`;
234
- }
235
- else {
236
- try {
237
- for (const key of Object.keys(window.localStorage))
238
- if (matchesStorageName(item.name, key))
239
- window.localStorage.removeItem(key);
240
- }
241
- catch {
242
- // Without storage access there is nothing stored to remove.
243
- }
244
- }
245
- }
246
- }
247
- /** Posts each choice saved on this page to the site's consent records. */
248
- function ConsentRecorder({ config }) {
249
- const { consentInfo, consents } = useConsentManager();
250
- const mountedAt = useRef(Date.now());
251
- const savedAt = consentInfo?.time;
252
- // biome-ignore lint/correctness/useExhaustiveDependencies: a new save time is a new choice.
253
- useEffect(() => {
254
- if (!savedAt || savedAt < mountedAt.current)
255
- return;
256
- writePolicy(config);
257
- recordChoice(config, consentInfo?.subjectId, consents);
258
- }, [savedAt]);
259
- return null;
260
- }
261
- /** c15t's dialog; a click on the backdrop discards unsaved toggles and returns to the banner. */
262
- function SettingsDialog() {
263
- const { consents, selectedConsents, setSelectedConsent, hasConsented, setActiveUI } = useConsentManager();
264
- function discardAndReturn() {
265
- for (const name of Object.keys(selectedConsents))
266
- setSelectedConsent(name, consents[name] ?? false);
267
- setActiveUI(hasConsented() ? "none" : "banner");
268
- }
269
- function dismiss(event) {
270
- if (event.target === event.currentTarget)
271
- discardAndReturn();
272
- }
273
- // c15t's dialog ignores Escape; a modal dialog closes on it (WAI-ARIA), here as the backdrop does.
274
- function onKeyDown(event) {
275
- if (event.key !== "Escape")
276
- return;
277
- event.preventDefault();
278
- discardAndReturn();
279
- }
280
- // With only necessary storage there is nothing to reject; c15t's dialog has no option to drop
281
- // the button, so a class hides it (see consent.css).
282
- const necessaryOnly = useContext(ConfigContext)?.categories.length === 1;
283
- return (_jsx(C15tDialog.Root, { className: necessaryOnly ? "sc-dialog--necessary-only" : undefined, onClick: dismiss, onKeyDown: onKeyDown, children: _jsx(C15tDialog.ConsentCustomizationCard, { hideBranding: true }) }));
131
+ return (_jsx(ConfigContext.Provider, { value: config, children: _jsxs(C15tProvider, { options: options, children: [children, necessaryOnly ? null : _jsx(ConsentBanner, { blocking: true, hideBranding: true }), _jsx(ConsentDialog.Root, { className: necessaryOnly ? "sc-dialog--necessary-only" : undefined, children: _jsx(ConsentDialog.ConsentCustomizationCard, { hideBranding: true }) })] }) }));
284
132
  }
285
133
  /**
286
134
  * Embedded content, such as a video or a map, that is not mounted until the visitor allows its
@@ -290,13 +138,13 @@ export function ConsentFrame({ category, provider, children, className }) {
290
138
  const config = useContext(ConfigContext);
291
139
  if (!config)
292
140
  return _jsx(_Fragment, { children: children });
293
- return (_jsx(Frame, { category: category, className: className, noStyle: true, placeholder: _jsx(EmbedPlaceholder, { category: category, config: config, provider: provider }), children: children }));
141
+ return (_jsx(ConsentGate, { category: category, className: className, noStyle: true, placeholder: _jsx(EmbedPlaceholder, { category: category, config: config, provider: provider }), children: children }));
294
142
  }
295
143
  function EmbedPlaceholder({ category, config, provider, }) {
296
- const { setConsent } = useConsentManager();
144
+ const save = useSaveConsents();
297
145
  const title = (config.messages.consentTypes?.[category]?.title ?? category).toLocaleLowerCase(config.locale);
298
146
  const fill = (text) => text.replaceAll("{category}", title).replaceAll("{provider}", provider);
299
- return (_jsxs("div", { className: "sc-frame", children: [_jsx("p", { children: fill(config.embeds.title) }), _jsx("button", { type: "button", onClick: () => setConsent(category, true), children: fill(config.embeds.button) })] }));
147
+ return (_jsxs("div", { className: "sc-frame", children: [_jsx("p", { children: fill(config.embeds.title) }), _jsx("button", { type: "button", onClick: () => void save({ [category]: true }), children: fill(config.embeds.button) })] }));
300
148
  }
301
149
  /** The cookie services by category, from `getCookieTable`, for the site's cookie page. */
302
150
  export function CookieTable({ data, heading }) {
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The c15t script integrations an editor can pick for a service, from `@c15t/scripts` 2.2.0. A
2
+ * The c15t script integrations an editor can pick for a service, from `@c15t/integrations` 3.2.2. A
3
3
  * picked integration is loaded by c15t and follows the visitor's choice. The client imports each
4
4
  * one, so the list stays short: the services our sites use, not the whole registry.
5
5
  */
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The c15t script integrations an editor can pick for a service, from `@c15t/scripts` 2.2.0. A
2
+ * The c15t script integrations an editor can pick for a service, from `@c15t/integrations` 3.2.2. A
3
3
  * picked integration is loaded by c15t and follows the visitor's choice. The client imports each
4
4
  * one, so the list stays short: the services our sites use, not the whole registry.
5
5
  */
package/dist/renewal.d.ts CHANGED
@@ -1,21 +1,4 @@
1
1
  /** How long a choice is kept before the visitor is asked again, unless the host sets `consentMonths`. */
2
2
  export declare const DEFAULT_CONSENT_MONTHS = 12;
3
- /** The consent lifetime in days, as c15t and the cookies count it: 12 months is 365 days. */
3
+ /** The consent lifetime in days, as c15t's policy rule counts it: 12 months is 365 days. */
4
4
  export declare function consentDays(months: number): number;
5
- /** When the choice in c15t's cookie was saved (`i.t:<ms>`). */
6
- export declare function savedAtFromCookie(cookie: string): number | undefined;
7
- /** When the choice in c15t's localStorage entry was saved. */
8
- export declare function savedAtFromStorage(json: string | null): number | undefined;
9
- /**
10
- * Whether a stored choice still applies: made under the current policy version and within the
11
- * consent lifetime. c15t never lets a choice expire by itself: when its cookie expires it restores
12
- * the cookie from localStorage, so the plugin forgets the choice before c15t reads it.
13
- */
14
- export declare function isChoiceCurrent(choice: {
15
- savedAt?: number;
16
- policyVersion?: string | null;
17
- }, current: {
18
- policyVersion: string;
19
- consentDays: number;
20
- now: number;
21
- }): boolean;
package/dist/renewal.js CHANGED
@@ -1,33 +1,6 @@
1
1
  /** How long a choice is kept before the visitor is asked again, unless the host sets `consentMonths`. */
2
2
  export const DEFAULT_CONSENT_MONTHS = 12;
3
- /** The consent lifetime in days, as c15t and the cookies count it: 12 months is 365 days. */
3
+ /** The consent lifetime in days, as c15t's policy rule counts it: 12 months is 365 days. */
4
4
  export function consentDays(months) {
5
5
  return Math.round((months * 365) / 12);
6
6
  }
7
- /** When the choice in c15t's cookie was saved (`i.t:<ms>`). */
8
- export function savedAtFromCookie(cookie) {
9
- const match = /(?:^|; )c15t=[^;]*?i\.t:(\d+)/.exec(cookie);
10
- return match ? Number(match[1]) : undefined;
11
- }
12
- /** When the choice in c15t's localStorage entry was saved. */
13
- export function savedAtFromStorage(json) {
14
- if (!json)
15
- return undefined;
16
- try {
17
- const time = JSON.parse(json)?.consentInfo?.time;
18
- return typeof time === "number" ? time : undefined;
19
- }
20
- catch {
21
- return undefined;
22
- }
23
- }
24
- /**
25
- * Whether a stored choice still applies: made under the current policy version and within the
26
- * consent lifetime. c15t never lets a choice expire by itself: when its cookie expires it restores
27
- * the cookie from localStorage, so the plugin forgets the choice before c15t reads it.
28
- */
29
- export function isChoiceCurrent(choice, current) {
30
- if (choice.policyVersion !== current.policyVersion || choice.savedAt === undefined)
31
- return false;
32
- return current.now - choice.savedAt < current.consentDays * 24 * 60 * 60 * 1000;
33
- }
package/dist/scans.d.ts CHANGED
@@ -5,8 +5,8 @@ import { type ConsentConfig } from "./site-config.ts";
5
5
  import { type ConsentPluginOptions } from "./types.ts";
6
6
  /**
7
7
  * The states a scan runs: a new visitor, rejecting, accepting everything and, with more than one
8
- * optional category, each category on its own. Each state presets c15t's cookie as c15t 2.2.1
9
- * writes it, and the policy cookie, so the banner treats it as a choice already made.
8
+ * optional category, each category on its own. Each state presets c15t's cookie in the v2 format,
9
+ * which c15t 3 reads as a choice already made.
10
10
  */
11
11
  export declare function scanStates(config: Pick<ConsentConfig, "categories" | "policyVersion">, now?: number): ScanState[];
12
12
  /**
package/dist/scans.js CHANGED
@@ -6,11 +6,11 @@ import { evidenceEndpoint } from "./evidence.js";
6
6
  import { notifyScan } from "./notify.js";
7
7
  import { retentionIn } from "./retention.js";
8
8
  import { readConsent, toConsentConfig, } from "./site-config.js";
9
- import { CONSENT_GLOBAL, CONSENT_SCAN_EVIDENCE, CONSENT_SCANS, CONSENT_SERVICES, MAX_SCAN_PAGES, POLICY_COOKIE, SCAN_STATE_PAGES, SCAN_TASK, } from "./types.js";
9
+ import { CONSENT_GLOBAL, CONSENT_SCAN_EVIDENCE, CONSENT_SCANS, CONSENT_SERVICES, MAX_SCAN_PAGES, SCAN_STATE_PAGES, SCAN_TASK, } from "./types.js";
10
10
  /**
11
11
  * The states a scan runs: a new visitor, rejecting, accepting everything and, with more than one
12
- * optional category, each category on its own. Each state presets c15t's cookie as c15t 2.2.1
13
- * writes it, and the policy cookie, so the banner treats it as a choice already made.
12
+ * optional category, each category on its own. Each state presets c15t's cookie in the v2 format,
13
+ * which c15t 3 reads as a choice already made.
14
14
  */
15
15
  export function scanStates(config, now = Date.now()) {
16
16
  const optional = config.categories.filter((category) => category !== "necessary");
@@ -25,7 +25,6 @@ export function scanStates(config, now = Date.now()) {
25
25
  `i.t:${now}`,
26
26
  ].join(","),
27
27
  },
28
- { name: POLICY_COOKIE, value: config.policyVersion },
29
28
  ],
30
29
  });
31
30
  const states = [{ id: "no-choice", allowed: ["necessary"], cookies: [] }];
@@ -1,4 +1,4 @@
1
- import type { ConsentManagerOptions, Translations } from "@c15t/react";
1
+ import type { ConsentProviderOptions } from "@c15t/react";
2
2
  import type { Payload } from "payload";
3
3
  import { type Category, defaultTexts } from "./defaults.ts";
4
4
  import { type IntegrationKey } from "./integrations.ts";
@@ -43,15 +43,16 @@ export type ServiceDocument = {
43
43
  host?: string | null;
44
44
  }[] | null;
45
45
  };
46
+ type Messages = NonNullable<NonNullable<ConsentProviderOptions["i18n"]>["messages"]>[string];
46
47
  /** What the banner needs, serializable: pass it from a server component to `ConsentProvider`. */
47
48
  export type ConsentConfig = {
48
49
  enabled: boolean;
49
50
  locale: string;
50
51
  /** Always starts with `necessary`. */
51
52
  categories: Category[];
52
- legalLinks?: NonNullable<ConsentManagerOptions["legalLinks"]>;
53
+ legalLinks?: NonNullable<ConsentProviderOptions["legalLinks"]>;
53
54
  /** c15t's texts for `locale`. */
54
- messages: Partial<Translations>;
55
+ messages: Messages;
55
56
  /** Services the plugin loads through c15t, none before consent. */
56
57
  integrations: {
57
58
  key: IntegrationKey;
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { CATEGORIES, defaultTexts, isFormerSuggestion, OPTIONAL_CATEGORIES, } from "./defaults.js";
3
3
  import { integrationIdProblem, isIntegration } from "./integrations.js";
4
4
  import { consentDays, DEFAULT_CONSENT_MONTHS } from "./renewal.js";
5
- import { CONSENT_GLOBAL, CONSENT_RECORDS, CONSENT_SERVICES, POLICY_COOKIE, } from "./types.js";
5
+ import { CONSENT_GLOBAL, CONSENT_RECORDS, CONSENT_SERVICES, } from "./types.js";
6
6
  const isDoc = (value) => Boolean(value) && typeof value === "object";
7
7
  /** A short hash of what a visitor consents to: the categories and each service's storage. */
8
8
  export function policyVersion(categories, services) {
@@ -218,22 +218,14 @@ export function toCookieTable(doc, services, locale, consentMonths = DEFAULT_CON
218
218
  provider: undefined,
219
219
  purpose: labels.consentPurpose,
220
220
  policyUrl: undefined,
221
- storage: [
222
- ...["cookie", "localStorage"].map((storageType) => ({
223
- name: "c15t",
224
- type: storageType,
225
- duration: consentDuration,
226
- thirdParty: false,
227
- description: undefined,
228
- })),
229
- {
230
- name: POLICY_COOKIE,
231
- type: "cookie",
232
- duration: consentDuration,
233
- thirdParty: false,
234
- description: undefined,
235
- },
236
- ],
221
+ // What c15t stores, for its own use: the choice, the visitor's ID and vendor switches.
222
+ storage: ["c15t", "c15t-sid", "c15t-vendors"].flatMap((name) => ["cookie", "localStorage"].map((storageType) => ({
223
+ name,
224
+ type: storageType,
225
+ duration: consentDuration,
226
+ thirdParty: false,
227
+ description: undefined,
228
+ }))),
237
229
  });
238
230
  return {
239
231
  key,
@@ -187,20 +187,19 @@
187
187
  transition: none;
188
188
  }
189
189
  }
190
- /* Category structure exposed by c15t 2.2.1. */
191
- .sc-categories [data-testid^="consent-widget-accordion-item-"] {
190
+ /* Category structure exposed by c15t 3.2.2. */
191
+ .sc-categories [data-slot="preference-item-root"] {
192
192
  border: 1px solid var(--consent-border, #dededb);
193
193
  border-radius: 8px;
194
194
  overflow: hidden;
195
195
  }
196
- .sc-categories
197
- [data-testid^="consent-widget-accordion-trigger-"]:not([data-testid*="trigger-inner"]) {
196
+ .sc-categories [data-slot="preference-item-root"] > :first-child {
198
197
  display: flex;
199
198
  align-items: center;
200
199
  gap: 12px;
201
200
  padding: 14px;
202
201
  }
203
- .sc-categories [data-testid^="consent-widget-accordion-trigger-inner-"] {
202
+ .sc-categories [data-slot="preference-item-trigger"] {
204
203
  display: flex;
205
204
  align-items: center;
206
205
  flex: 1;
@@ -208,14 +207,20 @@
208
207
  border: 0;
209
208
  background: none;
210
209
  color: inherit;
210
+ font: inherit;
211
211
  padding: 0;
212
212
  text-align: left;
213
+ cursor: pointer;
214
+ }
215
+ .sc-categories [data-slot="preference-item-title"] {
216
+ margin: 0;
217
+ font: inherit;
213
218
  }
214
219
  .sc-categories [data-testid^="consent-widget-accordion-content-"] {
215
220
  color: var(--consent-muted, #606660);
216
221
  font: inherit;
217
222
  }
218
- .sc-categories [data-testid^="consent-widget-accordion-content-"] > * {
223
+ .sc-categories [data-slot="preference-item-content-inner"] {
219
224
  padding: 0 14px 14px;
220
225
  }
221
226
 
package/dist/types.d.ts CHANGED
@@ -80,11 +80,6 @@ export declare const CONSENT_SCAN_EVIDENCE = "consent-scan-evidence";
80
80
  /** The jobs task that runs the monthly scan. */
81
81
  export declare const SCAN_TASK = "consentScan";
82
82
  export declare const SCAN_WIDGET = "consent-scan";
83
- /**
84
- * The cookie with the policy version the visitor last chose under, beside c15t's own: a scanner can
85
- * set cookies before the first page loads, but not localStorage.
86
- */
87
- export declare const POLICY_COOKIE = "c15t-policy";
88
83
  /** Three years, unless the host sets `records.retentionDays`. */
89
84
  export declare const DEFAULT_RETENTION_DAYS: number;
90
85
  export declare const DEFAULT_KEEP_EVIDENCE = 12;
package/dist/types.js CHANGED
@@ -7,11 +7,6 @@ export const CONSENT_SCAN_EVIDENCE = "consent-scan-evidence";
7
7
  /** The jobs task that runs the monthly scan. */
8
8
  export const SCAN_TASK = "consentScan";
9
9
  export const SCAN_WIDGET = "consent-scan";
10
- /**
11
- * The cookie with the policy version the visitor last chose under, beside c15t's own: a scanner can
12
- * set cookies before the first page loads, but not localStorage.
13
- */
14
- export const POLICY_COOKIE = "c15t-policy";
15
10
  /** Three years, unless the host sets `records.retentionDays`. */
16
11
  export const DEFAULT_RETENTION_DAYS = 3 * 365;
17
12
  export const DEFAULT_KEEP_EVIDENCE = 12;
@@ -1,3 +1,4 @@
1
+ import type { ClearOnRevocationConfig } from "@c15t/react";
1
2
  import type { Category } from "./defaults.ts";
2
3
  /** A cookie or localStorage key a service stores on the site itself, in its service's category. */
3
4
  export type StoredItem = {
@@ -5,15 +6,5 @@ export type StoredItem = {
5
6
  type: "cookie" | "localStorage";
6
7
  name: string;
7
8
  };
8
- /** `_ga_*` names a family of cookies by prefix; any other name matches itself. */
9
- export declare function matchesStorageName(pattern: string, name: string): boolean;
10
- /** What the services of the categories the visitor no longer allows stored on this site. */
11
- export declare function withdrawnStorage(storage: StoredItem[], consents: Partial<Record<string, boolean>>): StoredItem[];
12
- /**
13
- * The domains a cookie set on `hostname` may live under: none (the host itself), the host and
14
- * each parent, so `www.kundsajt.se` gives `www.kundsajt.se` and `kundsajt.se`. Analytics cookies
15
- * are usually set on the highest one the browser allows.
16
- */
17
- export declare function cookieDomains(hostname: string): (string | undefined)[];
18
- /** The visitor ID in c15t 2.2.1's cookie, `…,i.sid:sub_…,…`. */
19
- export declare function subjectIdFromCookie(cookie: string): string | undefined;
9
+ /** What c15t deletes when a category is denied: the storage the Cookie services list for it. */
10
+ export declare function clearOnRevocation(storage: StoredItem[]): ClearOnRevocationConfig;
@@ -1,24 +1,11 @@
1
- /** `_ga_*` names a family of cookies by prefix; any other name matches itself. */
2
- export function matchesStorageName(pattern, name) {
3
- return pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern;
4
- }
5
- /** What the services of the categories the visitor no longer allows stored on this site. */
6
- export function withdrawnStorage(storage, consents) {
7
- return storage.filter((item) => item.category !== "necessary" && !consents[item.category]);
8
- }
9
- /**
10
- * The domains a cookie set on `hostname` may live under: none (the host itself), the host and
11
- * each parent, so `www.kundsajt.se` gives `www.kundsajt.se` and `kundsajt.se`. Analytics cookies
12
- * are usually set on the highest one the browser allows.
13
- */
14
- export function cookieDomains(hostname) {
15
- const parts = hostname.split(".");
16
- const domains = [undefined];
17
- for (let index = 0; index < parts.length - 1; index += 1)
18
- domains.push(parts.slice(index).join("."));
19
- return domains;
20
- }
21
- /** The visitor ID in c15t 2.2.1's cookie, `…,i.sid:sub_…,…`. */
22
- export function subjectIdFromCookie(cookie) {
23
- return /(?:^|; )c15t=[^;]*?i\.sid:([^,;]+)/.exec(cookie)?.[1];
1
+ /** What c15t deletes when a category is denied: the storage the Cookie services list for it. */
2
+ export function clearOnRevocation(storage) {
3
+ const config = {};
4
+ for (const { category, type, name } of storage) {
5
+ if (category === "necessary")
6
+ continue;
7
+ config[category] ??= { cookies: [], localStorage: [] };
8
+ config[category][type === "cookie" ? "cookies" : "localStorage"].push(name);
9
+ }
10
+ return config;
24
11
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simmalugnt-se/payload-consent",
3
- "version": "0.6.11",
3
+ "version": "0.7.0",
4
4
  "description": "Cookie consent for Payload sites: banner texts, services and scans in Admin",
5
5
  "keywords": [
6
6
  "payload",
@@ -46,14 +46,14 @@
46
46
  "access": "public"
47
47
  },
48
48
  "peerDependencies": {
49
- "@c15t/react": "2.2.1",
49
+ "@c15t/react": "3.2.2",
50
50
  "@payloadcms/ui": ">=3.90.2 <4",
51
51
  "payload": ">=3.90.2 <4",
52
52
  "react": "^19.0.0",
53
53
  "react-dom": "^19.0.0"
54
54
  },
55
55
  "devDependencies": {
56
- "@c15t/react": "2.2.1",
56
+ "@c15t/react": "3.2.2",
57
57
  "@payloadcms/ui": "3.90.2",
58
58
  "@types/node": "^22",
59
59
  "@types/react": "^19.2.18",
@@ -67,7 +67,7 @@
67
67
  "*.css"
68
68
  ],
69
69
  "dependencies": {
70
- "@c15t/scripts": "2.2.0"
70
+ "@c15t/integrations": "3.2.2"
71
71
  },
72
72
  "scripts": {
73
73
  "build": "rm -rf dist && tsc -p tsconfig.build.json && cp -R src/styles dist/styles",