@simmalugnt-se/payload-consent 0.0.0-stage → 0.1.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.
Files changed (44) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/LICENSE +21 -0
  3. package/README.md +238 -2
  4. package/dist/admin/ScanPanel.d.ts +3 -0
  5. package/dist/admin/ScanPanel.js +232 -0
  6. package/dist/block.d.ts +6 -0
  7. package/dist/block.js +27 -0
  8. package/dist/defaults.d.ts +56 -0
  9. package/dist/defaults.js +137 -0
  10. package/dist/evaluate.d.ts +106 -0
  11. package/dist/evaluate.js +101 -0
  12. package/dist/evidence.d.ts +12 -0
  13. package/dist/evidence.js +113 -0
  14. package/dist/exports/admin.d.ts +1 -0
  15. package/dist/exports/admin.js +1 -0
  16. package/dist/exports/client.d.ts +37 -0
  17. package/dist/exports/client.js +177 -0
  18. package/dist/exports/rsc.d.ts +1 -0
  19. package/dist/exports/rsc.js +1 -0
  20. package/dist/global.d.ts +14 -0
  21. package/dist/global.js +272 -0
  22. package/dist/index.d.ts +13 -0
  23. package/dist/index.js +75 -0
  24. package/dist/integrations.d.ts +40 -0
  25. package/dist/integrations.js +32 -0
  26. package/dist/notify.d.ts +15 -0
  27. package/dist/notify.js +86 -0
  28. package/dist/records.d.ts +15 -0
  29. package/dist/records.js +197 -0
  30. package/dist/scans.d.ts +37 -0
  31. package/dist/scans.js +423 -0
  32. package/dist/schedule.d.ts +17 -0
  33. package/dist/schedule.js +18 -0
  34. package/dist/services.d.ts +8 -0
  35. package/dist/services.js +257 -0
  36. package/dist/site-config.d.ts +128 -0
  37. package/dist/site-config.js +204 -0
  38. package/dist/styles/admin.css +144 -0
  39. package/dist/styles/consent.css +296 -0
  40. package/dist/types.d.ts +65 -0
  41. package/dist/types.js +17 -0
  42. package/dist/widget/ConsentScanWidget.d.ts +8 -0
  43. package/dist/widget/ConsentScanWidget.js +99 -0
  44. package/package.json +76 -3
package/CHANGELOG.md ADDED
@@ -0,0 +1,39 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ - A Cookies global with the banner's texts, localized and prefilled with Swedish and English
6
+ suggestions, the site's optional categories and links to the privacy and cookie policy pages.
7
+ - `getConsentConfig` reads the global for a locale; `ConsentProvider` shows the banner and settings
8
+ dialog through c15t 2.2.1, and `ConsentSettingsLink` reopens the dialog. The banner, dialog and
9
+ styles come from `@simmalugnt-se/consent-ui` 0.2.1, copied in rather than depended on.
10
+ - Cookie services (`consent-services`): category, purpose, policy link, cookies and storage keys,
11
+ and hosts per service. The banner's categories follow the services.
12
+ - Services can be loaded by the plugin through eight c15t integrations (Google Tag Manager,
13
+ Google Analytics 4, Meta Pixel, LinkedIn, TikTok, Microsoft Ads, Clarity, Hotjar), after consent.
14
+ Google Consent Mode is basic by default: nothing loads before consent.
15
+ - `cookieTableBlock`, `getCookieTable` and `CookieTable` list the services by category, with the
16
+ banner's own consent storage.
17
+ - `ConsentFrame` keeps embedded content behind a placeholder until its category is allowed.
18
+ - Banner texts are optional: an empty text, or one never saved in a language, shows that
19
+ language's suggestion.
20
+ - A consent log: each saved choice is recorded in `consent-records` with c15t's random visitor ID
21
+ and the policy version, and `consent-policies` keeps what visitors were shown per version and
22
+ language. No IP address or browser details; kept three years by default (`records`).
23
+ - Visitors are asked again when the categories or the services' cookies change. The version they
24
+ chose under is kept in the `c15t-policy` cookie, so a scanner can preset a consent state, and an
25
+ outdated choice is removed before c15t reads it: nothing it allowed loads first.
26
+ - Scans from Admin: a Scan tab in the Cookies global starts a scan by `consent-scanner` in every
27
+ consent state, follows it in the queue, and lists what it found, judged against the Cookie
28
+ services. Unknown findings become part of a service in one step, with the Open Cookie
29
+ Database's suggestion. Scans are kept in `consent-scans` (`scanner` option).
30
+ - A service's purpose is optional, so a service saved in one language stays editable in the others.
31
+ - A monthly scan through Payload's jobs queue (`consentScan`), on a day and at a time picked from
32
+ the site's address so sites sharing a scanner spread over the month. It runs when the host's
33
+ cron calls `/api/payload-jobs/run`; Cookies → Scan turns it off.
34
+ - Email about a scan that fails, needs action, has findings outside the services or finds
35
+ something new, to the users chosen under Cookies → Scan, through the host's email adapter.
36
+ - A dashboard widget, Cookie scan, with the latest result, red when something needs handling.
37
+ - Evidence: WEC's PDF report and network traffic (HAR, gzipped) per consent state, sent by the
38
+ scanner after each result and kept in `consent-scan-evidence` for the last twelve scans
39
+ (`scanner.keepEvidence`). Deleting a scan deletes its evidence.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Simmalugnt AB
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,239 @@
1
- # Temporary Holding Version
1
+ # Payload consent
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A cookie banner for Payload sites, with its texts and the site's cookie services edited in Admin
4
+ like other content. Built on [c15t](https://c15t.com) 2.2.1: no external consent script, nothing
5
+ loaded from a third party. Consent records and scans by our own scanner; see `docs/plans/consent.md` in the repository.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ pnpm add @simmalugnt-se/payload-consent @c15t/react@2.2.1
11
+ ```
12
+
13
+ ```ts
14
+ import { consentPlugin } from '@simmalugnt-se/payload-consent'
15
+
16
+ export default buildConfig({
17
+ // ...
18
+ plugins: [
19
+ consentPlugin({
20
+ // Optional: pick the privacy and cookie policy pages in Admin.
21
+ legalPages: { collection: 'pages', url: (doc) => `/${doc.slug}` },
22
+ }),
23
+ ],
24
+ })
25
+ ```
26
+
27
+ The plugin adds a `consent` global (Cookies) and the collections `consent-services` (Cookie
28
+ services), `consent-records` and `consent-policies` (the consent log), `consent-scans` and
29
+ `consent-scan-evidence`, all under Settings, a jobs task (`consentScan`) and a dashboard widget. Generate types, then create and apply a migration with the
30
+ project's usual commands.
31
+
32
+ ## The Cookies global
33
+
34
+ - **Banner**: title, description, buttons, the settings dialog and a title and description per
35
+ category. Every text is localized and prefilled with a suggestion in the language being edited
36
+ (Swedish or English; other languages get English). The description and the accept button have
37
+ one version for sites with optional categories and one for sites with only necessary storage;
38
+ Admin shows the one that applies. The placeholder for embedded content has its own text and
39
+ button.
40
+ - **Settings**: whether the banner is shown, the optional categories (read-only: they follow the
41
+ services), Google Consent Mode and, with `legalPages`, the policy pages.
42
+
43
+ Texts are optional: an empty one shows the suggestion for the visitor's language.
44
+
45
+ ## Cookie services
46
+
47
+ One document per service the site uses: name, provider, category, purpose, the provider's privacy
48
+ policy, the cookies and storage keys it sets (with how long they are kept and whether they are
49
+ third-party) and the hosts it contacts. The banner's categories are the services' categories.
50
+
51
+ A service is loaded either by the site's code, which must then wait for consent itself, or by the
52
+ plugin through one of c15t's integrations: Google Tag Manager, Google Analytics 4, Meta Pixel,
53
+ LinkedIn Insight Tag, TikTok Pixel, Microsoft Ads (UET), Microsoft Clarity and Hotjar. The editor
54
+ picks the integration and enters its ID; the script then loads in the service's category, after
55
+ consent.
56
+
57
+ **Google Consent Mode**: basic, the default, loads nothing before consent. Advanced lets the tags
58
+ c15t supports load at once in a denied state, which sends cookieless measurements to the provider
59
+ before the visitor has chosen. Pick it only when that has been assessed as acceptable.
60
+
61
+ The rules that keep the banner lawful are not settings: rejecting is always as easy as accepting,
62
+ and the banner and dialog work with a keyboard and a screen reader.
63
+
64
+ ## Consent records
65
+
66
+ Every choice a visitor saves is posted to `/api/consent-records/record` and kept in
67
+ `consent-records`: the random visitor ID from c15t's cookie (`sub_…`), the choices, the policy
68
+ version, the language and the page. No IP address or browser details. The first choice under each
69
+ policy version and language also saves what the visitor was shown in `consent-policies`:
70
+ categories, services and texts. Records are kept for three years (`records.retentionDays`) and
71
+ readable by signed-in users only; `records: false` turns the log off.
72
+
73
+ The policy version is a hash of the categories and each service's cookies and storage keys. When
74
+ it changes, for example because a service gains a cookie, visitors are asked again. Rewording a
75
+ text does not change it.
76
+
77
+ The site keeps c15t in offline mode: the banner works without the server, and a record that cannot
78
+ be posted only leaves the log without that entry.
79
+
80
+ ## Scans
81
+
82
+ The Scan tab scans the published site with `consent-scanner`, a separate repository and a small
83
+ service of our own that runs the EDPS Website Evidence Collector. One scanner serves many
84
+ sites; give the plugin its address and this site's token:
85
+
86
+ ```ts
87
+ consentPlugin({
88
+ scanner: {
89
+ url: process.env.CONSENT_SCANNER_URL,
90
+ token: process.env.CONSENT_SCANNER_TOKEN,
91
+ // Only when the scanner cannot reach serverURL, e.g. Docker beside a dev server:
92
+ // callbackBaseUrl: 'http://host.docker.internal:3000',
93
+ },
94
+ })
95
+ ```
96
+
97
+ Scan now scans the site's address (the field above the button, or `serverURL`) as a new visitor,
98
+ after rejecting, after accepting and, with several optional categories, with each one alone. The
99
+ plugin presets c15t's cookie for each state, so no click is needed. The scanner posts the result
100
+ back to `/api/consent-scans/result`, and the tab shows every cookie, localStorage key and
101
+ third-party host:
102
+
103
+ - **Needs action**: a service seen in a state that does not allow its category, such as analytics
104
+ before consent.
105
+ - **Not in the Cookie services**: nothing explains it. Each comes with a suggestion from the Open
106
+ Cookie Database where there is one; Add to service puts it in a new or existing service (with
107
+ `_ga_*` rather than one property's `_ga_G123`), and the scan is judged again.
108
+ - **In order**: explained and seen only where allowed.
109
+
110
+ Findings new since the previous scan are marked. A scan's raw results stay in `consent-scans`.
111
+
112
+ ### Every month
113
+
114
+ The plugin schedules a scan once a month through Payload's jobs queue: on a day from 1 to 28 and
115
+ at a time between 01:00 and 05:00 (server time) picked from `serverURL`, so sites sharing a
116
+ scanner do not all queue at once. The Scan tab shows the day and has the switch that turns it
117
+ off. Payload queues and runs scheduled jobs when something calls its runner, so give the host a
118
+ daily cron and let `jobs.access.run` accept it:
119
+
120
+ ```ts
121
+ // payload.config.ts
122
+ jobs: {
123
+ access: {
124
+ run: ({ req }) =>
125
+ Boolean(req.user) ||
126
+ req.headers.get("authorization") === `Bearer ${process.env.CRON_SECRET}`,
127
+ },
128
+ },
129
+ ```
130
+
131
+ ```json
132
+ // vercel.json: Vercel sends CRON_SECRET as the bearer token.
133
+ { "crons": [{ "path": "/api/payload-jobs/run", "schedule": "0 5 * * *" }] }
134
+ ```
135
+
136
+ The plugin adds its task to `jobs.tasks`; Payload creates its `payload-jobs` collection once a
137
+ task exists, so the migration that adds the plugin may add that table too.
138
+
139
+ ### Email
140
+
141
+ When a scan fails, needs action, has findings outside the services or finds something new, the
142
+ plugin emails the users chosen under Cookies → Scan (Email about scans) through
143
+ `payload.sendEmail`. A scan with nothing to handle sends nothing. The site's email adapter sends
144
+ it, for example Resend:
145
+
146
+ ```ts
147
+ import { resendAdapter } from "@payloadcms/email-resend"
148
+
149
+ email: resendAdapter({
150
+ apiKey: process.env.RESEND_API_KEY!,
151
+ defaultFromAddress: process.env.EMAIL_FROM_ADDRESS!,
152
+ defaultFromName: process.env.EMAIL_FROM_NAME!,
153
+ }),
154
+ ```
155
+
156
+ Without an adapter Payload writes the email to the console. The text follows Admin's default
157
+ language (`i18n.fallbackLanguage`, Swedish or English).
158
+
159
+ ### Evidence
160
+
161
+ After each result the scanner sends the EDPS collector's PDF report and the network traffic as a
162
+ gzipped HAR file per consent state. They are kept in `consent-scan-evidence` and listed on the
163
+ scan, for the last twelve finished scans (`scanner.keepEvidence`; `0` asks for none). Deleting a
164
+ scan deletes its evidence. Files over 4 MB are not sent.
165
+
166
+ On a host without a lasting disk, such as Vercel, add the collection to the storage adapter:
167
+
168
+ ```ts
169
+ s3Storage({ collections: { "consent-scan-evidence": true, /* ... */ } })
170
+ ```
171
+
172
+ ### On the dashboard
173
+
174
+ The Cookie scan widget shows the latest result, red when something needs action or is outside
175
+ the services, and the date of the next scan. The plugin does not change the dashboard's default
176
+ layout: add the widget in the dashboard's Edit mode, or put
177
+ `{ widgetSlug: "consent-scan", width: "small" }` in `admin.dashboard.defaultLayout`.
178
+
179
+ ## On the site
180
+
181
+ Read the global and the services on the server and pass them to the provider around the site:
182
+
183
+ ```tsx
184
+ import { getConsentConfig } from '@simmalugnt-se/payload-consent'
185
+ import { ConsentProvider } from '@simmalugnt-se/payload-consent/client'
186
+ import '@simmalugnt-se/payload-consent/styles.css'
187
+
188
+ const consent = await getConsentConfig({ payload, locale })
189
+
190
+ return <ConsentProvider config={consent}>{children}</ConsentProvider>
191
+ ```
192
+
193
+ Put `ConsentSettingsLink` from the client export in the footer, inside the provider, when
194
+ `consent.enabled` is true: it reopens the settings dialog.
195
+
196
+ The services picked in Admin load on their own. Other c15t integrations go in `scripts`:
197
+
198
+ ```tsx
199
+ 'use client'
200
+ import { googleTagManager } from '@c15t/scripts/google-tag-manager'
201
+
202
+ <ConsentProvider config={consent} scripts={[googleTagManager({ id: 'GTM-XXXXXXX' })]}>
203
+ ```
204
+
205
+ Embedded content, such as a video or a map, waits behind a placeholder until the visitor allows
206
+ its category:
207
+
208
+ ```tsx
209
+ import { ConsentFrame } from '@simmalugnt-se/payload-consent/client'
210
+
211
+ <ConsentFrame category="functionality">
212
+ <iframe src="https://www.youtube-nocookie.com/embed/…" title="…" />
213
+ </ConsentFrame>
214
+ ```
215
+
216
+ ### The cookie table
217
+
218
+ Add `cookieTableBlock` to a blocks field, then render it on the cookie page:
219
+
220
+ ```tsx
221
+ import { getCookieTable } from '@simmalugnt-se/payload-consent'
222
+ import { CookieTable } from '@simmalugnt-se/payload-consent/client'
223
+
224
+ <CookieTable data={await getCookieTable({ payload, locale })} heading={block.heading} />
225
+ ```
226
+
227
+ It lists the services by category, each with its purpose, policy link and storage, and the
228
+ banner's own consent storage first: `c15t`, a cookie and a localStorage key, and the cookie
229
+ `c15t-policy` with the policy version the visitor chose under, all kept for a year.
230
+
231
+ The global and the services are public to read by default (`access.read`), since the site shows
232
+ them to everyone. `overrideGlobal` and `overrideServices` change them, for example to add hooks
233
+ that revalidate the site's cache.
234
+
235
+ ## Look
236
+
237
+ `styles.css` styles c15t's unstyled banner and dialog. Set these variables on `:root` (c15t renders
238
+ through portals): `--consent-font`, `--consent-text`, `--consent-muted`, `--consent-surface`,
239
+ `--consent-border`, `--consent-hover`, `--consent-accent`, `--consent-radius`.
@@ -0,0 +1,3 @@
1
+ import "../styles/admin.css";
2
+ /** The Scan tab: start a scan, follow it, and turn what it found into Cookie services. */
3
+ export declare function ScanPanel(): import("react").JSX.Element;
@@ -0,0 +1,232 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { Button, Pill, useConfig, useFormFields, useLocale, useTranslation } from "@payloadcms/ui";
4
+ import { useCallback, useEffect, useState } from "react";
5
+ import { CATEGORIES } from "../defaults.js";
6
+ import { CONSENT_SCANS } from "../types.js";
7
+ import "../styles/admin.css";
8
+ const COPY = {
9
+ en: {
10
+ noScanner: "No scanner is set up. Give the plugin `scanner: { url, token }` (see the README), then scan from here.",
11
+ scan: "Scan now",
12
+ starting: "Starting…",
13
+ none: "The site has not been scanned yet.",
14
+ queued: (position) => position
15
+ ? `Waiting for the scanner, number ${position} in line.`
16
+ : "Waiting for the scanner.",
17
+ running: (progress) => `Scanning${progress ? `: ${progress}` : "…"}`,
18
+ lost: "The scanner no longer knows this scan, perhaps after a restart. Scan again.",
19
+ failed: "The scan failed:",
20
+ done: (date, pages) => `Scanned ${date}, ${pages} pages.`,
21
+ groups: {
22
+ action: "Needs action",
23
+ unknown: "Not in the Cookie services",
24
+ ok: "In order",
25
+ },
26
+ explain: {
27
+ action: "These services load in a state where their category is not allowed. Load them through the plugin (Loaded by: this plugin) or make the site's code wait for consent.",
28
+ unknown: "Nothing in the Cookie services explains these. Add each to a service, or remove it from the site.",
29
+ ok: "Explained by the Cookie services and seen only where their category is allowed.",
30
+ },
31
+ kinds: { cookie: "Cookie", localStorage: "localStorage", host: "Third-party host" },
32
+ beforeConsent: "Before consent",
33
+ isNew: "New",
34
+ seenIn: "Seen in",
35
+ withoutConsent: "without consent in",
36
+ service: "Service",
37
+ category: "Category",
38
+ add: "Add to service",
39
+ adding: "Adding…",
40
+ suggestion: "Suggestion",
41
+ trackerList: "On tracker list",
42
+ states: {
43
+ "no-choice": "new visitor",
44
+ "reject-all": "after rejecting",
45
+ "accept-all": "after accepting",
46
+ },
47
+ categories: {
48
+ necessary: "Necessary",
49
+ functionality: "Functionality",
50
+ experience: "Experience",
51
+ measurement: "Statistics",
52
+ marketing: "Marketing",
53
+ },
54
+ summary: (s) => `${s.action} need action · ${s.unknown} unknown · ${s.ok} in order${s.new ? ` · ${s.new} new` : ""}`,
55
+ },
56
+ sv: {
57
+ noScanner: "Ingen skanner är inställd. Ge pluginet `scanner: { url, token }` (se README), och skanna sedan härifrån.",
58
+ scan: "Skanna nu",
59
+ starting: "Startar…",
60
+ none: "Webbplatsen har inte skannats än.",
61
+ queued: (position) => position ? `Väntar på skannern, nummer ${position} i kön.` : "Väntar på skannern.",
62
+ running: (progress) => `Skannar${progress ? `: ${progress}` : "…"}`,
63
+ lost: "Skannern känner inte längre till skanningen, kanske efter en omstart. Skanna igen.",
64
+ failed: "Skanningen misslyckades:",
65
+ done: (date, pages) => `Skannad ${date}, ${pages} sidor.`,
66
+ groups: {
67
+ action: "Åtgärd krävs",
68
+ unknown: "Finns inte bland Cookietjänsterna",
69
+ ok: "I ordning",
70
+ },
71
+ explain: {
72
+ action: "De här tjänsterna laddas i ett läge där deras kategori inte är tillåten. Ladda dem via pluginet (Laddas av: det här pluginet) eller låt webbplatsens kod vänta på samtycke.",
73
+ unknown: "Inget bland Cookietjänsterna förklarar de här. Lägg till var och en i en tjänst, eller ta bort den från webbplatsen.",
74
+ ok: "Förklaras av Cookietjänsterna och syns bara där deras kategori är tillåten.",
75
+ },
76
+ kinds: { cookie: "Cookie", localStorage: "localStorage", host: "Tredjepartsvärd" },
77
+ beforeConsent: "Före samtycke",
78
+ isNew: "Ny",
79
+ seenIn: "Sågs",
80
+ withoutConsent: "utan samtycke",
81
+ service: "Tjänst",
82
+ category: "Kategori",
83
+ add: "Lägg till i tjänst",
84
+ adding: "Lägger till…",
85
+ suggestion: "Förslag",
86
+ trackerList: "På spårningslista",
87
+ states: {
88
+ "no-choice": "ny besökare",
89
+ "reject-all": "efter avvisa",
90
+ "accept-all": "efter godkänn",
91
+ },
92
+ categories: {
93
+ necessary: "Nödvändiga",
94
+ functionality: "Funktionalitet",
95
+ experience: "Upplevelse",
96
+ measurement: "Statistik",
97
+ marketing: "Marknadsföring",
98
+ },
99
+ summary: (s) => `${s.action} kräver åtgärd · ${s.unknown} okända · ${s.ok} i ordning${s.new ? ` · ${s.new} nya` : ""}`,
100
+ },
101
+ };
102
+ function stateLabel(copy, id) {
103
+ if (copy.states[id])
104
+ return copy.states[id];
105
+ const category = id.replace(/^only-/, "");
106
+ return copy.categories[category] ? `${copy.categories[category]}` : id;
107
+ }
108
+ /** `accept-all (3/3)` from the scanner, in the editor's words. */
109
+ function progressLabel(copy, progress) {
110
+ const match = progress?.match(/^(\S+) \((\d+\/\d+)\)$/);
111
+ return match ? `${stateLabel(copy, match[1] ?? "")} (${match[2]})` : progress;
112
+ }
113
+ /** The Scan tab: start a scan, follow it, and turn what it found into Cookie services. */
114
+ export function ScanPanel() {
115
+ const { config } = useConfig();
116
+ const { i18n } = useTranslation();
117
+ const locale = useLocale();
118
+ const language = i18n.language === "sv" ? "sv" : "en";
119
+ const copy = COPY[language];
120
+ const api = `${config.serverURL ?? ""}${config.routes.api}/${CONSENT_SCANS}`;
121
+ const hasScanner = Boolean(config.admin?.custom?.consent?.scanner);
122
+ const formUrl = useFormFields(([fields]) => fields.scanUrl?.value);
123
+ const [scan, setScan] = useState(undefined);
124
+ const [live, setLive] = useState({});
125
+ const [busy, setBusy] = useState(false);
126
+ const [error, setError] = useState();
127
+ const load = useCallback(async () => {
128
+ const response = await fetch(`${api}?sort=-createdAt&limit=1&depth=0`, {
129
+ credentials: "include",
130
+ });
131
+ const body = (await response.json().catch(() => ({})));
132
+ setScan(body.docs?.[0] ?? null);
133
+ }, [api]);
134
+ useEffect(() => {
135
+ load();
136
+ }, [load]);
137
+ // While a scan waits or runs, ask for its progress; reload it when it ends.
138
+ useEffect(() => {
139
+ if (!scan || (scan.status !== "queued" && scan.status !== "running"))
140
+ return;
141
+ let stopped = false;
142
+ const poll = async () => {
143
+ const response = await fetch(`${api}/${scan.id}/status`, { credentials: "include" });
144
+ const next = (await response.json().catch(() => ({})));
145
+ if (stopped)
146
+ return;
147
+ setLive(next);
148
+ if (next.status === "done" || next.status === "failed")
149
+ await load();
150
+ };
151
+ poll();
152
+ const timer = setInterval(poll, 4000);
153
+ return () => {
154
+ stopped = true;
155
+ clearInterval(timer);
156
+ };
157
+ }, [api, load, scan]);
158
+ async function start() {
159
+ setBusy(true);
160
+ setError(undefined);
161
+ const response = await fetch(`${api}/start`, {
162
+ method: "POST",
163
+ credentials: "include",
164
+ headers: { "content-type": "application/json" },
165
+ body: JSON.stringify({ url: formUrl }),
166
+ });
167
+ const body = (await response.json().catch(() => ({})));
168
+ setBusy(false);
169
+ if (!response.ok)
170
+ setError(body.error ?? String(response.status));
171
+ else {
172
+ setLive({});
173
+ await load();
174
+ }
175
+ }
176
+ if (!hasScanner)
177
+ return _jsx("p", { className: "consent-scan__note", children: copy.noScanner });
178
+ const active = scan?.status === "queued" || scan?.status === "running";
179
+ // The scanner knows first when a queued scan starts running.
180
+ const current = active ? (live.status ?? scan?.status) : scan?.status;
181
+ const findings = scan?.findings ?? [];
182
+ return (_jsxs("div", { className: "consent-scan", children: [_jsxs("div", { className: "consent-scan__bar", children: [_jsx(Button, { buttonStyle: "primary", disabled: busy || active, margin: false, onClick: start, size: "medium", children: busy ? copy.starting : copy.scan }), _jsxs("span", { "aria-live": "polite", className: "consent-scan__status", children: [scan === null ? copy.none : null, current === "queued" ? copy.queued(live.position) : null, current === "running" ? copy.running(progressLabel(copy, live.progress)) : null, live.lost ? ` ${copy.lost}` : null, scan?.status === "failed" ? `${copy.failed} ${scan.error ?? ""}` : null, scan?.status === "done"
183
+ ? copy.done(new Date(scan.finishedAt ?? "").toLocaleString(language === "sv" ? "sv-SE" : "en-GB"), scan.pages?.selected?.length ?? 0)
184
+ : null] })] }), error ? _jsx("p", { className: "consent-scan__error", children: error }) : null, scan?.status === "done" && scan.summary ? (_jsx("p", { className: "consent-scan__summary", children: copy.summary(scan.summary) })) : null, scan?.status === "done"
185
+ ? ["action", "unknown", "ok"].map((status) => {
186
+ const rows = findings.filter((finding) => finding.status === status);
187
+ if (!rows.length)
188
+ return null;
189
+ const list = (_jsx("ul", { className: "consent-scan__list", children: rows.map((finding) => (_jsx(FindingRow, { copy: copy, finding: finding, locale: locale.code, onAdded: load, api: api }, finding.key))) }));
190
+ return (_jsx("section", { className: `consent-scan__group consent-scan__group--${status}`, children: status === "ok" ? (_jsxs("details", { children: [_jsx("summary", { children: _jsxs("h4", { children: [copy.groups[status], " (", rows.length, ")"] }) }), _jsx("p", { className: "consent-scan__note", children: copy.explain[status] }), list] })) : (_jsxs(_Fragment, { children: [_jsxs("h4", { children: [copy.groups[status], " (", rows.length, ")"] }), _jsx("p", { className: "consent-scan__note", children: copy.explain[status] }), list] })) }, status));
191
+ })
192
+ : null] }));
193
+ }
194
+ function FindingRow({ api, copy, finding, locale, onAdded, }) {
195
+ const suggestion = finding.suggestion;
196
+ const [service, setService] = useState(suggestion?.platform ?? (finding.kind === "host" ? finding.name : ""));
197
+ const [category, setCategory] = useState(suggestion?.category ?? "necessary");
198
+ const [busy, setBusy] = useState(false);
199
+ const [error, setError] = useState();
200
+ async function add() {
201
+ setBusy(true);
202
+ setError(undefined);
203
+ const response = await fetch(`${api}/classify`, {
204
+ method: "POST",
205
+ credentials: "include",
206
+ headers: { "content-type": "application/json" },
207
+ body: JSON.stringify({
208
+ kind: finding.kind,
209
+ // `_ga_*` rather than one property's `_ga_G123`, so the next property is explained too.
210
+ name: suggestion?.pattern ?? finding.name,
211
+ service,
212
+ category,
213
+ provider: suggestion?.provider,
214
+ purpose: suggestion?.description,
215
+ duration: suggestion?.retention,
216
+ policyUrl: suggestion?.privacyUrl,
217
+ locale,
218
+ }),
219
+ });
220
+ const body = (await response.json().catch(() => ({})));
221
+ setBusy(false);
222
+ if (!response.ok)
223
+ setError(body.error ?? String(response.status));
224
+ else
225
+ await onAdded();
226
+ }
227
+ const seen = finding.states.map((id) => stateLabel(copy, id)).join(", ");
228
+ const without = finding.withoutConsent.map((id) => stateLabel(copy, id)).join(", ");
229
+ return (_jsxs("li", { className: "consent-scan__row", children: [_jsxs("div", { className: "consent-scan__name", children: [_jsx("span", { className: "consent-scan__kind", children: copy.kinds[finding.kind] }), _jsx("code", { children: finding.name }), finding.where ? _jsx("span", { className: "consent-scan__where", children: finding.where }) : null, finding.beforeConsent && finding.status !== "ok" ? (_jsx(Pill, { pillStyle: "error", size: "small", children: copy.beforeConsent })) : null, finding.isNew ? (_jsx(Pill, { pillStyle: "warning", size: "small", children: copy.isNew })) : null] }), _jsxs("p", { className: "consent-scan__detail", children: [copy.seenIn, ": ", seen, without ? ` · ${copy.withoutConsent}: ${without}` : "", finding.service ? ` · ${copy.service}: ${finding.service}` : "", finding.category ? ` (${copy.categories[finding.category]})` : "", finding.trackerLists?.length
230
+ ? ` · ${copy.trackerList}: ${finding.trackerLists.join(", ")}`
231
+ : ""] }), suggestion?.platform ? (_jsxs("p", { className: "consent-scan__detail", children: [copy.suggestion, ": ", suggestion.platform, suggestion.category ? `, ${copy.categories[suggestion.category]}` : "", suggestion.retention ? `, ${suggestion.retention}` : "", suggestion.description ? ` · ${suggestion.description}` : ""] })) : null, finding.status === "unknown" ? (_jsxs("div", { className: "consent-scan__classify", children: [_jsxs("label", { children: [_jsx("span", { children: copy.service }), _jsx("input", { onChange: (event) => setService(event.target.value), type: "text", value: service })] }), _jsxs("label", { children: [_jsx("span", { children: copy.category }), _jsx("select", { onChange: (event) => setCategory(event.target.value), value: category, children: CATEGORIES.map((value) => (_jsx("option", { value: value, children: copy.categories[value] }, value))) })] }), _jsx(Button, { buttonStyle: "secondary", disabled: busy || !service.trim(), margin: false, onClick: add, size: "small", children: busy ? copy.adding : copy.add }), error ? _jsx("span", { className: "consent-scan__error", children: error }) : null] })) : null] }));
232
+ }
@@ -0,0 +1,6 @@
1
+ import type { Block } from "payload";
2
+ /**
3
+ * A block that lists the cookie services by category, for the site's cookie page. Add it to a
4
+ * blocks field and render it with `CookieTable` and `getCookieTable`.
5
+ */
6
+ export declare const cookieTableBlock: Block;
package/dist/block.js ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * A block that lists the cookie services by category, for the site's cookie page. Add it to a
3
+ * blocks field and render it with `CookieTable` and `getCookieTable`.
4
+ */
5
+ export const cookieTableBlock = {
6
+ slug: "cookieTable",
7
+ interfaceName: "CookieTableBlock",
8
+ labels: {
9
+ singular: { en: "Cookie table", sv: "Cookietabell" },
10
+ plural: { en: "Cookie tables", sv: "Cookietabeller" },
11
+ },
12
+ admin: { disableBlockName: true },
13
+ fields: [
14
+ {
15
+ name: "heading",
16
+ type: "text",
17
+ localized: true,
18
+ label: { en: "Heading", sv: "Rubrik" },
19
+ admin: {
20
+ description: {
21
+ en: "Optional. The table lists every cookie service, grouped by category, from Settings → Cookie services.",
22
+ sv: "Valfri. Tabellen listar varje cookietjänst, grupperad per kategori, från Inställningar → Cookietjänster.",
23
+ },
24
+ },
25
+ },
26
+ ],
27
+ };
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Suggested banner texts per language, prefilled in the Cookies global. They follow
3
+ * `@simmalugnt-se/consent-ui` 0.2.1; a language without its own texts gets English.
4
+ */
5
+ export declare const OPTIONAL_CATEGORIES: readonly ["functionality", "experience", "measurement", "marketing"];
6
+ export type OptionalCategory = (typeof OPTIONAL_CATEGORIES)[number];
7
+ export type Category = "necessary" | OptionalCategory;
8
+ export declare const CATEGORIES: readonly Category[];
9
+ export type ConsentTexts = {
10
+ bannerTitle: string;
11
+ /** When visitors can choose optional categories. */
12
+ bannerDescription: string;
13
+ /** When the site only uses necessary storage. */
14
+ bannerDescriptionNecessaryOnly: string;
15
+ buttons: {
16
+ acceptAll: string;
17
+ /** The only button besides Settings when the site only uses necessary storage. */
18
+ acceptNecessaryOnly: string;
19
+ rejectAll: string;
20
+ customize: string;
21
+ save: string;
22
+ close: string;
23
+ };
24
+ dialog: {
25
+ title: string;
26
+ description: string;
27
+ descriptionNecessaryOnly: string;
28
+ };
29
+ categoryTexts: Record<Category, {
30
+ title: string;
31
+ description: string;
32
+ }>;
33
+ embeds: {
34
+ title: string;
35
+ button: string;
36
+ };
37
+ /** Fixed texts in the cookie table and for the plugin's own consent storage. */
38
+ table: {
39
+ service: string;
40
+ provider: string;
41
+ purpose: string;
42
+ name: string;
43
+ type: string;
44
+ duration: string;
45
+ thirdParty: string;
46
+ yes: string;
47
+ no: string;
48
+ policy: string;
49
+ consentService: string;
50
+ consentPurpose: string;
51
+ consentDuration: string;
52
+ noServices: string;
53
+ };
54
+ };
55
+ /** The suggested texts for a locale code such as `sv` or `sv-SE`; English when there are none. */
56
+ export declare function defaultTexts(locale: string | null | undefined): ConsentTexts;