@simmalugnt-se/payload-consent 0.6.10 → 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,34 @@
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
+
20
+ ## 0.6.11
21
+
22
+ - A scan judges findings by the Cookie services and their categories again, as in 0.6.9. The rules
23
+ added in 0.6.10 are gone: a service in Necessary counts as in order again, whatever it loads, and
24
+ no finding is judged by its kind of request. They were our own reading, not c15t's or the law's.
25
+ - The per-finding instructions and the email's list of them are gone. The Scan tab says per group how
26
+ to handle findings, with c15t's own ways: a known integration, `ConsentFrame`, or `scripts`. The
27
+ email again gives the counts and a link.
28
+ - Add to service starts in Necessary again when the Open Cookie Database has no suggestion.
29
+ - Kept from 0.6.10: unreached pages make a scan incomplete, a finding names a page it was seen on,
30
+ and the README's Google Tag Manager example loads the tag after consent.
31
+
3
32
  ## 0.6.10
4
33
 
5
34
  - A scan says what to do. Each finding that needs handling carries one instruction, in the Scan tab
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
 
@@ -172,12 +171,10 @@ every cookie, localStorage key and third-party host:
172
171
  `_ga_*` rather than one property's `_ga_G123`), and the scan is judged again.
173
172
  - **In order**: explained and seen only where allowed.
174
173
 
175
- A finding that needs handling says what to do, judged from what the scan measured: code or a frame
176
- from another site before any choice must wait for consent, even in a service marked Necessary; a
177
- font or stylesheet from another site belongs on the site's own domain; a plain file with nothing
178
- stored needs its provider checked; storage no service explains goes in one. The email lists the same,
179
- with a page each was seen on. `docs/research/consent-rules.md` in the repository has the rule and its
180
- sources.
174
+ The Scan tab says how to handle each group, using c15t's own ways: a tool in the list under Loaded
175
+ by is picked there, an embed goes in `ConsentFrame`, and other code goes in `scripts`, so c15t loads
176
+ it after consent. The plugin decides nothing about what is necessary: that is the category you give
177
+ the service, by what it does on the site. A finding names a page it was seen on.
181
178
 
182
179
  Findings new since the previous scan are marked. A scan's raw results stay in `consent-scans`.
183
180
 
@@ -269,7 +266,7 @@ The services picked in Admin load on their own. Other c15t integrations go in `s
269
266
 
270
267
  ```tsx
271
268
  'use client'
272
- import { googleTagManager } from '@c15t/scripts/google-tag-manager'
269
+ import { googleTagManager } from '@c15t/integrations/google-tag-manager'
273
270
 
274
271
  <ConsentProvider
275
272
  config={consent}
@@ -301,8 +298,8 @@ import { CookieTable } from '@simmalugnt-se/payload-consent/client'
301
298
  ```
302
299
 
303
300
  It lists the services by category, each with its purpose, policy link and storage, and the
304
- banner's own consent storage first: `c15t`, a cookie and a localStorage key, and the cookie
305
- `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`.
306
303
 
307
304
  The global and the services are public to read by default (`access.read`), since the site shows
308
305
  them to everyone. `access.manage` says who works with cookies in Admin: changing the texts and
@@ -2,7 +2,6 @@
2
2
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
3
  import { Button, Collapsible, Pill, SelectInput, ShimmerEffect, TextInput, useConfig, useFormFields, useLocale, useTranslation, } from "@payloadcms/ui";
4
4
  import { useCallback, useEffect, useRef, useState, } from "react";
5
- import { adviceText } from "../advice.js";
6
5
  import { CATEGORIES } from "../defaults.js";
7
6
  import { CONSENT_SCANS } from "../types.js";
8
7
  import { describeProblem, estimateLeft, findingHeading, finishedPages, formatElapsed, markPace, pagePath, scanVerdict, } from "./scan-view.js";
@@ -86,8 +85,8 @@ const COPY = {
86
85
  ok: "In order",
87
86
  },
88
87
  explain: {
89
- action: "Loads before or without consent. Each one says what to do.",
90
- unknown: "Add each to a service, new or existing, or remove it from the site.",
88
+ action: "Seen where their category is not allowed. A tool in the list under Loaded by: pick “This plugin, after consent” on the service. An embed: wrap it in ConsentFrame. Other code: pass it to ConsentProvider's scripts, so c15t loads it after consent.",
89
+ unknown: "Add each to a service: Necessary if the site cannot work without it, otherwise the category that fits. Or remove it from the site.",
91
90
  ok: "In a Cookie service, and seen only where its category is allowed.",
92
91
  },
93
92
  // What the finding is, leading the sentence of when it was seen.
@@ -205,8 +204,8 @@ const COPY = {
205
204
  ok: "I ordning",
206
205
  },
207
206
  explain: {
208
- action: "Laddas före eller utan samtycke. Varje rad säger vad du ska göra.",
209
- unknown: "Lägg till var och en i en tjänst, ny eller befintlig, eller ta bort den från webbplatsen.",
207
+ action: "Syns där kategorin inte är tillåten. Ett verktyg i listan under Laddas av: välj ”Det här pluginet, efter samtycke” i tjänsten. En inbäddning: lägg den i ConsentFrame. Annan kod: skicka den till ConsentProviders scripts, så laddar c15t den efter samtycke.",
208
+ unknown: "Lägg var och en i en tjänst: Nödvändig om webbplatsen inte fungerar utan den, annars den kategori som passar. Eller ta bort den från webbplatsen.",
210
209
  ok: "Finns i en Cookietjänst och syns bara där kategorin är tillåten.",
211
210
  },
212
211
  seen: {
@@ -491,8 +490,8 @@ export function ScanPanel() {
491
490
  function FindingRow({ api, copy, finding, language, locale, onAdded, }) {
492
491
  const suggestion = finding.suggestion;
493
492
  const [service, setService] = useState(suggestion?.platform ?? (finding.kind === "host" ? finding.name : ""));
494
- // What must wait for consent starts in a category that does, not in Necessary.
495
- const [category, setCategory] = useState(suggestion?.category ?? (finding.advice === "waitForConsent" ? "functionality" : "necessary"));
493
+ // Without a suggestion nothing is preselected: one click must not make a tracker Necessary.
494
+ const [category, setCategory] = useState(suggestion?.category);
496
495
  const [busy, setBusy] = useState(false);
497
496
  const [error, setError] = useState();
498
497
  async function add() {
@@ -547,16 +546,16 @@ function FindingRow({ api, copy, finding, language, locale, onAdded, }) {
547
546
  const without = serviceCategory ? finding.withoutConsent : [];
548
547
  const rest = finding.states.filter((id) => !without.includes(id));
549
548
  const path = `consent-scan-${finding.key}`;
550
- return (_jsxs("li", { className: "consent-scan__row", children: [_jsxs("div", { className: "consent-scan__row-head", children: [_jsx("h4", { className: "consent-scan__name", children: heading.from === "name" ? (_jsx("code", { children: heading.text })) : heading.from === "suggestion" ? (copy.looksLike(heading.text)) : (heading.text) }), (finding.beforeConsent && finding.status !== "ok") || finding.isNew ? (_jsxs("div", { className: "consent-scan__pills", children: [finding.beforeConsent && finding.status !== "ok" ? (_jsx(Pill, { pillStyle: "error", size: "small", children: copy.beforeConsent })) : null, finding.isNew ? (_jsx(Pill, { pillStyle: "light", size: "small", children: copy.isNew })) : null] })) : null] }), _jsx("p", { className: "consent-scan__seen", children: without.length ? (_jsxs(_Fragment, { children: [`${copy.seen[finding.kind]} ${whenLabel(copy, without, language)}`, _jsx("strong", { children: copy.notAllowed(serviceCategory) }), ".", rest.length ? ` ${copy.also(whenLabel(copy, rest, language))}` : null] })) : (`${copy.seen[finding.kind]} ${whenLabel(copy, finding.states, language)}.`) }), finding.advice && finding.status !== "ok" ? (_jsx("p", { className: "consent-scan__advice", children: adviceText(finding.advice, language) })) : null, suggestion?.description && heading.from === "suggestion" ? (_jsx("p", { className: "consent-scan__note", children: suggestion.description })) : null, details.length ? (_jsx("p", { className: "consent-scan__details", children: details.map((detail, index) => (_jsx("span", { children: detail }, typeof detail === "string" ? detail : index))) })) : null, finding.status === "unknown" ? (_jsxs("div", { className: "consent-scan__classify", children: [_jsx(TextInput, { label: copy.service, onChange: (event) => setService(event.target.value), onKeyDown: (event) => {
549
+ return (_jsxs("li", { className: "consent-scan__row", children: [_jsxs("div", { className: "consent-scan__row-head", children: [_jsx("h4", { className: "consent-scan__name", children: heading.from === "name" ? (_jsx("code", { children: heading.text })) : heading.from === "suggestion" ? (copy.looksLike(heading.text)) : (heading.text) }), (finding.beforeConsent && finding.status !== "ok") || finding.isNew ? (_jsxs("div", { className: "consent-scan__pills", children: [finding.beforeConsent && finding.status !== "ok" ? (_jsx(Pill, { pillStyle: "error", size: "small", children: copy.beforeConsent })) : null, finding.isNew ? (_jsx(Pill, { pillStyle: "light", size: "small", children: copy.isNew })) : null] })) : null] }), _jsx("p", { className: "consent-scan__seen", children: without.length ? (_jsxs(_Fragment, { children: [`${copy.seen[finding.kind]} ${whenLabel(copy, without, language)}`, _jsx("strong", { children: copy.notAllowed(serviceCategory) }), ".", rest.length ? ` ${copy.also(whenLabel(copy, rest, language))}` : null] })) : (`${copy.seen[finding.kind]} ${whenLabel(copy, finding.states, language)}.`) }), suggestion?.description && heading.from === "suggestion" ? (_jsx("p", { className: "consent-scan__note", children: suggestion.description })) : null, details.length ? (_jsx("p", { className: "consent-scan__details", children: details.map((detail, index) => (_jsx("span", { children: detail }, typeof detail === "string" ? detail : index))) })) : null, finding.status === "unknown" ? (_jsxs("div", { className: "consent-scan__classify", children: [_jsx(TextInput, { label: copy.service, onChange: (event) => setService(event.target.value), onKeyDown: (event) => {
551
550
  // Enter adds the finding; it would otherwise submit the Cookies form around the tab.
552
551
  if (event.key !== "Enter")
553
552
  return;
554
553
  event.preventDefault();
555
- if (!busy && service.trim())
554
+ if (!busy && service.trim() && category)
556
555
  add();
557
556
  }, path: `${path}-service`, readOnly: busy, value: service }), _jsx(SelectInput, { isClearable: false, label: copy.category, name: `${path}-category`, onChange: (selected) => {
558
557
  const option = Array.isArray(selected) ? selected[0] : selected;
559
558
  if (option && typeof option === "object" && "value" in option)
560
559
  setCategory(option.value);
561
- }, 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] }));
562
561
  }
@@ -1,4 +1,3 @@
1
- import { type Advice } from "./advice.ts";
2
1
  import type { Category } from "./defaults.ts";
3
2
  import type { ServiceDocument } from "./site-config.ts";
4
3
  /** A consent state the scanner runs, and the categories the visitor allowed in it. */
@@ -88,10 +87,6 @@ export type Finding = {
88
87
  suggestion?: Suggestion;
89
88
  /** For hosts: the tracker lists that flagged it (EasyPrivacy and others). */
90
89
  trackerLists?: string[];
91
- /** For hosts: requests by kind in the states with only necessary storage, to judge by. */
92
- kinds?: Record<string, number>;
93
- /** What to do about it. */
94
- advice?: Advice;
95
90
  };
96
91
  export type ScanSummary = Record<FindingStatus, number> & {
97
92
  new: number;
package/dist/evaluate.js CHANGED
@@ -1,4 +1,3 @@
1
- import { hostAdvice } from "./advice.js";
2
1
  /**
3
2
  * Why a finished scan may not show everything: a state the scanner did not return or that
4
3
  * visited no pages, its errors, and sitemaps it could not read. Empty when the scan is complete.
@@ -25,7 +24,7 @@ export function scanProblems(args) {
25
24
  return problems.slice(0, 20).map((problem) => problem.slice(0, 300));
26
25
  }
27
26
  /** The banner's own storage; always necessary. */
28
- const OWN_STORAGE = /^c15t(-policy|-storage-test-key)?$/;
27
+ const OWN_STORAGE = /^c15t(-sid|-vendors|-policy|-storage-test-key)?$/;
29
28
  /** `_ga_*` matches `_ga_ABC`; anything else must be equal. */
30
29
  export function matchesName(pattern, name) {
31
30
  return pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : pattern === name;
@@ -99,12 +98,6 @@ export function evaluateScan({ states, results, services, previousKeys = [], })
99
98
  trackerLists: lists.get(host.host),
100
99
  page: host.pages?.[0],
101
100
  });
102
- const finding = found.get(`host::${host.host}`);
103
- if (finding && host.kinds && necessaryOnly.has(state.id)) {
104
- finding.kinds ??= {};
105
- for (const [kind, count] of Object.entries(host.kinds))
106
- finding.kinds[kind] = (finding.kinds[kind] ?? 0) + count;
107
- }
108
101
  }
109
102
  }
110
103
  for (const finding of found.values()) {
@@ -123,38 +116,6 @@ export function evaluateScan({ states, results, services, previousKeys = [], })
123
116
  finding.withoutConsent = finding.states.filter((stateId) => category !== "necessary" && !allowedIn.get(stateId)?.has(category));
124
117
  finding.status = finding.withoutConsent.length ? "action" : "ok";
125
118
  }
126
- for (const finding of found.values()) {
127
- if (finding.service === "c15t")
128
- continue;
129
- if (finding.kind === "host") {
130
- if (!finding.beforeConsent) {
131
- if (finding.status === "action")
132
- finding.advice = "waitForConsent";
133
- continue;
134
- }
135
- finding.advice = hostAdvice(finding.kinds, Boolean(finding.trackerLists?.length));
136
- // A service marked necessary does not excuse code from another site before any choice.
137
- if (finding.status !== "unknown" && finding.advice !== "checkProvider" && finding.advice)
138
- finding.status = "action";
139
- // A category seen where it is not allowed must wait, whatever kind of request it is.
140
- if (finding.status === "action" && finding.withoutConsent.length)
141
- finding.advice = "waitForConsent";
142
- if (finding.status === "action")
143
- finding.advice ??= "waitForConsent";
144
- }
145
- else if (finding.status === "action") {
146
- finding.advice = "waitForConsent";
147
- }
148
- else if (finding.status === "unknown" && finding.beforeConsent) {
149
- finding.advice = "classifyStorage";
150
- }
151
- else if (finding.category === "necessary" &&
152
- finding.suggestion?.category &&
153
- finding.suggestion.category !== "necessary") {
154
- finding.status = "action";
155
- finding.advice = "reviewNecessary";
156
- }
157
- }
158
119
  const order = { action: 0, unknown: 1, ok: 2 };
159
120
  const findings = [...found.values()].sort((a, b) => order[a.status] - order[b.status] ||
160
121
  Number(b.beforeConsent) - Number(a.beforeConsent) ||
@@ -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/notify.d.ts CHANGED
@@ -1,18 +1,10 @@
1
1
  import type { Payload } from "payload";
2
- import type { Finding, ScanSummary } from "./evaluate.ts";
3
- type Language = "en" | "sv";
2
+ import type { ScanSummary } from "./evaluate.ts";
4
3
  export type ScanOutcome = {
5
4
  url: string;
6
5
  status: "done" | "failed";
7
6
  error?: string | null;
8
7
  summary?: ScanSummary | null;
9
- /** What the scan found; the email lists what needs handling and how. */
10
- findings?: Finding[] | null;
11
- };
12
- /** `name (page): what to do`, for each finding with advice that is not in order. */
13
- export declare function listedActions(findings: Finding[] | null | undefined, language: Language): {
14
- lines: string[];
15
- more: number;
16
8
  };
17
9
  /**
18
10
  * A scan worth an email: it failed, could not see everything, found something to handle, or found
@@ -24,4 +16,3 @@ export declare function needsNotice(outcome: ScanOutcome): boolean;
24
16
  * email adapter, when it needs a look. Admin's default language picks the text.
25
17
  */
26
18
  export declare function notifyScan(payload: Payload, outcome: ScanOutcome): Promise<void>;
27
- export {};
package/dist/notify.js CHANGED
@@ -1,27 +1,4 @@
1
- import { adviceText } from "./advice.js";
2
1
  import { CONSENT_GLOBAL } from "./types.js";
3
- /** The most an email lists: the Scan tab has the rest. */
4
- const MAX_LISTED = 10;
5
- /** `name (page): what to do`, for each finding with advice that is not in order. */
6
- export function listedActions(findings, language) {
7
- const open = (findings ?? []).filter((finding) => finding.advice && finding.status !== "ok");
8
- const page = (url) => {
9
- if (!url)
10
- return "";
11
- try {
12
- return ` (${new URL(url).pathname})`;
13
- }
14
- catch {
15
- return "";
16
- }
17
- };
18
- return {
19
- lines: open
20
- .slice(0, MAX_LISTED)
21
- .map((finding) => `${finding.name}${page(finding.page)}: ${adviceText(finding.advice, language)}`),
22
- more: Math.max(0, open.length - MAX_LISTED),
23
- };
24
- }
25
2
  /**
26
3
  * A scan worth an email: it failed, could not see everything, found something to handle, or found
27
4
  * something new.
@@ -42,7 +19,6 @@ const COPY = {
42
19
  done: (o) => `The cookie scan of ${o.url} found ${count(o.summary, "en")}.${problems(o).length
43
20
  ? ` It is incomplete, so it may have missed something: ${problems(o).slice(0, 3).join("; ")}.`
44
21
  : ""}`,
45
- more: (n) => `And ${n} more in the Scan tab.`,
46
22
  open: "Open Cookies in Admin",
47
23
  why: "You get this because you are chosen under Cookies → Scan.",
48
24
  },
@@ -54,7 +30,6 @@ const COPY = {
54
30
  done: (o) => `Cookieskanningen av ${o.url} hittade ${count(o.summary, "sv")}.${problems(o).length
55
31
  ? ` Den är ofullständig och kan ha missat något: ${problems(o).slice(0, 3).join("; ")}.`
56
32
  : ""}`,
57
- more: (n) => `Och ${n} till under fliken Skanning.`,
58
33
  open: "Öppna Cookies i Admin",
59
34
  why: "Du får det här för att du är vald under Cookies → Skanning.",
60
35
  },
@@ -112,8 +87,6 @@ export async function notifyScan(payload, outcome) {
112
87
  }
113
88
  })();
114
89
  const text = outcome.status === "failed" ? copy.failed(outcome) : copy.done(outcome);
115
- const { lines, more } = listedActions(outcome.findings, language);
116
- const andMore = more ? copy.more(more) : "";
117
90
  // Admin is on the scanned site's origin when Payload has no serverURL.
118
91
  const base = payload.config.serverURL || origin(outcome.url);
119
92
  const link = `${base}${payload.config.routes.admin}/globals/${CONSENT_GLOBAL}`;
@@ -121,8 +94,8 @@ export async function notifyScan(payload, outcome) {
121
94
  await payload.sendEmail({
122
95
  to,
123
96
  subject: copy.subject(outcome, host),
124
- text: `${text}\n\n${lines.map((line) => `- ${line}`).join("\n")}${andMore ? `\n${andMore}` : ""}${lines.length ? "\n\n" : ""}${copy.open}: ${link}\n\n${copy.why}`,
125
- html: `<p>${escape(text)}</p>${lines.length ? `<ul>${lines.map((line) => `<li>${escape(line)}</li>`).join("")}</ul>` : ""}${andMore ? `<p>${escape(andMore)}</p>` : ""}<p><a href="${escape(link)}">${copy.open}</a></p><p><small>${copy.why}</small></p>`,
97
+ text: `${text}\n\n${copy.open}: ${link}\n\n${copy.why}`,
98
+ html: `<p>${escape(text)}</p><p><a href="${escape(link)}">${copy.open}</a></p><p><small>${copy.why}</small></p>`,
126
99
  });
127
100
  }
128
101
  catch (error) {
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: [] }];
@@ -342,7 +341,6 @@ function endpoints(options) {
342
341
  status: done ? "done" : "failed",
343
342
  error: done ? null : (result.error ?? "The scan failed"),
344
343
  summary: (summary ?? undefined),
345
- findings: evaluated?.findings,
346
344
  });
347
345
  return Response.json({ ok: true });
348
346
  },
@@ -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,
@@ -138,10 +138,6 @@
138
138
  color: var(--theme-elevation-800);
139
139
  word-break: break-all;
140
140
  }
141
- .consent-scan__advice {
142
- margin: 0;
143
- font-weight: 500;
144
- }
145
141
  .consent-scan__note {
146
142
  margin: 0;
147
143
  color: var(--theme-elevation-500);
@@ -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.10",
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",
package/dist/advice.d.ts DELETED
@@ -1,24 +0,0 @@
1
- /**
2
- * What to do about a finding, from what a scan measured. The rule behind it and its sources are in
3
- * `docs/research/consent-rules.md` in the repository.
4
- */
5
- export type Advice =
6
- /** Third-party code, a frame, a tracking pixel, or a category seen where it is not allowed. */
7
- "waitForConsent"
8
- /** A font or stylesheet from another site gives that site the visitor's IP address. */
9
- | "selfHost"
10
- /** A plain file from another site, with nothing stored: fine if the provider only delivers it. */
11
- | "checkProvider"
12
- /** Storage no service explains. */
13
- | "classifyStorage"
14
- /** Registered as necessary, but the Open Cookie Database puts it in another category. */
15
- | "reviewNecessary";
16
- type Language = "en" | "sv";
17
- export declare function adviceText(advice: Advice, language: Language): string;
18
- /**
19
- * What a host's requests before consent call for. No kinds at all means the scanner saw the host
20
- * only inside a frame, so it is treated as code; `undefined` kinds come from an older scanner, which
21
- * did not report them.
22
- */
23
- export declare function hostAdvice(kinds: Record<string, number> | undefined, onTrackerList: boolean): Advice | undefined;
24
- export {};
package/dist/advice.js DELETED
@@ -1,37 +0,0 @@
1
- const TEXTS = {
2
- en: {
3
- waitForConsent: "Must wait for consent. Put it in the category that fits. If a c15t integration loads it, pick that integration on the service; if your code loads it, wrap it in ConsentFrame.",
4
- selfHost: "Serve it from the site's own domain, for example fonts with next/font, so the visitor's IP address does not go to another site.",
5
- checkProvider: "Only a file, and nothing is stored, so it can load before consent if the provider just delivers it for the site. Add the provider to a service and check its terms.",
6
- classifyStorage: "Add it to a service. Unless the site cannot work without it for something the visitor asked for, it must wait for consent.",
7
- reviewNecessary: "Registered as necessary, but the Open Cookie Database says otherwise. Move it to the category that fits and make it wait for consent, or remove the service from Necessary only if the site cannot work without it.",
8
- },
9
- sv: {
10
- waitForConsent: "Måste vänta på samtycke. Lägg den i rätt kategori. Laddas den av en c15t-integration, välj integrationen i tjänsten. Laddas den av din kod, lägg den i ConsentFrame.",
11
- selfHost: "Lägg filen på webbplatsens egen domän, till exempel typsnitt med next/font, så att besökarens IP-adress inte går till en annan webbplats.",
12
- checkProvider: "Bara en fil, och inget lagras, så den får laddas före samtycke om leverantören enbart levererar den åt webbplatsen. Lägg leverantören i en tjänst och kontrollera dess villkor.",
13
- classifyStorage: "Lägg den i en tjänst. Om inte webbplatsen behöver den för något besökaren har bett om måste den vänta på samtycke.",
14
- reviewNecessary: "Står som nödvändig, men Open Cookie Database säger något annat. Flytta den till rätt kategori och låt den vänta på samtycke, eller behåll den bara om webbplatsen inte fungerar utan den.",
15
- },
16
- };
17
- export function adviceText(advice, language) {
18
- return TEXTS[language][advice];
19
- }
20
- /** Request kinds that only deliver a file: they run no code on the visitor's device. */
21
- const PASSIVE = new Set(["image", "media", "manifest", "other"]);
22
- const STYLING = new Set(["font", "stylesheet"]);
23
- /**
24
- * What a host's requests before consent call for. No kinds at all means the scanner saw the host
25
- * only inside a frame, so it is treated as code; `undefined` kinds come from an older scanner, which
26
- * did not report them.
27
- */
28
- export function hostAdvice(kinds, onTrackerList) {
29
- if (!kinds)
30
- return undefined;
31
- const seen = Object.keys(kinds);
32
- if (!seen.length || onTrackerList)
33
- return "waitForConsent";
34
- if (seen.some((kind) => !PASSIVE.has(kind) && !STYLING.has(kind)))
35
- return "waitForConsent";
36
- return seen.some((kind) => STYLING.has(kind)) ? "selfHost" : "checkProvider";
37
- }