@simmalugnt-se/payload-consent 0.0.0-stage → 0.2.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 (46) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/LICENSE +21 -0
  3. package/README.md +242 -2
  4. package/dist/admin/ScanPanel.d.ts +3 -0
  5. package/dist/admin/ScanPanel.js +232 -0
  6. package/dist/admin/ServicesPanel.d.ts +11 -0
  7. package/dist/admin/ServicesPanel.js +136 -0
  8. package/dist/block.d.ts +6 -0
  9. package/dist/block.js +27 -0
  10. package/dist/defaults.d.ts +56 -0
  11. package/dist/defaults.js +137 -0
  12. package/dist/evaluate.d.ts +106 -0
  13. package/dist/evaluate.js +101 -0
  14. package/dist/evidence.d.ts +12 -0
  15. package/dist/evidence.js +114 -0
  16. package/dist/exports/admin.d.ts +2 -0
  17. package/dist/exports/admin.js +2 -0
  18. package/dist/exports/client.d.ts +37 -0
  19. package/dist/exports/client.js +180 -0
  20. package/dist/exports/rsc.d.ts +1 -0
  21. package/dist/exports/rsc.js +1 -0
  22. package/dist/global.d.ts +14 -0
  23. package/dist/global.js +317 -0
  24. package/dist/index.d.ts +13 -0
  25. package/dist/index.js +75 -0
  26. package/dist/integrations.d.ts +40 -0
  27. package/dist/integrations.js +32 -0
  28. package/dist/notify.d.ts +15 -0
  29. package/dist/notify.js +86 -0
  30. package/dist/records.d.ts +15 -0
  31. package/dist/records.js +198 -0
  32. package/dist/scans.d.ts +37 -0
  33. package/dist/scans.js +424 -0
  34. package/dist/schedule.d.ts +17 -0
  35. package/dist/schedule.js +18 -0
  36. package/dist/services.d.ts +8 -0
  37. package/dist/services.js +258 -0
  38. package/dist/site-config.d.ts +128 -0
  39. package/dist/site-config.js +204 -0
  40. package/dist/styles/admin.css +202 -0
  41. package/dist/styles/consent.css +301 -0
  42. package/dist/types.d.ts +65 -0
  43. package/dist/types.js +17 -0
  44. package/dist/widget/ConsentScanWidget.d.ts +8 -0
  45. package/dist/widget/ConsentScanWidget.js +99 -0
  46. package/package.json +76 -3
package/CHANGELOG.md ADDED
@@ -0,0 +1,46 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0
4
+
5
+ - Cookies is the one entry in Admin: a Services tab lists the Cookie services with links to edit
6
+ and add them, a Consent log tab links to the records and policy versions, and the Scan tab links
7
+ to every scan. The plugin's collections no longer appear in the navigation or on the dashboard.
8
+ - The settings dialog no longer shows "Reject optional" when the site has only necessary storage.
9
+
10
+ ## 0.1.0
11
+
12
+ - A Cookies global with the banner's texts, localized and prefilled with Swedish and English
13
+ suggestions, the site's optional categories and links to the privacy and cookie policy pages.
14
+ - `getConsentConfig` reads the global for a locale; `ConsentProvider` shows the banner and settings
15
+ dialog through c15t 2.2.1, and `ConsentSettingsLink` reopens the dialog. The banner, dialog and
16
+ styles come from `@simmalugnt-se/consent-ui` 0.2.1, copied in rather than depended on.
17
+ - Cookie services (`consent-services`): category, purpose, policy link, cookies and storage keys,
18
+ and hosts per service. The banner's categories follow the services.
19
+ - Services can be loaded by the plugin through eight c15t integrations (Google Tag Manager,
20
+ Google Analytics 4, Meta Pixel, LinkedIn, TikTok, Microsoft Ads, Clarity, Hotjar), after consent.
21
+ Google Consent Mode is basic by default: nothing loads before consent.
22
+ - `cookieTableBlock`, `getCookieTable` and `CookieTable` list the services by category, with the
23
+ banner's own consent storage.
24
+ - `ConsentFrame` keeps embedded content behind a placeholder until its category is allowed.
25
+ - Banner texts are optional: an empty text, or one never saved in a language, shows that
26
+ language's suggestion.
27
+ - A consent log: each saved choice is recorded in `consent-records` with c15t's random visitor ID
28
+ and the policy version, and `consent-policies` keeps what visitors were shown per version and
29
+ language. No IP address or browser details; kept three years by default (`records`).
30
+ - Visitors are asked again when the categories or the services' cookies change. The version they
31
+ chose under is kept in the `c15t-policy` cookie, so a scanner can preset a consent state, and an
32
+ outdated choice is removed before c15t reads it: nothing it allowed loads first.
33
+ - Scans from Admin: a Scan tab in the Cookies global starts a scan by `consent-scanner` in every
34
+ consent state, follows it in the queue, and lists what it found, judged against the Cookie
35
+ services. Unknown findings become part of a service in one step, with the Open Cookie
36
+ Database's suggestion. Scans are kept in `consent-scans` (`scanner` option).
37
+ - A service's purpose is optional, so a service saved in one language stays editable in the others.
38
+ - A monthly scan through Payload's jobs queue (`consentScan`), on a day and at a time picked from
39
+ the site's address so sites sharing a scanner spread over the month. It runs when the host's
40
+ cron calls `/api/payload-jobs/run`; Cookies → Scan turns it off.
41
+ - Email about a scan that fails, needs action, has findings outside the services or finds
42
+ something new, to the users chosen under Cookies → Scan, through the host's email adapter.
43
+ - A dashboard widget, Cookie scan, with the latest result, red when something needs handling.
44
+ - Evidence: WEC's PDF report and network traffic (HAR, gzipped) per consent state, sent by the
45
+ scanner after each result and kept in `consent-scan-evidence` for the last twelve scans
46
+ (`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,243 @@
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, under Settings), the collections `consent-services`
28
+ (Cookie services), `consent-records` and `consent-policies` (the consent log), `consent-scans` and
29
+ `consent-scan-evidence`, a jobs task (`consentScan`) and a dashboard widget. Cookies is the one
30
+ entry in the navigation and on the dashboard: its tabs list the services and link to the log and
31
+ the scans, whose collections stay out of the navigation (`admin.group: false`). Generate types, then create and apply a migration with the
32
+ project's usual commands.
33
+
34
+ ## The Cookies global
35
+
36
+ Five tabs: Banner, Services, Scan, Consent log and Settings.
37
+
38
+ - **Banner**: title, description, buttons, the settings dialog and a title and description per
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.
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.
46
+
47
+ Texts are optional: an empty one shows the suggestion for the visitor's language.
48
+
49
+ ## Cookie services
50
+
51
+ One document per service the site uses: name, provider, category, purpose, the provider's privacy
52
+ policy, the cookies and storage keys it sets (with how long they are kept and whether they are
53
+ third-party) and the hosts it contacts. The banner's categories are the services' categories.
54
+
55
+ A service is loaded either by the site's code, which must then wait for consent itself, or by the
56
+ plugin through one of c15t's integrations: Google Tag Manager, Google Analytics 4, Meta Pixel,
57
+ LinkedIn Insight Tag, TikTok Pixel, Microsoft Ads (UET), Microsoft Clarity and Hotjar. The editor
58
+ picks the integration and enters its ID; the script then loads in the service's category, after
59
+ consent.
60
+
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.
64
+
65
+ 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.
67
+
68
+ ## Consent records
69
+
70
+ Every choice a visitor saves is posted to `/api/consent-records/record` and kept in
71
+ `consent-records`: the random visitor ID from c15t's cookie (`sub_…`), the choices, the policy
72
+ version, the language and the page. No IP address or browser details. The first choice under each
73
+ policy version and language also saves what the visitor was shown in `consent-policies`:
74
+ 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.
76
+
77
+ The policy version is a hash of the categories and each service's cookies and storage keys. When
78
+ it changes, for example because a service gains a cookie, visitors are asked again. Rewording a
79
+ text does not change it.
80
+
81
+ The site keeps c15t in offline mode: the banner works without the server, and a record that cannot
82
+ be posted only leaves the log without that entry.
83
+
84
+ ## Scans
85
+
86
+ The Scan tab scans the published site with `consent-scanner`, a separate repository and a small
87
+ service of our own that runs the EDPS Website Evidence Collector. One scanner serves many
88
+ sites; give the plugin its address and this site's token:
89
+
90
+ ```ts
91
+ consentPlugin({
92
+ scanner: {
93
+ url: process.env.CONSENT_SCANNER_URL,
94
+ token: process.env.CONSENT_SCANNER_TOKEN,
95
+ // Only when the scanner cannot reach serverURL, e.g. Docker beside a dev server:
96
+ // callbackBaseUrl: 'http://host.docker.internal:3000',
97
+ },
98
+ })
99
+ ```
100
+
101
+ Scan now scans the site's address (the field above the button, or `serverURL`) as a new visitor,
102
+ after rejecting, after accepting and, with several optional categories, with each one alone. The
103
+ plugin presets c15t's cookie for each state, so no click is needed. The scanner posts the result
104
+ back to `/api/consent-scans/result`, and the tab shows every cookie, localStorage key and
105
+ third-party host:
106
+
107
+ - **Needs action**: a service seen in a state that does not allow its category, such as analytics
108
+ before consent.
109
+ - **Not in the Cookie services**: nothing explains it. Each comes with a suggestion from the Open
110
+ Cookie Database where there is one; Add to service puts it in a new or existing service (with
111
+ `_ga_*` rather than one property's `_ga_G123`), and the scan is judged again.
112
+ - **In order**: explained and seen only where allowed.
113
+
114
+ Findings new since the previous scan are marked. A scan's raw results stay in `consent-scans`.
115
+
116
+ ### Every month
117
+
118
+ The plugin schedules a scan once a month through Payload's jobs queue: on a day from 1 to 28 and
119
+ at a time between 01:00 and 05:00 (server time) picked from `serverURL`, so sites sharing a
120
+ scanner do not all queue at once. The Scan tab shows the day and has the switch that turns it
121
+ off. Payload queues and runs scheduled jobs when something calls its runner, so give the host a
122
+ daily cron and let `jobs.access.run` accept it:
123
+
124
+ ```ts
125
+ // payload.config.ts
126
+ jobs: {
127
+ access: {
128
+ run: ({ req }) =>
129
+ Boolean(req.user) ||
130
+ req.headers.get("authorization") === `Bearer ${process.env.CRON_SECRET}`,
131
+ },
132
+ },
133
+ ```
134
+
135
+ ```json
136
+ // vercel.json: Vercel sends CRON_SECRET as the bearer token.
137
+ { "crons": [{ "path": "/api/payload-jobs/run", "schedule": "0 5 * * *" }] }
138
+ ```
139
+
140
+ The plugin adds its task to `jobs.tasks`; Payload creates its `payload-jobs` collection once a
141
+ task exists, so the migration that adds the plugin may add that table too.
142
+
143
+ ### Email
144
+
145
+ When a scan fails, needs action, has findings outside the services or finds something new, the
146
+ plugin emails the users chosen under Cookies → Scan (Email about scans) through
147
+ `payload.sendEmail`. A scan with nothing to handle sends nothing. The site's email adapter sends
148
+ it, for example Resend:
149
+
150
+ ```ts
151
+ import { resendAdapter } from "@payloadcms/email-resend"
152
+
153
+ email: resendAdapter({
154
+ apiKey: process.env.RESEND_API_KEY!,
155
+ defaultFromAddress: process.env.EMAIL_FROM_ADDRESS!,
156
+ defaultFromName: process.env.EMAIL_FROM_NAME!,
157
+ }),
158
+ ```
159
+
160
+ Without an adapter Payload writes the email to the console. The text follows Admin's default
161
+ language (`i18n.fallbackLanguage`, Swedish or English).
162
+
163
+ ### Evidence
164
+
165
+ After each result the scanner sends the EDPS collector's PDF report and the network traffic as a
166
+ gzipped HAR file per consent state. They are kept in `consent-scan-evidence` and listed on the
167
+ scan, for the last twelve finished scans (`scanner.keepEvidence`; `0` asks for none). Deleting a
168
+ scan deletes its evidence. Files over 4 MB are not sent.
169
+
170
+ On a host without a lasting disk, such as Vercel, add the collection to the storage adapter:
171
+
172
+ ```ts
173
+ s3Storage({ collections: { "consent-scan-evidence": true, /* ... */ } })
174
+ ```
175
+
176
+ ### On the dashboard
177
+
178
+ The Cookie scan widget shows the latest result, red when something needs action or is outside
179
+ the services, and the date of the next scan. The plugin does not change the dashboard's default
180
+ layout: add the widget in the dashboard's Edit mode, or put
181
+ `{ widgetSlug: "consent-scan", width: "small" }` in `admin.dashboard.defaultLayout`.
182
+
183
+ ## On the site
184
+
185
+ Read the global and the services on the server and pass them to the provider around the site:
186
+
187
+ ```tsx
188
+ import { getConsentConfig } from '@simmalugnt-se/payload-consent'
189
+ import { ConsentProvider } from '@simmalugnt-se/payload-consent/client'
190
+ import '@simmalugnt-se/payload-consent/styles.css'
191
+
192
+ const consent = await getConsentConfig({ payload, locale })
193
+
194
+ return <ConsentProvider config={consent}>{children}</ConsentProvider>
195
+ ```
196
+
197
+ Put `ConsentSettingsLink` from the client export in the footer, inside the provider, when
198
+ `consent.enabled` is true: it reopens the settings dialog.
199
+
200
+ The services picked in Admin load on their own. Other c15t integrations go in `scripts`:
201
+
202
+ ```tsx
203
+ 'use client'
204
+ import { googleTagManager } from '@c15t/scripts/google-tag-manager'
205
+
206
+ <ConsentProvider config={consent} scripts={[googleTagManager({ id: 'GTM-XXXXXXX' })]}>
207
+ ```
208
+
209
+ Embedded content, such as a video or a map, waits behind a placeholder until the visitor allows
210
+ its category:
211
+
212
+ ```tsx
213
+ import { ConsentFrame } from '@simmalugnt-se/payload-consent/client'
214
+
215
+ <ConsentFrame category="functionality">
216
+ <iframe src="https://www.youtube-nocookie.com/embed/…" title="…" />
217
+ </ConsentFrame>
218
+ ```
219
+
220
+ ### The cookie table
221
+
222
+ Add `cookieTableBlock` to a blocks field, then render it on the cookie page:
223
+
224
+ ```tsx
225
+ import { getCookieTable } from '@simmalugnt-se/payload-consent'
226
+ import { CookieTable } from '@simmalugnt-se/payload-consent/client'
227
+
228
+ <CookieTable data={await getCookieTable({ payload, locale })} heading={block.heading} />
229
+ ```
230
+
231
+ It lists the services by category, each with its purpose, policy link and storage, and the
232
+ banner's own consent storage first: `c15t`, a cookie and a localStorage key, and the cookie
233
+ `c15t-policy` with the policy version the visitor chose under, all kept for a year.
234
+
235
+ The global and the services are public to read by default (`access.read`), since the site shows
236
+ them to everyone. `overrideGlobal` and `overrideServices` change them, for example to add hooks
237
+ that revalidate the site's cache.
238
+
239
+ ## Look
240
+
241
+ `styles.css` styles c15t's unstyled banner and dialog. Set these variables on `:root` (c15t renders
242
+ through portals): `--consent-font`, `--consent-text`, `--consent-muted`, `--consent-surface`,
243
+ `--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,11 @@
1
+ import "../styles/admin.css";
2
+ /**
3
+ * The Services tab: the Cookie services as a short table with links into the collection, so the
4
+ * Cookies page is the one place editors start from. A table of our own: Payload's list view is a
5
+ * whole route, not something a field can hold.
6
+ */
7
+ export declare function ServicesPanel(): import("react").JSX.Element;
8
+ /** The Consent log tab: how many choices are on record, with links to the records and policies. */
9
+ export declare function ConsentLogPanel(): import("react").JSX.Element;
10
+ /** Links under the Scan tab to every scan, since the collection is not in the navigation. */
11
+ export declare function ScanLinks(): import("react").JSX.Element;