@simmalugnt-se/payload-consent 0.2.0 → 0.2.1

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,12 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.1
4
+
5
+ - Withdrawing a category removes the cookies and localStorage keys its Cookie services list on the
6
+ site, such as `_ga` and `_ga_*`, before and once more after c15t reloads the page. Third-party
7
+ storage cannot be reached from the site and stays.
8
+ - A choice is posted to the consent log once per page load: a withdrawal no longer posts it twice.
9
+
3
10
  ## 0.2.0
4
11
 
5
12
  - Cookies is the one entry in Admin: a Services tab lists the Cookie services with links to edit
package/README.md CHANGED
@@ -74,6 +74,10 @@ policy version and language also saves what the visitor was shown in `consent-po
74
74
  categories, services and texts. Records are kept for three years (`records.retentionDays`) and
75
75
  readable by signed-in users only; `records: false` turns the log off.
76
76
 
77
+ When a visitor withdraws a category, c15t reloads the page and the plugin removes the cookies
78
+ and localStorage keys the category's services list as their own (not third-party), so list the
79
+ names a service stores, with `*` for a family such as `_ga_*`.
80
+
77
81
  The policy version is a hash of the categories and each service's cookies and storage keys. When
78
82
  it changes, for example because a service gains a cookie, visitors are asked again. Rewording a
79
83
  text does not change it.
@@ -11,6 +11,7 @@ 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
13
  import { POLICY_COOKIE } from "../types.js";
14
+ import { cookieDomains, matchesStorageName, subjectIdFromCookie, withdrawnStorage, } from "../withdrawal.js";
14
15
  /** A button that opens the settings dialog, for the site's footer. Render it inside `ConsentProvider`. */
15
16
  export { ConsentDialogLink as ConsentSettingsLink } from "@c15t/react";
16
17
  /** Class names for c15t's unstyled parts, styled by `styles.css`. */
@@ -66,6 +67,7 @@ export function ConsentProvider({ config, scripts, children }) {
66
67
  if (!config.enabled)
67
68
  return _jsx(_Fragment, { children: children });
68
69
  forgetOutdatedConsent(config.policyVersion);
70
+ clearAfterWithdrawal(config);
69
71
  const options = {
70
72
  mode: "offline",
71
73
  overrides: { country: "SE" },
@@ -80,11 +82,52 @@ export function ConsentProvider({ config, scripts, children }) {
80
82
  detectBrowserLanguage: false,
81
83
  messages: { [config.locale]: config.messages },
82
84
  },
85
+ callbacks: {
86
+ // c15t reloads the page when a category is withdrawn. ConsentRecorder usually records the
87
+ // choice first, but nothing waits for it: record here too (once, see recordChoice) and
88
+ // clear the withdrawn services' storage.
89
+ onBeforeConsentRevocationReload: ({ preferences }) => {
90
+ const consents = preferences;
91
+ writePolicy(config.policyVersion);
92
+ recordChoice(config, subjectIdFromCookie(document.cookie), consents);
93
+ clearWithdrawnStorage(config, consents);
94
+ // A tag still running while the page unloads can write its cookie again: clear once more
95
+ // after the reload (see clearAfterWithdrawal).
96
+ try {
97
+ window.sessionStorage.setItem(WITHDRAWN_KEY, JSON.stringify(consents));
98
+ }
99
+ catch {
100
+ // Without session storage the cleanup above is all there is.
101
+ }
102
+ },
103
+ },
83
104
  };
84
105
  // With only necessary storage there is nothing to reject: Settings and the Okay button remain.
85
106
  const necessaryOnly = config.categories.length === 1;
86
107
  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 })] }) }));
87
108
  }
109
+ /** Set by a withdrawal just before c15t reloads the page; read once by the next page load. */
110
+ const WITHDRAWN_KEY = "c15t-withdrawn";
111
+ let checkedWithdrawal = false;
112
+ /**
113
+ * Clears what the withdrawn categories' services stored once more, on the page load that follows a
114
+ * withdrawal. Only then: a fresh visitor, or a scanner, never has the marker.
115
+ */
116
+ function clearAfterWithdrawal(config) {
117
+ if (typeof window === "undefined" || checkedWithdrawal)
118
+ return;
119
+ checkedWithdrawal = true;
120
+ try {
121
+ const saved = window.sessionStorage.getItem(WITHDRAWN_KEY);
122
+ if (!saved)
123
+ return;
124
+ window.sessionStorage.removeItem(WITHDRAWN_KEY);
125
+ clearWithdrawnStorage(config, JSON.parse(saved));
126
+ }
127
+ catch {
128
+ // Without session storage there is no marker to act on.
129
+ }
130
+ }
88
131
  function readPolicy() {
89
132
  const match = document.cookie.match(new RegExp(`(?:^|; )${POLICY_COOKIE}=([^;]*)`));
90
133
  return match ? decodeURIComponent(match[1] ?? "") : null;
@@ -113,7 +156,65 @@ function writePolicy(version) {
113
156
  const secure = window.location.protocol === "https:" ? "; Secure" : "";
114
157
  document.cookie = `${POLICY_COOKIE}=${encodeURIComponent(version)}; Path=/; Max-Age=${365 * 24 * 60 * 60}; SameSite=Lax${secure}`;
115
158
  }
116
- /** Posts each choice saved on this page to the site's consent records, with its policy version. */
159
+ /** The last choice posted from this page: a withdrawal reaches both the callback and the effect. */
160
+ let lastRecorded;
161
+ /** Posts a saved choice to the site's consent records, with its policy version, once. */
162
+ function recordChoice(config, subjectId, consents) {
163
+ if (!config.recordUrl || !subjectId)
164
+ return;
165
+ const choices = Object.fromEntries(config.categories.map((category) => [category, Boolean(consents[category])]));
166
+ const key = JSON.stringify([subjectId, choices]);
167
+ if (key === lastRecorded)
168
+ return;
169
+ lastRecorded = key;
170
+ // keepalive: a withdrawal posts this just before the page reloads.
171
+ fetch(config.recordUrl, {
172
+ method: "POST",
173
+ headers: { "Content-Type": "application/json" },
174
+ keepalive: true,
175
+ body: JSON.stringify({
176
+ subjectId,
177
+ choices,
178
+ policyVersion: config.policyVersion,
179
+ locale: config.locale,
180
+ path: window.location.pathname,
181
+ }),
182
+ }).catch(() => {
183
+ // The choice still applies in the browser; only the record is missing.
184
+ });
185
+ }
186
+ /**
187
+ * Removes the cookies and localStorage keys the Cookie services list for the categories the
188
+ * visitor withdrew, such as `_ga` and `_ga_*`. Only on a withdrawal, never on an ordinary page
189
+ * load: a scan must still see a service that stores something it should not.
190
+ */
191
+ function clearWithdrawnStorage(config, consents) {
192
+ const items = withdrawnStorage(config.storage ?? [], consents);
193
+ if (!items.length)
194
+ return;
195
+ const cookieNames = document.cookie
196
+ .split("; ")
197
+ .map((pair) => pair.slice(0, pair.indexOf("=")))
198
+ .filter(Boolean);
199
+ for (const item of items) {
200
+ if (item.type === "cookie") {
201
+ for (const name of cookieNames.filter((cookie) => matchesStorageName(item.name, cookie)))
202
+ for (const domain of cookieDomains(window.location.hostname))
203
+ document.cookie = `${name}=; Path=/; Max-Age=0${domain ? `; Domain=${domain}` : ""}`;
204
+ }
205
+ else {
206
+ try {
207
+ for (const key of Object.keys(window.localStorage))
208
+ if (matchesStorageName(item.name, key))
209
+ window.localStorage.removeItem(key);
210
+ }
211
+ catch {
212
+ // Without storage access there is nothing stored to remove.
213
+ }
214
+ }
215
+ }
216
+ }
217
+ /** Posts each choice saved on this page to the site's consent records. */
117
218
  function ConsentRecorder({ config }) {
118
219
  const { consentInfo, consents } = useConsentManager();
119
220
  const mountedAt = useRef(Date.now());
@@ -123,23 +224,7 @@ function ConsentRecorder({ config }) {
123
224
  if (!savedAt || savedAt < mountedAt.current)
124
225
  return;
125
226
  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
- });
227
+ recordChoice(config, consentInfo?.subjectId, consents);
143
228
  }, [savedAt]);
144
229
  return null;
145
230
  }
@@ -2,6 +2,7 @@ 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;
@@ -73,6 +74,11 @@ export type ConsentConfig = {
73
74
  policyVersion: string;
74
75
  /** Where the site posts each saved choice; absent when records are off. */
75
76
  recordUrl?: string;
77
+ /**
78
+ * The services' own cookies and localStorage keys by category, removed when the visitor withdraws
79
+ * the category. Third-party storage lives on other sites and cannot be removed from here.
80
+ */
81
+ storage: StoredItem[];
76
82
  };
77
83
  type Options = {
78
84
  locale: string;
@@ -35,6 +35,19 @@ export function toConsentConfig(doc, services, options) {
35
35
  isCategory(service.category)
36
36
  ? [{ key: service.integration, id: service.integrationId.trim(), category: service.category }]
37
37
  : []);
38
+ const storage = services.flatMap((service) => isCategory(service.category) && service.category !== "necessary"
39
+ ? (service.storage ?? []).flatMap((entry) => entry.name?.trim() &&
40
+ !entry.thirdParty &&
41
+ (entry.type === "cookie" || entry.type === "localStorage")
42
+ ? [
43
+ {
44
+ category: service.category,
45
+ type: entry.type,
46
+ name: entry.name.trim(),
47
+ },
48
+ ]
49
+ : [])
50
+ : []);
38
51
  const optional = categories.length > 1;
39
52
  const pick = (value, fallback) => value?.trim() || fallback;
40
53
  const buttons = doc.buttons ?? {};
@@ -52,6 +65,7 @@ export function toConsentConfig(doc, services, options) {
52
65
  policyVersion: policyVersion(categories, services),
53
66
  googleConsentMode: doc.googleConsentMode === "advanced" ? "advanced" : "basic",
54
67
  integrations,
68
+ storage,
55
69
  embeds: {
56
70
  title: pick(doc.embeds?.title, suggested.embeds.title),
57
71
  button: pick(doc.embeds?.button, suggested.embeds.button),
@@ -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.2.1",
4
4
  "description": "Cookie consent for Payload sites: banner texts, services and scans in Admin",
5
5
  "keywords": [
6
6
  "payload",