@simmalugnt-se/payload-consent 0.2.1 → 0.4.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.4.0
4
+
5
+ - `access.manage` says who works with cookies in Admin: the texts and services, the consent log,
6
+ policies, scans and evidence, starting scans and adding their findings (the `/start`,
7
+ `/:id/status` and `/classify` endpoints answer 403 to others), and the dashboard widget, which
8
+ others no longer see. Signed-in users by default, as before.
9
+
10
+ ## 0.3.0
11
+
12
+ Defaults and behaviour reviewed against the EDPB's guidelines and PTS's cookie decisions; the
13
+ findings are in `docs/research/consent-legal-questions.md`.
14
+
15
+ - **Breaking:** Google Consent Mode's advanced mode is gone, with the `googleConsentMode` field:
16
+ its pings before consent and after a refusal need consent too. Every integration waits for
17
+ consent. Generate types and migrate.
18
+ - **Breaking:** a site with only necessary storage shows no banner and records no choice, and the
19
+ banner description for such sites (`bannerDescriptionNecessaryOnly`) is gone. The settings link
20
+ still opens the dialog.
21
+ - **Breaking:** `ConsentFrame` takes a `provider`, which the placeholder names: "Innehållet visas
22
+ från {provider}. Om du tillåter {category} får {provider} uppgifter om ditt besök …".
23
+ - A choice expires after twelve months (`consentMonths`). c15t restored its expired cookie from
24
+ localStorage, so a choice never expired and one without the policy cookie skipped the policy
25
+ check; the plugin now forgets such a choice before c15t reads it.
26
+ - The banner names the site's optional categories (`{categories}` in its description) and says the
27
+ choice can be changed or withdrawn at any time; the dialog says withdraw too, and lists each
28
+ category's services and providers.
29
+ - Category descriptions say what happens instead of "improves your experience", and the cookie
30
+ table says the consent cookie holds a random ID linked to the consent log.
31
+ - A saved text equal to an earlier version's suggestion shows the current suggestion.
32
+ - Escape closes the settings dialog, as a click outside it does: unsaved switches are discarded
33
+ and, before a choice, the banner comes back. c15t's dialog ignored Escape.
34
+
3
35
  ## 0.2.1
4
36
 
5
37
  - Withdrawing a category removes the cookies and localStorage keys its Cookie services list on the
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,14 @@ 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.
76
102
 
77
103
  When a visitor withdraws a category, c15t reloads the page and the plugin removes the cookies
78
104
  and localStorage keys the category's services list as their own (not third-party), so list the
@@ -211,12 +237,13 @@ import { googleTagManager } from '@c15t/scripts/google-tag-manager'
211
237
  ```
212
238
 
213
239
  Embedded content, such as a video or a map, waits behind a placeholder until the visitor allows
214
- its category:
240
+ its category. The placeholder names the provider, who receives data about the visit once the
241
+ content loads:
215
242
 
216
243
  ```tsx
217
244
  import { ConsentFrame } from '@simmalugnt-se/payload-consent/client'
218
245
 
219
- <ConsentFrame category="functionality">
246
+ <ConsentFrame category="functionality" provider="YouTube">
220
247
  <iframe src="https://www.youtube-nocookie.com/embed/…" title="…" />
221
248
  </ConsentFrame>
222
249
  ```
@@ -234,10 +261,21 @@ import { CookieTable } from '@simmalugnt-se/payload-consent/client'
234
261
 
235
262
  It lists the services by category, each with its purpose, policy link and storage, and the
236
263
  banner's own consent storage first: `c15t`, a cookie and a localStorage key, and the cookie
237
- `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`.
238
265
 
239
266
  The global and the services are public to read by default (`access.read`), since the site shows
240
- them to everyone. `overrideGlobal` and `overrideServices` change them, for example to add hooks
267
+ them to everyone. `access.manage` says who works with cookies in Admin: changing the texts and
268
+ services, reading the consent log, the policies, the scans and their evidence, starting a scan and
269
+ adding its findings, and seeing the dashboard widget. It defaults to signed-in users; with roles,
270
+ pass the project's:
271
+
272
+ ```ts
273
+ consentPlugin({ access: { manage: ({ req }) => req.user?.role === "admin" } });
274
+ ```
275
+
276
+ `access.update` overrides `manage` for changing the global and the services only. The global
277
+ stays in the navigation for everyone who can read it; hide it with `overrideGlobal` and
278
+ `admin.hidden`. `overrideGlobal` and `overrideServices` change them, for example to add hooks
241
279
  that revalidate the site's cache.
242
280
 
243
281
  ## Look
@@ -0,0 +1,6 @@
1
+ import type { Access, PayloadRequest } from "payload";
2
+ import type { ConsentPluginOptions } from "./types.ts";
3
+ /** Who works with cookies in Admin (`access.manage`); signed-in users unless the host says. */
4
+ export declare function manageAccess(options: ConsentPluginOptions): Access;
5
+ /** Whether `manage` lets this request through; a query result counts as yes. */
6
+ export declare function canManage(options: ConsentPluginOptions, req: PayloadRequest): Promise<boolean>;
package/dist/access.js ADDED
@@ -0,0 +1,9 @@
1
+ const signedIn = ({ req }) => Boolean(req.user);
2
+ /** Who works with cookies in Admin (`access.manage`); signed-in users unless the host says. */
3
+ export function manageAccess(options) {
4
+ return options.access?.manage ?? signedIn;
5
+ }
6
+ /** Whether `manage` lets this request through; a query result counts as yes. */
7
+ export async function canManage(options, req) {
8
+ return Boolean(req.user && (await manageAccess(options)({ req })));
9
+ }
@@ -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
+ }
package/dist/evidence.js CHANGED
@@ -1,7 +1,7 @@
1
+ import { manageAccess } from "./access.js";
1
2
  import { CONSENT_SCAN_EVIDENCE, CONSENT_SCANS, DEFAULT_KEEP_EVIDENCE, } from "./types.js";
2
3
  /** What the scanner sends: `<state>.pdf`, `<state>-2.pdf` for a later batch, `<state>.har.gz`. */
3
4
  const FILE_NAME = /^([a-z0-9-]{1,40}?)(?:-(\d+))?\.(pdf|har\.gz)$/;
4
- const signedIn = ({ req }) => Boolean(req.user);
5
5
  /**
6
6
  * WEC's evidence per scan: its PDF report and the network traffic (HAR, gzipped) for each consent
7
7
  * state. On a host without a persistent disk, such as Vercel, add this collection to the storage
@@ -20,7 +20,12 @@ export function evidenceCollection(options) {
20
20
  group: false,
21
21
  defaultColumns: ["filename", "scan", "state", "kind", "createdAt"],
22
22
  },
23
- access: { read: signedIn, create: () => false, update: () => false, delete: signedIn },
23
+ access: {
24
+ read: manageAccess(options),
25
+ create: () => false,
26
+ update: () => false,
27
+ delete: manageAccess(options),
28
+ },
24
29
  upload: { mimeTypes: ["application/pdf", "application/gzip", "application/x-gzip"] },
25
30
  timestamps: true,
26
31
  fields: [
@@ -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,6 +10,7 @@ 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";
14
15
  import { cookieDomains, matchesStorageName, subjectIdFromCookie, withdrawnStorage, } from "../withdrawal.js";
15
16
  /** A button that opens the settings dialog, for the site's footer. Render it inside `ConsentProvider`. */
@@ -51,14 +52,15 @@ const factories = {
51
52
  hotjar: (siteId) => hotjar({ siteId }),
52
53
  };
53
54
  /**
54
- * The services the plugin loads, each in its service's category. In basic consent mode nothing
55
- * 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.
56
58
  */
57
59
  export function integrationScripts(config) {
58
60
  return config.integrations.map(({ key, id, category }) => ({
59
61
  ...factories[key](id, category),
60
62
  category,
61
- ...(config.googleConsentMode === "basic" ? { alwaysLoad: false } : {}),
63
+ alwaysLoad: false,
62
64
  }));
63
65
  }
64
66
  const ConfigContext = createContext(null);
@@ -66,12 +68,13 @@ const ConfigContext = createContext(null);
66
68
  export function ConsentProvider({ config, scripts, children }) {
67
69
  if (!config.enabled)
68
70
  return _jsx(_Fragment, { children: children });
69
- forgetOutdatedConsent(config.policyVersion);
71
+ forgetOutdatedConsent(config);
70
72
  clearAfterWithdrawal(config);
71
73
  const options = {
72
74
  mode: "offline",
73
75
  overrides: { country: "SE" },
74
76
  consentCategories: config.categories,
77
+ storageConfig: { defaultExpiryDays: config.consentDays },
75
78
  scripts: [...integrationScripts(config), ...(scripts ?? [])],
76
79
  legalLinks: config.legalLinks,
77
80
  noStyle: true,
@@ -88,7 +91,7 @@ export function ConsentProvider({ config, scripts, children }) {
88
91
  // clear the withdrawn services' storage.
89
92
  onBeforeConsentRevocationReload: ({ preferences }) => {
90
93
  const consents = preferences;
91
- writePolicy(config.policyVersion);
94
+ writePolicy(config);
92
95
  recordChoice(config, subjectIdFromCookie(document.cookie), consents);
93
96
  clearWithdrawnStorage(config, consents);
94
97
  // A tag still running while the page unloads can write its cookie again: clear once more
@@ -102,9 +105,10 @@ export function ConsentProvider({ config, scripts, children }) {
102
105
  },
103
106
  },
104
107
  };
105
- // 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.
106
110
  const necessaryOnly = config.categories.length === 1;
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 })] }) }));
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 })] }) }));
108
112
  }
109
113
  /** Set by a withdrawal just before c15t reloads the page; read once by the next page load. */
110
114
  const WITHDRAWN_KEY = "c15t-withdrawn";
@@ -133,16 +137,34 @@ function readPolicy() {
133
137
  return match ? decodeURIComponent(match[1] ?? "") : null;
134
138
  }
135
139
  const checkedPolicies = new Set();
140
+ function readStoredChoice() {
141
+ try {
142
+ return window.localStorage.getItem("c15t");
143
+ }
144
+ catch {
145
+ return null;
146
+ }
147
+ }
136
148
  /**
137
- * Removes a choice made under another policy version before c15t reads it, so nothing it allowed
138
- * loads before the visitor is asked again. Runs once per page load and version: a choice saved on
139
- * 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.
140
153
  */
141
- function forgetOutdatedConsent(version) {
154
+ function forgetOutdatedConsent(config) {
155
+ const version = config.policyVersion;
142
156
  if (typeof document === "undefined" || checkedPolicies.has(version))
143
157
  return;
144
158
  checkedPolicies.add(version);
145
- 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)
146
168
  return;
147
169
  document.cookie = "c15t=; Path=/; Max-Age=0";
148
170
  try {
@@ -152,15 +174,18 @@ function forgetOutdatedConsent(version) {
152
174
  // Without storage access there is nothing stored to remove.
153
175
  }
154
176
  }
155
- function writePolicy(version) {
177
+ function writePolicy(config) {
156
178
  const secure = window.location.protocol === "https:" ? "; Secure" : "";
157
- 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}`;
158
180
  }
159
181
  /** The last choice posted from this page: a withdrawal reaches both the callback and the effect. */
160
182
  let lastRecorded;
161
- /** Posts a saved choice to the site's consent records, with its policy version, once. */
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
+ */
162
187
  function recordChoice(config, subjectId, consents) {
163
- if (!config.recordUrl || !subjectId)
188
+ if (!config.recordUrl || !subjectId || config.categories.length === 1)
164
189
  return;
165
190
  const choices = Object.fromEntries(config.categories.map((category) => [category, Boolean(consents[category])]));
166
191
  const key = JSON.stringify([subjectId, choices]);
@@ -223,7 +248,7 @@ function ConsentRecorder({ config }) {
223
248
  useEffect(() => {
224
249
  if (!savedAt || savedAt < mountedAt.current)
225
250
  return;
226
- writePolicy(config.policyVersion);
251
+ writePolicy(config);
227
252
  recordChoice(config, consentInfo?.subjectId, consents);
228
253
  }, [savedAt]);
229
254
  return null;
@@ -231,32 +256,42 @@ function ConsentRecorder({ config }) {
231
256
  /** c15t's dialog; a click on the backdrop discards unsaved toggles and returns to the banner. */
232
257
  function SettingsDialog() {
233
258
  const { consents, selectedConsents, setSelectedConsent, hasConsented, setActiveUI } = useConsentManager();
234
- function dismiss(event) {
235
- if (event.target !== event.currentTarget)
236
- return;
259
+ function discardAndReturn() {
237
260
  for (const name of Object.keys(selectedConsents))
238
261
  setSelectedConsent(name, consents[name] ?? false);
239
262
  setActiveUI(hasConsented() ? "none" : "banner");
240
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
+ }
241
275
  // With only necessary storage there is nothing to reject; c15t's dialog has no option to drop
242
276
  // the button, so a class hides it (see consent.css).
243
277
  const necessaryOnly = useContext(ConfigContext)?.categories.length === 1;
244
- 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 }) }));
245
279
  }
246
280
  /**
247
281
  * Embedded content, such as a video or a map, that is not mounted until the visitor allows its
248
282
  * category. Until then a placeholder offers to allow it. Without the banner, the content shows.
249
283
  */
250
- export function ConsentFrame({ category, children, className }) {
284
+ export function ConsentFrame({ category, provider, children, className }) {
251
285
  const config = useContext(ConfigContext);
252
286
  if (!config)
253
287
  return _jsx(_Fragment, { children: children });
254
- 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 }));
255
289
  }
256
- function EmbedPlaceholder({ category, config }) {
290
+ function EmbedPlaceholder({ category, config, provider, }) {
257
291
  const { setConsent } = useConsentManager();
258
- const title = config.messages.consentTypes?.[category]?.title ?? category;
259
- 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) })] }));
260
295
  }
261
296
  /** The cookie services by category, from `getCookieTable`, for the site's cookie page. */
262
297
  export function CookieTable({ data, heading }) {
package/dist/global.js CHANGED
@@ -1,4 +1,5 @@
1
- import { defaultTexts, OPTIONAL_CATEGORIES } from "./defaults.js";
1
+ import { manageAccess } from "./access.js";
2
+ import { defaultTexts, isFormerSuggestion, OPTIONAL_CATEGORIES, } from "./defaults.js";
2
3
  import { CONSENT_GLOBAL } from "./types.js";
3
4
  export const categoryLabels = {
4
5
  necessary: { en: "Necessary", sv: "Nödvändiga" },
@@ -19,6 +20,12 @@ function text(name, label, suggestion, extra = {}) {
19
20
  label,
20
21
  localized: true,
21
22
  defaultValue: ({ locale }) => suggestion(defaultTexts(locale)),
23
+ // A suggestion saved by an earlier version shows as the current one, as on the site.
24
+ hooks: {
25
+ afterRead: [
26
+ ({ value, req }) => isFormerSuggestion(value) ? suggestion(defaultTexts(req.locale)) : value,
27
+ ],
28
+ },
22
29
  admin: {
23
30
  ...(extra.width ? { width: extra.width } : {}),
24
31
  ...(extra.description ? { description: extra.description } : {}),
@@ -48,7 +55,10 @@ export function consentGlobal(options, { usersSlug, schedule }) {
48
55
  slug: CONSENT_GLOBAL,
49
56
  label: { en: "Cookies", sv: "Cookies" },
50
57
  admin: { group: options.group ?? { en: "Settings", sv: "Inställningar" } },
51
- access: { read: () => true, ...options.access },
58
+ access: {
59
+ read: options.access?.read ?? (() => true),
60
+ update: options.access?.update ?? manageAccess(options),
61
+ },
52
62
  fields: [
53
63
  {
54
64
  type: "tabs",
@@ -60,9 +70,17 @@ export function consentGlobal(options, { usersSlug, schedule }) {
60
70
  sv: "Det besökaren ser innan hen har valt. Godkänn och avvisa visas alltid sida vid sida.",
61
71
  },
62
72
  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 }),
73
+ text("bannerTitle", { en: "Title", sv: "Rubrik" }, (t) => t.bannerTitle, {
74
+ condition: hasOptional,
75
+ }),
76
+ text("bannerDescription", { en: "Description", sv: "Beskrivning" }, (t) => t.bannerDescription, {
77
+ textarea: true,
78
+ condition: hasOptional,
79
+ description: {
80
+ 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.",
81
+ 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.",
82
+ },
83
+ }),
66
84
  {
67
85
  name: "buttons",
68
86
  type: "group",
@@ -106,8 +124,8 @@ export function consentGlobal(options, { usersSlug, schedule }) {
106
124
  label: { en: "Embedded content", sv: "Inbäddat innehåll" },
107
125
  admin: {
108
126
  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.",
127
+ 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.",
128
+ 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
129
  },
112
130
  },
113
131
  fields: [
@@ -260,8 +278,8 @@ export function consentGlobal(options, { usersSlug, schedule }) {
260
278
  admin: {
261
279
  readOnly: true,
262
280
  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.",
281
+ 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.",
282
+ 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
283
  },
266
284
  },
267
285
  options: OPTIONAL_CATEGORIES.map((value) => ({
@@ -269,34 +287,6 @@ export function consentGlobal(options, { usersSlug, schedule }) {
269
287
  label: categoryLabels[value],
270
288
  })),
271
289
  },
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
290
  ...(legal
301
291
  ? ["privacyPolicy", "cookiePolicy"].map((name) => ({
302
292
  name,
package/dist/records.js CHANGED
@@ -1,7 +1,7 @@
1
+ import { manageAccess } from "./access.js";
1
2
  import { CATEGORIES } from "./defaults.js";
2
3
  import { readConsent, toConsentConfig } from "./site-config.js";
3
4
  import { CONSENT_POLICIES, CONSENT_RECORDS, DEFAULT_RETENTION_DAYS, } from "./types.js";
4
- const signedIn = ({ req }) => Boolean(req.user);
5
5
  const nobody = () => false;
6
6
  /** Checks a posted record; returns why it is refused, or the record. */
7
7
  export function parseRecord(body) {
@@ -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,
@@ -133,7 +132,7 @@ export function recordsCollection(options) {
133
132
  sv: `Varje val en besökare har sparat, med policyn det gavs för. Identifieras bara med det slumpade ID:t i besökarens c15t-cookie; ingen IP-adress eller webbläsarinformation. Sparas i ${retention} dagar.`,
134
133
  },
135
134
  },
136
- access: { read: signedIn, create: nobody, update: nobody, delete: nobody },
135
+ access: { read: manageAccess(options), create: nobody, update: nobody, delete: nobody },
137
136
  endpoints: [recordEndpoint(options)],
138
137
  timestamps: true,
139
138
  fields: [
@@ -181,7 +180,7 @@ export function policiesCollection(options) {
181
180
  sv: "Det besökarna fick se, per policyversion och språk: kategorier, tjänster och texter. Sparas med det första valet för varje version.",
182
181
  },
183
182
  },
184
- access: { read: signedIn, create: nobody, update: nobody, delete: nobody },
183
+ access: { read: manageAccess(options), create: nobody, update: nobody, delete: nobody },
185
184
  timestamps: true,
186
185
  fields: [
187
186
  {
@@ -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
+ }
package/dist/scans.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { timingSafeEqual } from "node:crypto";
2
+ import { canManage, manageAccess } from "./access.js";
2
3
  import { evaluateScan, } from "./evaluate.js";
3
4
  import { evidenceEndpoint } from "./evidence.js";
4
5
  import { notifyScan } from "./notify.js";
@@ -34,7 +35,6 @@ export function scanStates(config, now = Date.now()) {
34
35
  states.push(state(`only-${category}`, [category]));
35
36
  return states;
36
37
  }
37
- const signedIn = ({ req }) => Boolean(req.user);
38
38
  function sameToken(given, expected) {
39
39
  const a = Buffer.from(given);
40
40
  const b = Buffer.from(expected);
@@ -167,6 +167,8 @@ function endpoints(options) {
167
167
  handler: async (req) => {
168
168
  if (!req.user)
169
169
  return Response.json({ error: "Sign in" }, { status: 401 });
170
+ if (!(await canManage(options, req)))
171
+ return Response.json({ error: "Not allowed" }, { status: 403 });
170
172
  const body = (await req.json?.().catch(() => null));
171
173
  const started = await startScan({ payload: req.payload, options, url: body?.url, req });
172
174
  return "error" in started
@@ -236,6 +238,8 @@ function endpoints(options) {
236
238
  handler: async (req) => {
237
239
  if (!req.user)
238
240
  return Response.json({ error: "Sign in" }, { status: 401 });
241
+ if (!(await canManage(options, req)))
242
+ return Response.json({ error: "Not allowed" }, { status: 403 });
239
243
  const scan = (await req.payload.findByID({
240
244
  collection: CONSENT_SCANS,
241
245
  id: req.routeParams?.id,
@@ -274,6 +278,8 @@ function endpoints(options) {
274
278
  handler: async (req) => {
275
279
  if (!req.user)
276
280
  return Response.json({ error: "Sign in" }, { status: 401 });
281
+ if (!(await canManage(options, req)))
282
+ return Response.json({ error: "Not allowed" }, { status: 403 });
277
283
  const body = (await req.json?.().catch(() => null));
278
284
  const kind = body?.kind;
279
285
  const name = body?.name?.trim();
@@ -362,7 +368,12 @@ export function scansCollection(options) {
362
368
  sv: "Varje skanning av den publicerade webbplatsen. Starta en under Cookies → Skanning.",
363
369
  },
364
370
  },
365
- access: { read: signedIn, create: () => false, update: () => false, delete: signedIn },
371
+ access: {
372
+ read: manageAccess(options),
373
+ create: () => false,
374
+ update: () => false,
375
+ delete: manageAccess(options),
376
+ },
366
377
  endpoints: endpoints(options),
367
378
  hooks: {
368
379
  beforeDelete: [
package/dist/services.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { manageAccess } from "./access.js";
1
2
  import { CATEGORIES, OPTIONAL_CATEGORIES } from "./defaults.js";
2
3
  import { categoryLabels } from "./global.js";
3
4
  import { INTEGRATIONS } from "./integrations.js";
@@ -59,7 +60,12 @@ export function servicesCollection(options) {
59
60
  sv: "Varje tjänst som sparar något i besökarens webbläsare eller som webbplatsen kontaktar. Bannerns kategorier och cookietabellen följer listan.",
60
61
  },
61
62
  },
62
- access: { read: () => true, ...options.access },
63
+ access: {
64
+ read: options.access?.read ?? (() => true),
65
+ create: manageAccess(options),
66
+ update: options.access?.update ?? manageAccess(options),
67
+ delete: manageAccess(options),
68
+ },
63
69
  hooks: {
64
70
  afterChange: [afterChange],
65
71
  afterDelete: [async ({ req }) => syncCategories(req)],
@@ -9,7 +9,6 @@ export type ConsentDocument = {
9
9
  categories?: string[] | null;
10
10
  bannerTitle?: string | null;
11
11
  bannerDescription?: string | null;
12
- bannerDescriptionNecessaryOnly?: string | null;
13
12
  buttons?: Partial<Record<string, string | null>> | null;
14
13
  dialog?: Partial<Record<string, string | null>> | null;
15
14
  categoryTexts?: Partial<Record<string, {
@@ -20,7 +19,6 @@ export type ConsentDocument = {
20
19
  title?: string | null;
21
20
  button?: string | null;
22
21
  } | null;
23
- googleConsentMode?: string | null;
24
22
  privacyPolicy?: unknown;
25
23
  cookiePolicy?: unknown;
26
24
  };
@@ -54,19 +52,22 @@ export type ConsentConfig = {
54
52
  legalLinks?: NonNullable<ConsentManagerOptions["legalLinks"]>;
55
53
  /** c15t's texts for `locale`. */
56
54
  messages: Partial<Translations>;
57
- /** Basic waits for consent; advanced lets tags that support it load at once in a denied state. */
58
- googleConsentMode: "basic" | "advanced";
59
- /** Services the plugin loads through c15t. */
55
+ /** Services the plugin loads through c15t, none before consent. */
60
56
  integrations: {
61
57
  key: IntegrationKey;
62
58
  id: string;
63
59
  category: Category;
64
60
  }[];
65
- /** 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
+ */
66
65
  embeds: {
67
66
  title: string;
68
67
  button: string;
69
68
  };
69
+ /** How long a choice is kept before the visitor is asked again. */
70
+ consentDays: number;
70
71
  /**
71
72
  * Changes when the categories or the services' cookies change: visitors who chose under an older
72
73
  * version are asked again.
@@ -83,6 +84,8 @@ export type ConsentConfig = {
83
84
  type Options = {
84
85
  locale: string;
85
86
  legalUrl?: (doc: Record<string, unknown>, locale: string) => string;
87
+ /** See `ConsentPluginOptions.consentMonths`. */
88
+ consentMonths?: number;
86
89
  };
87
90
  /** A short hash of what a visitor consents to: the categories and each service's storage. */
88
91
  export declare function policyVersion(categories: Category[], services: ServiceDocument[]): string;
@@ -128,7 +131,7 @@ export type CookieTableData = {
128
131
  }[];
129
132
  };
130
133
  /** Turns the services into the cookie table, with the consent storage itself as necessary. */
131
- 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;
132
135
  /** Reads what the cookie table block shows, in a locale. */
133
136
  export declare function getCookieTable(args: ReadArgs): Promise<CookieTableData>;
134
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.
@@ -49,7 +66,22 @@ export function toConsentConfig(doc, services, options) {
49
66
  : [])
50
67
  : []);
51
68
  const optional = categories.length > 1;
52
- 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
+ };
53
85
  const buttons = doc.buttons ?? {};
54
86
  const dialog = doc.dialog ?? {};
55
87
  const legalLinks = {};
@@ -63,7 +95,7 @@ export function toConsentConfig(doc, services, options) {
63
95
  locale: options.locale,
64
96
  categories,
65
97
  policyVersion: policyVersion(categories, services),
66
- googleConsentMode: doc.googleConsentMode === "advanced" ? "advanced" : "basic",
98
+ consentDays: consentDays(options.consentMonths ?? DEFAULT_CONSENT_MONTHS),
67
99
  integrations,
68
100
  storage,
69
101
  embeds: {
@@ -83,9 +115,8 @@ export function toConsentConfig(doc, services, options) {
83
115
  },
84
116
  cookieBanner: {
85
117
  title: pick(doc.bannerTitle, suggested.bannerTitle),
86
- description: optional
87
- ? pick(doc.bannerDescription, suggested.bannerDescription)
88
- : 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),
89
120
  },
90
121
  consentManagerDialog: {
91
122
  title: pick(dialog.title, suggested.dialog.title),
@@ -93,17 +124,13 @@ export function toConsentConfig(doc, services, options) {
93
124
  ? pick(dialog.description, suggested.dialog.description)
94
125
  : pick(dialog.descriptionNecessaryOnly, suggested.dialog.descriptionNecessaryOnly),
95
126
  },
96
- consentTypes: Object.fromEntries(CATEGORIES.map((category) => {
97
- const own = doc.categoryTexts?.[category];
98
- const fallback = suggested.categoryTexts[category];
99
- return [
100
- category,
101
- {
102
- title: pick(own?.title, fallback.title),
103
- description: pick(own?.description, fallback.description),
104
- },
105
- ];
106
- })),
127
+ consentTypes: Object.fromEntries(CATEGORIES.map((category) => [
128
+ category,
129
+ {
130
+ title: categoryTexts[category].title,
131
+ description: `${categoryTexts[category].description}${serviceList(category)}`,
132
+ },
133
+ ])),
107
134
  },
108
135
  };
109
136
  }
@@ -147,6 +174,7 @@ export async function getConsentConfig(args) {
147
174
  const { locale, doc, services } = await readConsent(args, legalPages ? 1 : 0);
148
175
  const config = toConsentConfig(doc, services, {
149
176
  locale,
177
+ consentMonths: options?.consentMonths,
150
178
  legalUrl: legalPages ? (page, pageLocale) => legalPages.url(page, pageLocale) : undefined,
151
179
  });
152
180
  if (options?.records === false)
@@ -155,15 +183,18 @@ export async function getConsentConfig(args) {
155
183
  return { ...config, recordUrl: `${serverURL ?? ""}${routes.api}/${CONSENT_RECORDS}/record` };
156
184
  }
157
185
  /** Turns the services into the cookie table, with the consent storage itself as necessary. */
158
- export function toCookieTable(doc, services, locale) {
186
+ export function toCookieTable(doc, services, locale, consentMonths = DEFAULT_CONSENT_MONTHS) {
159
187
  const config = toConsentConfig(doc, services, { locale });
160
188
  const suggested = defaultTexts(locale);
161
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));
162
194
  const text = (value) => value?.trim() || undefined;
163
195
  return {
164
196
  labels,
165
197
  categories: config.categories.map((key) => {
166
- const type = config.messages.consentTypes?.[key];
167
198
  const rows = services
168
199
  .filter((service) => service.category === key)
169
200
  .map((service) => ({
@@ -189,14 +220,14 @@ export function toCookieTable(doc, services, locale) {
189
220
  ...["cookie", "localStorage"].map((storageType) => ({
190
221
  name: "c15t",
191
222
  type: storageType,
192
- duration: labels.consentDuration,
223
+ duration: consentDuration,
193
224
  thirdParty: false,
194
225
  description: undefined,
195
226
  })),
196
227
  {
197
228
  name: POLICY_COOKIE,
198
229
  type: "cookie",
199
- duration: labels.consentDuration,
230
+ duration: consentDuration,
200
231
  thirdParty: false,
201
232
  description: undefined,
202
233
  },
@@ -204,8 +235,8 @@ export function toCookieTable(doc, services, locale) {
204
235
  });
205
236
  return {
206
237
  key,
207
- title: type?.title ?? key,
208
- description: type?.description ?? "",
238
+ title: categoryTexts[key].title,
239
+ description: categoryTexts[key].description,
209
240
  services: rows,
210
241
  };
211
242
  }),
@@ -214,5 +245,6 @@ export function toCookieTable(doc, services, locale) {
214
245
  /** Reads what the cookie table block shows, in a locale. */
215
246
  export async function getCookieTable(args) {
216
247
  const { locale, doc, services } = await readConsent(args);
217
- return toCookieTable(doc, services, locale);
248
+ const options = args.payload.config.custom?.consent;
249
+ return toCookieTable(doc, services, locale, options?.consentMonths);
218
250
  }
package/dist/types.d.ts CHANGED
@@ -11,10 +11,17 @@ export type ConsentPluginOptions = {
11
11
  collection: CollectionSlug;
12
12
  url: (doc: Record<string, unknown>, locale: string | undefined) => string;
13
13
  };
14
- /** Read access from outside Admin, such as the site's own API. Defaults to public. */
14
+ /**
15
+ * `read`: the global's and services' reads from outside Admin, such as the site's own API;
16
+ * public by default. `manage`: who works with cookies in Admin: changes the texts and services,
17
+ * reads the consent log, policies, scans and their evidence, starts scans and adds their
18
+ * findings, and sees the dashboard widget. Signed-in users by default. `update` overrides
19
+ * `manage` for changing the global and services only.
20
+ */
15
21
  access?: {
16
22
  read?: Access;
17
23
  update?: Access;
24
+ manage?: Access;
18
25
  };
19
26
  /** Change the global, for example to add hooks that revalidate the site's cache. */
20
27
  overrideGlobal?: (global: GlobalConfig) => GlobalConfig;
@@ -25,6 +32,11 @@ export type ConsentPluginOptions = {
25
32
  records?: false | {
26
33
  retentionDays?: number;
27
34
  };
35
+ /**
36
+ * How many months a visitor's choice is kept before the banner asks again. Defaults to 12.
37
+ * Changes and withdrawals are possible at any time through `ConsentSettingsLink`.
38
+ */
39
+ consentMonths?: number;
28
40
  /**
29
41
  * The consent scanner (`consent-scanner`) that scans the published site from Admin. Without it,
30
42
  * the Scan tab explains how to set one up.
@@ -5,4 +5,4 @@ import "../styles/admin.css";
5
5
  * the Cookies global. A panel of our own like content health's: Payload's `Card` is a link to one
6
6
  * collection, not a status.
7
7
  */
8
- export declare function ConsentScanWidget({ req }: WidgetServerProps): Promise<import("react").JSX.Element>;
8
+ export declare function ConsentScanWidget({ req }: WidgetServerProps): Promise<import("react").JSX.Element | null>;
@@ -1,5 +1,6 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Button, Pill } from "@payloadcms/ui";
3
+ import { canManage } from "../access.js";
3
4
  import { nextScan } from "../schedule.js";
4
5
  import { CONSENT_GLOBAL, CONSENT_SCANS } from "../types.js";
5
6
  import "../styles/admin.css";
@@ -41,6 +42,10 @@ const COPY = {
41
42
  * collection, not a status.
42
43
  */
43
44
  export async function ConsentScanWidget({ req }) {
45
+ // Only for those who work with cookies: the scans are theirs to read.
46
+ const options = (req.payload.config.custom?.consent ?? {});
47
+ if (!(await canManage(options, req)))
48
+ return null;
44
49
  const language = req.i18n?.language === "sv" ? "sv" : "en";
45
50
  const copy = COPY[language];
46
51
  const [{ docs }, global] = await Promise.all([
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simmalugnt-se/payload-consent",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "description": "Cookie consent for Payload sites: banner texts, services and scans in Admin",
5
5
  "keywords": [
6
6
  "payload",