@simmalugnt-se/payload-consent 0.2.0 → 0.3.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,37 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0
4
+
5
+ Defaults and behaviour reviewed against the EDPB's guidelines and PTS's cookie decisions; the
6
+ findings are in `docs/research/consent-legal-questions.md`.
7
+
8
+ - **Breaking:** Google Consent Mode's advanced mode is gone, with the `googleConsentMode` field:
9
+ its pings before consent and after a refusal need consent too. Every integration waits for
10
+ consent. Generate types and migrate.
11
+ - **Breaking:** a site with only necessary storage shows no banner and records no choice, and the
12
+ banner description for such sites (`bannerDescriptionNecessaryOnly`) is gone. The settings link
13
+ still opens the dialog.
14
+ - **Breaking:** `ConsentFrame` takes a `provider`, which the placeholder names: "Innehållet visas
15
+ från {provider}. Om du tillåter {category} får {provider} uppgifter om ditt besök …".
16
+ - A choice expires after twelve months (`consentMonths`). c15t restored its expired cookie from
17
+ localStorage, so a choice never expired and one without the policy cookie skipped the policy
18
+ check; the plugin now forgets such a choice before c15t reads it.
19
+ - The banner names the site's optional categories (`{categories}` in its description) and says the
20
+ choice can be changed or withdrawn at any time; the dialog says withdraw too, and lists each
21
+ category's services and providers.
22
+ - Category descriptions say what happens instead of "improves your experience", and the cookie
23
+ table says the consent cookie holds a random ID linked to the consent log.
24
+ - A saved text equal to an earlier version's suggestion shows the current suggestion.
25
+ - Escape closes the settings dialog, as a click outside it does: unsaved switches are discarded
26
+ and, before a choice, the banner comes back. c15t's dialog ignored Escape.
27
+
28
+ ## 0.2.1
29
+
30
+ - Withdrawing a category removes the cookies and localStorage keys its Cookie services list on the
31
+ site, such as `_ga` and `_ga_*`, before and once more after c15t reloads the page. Third-party
32
+ storage cannot be reached from the site and stays.
33
+ - A choice is posted to the consent log once per page load: a withdrawal no longer posts it twice.
34
+
3
35
  ## 0.2.0
4
36
 
5
37
  - Cookies is the one entry in Admin: a Services tab lists the Cookie services with links to edit
package/README.md CHANGED
@@ -37,14 +37,20 @@ Five tabs: Banner, Services, Scan, Consent log and Settings.
37
37
 
38
38
  - **Banner**: title, description, buttons, the settings dialog and a title and description per
39
39
  category. Every text is localized and prefilled with a suggestion in the language being edited
40
- (Swedish or English; other languages get English). The description and the accept button have
41
- one version for sites with optional categories and one for sites with only necessary storage;
42
- Admin shows the one that applies. The placeholder for embedded content has its own text and
43
- button.
40
+ (Swedish or English; other languages get English). In the banner's description `{categories}`
41
+ becomes the site's optional categories ("statistik och marknadsföring"); the settings dialog
42
+ lists each category's services and providers after its description. The placeholder for
43
+ embedded content has its own text and button.
44
44
  - **Settings**: whether the banner is shown, the optional categories (read-only: they follow the
45
- services), Google Consent Mode and, with `legalPages`, the policy pages.
45
+ services) and, with `legalPages`, the policy pages.
46
46
 
47
- Texts are optional: an empty one shows the suggestion for the visitor's language.
47
+ Texts are optional: an empty one shows the suggestion for the visitor's language. A saved text equal
48
+ to an earlier version's suggestion was never edited, and shows the current suggestion, in Admin
49
+ and on the site.
50
+
51
+ A site whose services are all necessary shows no banner: there is nothing to consent to. The
52
+ settings link still opens the dialog, which says the site only uses necessary storage, and the
53
+ cookie page lists that storage.
48
54
 
49
55
  ## Cookie services
50
56
 
@@ -58,12 +64,25 @@ LinkedIn Insight Tag, TikTok Pixel, Microsoft Ads (UET), Microsoft Clarity and H
58
64
  picks the integration and enters its ID; the script then loads in the service's category, after
59
65
  consent.
60
66
 
61
- **Google Consent Mode**: basic, the default, loads nothing before consent. Advanced lets the tags
62
- c15t supports load at once in a denied state, which sends cookieless measurements to the provider
63
- before the visitor has chosen. Pick it only when that has been assessed as acceptable.
67
+ **Google Consent Mode** is basic: nothing loads before consent, and Google's tags then get the
68
+ matching consent signals. Advanced mode, where the tags load at once and send cookieless pings
69
+ before and after a refusal, is not offered: under the EDPB's Guidelines 2/2023 those requests need
70
+ consent too.
64
71
 
65
72
  The rules that keep the banner lawful are not settings: rejecting is always as easy as accepting,
66
- and the banner and dialog work with a keyboard and a screen reader.
73
+ and the banner and dialog work with a keyboard and a screen reader. A site's own colours
74
+ (`--consent-*`) must keep it so: both buttons equally prominent.
75
+
76
+ A service's purpose is what the cookie page shows: say what the service does and what data it
77
+ collects (pages visited, the IP address, an identifier), not only why the site uses it.
78
+
79
+ ### How long a choice lasts
80
+
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.
67
86
 
68
87
  ## Consent records
69
88
 
@@ -72,7 +91,18 @@ Every choice a visitor saves is posted to `/api/consent-records/record` and kept
72
91
  version, the language and the page. No IP address or browser details. The first choice under each
73
92
  policy version and language also saves what the visitor was shown in `consent-policies`:
74
93
  categories, services and texts. Records are kept for three years (`records.retentionDays`) and
75
- readable by signed-in users only; `records: false` turns the log off.
94
+ readable by signed-in users only; `records: false` turns the log off. A site with only necessary
95
+ storage records nothing: there is no consent to show.
96
+
97
+ The random ID links a record to a visitor's browser, so the log is personal data. The site's
98
+ privacy policy should say so: the log exists to show that consent was given (GDPR art. 7(1)), its
99
+ legal basis is a legal obligation (art. 6(1)(c)), and records are deleted after the retention
100
+ period. Three years is a judgement, not a rule; `docs/research/consent-legal-questions.md` in the
101
+ repository has the reasoning.
102
+
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_*`.
76
106
 
77
107
  The policy version is a hash of the categories and each service's cookies and storage keys. When
78
108
  it changes, for example because a service gains a cookie, visitors are asked again. Rewording a
@@ -207,12 +237,13 @@ import { googleTagManager } from '@c15t/scripts/google-tag-manager'
207
237
  ```
208
238
 
209
239
  Embedded content, such as a video or a map, waits behind a placeholder until the visitor allows
210
- its category:
240
+ its category. The placeholder names the provider, who receives data about the visit once the
241
+ content loads:
211
242
 
212
243
  ```tsx
213
244
  import { ConsentFrame } from '@simmalugnt-se/payload-consent/client'
214
245
 
215
- <ConsentFrame category="functionality">
246
+ <ConsentFrame category="functionality" provider="YouTube">
216
247
  <iframe src="https://www.youtube-nocookie.com/embed/…" title="…" />
217
248
  </ConsentFrame>
218
249
  ```
@@ -230,7 +261,7 @@ import { CookieTable } from '@simmalugnt-se/payload-consent/client'
230
261
 
231
262
  It lists the services by category, each with its purpose, policy link and storage, and the
232
263
  banner's own consent storage first: `c15t`, a cookie and a localStorage key, and the cookie
233
- `c15t-policy` with the policy version the visitor chose under, all kept for a year.
264
+ `c15t-policy` with the policy version the visitor chose under, all kept for `consentMonths`.
234
265
 
235
266
  The global and the services are public to read by default (`access.read`), since the site shows
236
267
  them to everyone. `overrideGlobal` and `overrideServices` change them, for example to add hooks
@@ -8,10 +8,8 @@ export type Category = "necessary" | OptionalCategory;
8
8
  export declare const CATEGORIES: readonly Category[];
9
9
  export type ConsentTexts = {
10
10
  bannerTitle: string;
11
- /** When visitors can choose optional categories. */
11
+ /** `{categories}` becomes the site's optional categories, such as "statistik och marknadsföring". */
12
12
  bannerDescription: string;
13
- /** When the site only uses necessary storage. */
14
- bannerDescriptionNecessaryOnly: string;
15
13
  buttons: {
16
14
  acceptAll: string;
17
15
  /** The only button besides Settings when the site only uses necessary storage. */
@@ -30,6 +28,7 @@ export type ConsentTexts = {
30
28
  title: string;
31
29
  description: string;
32
30
  }>;
31
+ /** `{provider}` becomes the embed's provider and `{category}` its category's title. */
33
32
  embeds: {
34
33
  title: string;
35
34
  button: string;
@@ -48,9 +47,15 @@ export type ConsentTexts = {
48
47
  policy: string;
49
48
  consentService: string;
50
49
  consentPurpose: string;
50
+ /** The lifetime of the plugin's own consent storage: one year, or `{months}` months. */
51
51
  consentDuration: string;
52
+ consentDurationMonths: string;
52
53
  noServices: string;
54
+ /** After a category's description in the settings dialog; `{services}` lists them. */
55
+ services: string;
53
56
  };
54
57
  };
55
58
  /** The suggested texts for a locale code such as `sv` or `sv-SE`; English when there are none. */
56
59
  export declare function defaultTexts(locale: string | null | undefined): ConsentTexts;
60
+ /** Whether a saved text is a suggestion from an earlier version, never edited. */
61
+ export declare function isFormerSuggestion(value: unknown): boolean;
package/dist/defaults.js CHANGED
@@ -11,8 +11,7 @@ export const OPTIONAL_CATEGORIES = [
11
11
  export const CATEGORIES = ["necessary", ...OPTIONAL_CATEGORIES];
12
12
  const sv = {
13
13
  bannerTitle: "Vi använder cookies",
14
- bannerDescription: "Vi använder nödvändig lagring för att webbplatsen ska fungera. Du väljer om du också vill tillåta andra kategorier.",
15
- bannerDescriptionNecessaryOnly: "Vi använder endast nödvändig lagring för att webbplatsen ska fungera och komma ihåg dina cookieinställningar.",
14
+ bannerDescription: "Vi använder nödvändig lagring för att webbplatsen ska fungera. Med ditt samtycke använder vi också {categories}. Du kan ändra eller ta tillbaka ditt val när som helst under Cookieinställningar längst ned på sidan.",
16
15
  buttons: {
17
16
  acceptAll: "Tillåt alla",
18
17
  acceptNecessaryOnly: "Okej",
@@ -23,7 +22,7 @@ const sv = {
23
22
  },
24
23
  dialog: {
25
24
  title: "Cookieinställningar",
26
- description: "Du kan välja vilka kategorier du tillåter och ändra ditt val när som helst.",
25
+ description: "Välj vilka kategorier du tillåter. Du kan ändra eller ta tillbaka ditt val när som helst.",
27
26
  descriptionNecessaryOnly: "Webbplatsen använder endast nödvändig lagring.",
28
27
  },
29
28
  categoryTexts: {
@@ -33,23 +32,23 @@ const sv = {
33
32
  },
34
33
  functionality: {
35
34
  title: "Funktionalitet",
36
- description: "Tillåter valfria funktioner från externa tjänster.",
35
+ description: "Visar innehåll och funktioner från externa tjänster, till exempel video eller kartor. Tjänsten får då uppgifter om ditt besök och kan spara cookies.",
37
36
  },
38
37
  experience: {
39
38
  title: "Upplevelse",
40
- description: "Tillåter anpassningar som förbättrar hur webbplatsen fungerar för dig.",
39
+ description: "Sparar dina val på webbplatsen, till exempel inställningar du gör, så att de finns kvar nästa gång.",
41
40
  },
42
41
  measurement: {
43
42
  title: "Statistik",
44
- description: "Tillåter mätning av hur webbplatsen används.",
43
+ description: "Mäter hur webbplatsen används, till exempel vilka sidor som besöks, så att vi kan förbättra den.",
45
44
  },
46
45
  marketing: {
47
46
  title: "Marknadsföring",
48
- description: "Tillåter mätning och innehåll för marknadsföring.",
47
+ description: "Låter annonstjänster mäta ditt besök för att följa upp och anpassa annonser, även på andra webbplatser.",
49
48
  },
50
49
  },
51
50
  embeds: {
52
- title: "Innehållet kräver att du tillåter {category}.",
51
+ title: "Innehållet visas från {provider}. Om du tillåter {category} får {provider} uppgifter om ditt besök och kan spara cookies.",
53
52
  button: "Tillåt {category}",
54
53
  },
55
54
  table: {
@@ -64,15 +63,16 @@ const sv = {
64
63
  no: "Nej",
65
64
  policy: "Leverantörens integritetspolicy",
66
65
  consentService: "Cookieinställningar",
67
- consentPurpose: "Sparar ditt val i cookiebannern.",
66
+ consentPurpose: "Sparar ditt val i cookiebannern och ett slumpat id som kopplar valet till webbplatsens logg över samtycken.",
68
67
  consentDuration: "1 år",
68
+ consentDurationMonths: "{months} månader",
69
69
  noServices: "Inga tjänster i den här kategorin.",
70
+ services: "Tjänster: {services}.",
70
71
  },
71
72
  };
72
73
  const en = {
73
74
  bannerTitle: "We use cookies",
74
- bannerDescription: "We use necessary storage for the website to work. You choose whether to allow other categories.",
75
- bannerDescriptionNecessaryOnly: "We only use necessary storage for the website to work and to remember your cookie settings.",
75
+ bannerDescription: "We use necessary storage for the website to work. With your consent we also use {categories}. You can change or withdraw your choice at any time in Cookie settings at the bottom of the page.",
76
76
  buttons: {
77
77
  acceptAll: "Allow all",
78
78
  acceptNecessaryOnly: "Okay",
@@ -83,7 +83,7 @@ const en = {
83
83
  },
84
84
  dialog: {
85
85
  title: "Cookie settings",
86
- description: "Choose which categories to allow. You can change your choice at any time.",
86
+ description: "Choose which categories to allow. You can change or withdraw your choice at any time.",
87
87
  descriptionNecessaryOnly: "The website only uses necessary storage.",
88
88
  },
89
89
  categoryTexts: {
@@ -93,23 +93,23 @@ const en = {
93
93
  },
94
94
  functionality: {
95
95
  title: "Functionality",
96
- description: "Allows optional functions provided by external services.",
96
+ description: "Shows content and features from external services, such as video or maps. The service then receives information about your visit and may store cookies.",
97
97
  },
98
98
  experience: {
99
99
  title: "Experience",
100
- description: "Allows preferences that improve how the website works for you.",
100
+ description: "Remembers choices you make on the website, such as your settings, for your next visit.",
101
101
  },
102
102
  measurement: {
103
103
  title: "Statistics",
104
- description: "Allows measurement of how the website is used.",
104
+ description: "Measures how the website is used, such as which pages are visited, so we can improve it.",
105
105
  },
106
106
  marketing: {
107
107
  title: "Marketing",
108
- description: "Allows measurement and content used for marketing.",
108
+ description: "Lets advertising services measure your visit to follow up and tailor ads, also on other websites.",
109
109
  },
110
110
  },
111
111
  embeds: {
112
- title: "This content needs you to allow {category}.",
112
+ title: "This content is shown from {provider}. If you allow {category}, {provider} receives information about your visit and may store cookies.",
113
113
  button: "Allow {category}",
114
114
  },
115
115
  table: {
@@ -124,9 +124,11 @@ const en = {
124
124
  no: "No",
125
125
  policy: "Provider's privacy policy",
126
126
  consentService: "Cookie settings",
127
- consentPurpose: "Remembers your choice in the cookie banner.",
127
+ consentPurpose: "Remembers your choice in the cookie banner, with a random ID that links it to the website's record of consents.",
128
128
  consentDuration: "1 year",
129
+ consentDurationMonths: "{months} months",
129
130
  noServices: "No services in this category.",
131
+ services: "Services: {services}.",
130
132
  },
131
133
  };
132
134
  const texts = { sv, en };
@@ -135,3 +137,28 @@ export function defaultTexts(locale) {
135
137
  const language = locale?.toLowerCase().split("-")[0] ?? "en";
136
138
  return texts[language] ?? en;
137
139
  }
140
+ /**
141
+ * Suggestions from earlier versions. The Cookies global saves the suggestion it was prefilled with,
142
+ * so a saved text equal to one of these was never edited and shows the current suggestion instead.
143
+ */
144
+ const FORMER_SUGGESTIONS = new Set([
145
+ // 0.1.0–0.2.1
146
+ "Vi använder nödvändig lagring för att webbplatsen ska fungera. Du väljer om du också vill tillåta andra kategorier.",
147
+ "We use necessary storage for the website to work. You choose whether to allow other categories.",
148
+ "Du kan välja vilka kategorier du tillåter och ändra ditt val när som helst.",
149
+ "Choose which categories to allow. You can change your choice at any time.",
150
+ "Tillåter valfria funktioner från externa tjänster.",
151
+ "Allows optional functions provided by external services.",
152
+ "Tillåter anpassningar som förbättrar hur webbplatsen fungerar för dig.",
153
+ "Allows preferences that improve how the website works for you.",
154
+ "Tillåter mätning av hur webbplatsen används.",
155
+ "Allows measurement of how the website is used.",
156
+ "Tillåter mätning och innehåll för marknadsföring.",
157
+ "Allows measurement and content used for marketing.",
158
+ "Innehållet kräver att du tillåter {category}.",
159
+ "This content needs you to allow {category}.",
160
+ ]);
161
+ /** Whether a saved text is a suggestion from an earlier version, never edited. */
162
+ export function isFormerSuggestion(value) {
163
+ return typeof value === "string" && FORMER_SUGGESTIONS.has(value.trim());
164
+ }
@@ -6,8 +6,9 @@ import type { ConsentConfig, CookieTableData } from "../site-config.ts";
6
6
  export { ConsentDialogLink as ConsentSettingsLink } from "@c15t/react";
7
7
  type Script = NonNullable<ConsentManagerOptions["scripts"]>[number];
8
8
  /**
9
- * The services the plugin loads, each in its service's category. In basic consent mode nothing
10
- * loads before consent, including tags c15t would otherwise load at once in a denied state.
9
+ * The services the plugin loads, each in its service's category. Nothing loads before consent,
10
+ * including tags c15t would otherwise load at once in a denied state (Google Consent Mode's
11
+ * advanced mode), which sends data about the visit before the visitor has chosen.
11
12
  */
12
13
  export declare function integrationScripts(config: ConsentConfig): Script[];
13
14
  type Props = {
@@ -22,6 +23,8 @@ export declare function ConsentProvider({ config, scripts, children }: Props): i
22
23
  type FrameProps = {
23
24
  /** The category of the service the content comes from. */
24
25
  category: Category;
26
+ /** Who serves the content, such as YouTube: the placeholder names who receives data. */
27
+ provider: string;
25
28
  children: ReactNode;
26
29
  className?: string;
27
30
  };
@@ -29,7 +32,7 @@ type FrameProps = {
29
32
  * Embedded content, such as a video or a map, that is not mounted until the visitor allows its
30
33
  * category. Until then a placeholder offers to allow it. Without the banner, the content shows.
31
34
  */
32
- export declare function ConsentFrame({ category, children, className }: FrameProps): import("react").JSX.Element;
35
+ export declare function ConsentFrame({ category, provider, children, className }: FrameProps): import("react").JSX.Element;
33
36
  /** The cookie services by category, from `getCookieTable`, for the site's cookie page. */
34
37
  export declare function CookieTable({ data, heading }: {
35
38
  data: CookieTableData;
@@ -10,7 +10,9 @@ import { clarity } from "@c15t/scripts/microsoft-clarity";
10
10
  import { microsoftUet } from "@c15t/scripts/microsoft-uet";
11
11
  import { tiktokPixel } from "@c15t/scripts/tiktok-pixel";
12
12
  import { createContext, useContext, useEffect, useRef, } from "react";
13
+ import { isChoiceCurrent, savedAtFromCookie, savedAtFromStorage } from "../renewal.js";
13
14
  import { POLICY_COOKIE } from "../types.js";
15
+ import { cookieDomains, matchesStorageName, subjectIdFromCookie, withdrawnStorage, } from "../withdrawal.js";
14
16
  /** A button that opens the settings dialog, for the site's footer. Render it inside `ConsentProvider`. */
15
17
  export { ConsentDialogLink as ConsentSettingsLink } from "@c15t/react";
16
18
  /** Class names for c15t's unstyled parts, styled by `styles.css`. */
@@ -50,14 +52,15 @@ const factories = {
50
52
  hotjar: (siteId) => hotjar({ siteId }),
51
53
  };
52
54
  /**
53
- * The services the plugin loads, each in its service's category. In basic consent mode nothing
54
- * loads before consent, including tags c15t would otherwise load at once in a denied state.
55
+ * The services the plugin loads, each in its service's category. Nothing loads before consent,
56
+ * including tags c15t would otherwise load at once in a denied state (Google Consent Mode's
57
+ * advanced mode), which sends data about the visit before the visitor has chosen.
55
58
  */
56
59
  export function integrationScripts(config) {
57
60
  return config.integrations.map(({ key, id, category }) => ({
58
61
  ...factories[key](id, category),
59
62
  category,
60
- ...(config.googleConsentMode === "basic" ? { alwaysLoad: false } : {}),
63
+ alwaysLoad: false,
61
64
  }));
62
65
  }
63
66
  const ConfigContext = createContext(null);
@@ -65,11 +68,13 @@ const ConfigContext = createContext(null);
65
68
  export function ConsentProvider({ config, scripts, children }) {
66
69
  if (!config.enabled)
67
70
  return _jsx(_Fragment, { children: children });
68
- forgetOutdatedConsent(config.policyVersion);
71
+ forgetOutdatedConsent(config);
72
+ clearAfterWithdrawal(config);
69
73
  const options = {
70
74
  mode: "offline",
71
75
  overrides: { country: "SE" },
72
76
  consentCategories: config.categories,
77
+ storageConfig: { defaultExpiryDays: config.consentDays },
73
78
  scripts: [...integrationScripts(config), ...(scripts ?? [])],
74
79
  legalLinks: config.legalLinks,
75
80
  noStyle: true,
@@ -80,26 +85,86 @@ export function ConsentProvider({ config, scripts, children }) {
80
85
  detectBrowserLanguage: false,
81
86
  messages: { [config.locale]: config.messages },
82
87
  },
88
+ callbacks: {
89
+ // c15t reloads the page when a category is withdrawn. ConsentRecorder usually records the
90
+ // choice first, but nothing waits for it: record here too (once, see recordChoice) and
91
+ // clear the withdrawn services' storage.
92
+ onBeforeConsentRevocationReload: ({ preferences }) => {
93
+ const consents = preferences;
94
+ writePolicy(config);
95
+ recordChoice(config, subjectIdFromCookie(document.cookie), consents);
96
+ clearWithdrawnStorage(config, consents);
97
+ // A tag still running while the page unloads can write its cookie again: clear once more
98
+ // after the reload (see clearAfterWithdrawal).
99
+ try {
100
+ window.sessionStorage.setItem(WITHDRAWN_KEY, JSON.stringify(consents));
101
+ }
102
+ catch {
103
+ // Without session storage the cleanup above is all there is.
104
+ }
105
+ },
106
+ },
83
107
  };
84
- // With only necessary storage there is nothing to reject: Settings and the Okay button remain.
108
+ // With only necessary storage there is nothing to consent to, so no banner: the settings link
109
+ // still opens the dialog, which says the site only uses necessary storage.
85
110
  const necessaryOnly = config.categories.length === 1;
86
- return (_jsx(ConfigContext.Provider, { value: config, children: _jsxs(ConsentManagerProvider, { options: options, children: [children, _jsx(ConsentBanner, { hideBranding: true, layout: necessaryOnly ? [["customize", "accept"]] : undefined }), _jsx(SettingsDialog, {}), _jsx(ConsentRecorder, { config: config })] }) }));
111
+ 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 })] }) }));
112
+ }
113
+ /** Set by a withdrawal just before c15t reloads the page; read once by the next page load. */
114
+ const WITHDRAWN_KEY = "c15t-withdrawn";
115
+ let checkedWithdrawal = false;
116
+ /**
117
+ * Clears what the withdrawn categories' services stored once more, on the page load that follows a
118
+ * withdrawal. Only then: a fresh visitor, or a scanner, never has the marker.
119
+ */
120
+ function clearAfterWithdrawal(config) {
121
+ if (typeof window === "undefined" || checkedWithdrawal)
122
+ return;
123
+ checkedWithdrawal = true;
124
+ try {
125
+ const saved = window.sessionStorage.getItem(WITHDRAWN_KEY);
126
+ if (!saved)
127
+ return;
128
+ window.sessionStorage.removeItem(WITHDRAWN_KEY);
129
+ clearWithdrawnStorage(config, JSON.parse(saved));
130
+ }
131
+ catch {
132
+ // Without session storage there is no marker to act on.
133
+ }
87
134
  }
88
135
  function readPolicy() {
89
136
  const match = document.cookie.match(new RegExp(`(?:^|; )${POLICY_COOKIE}=([^;]*)`));
90
137
  return match ? decodeURIComponent(match[1] ?? "") : null;
91
138
  }
92
139
  const checkedPolicies = new Set();
140
+ function readStoredChoice() {
141
+ try {
142
+ return window.localStorage.getItem("c15t");
143
+ }
144
+ catch {
145
+ return null;
146
+ }
147
+ }
93
148
  /**
94
- * Removes a choice made under another policy version before c15t reads it, so nothing it allowed
95
- * loads before the visitor is asked again. Runs once per page load and version: a choice saved on
96
- * this page writes the new version itself.
149
+ * Removes a choice made under another policy version, or older than the consent lifetime, before
150
+ * c15t reads it, so nothing it allowed loads before the visitor is asked again. c15t keeps its
151
+ * choice in localStorage too and restores an expired cookie from it, so both are checked. Runs
152
+ * once per page load and version: a choice saved on this page writes the new version itself.
97
153
  */
98
- function forgetOutdatedConsent(version) {
154
+ function forgetOutdatedConsent(config) {
155
+ const version = config.policyVersion;
99
156
  if (typeof document === "undefined" || checkedPolicies.has(version))
100
157
  return;
101
158
  checkedPolicies.add(version);
102
- if (readPolicy() === version || !/(?:^|; )c15t=/.test(document.cookie))
159
+ const stored = readStoredChoice();
160
+ const hasCookie = /(?:^|; )c15t=/.test(document.cookie);
161
+ if (!hasCookie && !stored)
162
+ return;
163
+ const current = isChoiceCurrent({
164
+ savedAt: savedAtFromCookie(document.cookie) ?? savedAtFromStorage(stored),
165
+ policyVersion: readPolicy(),
166
+ }, { policyVersion: version, consentDays: config.consentDays, now: Date.now() });
167
+ if (current)
103
168
  return;
104
169
  document.cookie = "c15t=; Path=/; Max-Age=0";
105
170
  try {
@@ -109,11 +174,72 @@ function forgetOutdatedConsent(version) {
109
174
  // Without storage access there is nothing stored to remove.
110
175
  }
111
176
  }
112
- function writePolicy(version) {
177
+ function writePolicy(config) {
113
178
  const secure = window.location.protocol === "https:" ? "; Secure" : "";
114
- document.cookie = `${POLICY_COOKIE}=${encodeURIComponent(version)}; Path=/; Max-Age=${365 * 24 * 60 * 60}; SameSite=Lax${secure}`;
179
+ document.cookie = `${POLICY_COOKIE}=${encodeURIComponent(config.policyVersion)}; Path=/; Max-Age=${config.consentDays * 24 * 60 * 60}; SameSite=Lax${secure}`;
180
+ }
181
+ /** The last choice posted from this page: a withdrawal reaches both the callback and the effect. */
182
+ let lastRecorded;
183
+ /**
184
+ * Posts a saved choice to the site's consent records, with its policy version, once. Not when the
185
+ * site only uses necessary storage: there is no consent to show.
186
+ */
187
+ function recordChoice(config, subjectId, consents) {
188
+ if (!config.recordUrl || !subjectId || config.categories.length === 1)
189
+ return;
190
+ const choices = Object.fromEntries(config.categories.map((category) => [category, Boolean(consents[category])]));
191
+ const key = JSON.stringify([subjectId, choices]);
192
+ if (key === lastRecorded)
193
+ return;
194
+ lastRecorded = key;
195
+ // keepalive: a withdrawal posts this just before the page reloads.
196
+ fetch(config.recordUrl, {
197
+ method: "POST",
198
+ headers: { "Content-Type": "application/json" },
199
+ keepalive: true,
200
+ body: JSON.stringify({
201
+ subjectId,
202
+ choices,
203
+ policyVersion: config.policyVersion,
204
+ locale: config.locale,
205
+ path: window.location.pathname,
206
+ }),
207
+ }).catch(() => {
208
+ // The choice still applies in the browser; only the record is missing.
209
+ });
115
210
  }
116
- /** Posts each choice saved on this page to the site's consent records, with its policy version. */
211
+ /**
212
+ * Removes the cookies and localStorage keys the Cookie services list for the categories the
213
+ * visitor withdrew, such as `_ga` and `_ga_*`. Only on a withdrawal, never on an ordinary page
214
+ * load: a scan must still see a service that stores something it should not.
215
+ */
216
+ function clearWithdrawnStorage(config, consents) {
217
+ const items = withdrawnStorage(config.storage ?? [], consents);
218
+ if (!items.length)
219
+ return;
220
+ const cookieNames = document.cookie
221
+ .split("; ")
222
+ .map((pair) => pair.slice(0, pair.indexOf("=")))
223
+ .filter(Boolean);
224
+ for (const item of items) {
225
+ if (item.type === "cookie") {
226
+ for (const name of cookieNames.filter((cookie) => matchesStorageName(item.name, cookie)))
227
+ for (const domain of cookieDomains(window.location.hostname))
228
+ document.cookie = `${name}=; Path=/; Max-Age=0${domain ? `; Domain=${domain}` : ""}`;
229
+ }
230
+ else {
231
+ try {
232
+ for (const key of Object.keys(window.localStorage))
233
+ if (matchesStorageName(item.name, key))
234
+ window.localStorage.removeItem(key);
235
+ }
236
+ catch {
237
+ // Without storage access there is nothing stored to remove.
238
+ }
239
+ }
240
+ }
241
+ }
242
+ /** Posts each choice saved on this page to the site's consent records. */
117
243
  function ConsentRecorder({ config }) {
118
244
  const { consentInfo, consents } = useConsentManager();
119
245
  const mountedAt = useRef(Date.now());
@@ -122,56 +248,50 @@ function ConsentRecorder({ config }) {
122
248
  useEffect(() => {
123
249
  if (!savedAt || savedAt < mountedAt.current)
124
250
  return;
125
- writePolicy(config.policyVersion);
126
- if (!config.recordUrl || !consentInfo?.subjectId)
127
- return;
128
- const choices = Object.fromEntries(config.categories.map((category) => [category, Boolean(consents[category])]));
129
- fetch(config.recordUrl, {
130
- method: "POST",
131
- headers: { "Content-Type": "application/json" },
132
- keepalive: true,
133
- body: JSON.stringify({
134
- subjectId: consentInfo.subjectId,
135
- choices,
136
- policyVersion: config.policyVersion,
137
- locale: config.locale,
138
- path: window.location.pathname,
139
- }),
140
- }).catch(() => {
141
- // The choice still applies in the browser; only the record is missing.
142
- });
251
+ writePolicy(config);
252
+ recordChoice(config, consentInfo?.subjectId, consents);
143
253
  }, [savedAt]);
144
254
  return null;
145
255
  }
146
256
  /** c15t's dialog; a click on the backdrop discards unsaved toggles and returns to the banner. */
147
257
  function SettingsDialog() {
148
258
  const { consents, selectedConsents, setSelectedConsent, hasConsented, setActiveUI } = useConsentManager();
149
- function dismiss(event) {
150
- if (event.target !== event.currentTarget)
151
- return;
259
+ function discardAndReturn() {
152
260
  for (const name of Object.keys(selectedConsents))
153
261
  setSelectedConsent(name, consents[name] ?? false);
154
262
  setActiveUI(hasConsented() ? "none" : "banner");
155
263
  }
264
+ function dismiss(event) {
265
+ if (event.target === event.currentTarget)
266
+ discardAndReturn();
267
+ }
268
+ // c15t's dialog ignores Escape; a modal dialog closes on it (WAI-ARIA), here as the backdrop does.
269
+ function onKeyDown(event) {
270
+ if (event.key !== "Escape")
271
+ return;
272
+ event.preventDefault();
273
+ discardAndReturn();
274
+ }
156
275
  // With only necessary storage there is nothing to reject; c15t's dialog has no option to drop
157
276
  // the button, so a class hides it (see consent.css).
158
277
  const necessaryOnly = useContext(ConfigContext)?.categories.length === 1;
159
- return (_jsx(C15tDialog.Root, { className: necessaryOnly ? "sc-dialog--necessary-only" : undefined, onClick: dismiss, children: _jsx(C15tDialog.ConsentCustomizationCard, { hideBranding: true }) }));
278
+ return (_jsx(C15tDialog.Root, { className: necessaryOnly ? "sc-dialog--necessary-only" : undefined, onClick: dismiss, onKeyDown: onKeyDown, children: _jsx(C15tDialog.ConsentCustomizationCard, { hideBranding: true }) }));
160
279
  }
161
280
  /**
162
281
  * Embedded content, such as a video or a map, that is not mounted until the visitor allows its
163
282
  * category. Until then a placeholder offers to allow it. Without the banner, the content shows.
164
283
  */
165
- export function ConsentFrame({ category, children, className }) {
284
+ export function ConsentFrame({ category, provider, children, className }) {
166
285
  const config = useContext(ConfigContext);
167
286
  if (!config)
168
287
  return _jsx(_Fragment, { children: children });
169
- return (_jsx(Frame, { category: category, className: className, noStyle: true, placeholder: _jsx(EmbedPlaceholder, { category: category, config: config }), children: children }));
288
+ return (_jsx(Frame, { category: category, className: className, noStyle: true, placeholder: _jsx(EmbedPlaceholder, { category: category, config: config, provider: provider }), children: children }));
170
289
  }
171
- function EmbedPlaceholder({ category, config }) {
290
+ function EmbedPlaceholder({ category, config, provider, }) {
172
291
  const { setConsent } = useConsentManager();
173
- const title = config.messages.consentTypes?.[category]?.title ?? category;
174
- return (_jsxs("div", { className: "sc-frame", children: [_jsx("p", { children: config.embeds.title.replaceAll("{category}", title) }), _jsx("button", { type: "button", onClick: () => setConsent(category, true), children: config.embeds.button.replaceAll("{category}", title) })] }));
292
+ const title = (config.messages.consentTypes?.[category]?.title ?? category).toLocaleLowerCase(config.locale);
293
+ const fill = (text) => text.replaceAll("{category}", title).replaceAll("{provider}", provider);
294
+ 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) })] }));
175
295
  }
176
296
  /** The cookie services by category, from `getCookieTable`, for the site's cookie page. */
177
297
  export function CookieTable({ data, heading }) {
package/dist/global.js CHANGED
@@ -1,4 +1,4 @@
1
- import { defaultTexts, OPTIONAL_CATEGORIES } from "./defaults.js";
1
+ import { defaultTexts, isFormerSuggestion, OPTIONAL_CATEGORIES, } from "./defaults.js";
2
2
  import { CONSENT_GLOBAL } from "./types.js";
3
3
  export const categoryLabels = {
4
4
  necessary: { en: "Necessary", sv: "Nödvändiga" },
@@ -19,6 +19,12 @@ function text(name, label, suggestion, extra = {}) {
19
19
  label,
20
20
  localized: true,
21
21
  defaultValue: ({ locale }) => suggestion(defaultTexts(locale)),
22
+ // A suggestion saved by an earlier version shows as the current one, as on the site.
23
+ hooks: {
24
+ afterRead: [
25
+ ({ value, req }) => isFormerSuggestion(value) ? suggestion(defaultTexts(req.locale)) : value,
26
+ ],
27
+ },
22
28
  admin: {
23
29
  ...(extra.width ? { width: extra.width } : {}),
24
30
  ...(extra.description ? { description: extra.description } : {}),
@@ -60,9 +66,17 @@ export function consentGlobal(options, { usersSlug, schedule }) {
60
66
  sv: "Det besökaren ser innan hen har valt. Godkänn och avvisa visas alltid sida vid sida.",
61
67
  },
62
68
  fields: [
63
- text("bannerTitle", { en: "Title", sv: "Rubrik" }, (t) => t.bannerTitle),
64
- text("bannerDescription", { en: "Description", sv: "Beskrivning" }, (t) => t.bannerDescription, { textarea: true, ...withChoices }),
65
- text("bannerDescriptionNecessaryOnly", { en: "Description", sv: "Beskrivning" }, (t) => t.bannerDescriptionNecessaryOnly, { textarea: true, ...necessaryOnly }),
69
+ text("bannerTitle", { en: "Title", sv: "Rubrik" }, (t) => t.bannerTitle, {
70
+ condition: hasOptional,
71
+ }),
72
+ text("bannerDescription", { en: "Description", sv: "Beskrivning" }, (t) => t.bannerDescription, {
73
+ textarea: true,
74
+ condition: hasOptional,
75
+ description: {
76
+ en: "{categories} becomes the site's optional categories, such as “statistics and marketing”. Say here that the choice can be changed or withdrawn at any time.",
77
+ sv: "{categories} blir webbplatsens valfria kategorier, till exempel ”statistik och marknadsföring”. Säg här att valet kan ändras eller tas tillbaka när som helst.",
78
+ },
79
+ }),
66
80
  {
67
81
  name: "buttons",
68
82
  type: "group",
@@ -106,8 +120,8 @@ export function consentGlobal(options, { usersSlug, schedule }) {
106
120
  label: { en: "Embedded content", sv: "Inbäddat innehåll" },
107
121
  admin: {
108
122
  description: {
109
- en: "Shown in place of a video, map or other embed until the visitor allows its category. {category} becomes the category's title.",
110
- sv: "Visas i stället för en video, karta eller annan inbäddning tills besökaren tillåter dess kategori. {category} blir kategorins rubrik.",
123
+ en: "Shown in place of a video, map or other embed until the visitor allows its category. {provider} becomes the embed's provider, such as YouTube, and {category} the category's title.",
124
+ sv: "Visas i stället för en video, karta eller annan inbäddning tills besökaren tillåter dess kategori. {provider} blir inbäddningens leverantör, till exempel YouTube, och {category} kategorins rubrik.",
111
125
  },
112
126
  },
113
127
  fields: [
@@ -260,8 +274,8 @@ export function consentGlobal(options, { usersSlug, schedule }) {
260
274
  admin: {
261
275
  readOnly: true,
262
276
  description: {
263
- en: "Follows the categories of the Cookie services. With none, the banner only informs and has an Okay button.",
264
- sv: "Följer kategorierna under Cookietjänster. Utan valfria kategorier informerar bannern bara och har en Okej-knapp.",
277
+ en: "Follows the categories of the Cookie services. With none, no banner is shown: the site needs no consent, and Cookie settings in the footer says it only uses necessary storage.",
278
+ sv: "Följer kategorierna under Cookietjänster. Utan valfria kategorier visas ingen banner: webbplatsen behöver inget samtycke, och Cookieinställningar i sidfoten visar att den bara använder nödvändig lagring.",
265
279
  },
266
280
  },
267
281
  options: OPTIONAL_CATEGORIES.map((value) => ({
@@ -269,34 +283,6 @@ export function consentGlobal(options, { usersSlug, schedule }) {
269
283
  label: categoryLabels[value],
270
284
  })),
271
285
  },
272
- {
273
- name: "googleConsentMode",
274
- type: "radio",
275
- defaultValue: "basic",
276
- label: { en: "Google Consent Mode", sv: "Google Consent Mode" },
277
- options: [
278
- {
279
- value: "basic",
280
- label: {
281
- en: "Basic: nothing loads before consent",
282
- sv: "Basic: inget laddas före samtycke",
283
- },
284
- },
285
- {
286
- value: "advanced",
287
- label: {
288
- en: "Advanced: Google and similar tags load at once in a denied state",
289
- sv: "Advanced: Google och liknande taggar laddas direkt i nekat läge",
290
- },
291
- },
292
- ],
293
- admin: {
294
- description: {
295
- en: "Applies to the services the plugin loads. Advanced sends cookieless measurements to the provider before the visitor has chosen; pick it only when that has been assessed as acceptable.",
296
- sv: "Gäller tjänsterna som pluginet laddar. Advanced skickar mätningar utan cookies till leverantören innan besökaren har valt; välj det bara när det har bedömts som godtagbart.",
297
- },
298
- },
299
- },
300
286
  ...(legal
301
287
  ? ["privacyPolicy", "cookiePolicy"].map((name) => ({
302
288
  name,
package/dist/records.js CHANGED
@@ -77,7 +77,6 @@ function recordEndpoint(options) {
77
77
  snapshot: {
78
78
  categories: config.categories,
79
79
  messages: config.messages,
80
- googleConsentMode: config.googleConsentMode,
81
80
  services: services.map((service) => ({
82
81
  name: service.name,
83
82
  provider: service.provider,
@@ -0,0 +1,21 @@
1
+ /** How long a choice is kept before the visitor is asked again, unless the host sets `consentMonths`. */
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. */
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;
@@ -0,0 +1,33 @@
1
+ /** How long a choice is kept before the visitor is asked again, unless the host sets `consentMonths`. */
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. */
4
+ export function consentDays(months) {
5
+ return Math.round((months * 365) / 12);
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
+ }
@@ -2,13 +2,13 @@ import type { ConsentManagerOptions, Translations } 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";
5
+ import type { StoredItem } from "./withdrawal.ts";
5
6
  /** The Cookies global as read in one locale. Every text may be missing in an old document. */
6
7
  export type ConsentDocument = {
7
8
  enabled?: boolean | null;
8
9
  categories?: string[] | null;
9
10
  bannerTitle?: string | null;
10
11
  bannerDescription?: string | null;
11
- bannerDescriptionNecessaryOnly?: string | null;
12
12
  buttons?: Partial<Record<string, string | null>> | null;
13
13
  dialog?: Partial<Record<string, string | null>> | null;
14
14
  categoryTexts?: Partial<Record<string, {
@@ -19,7 +19,6 @@ export type ConsentDocument = {
19
19
  title?: string | null;
20
20
  button?: string | null;
21
21
  } | null;
22
- googleConsentMode?: string | null;
23
22
  privacyPolicy?: unknown;
24
23
  cookiePolicy?: unknown;
25
24
  };
@@ -53,19 +52,22 @@ export type ConsentConfig = {
53
52
  legalLinks?: NonNullable<ConsentManagerOptions["legalLinks"]>;
54
53
  /** c15t's texts for `locale`. */
55
54
  messages: Partial<Translations>;
56
- /** Basic waits for consent; advanced lets tags that support it load at once in a denied state. */
57
- googleConsentMode: "basic" | "advanced";
58
- /** Services the plugin loads through c15t. */
55
+ /** Services the plugin loads through c15t, none before consent. */
59
56
  integrations: {
60
57
  key: IntegrationKey;
61
58
  id: string;
62
59
  category: Category;
63
60
  }[];
64
- /** The placeholder in place of embedded content; `{category}` becomes the category's title. */
61
+ /**
62
+ * The placeholder in place of embedded content; `{provider}` becomes the embed's provider and
63
+ * `{category}` the category's title.
64
+ */
65
65
  embeds: {
66
66
  title: string;
67
67
  button: string;
68
68
  };
69
+ /** How long a choice is kept before the visitor is asked again. */
70
+ consentDays: number;
69
71
  /**
70
72
  * Changes when the categories or the services' cookies change: visitors who chose under an older
71
73
  * version are asked again.
@@ -73,10 +75,17 @@ export type ConsentConfig = {
73
75
  policyVersion: string;
74
76
  /** Where the site posts each saved choice; absent when records are off. */
75
77
  recordUrl?: string;
78
+ /**
79
+ * The services' own cookies and localStorage keys by category, removed when the visitor withdraws
80
+ * the category. Third-party storage lives on other sites and cannot be removed from here.
81
+ */
82
+ storage: StoredItem[];
76
83
  };
77
84
  type Options = {
78
85
  locale: string;
79
86
  legalUrl?: (doc: Record<string, unknown>, locale: string) => string;
87
+ /** See `ConsentPluginOptions.consentMonths`. */
88
+ consentMonths?: number;
80
89
  };
81
90
  /** A short hash of what a visitor consents to: the categories and each service's storage. */
82
91
  export declare function policyVersion(categories: Category[], services: ServiceDocument[]): string;
@@ -122,7 +131,7 @@ export type CookieTableData = {
122
131
  }[];
123
132
  };
124
133
  /** Turns the services into the cookie table, with the consent storage itself as necessary. */
125
- export declare function toCookieTable(doc: ConsentDocument, services: ServiceDocument[], locale: string): CookieTableData;
134
+ export declare function toCookieTable(doc: ConsentDocument, services: ServiceDocument[], locale: string, consentMonths?: number): CookieTableData;
126
135
  /** Reads what the cookie table block shows, in a locale. */
127
136
  export declare function getCookieTable(args: ReadArgs): Promise<CookieTableData>;
128
137
  export {};
@@ -1,6 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
- import { CATEGORIES, defaultTexts, OPTIONAL_CATEGORIES } from "./defaults.js";
2
+ import { CATEGORIES, defaultTexts, isFormerSuggestion, OPTIONAL_CATEGORIES, } from "./defaults.js";
3
3
  import { isIntegration } from "./integrations.js";
4
+ import { consentDays, DEFAULT_CONSENT_MONTHS } from "./renewal.js";
4
5
  import { CONSENT_GLOBAL, CONSENT_RECORDS, CONSENT_SERVICES, POLICY_COOKIE, } from "./types.js";
5
6
  const isDoc = (value) => Boolean(value) && typeof value === "object";
6
7
  /** A short hash of what a visitor consents to: the categories and each service's storage. */
@@ -18,6 +19,22 @@ export function policyVersion(categories, services) {
18
19
  return createHash("sha256").update(JSON.stringify(material)).digest("hex").slice(0, 16);
19
20
  }
20
21
  const isCategory = (value) => CATEGORIES.includes(value);
22
+ /** An empty text, or a suggestion from an earlier version never edited, shows the current one. */
23
+ const pick = (value, fallback) => (!isFormerSuggestion(value) && value?.trim()) || fallback;
24
+ /** Each category's title and description: the global's own, or the suggestion. */
25
+ function categoryTextsFor(doc, suggested) {
26
+ return Object.fromEntries(CATEGORIES.map((category) => {
27
+ const own = doc.categoryTexts?.[category];
28
+ const fallback = suggested.categoryTexts[category];
29
+ return [
30
+ category,
31
+ {
32
+ title: pick(own?.title, fallback.title),
33
+ description: pick(own?.description, fallback.description),
34
+ },
35
+ ];
36
+ }));
37
+ }
21
38
  /**
22
39
  * Maps the global and the services to the banner's config, filling any missing text with the
23
40
  * suggestion. The banner's categories are the services' categories.
@@ -35,8 +52,36 @@ export function toConsentConfig(doc, services, options) {
35
52
  isCategory(service.category)
36
53
  ? [{ key: service.integration, id: service.integrationId.trim(), category: service.category }]
37
54
  : []);
55
+ const storage = services.flatMap((service) => isCategory(service.category) && service.category !== "necessary"
56
+ ? (service.storage ?? []).flatMap((entry) => entry.name?.trim() &&
57
+ !entry.thirdParty &&
58
+ (entry.type === "cookie" || entry.type === "localStorage")
59
+ ? [
60
+ {
61
+ category: service.category,
62
+ type: entry.type,
63
+ name: entry.name.trim(),
64
+ },
65
+ ]
66
+ : [])
67
+ : []);
38
68
  const optional = categories.length > 1;
39
- const pick = (value, fallback) => value?.trim() || fallback;
69
+ const categoryTexts = categoryTextsFor(doc, suggested);
70
+ const listFormat = new Intl.ListFormat(options.locale, { type: "conjunction" });
71
+ const optionalTitles = listFormat.format(categories
72
+ .filter((category) => category !== "necessary")
73
+ .map((category) => categoryTexts[category].title.toLocaleLowerCase(options.locale)));
74
+ // The dialog names each category's services and providers after its description.
75
+ const serviceList = (category) => {
76
+ const names = services
77
+ .filter((service) => service.category === category && service.name?.trim())
78
+ .map((service) => service.provider?.trim()
79
+ ? `${service.name?.trim()} (${service.provider.trim()})`
80
+ : (service.name?.trim() ?? ""));
81
+ return names.length
82
+ ? ` ${suggested.table.services.replace("{services}", listFormat.format(names))}`
83
+ : "";
84
+ };
40
85
  const buttons = doc.buttons ?? {};
41
86
  const dialog = doc.dialog ?? {};
42
87
  const legalLinks = {};
@@ -50,8 +95,9 @@ export function toConsentConfig(doc, services, options) {
50
95
  locale: options.locale,
51
96
  categories,
52
97
  policyVersion: policyVersion(categories, services),
53
- googleConsentMode: doc.googleConsentMode === "advanced" ? "advanced" : "basic",
98
+ consentDays: consentDays(options.consentMonths ?? DEFAULT_CONSENT_MONTHS),
54
99
  integrations,
100
+ storage,
55
101
  embeds: {
56
102
  title: pick(doc.embeds?.title, suggested.embeds.title),
57
103
  button: pick(doc.embeds?.button, suggested.embeds.button),
@@ -69,9 +115,8 @@ export function toConsentConfig(doc, services, options) {
69
115
  },
70
116
  cookieBanner: {
71
117
  title: pick(doc.bannerTitle, suggested.bannerTitle),
72
- description: optional
73
- ? pick(doc.bannerDescription, suggested.bannerDescription)
74
- : pick(doc.bannerDescriptionNecessaryOnly, suggested.bannerDescriptionNecessaryOnly),
118
+ // Not shown when the site only uses necessary storage: there is no banner then.
119
+ description: pick(doc.bannerDescription, suggested.bannerDescription).replaceAll("{categories}", optionalTitles),
75
120
  },
76
121
  consentManagerDialog: {
77
122
  title: pick(dialog.title, suggested.dialog.title),
@@ -79,17 +124,13 @@ export function toConsentConfig(doc, services, options) {
79
124
  ? pick(dialog.description, suggested.dialog.description)
80
125
  : pick(dialog.descriptionNecessaryOnly, suggested.dialog.descriptionNecessaryOnly),
81
126
  },
82
- consentTypes: Object.fromEntries(CATEGORIES.map((category) => {
83
- const own = doc.categoryTexts?.[category];
84
- const fallback = suggested.categoryTexts[category];
85
- return [
86
- category,
87
- {
88
- title: pick(own?.title, fallback.title),
89
- description: pick(own?.description, fallback.description),
90
- },
91
- ];
92
- })),
127
+ consentTypes: Object.fromEntries(CATEGORIES.map((category) => [
128
+ category,
129
+ {
130
+ title: categoryTexts[category].title,
131
+ description: `${categoryTexts[category].description}${serviceList(category)}`,
132
+ },
133
+ ])),
93
134
  },
94
135
  };
95
136
  }
@@ -133,6 +174,7 @@ export async function getConsentConfig(args) {
133
174
  const { locale, doc, services } = await readConsent(args, legalPages ? 1 : 0);
134
175
  const config = toConsentConfig(doc, services, {
135
176
  locale,
177
+ consentMonths: options?.consentMonths,
136
178
  legalUrl: legalPages ? (page, pageLocale) => legalPages.url(page, pageLocale) : undefined,
137
179
  });
138
180
  if (options?.records === false)
@@ -141,15 +183,18 @@ export async function getConsentConfig(args) {
141
183
  return { ...config, recordUrl: `${serverURL ?? ""}${routes.api}/${CONSENT_RECORDS}/record` };
142
184
  }
143
185
  /** Turns the services into the cookie table, with the consent storage itself as necessary. */
144
- export function toCookieTable(doc, services, locale) {
186
+ export function toCookieTable(doc, services, locale, consentMonths = DEFAULT_CONSENT_MONTHS) {
145
187
  const config = toConsentConfig(doc, services, { locale });
146
188
  const suggested = defaultTexts(locale);
147
189
  const labels = suggested.table;
190
+ const categoryTexts = categoryTextsFor(doc, suggested);
191
+ const consentDuration = consentMonths === 12
192
+ ? labels.consentDuration
193
+ : labels.consentDurationMonths.replace("{months}", String(consentMonths));
148
194
  const text = (value) => value?.trim() || undefined;
149
195
  return {
150
196
  labels,
151
197
  categories: config.categories.map((key) => {
152
- const type = config.messages.consentTypes?.[key];
153
198
  const rows = services
154
199
  .filter((service) => service.category === key)
155
200
  .map((service) => ({
@@ -175,14 +220,14 @@ export function toCookieTable(doc, services, locale) {
175
220
  ...["cookie", "localStorage"].map((storageType) => ({
176
221
  name: "c15t",
177
222
  type: storageType,
178
- duration: labels.consentDuration,
223
+ duration: consentDuration,
179
224
  thirdParty: false,
180
225
  description: undefined,
181
226
  })),
182
227
  {
183
228
  name: POLICY_COOKIE,
184
229
  type: "cookie",
185
- duration: labels.consentDuration,
230
+ duration: consentDuration,
186
231
  thirdParty: false,
187
232
  description: undefined,
188
233
  },
@@ -190,8 +235,8 @@ export function toCookieTable(doc, services, locale) {
190
235
  });
191
236
  return {
192
237
  key,
193
- title: type?.title ?? key,
194
- description: type?.description ?? "",
238
+ title: categoryTexts[key].title,
239
+ description: categoryTexts[key].description,
195
240
  services: rows,
196
241
  };
197
242
  }),
@@ -200,5 +245,6 @@ export function toCookieTable(doc, services, locale) {
200
245
  /** Reads what the cookie table block shows, in a locale. */
201
246
  export async function getCookieTable(args) {
202
247
  const { locale, doc, services } = await readConsent(args);
203
- return toCookieTable(doc, services, locale);
248
+ const options = args.payload.config.custom?.consent;
249
+ return toCookieTable(doc, services, locale, options?.consentMonths);
204
250
  }
package/dist/types.d.ts CHANGED
@@ -25,6 +25,11 @@ export type ConsentPluginOptions = {
25
25
  records?: false | {
26
26
  retentionDays?: number;
27
27
  };
28
+ /**
29
+ * How many months a visitor's choice is kept before the banner asks again. Defaults to 12.
30
+ * Changes and withdrawals are possible at any time through `ConsentSettingsLink`.
31
+ */
32
+ consentMonths?: number;
28
33
  /**
29
34
  * The consent scanner (`consent-scanner`) that scans the published site from Admin. Without it,
30
35
  * the Scan tab explains how to set one up.
@@ -0,0 +1,19 @@
1
+ import type { Category } from "./defaults.ts";
2
+ /** A cookie or localStorage key a service stores on the site itself, in its service's category. */
3
+ export type StoredItem = {
4
+ category: Category;
5
+ type: "cookie" | "localStorage";
6
+ name: string;
7
+ };
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;
@@ -0,0 +1,24 @@
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];
24
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simmalugnt-se/payload-consent",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Cookie consent for Payload sites: banner texts, services and scans in Admin",
5
5
  "keywords": [
6
6
  "payload",