@simmalugnt-se/payload-consent 0.3.0 → 0.5.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,28 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0
4
+
5
+ - A scan that could not see everything says so: a state the scanner did not return or that
6
+ visited no pages, the scanner's errors and unreadable sitemaps are kept in the summary
7
+ (`summary.problems`), shown on the Scan tab, named in the email and marked incomplete in the
8
+ dashboard widget instead of "in order". Before, a scan whose "reject all" state failed looked
9
+ clean.
10
+ - A scan the scanner has forgotten (after a restart) is saved as failed when the Scan tab asks
11
+ about it, and the monthly job closes scans left queued or running for more than 26 hours; both
12
+ email the chosen users. Before, they stayed queued.
13
+
14
+ - The public `POST /api/consent-records/record` takes choices only from the site's own pages (the
15
+ request's host, `serverURL` or Payload's `csrf` list), up to 4 kB, and at most 20 a minute from
16
+ one address per server process; the address is only counted in memory, never stored. The same
17
+ choice from the same visitor within a minute is not stored twice; a changed choice is.
18
+
19
+ ## 0.4.0
20
+
21
+ - `access.manage` says who works with cookies in Admin: the texts and services, the consent log,
22
+ policies, scans and evidence, starting scans and adding their findings (the `/start`,
23
+ `/:id/status` and `/classify` endpoints answer 403 to others), and the dashboard widget, which
24
+ others no longer see. Signed-in users by default, as before.
25
+
3
26
  ## 0.3.0
4
27
 
5
28
  Defaults and behaviour reviewed against the EDPB's guidelines and PTS's cookie decisions; the
package/README.md CHANGED
@@ -264,7 +264,18 @@ banner's own consent storage first: `c15t`, a cookie and a localStorage key, and
264
264
  `c15t-policy` with the policy version the visitor chose under, all kept for `consentMonths`.
265
265
 
266
266
  The global and the services are public to read by default (`access.read`), since the site shows
267
- 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
268
279
  that revalidate the site's cache.
269
280
 
270
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
+ }
@@ -15,8 +15,8 @@ const COPY = {
15
15
  ? `Waiting for the scanner, number ${position} in line.`
16
16
  : "Waiting for the scanner.",
17
17
  running: (progress) => `Scanning${progress ? `: ${progress}` : "…"}`,
18
- lost: "The scanner no longer knows this scan, perhaps after a restart. Scan again.",
19
18
  failed: "The scan failed:",
19
+ incomplete: "The scan is incomplete, so it may have missed something. Fix what is listed and scan again:",
20
20
  done: (date, pages) => `Scanned ${date}, ${pages} pages.`,
21
21
  groups: {
22
22
  action: "Needs action",
@@ -60,7 +60,7 @@ const COPY = {
60
60
  none: "Webbplatsen har inte skannats än.",
61
61
  queued: (position) => position ? `Väntar på skannern, nummer ${position} i kön.` : "Väntar på skannern.",
62
62
  running: (progress) => `Skannar${progress ? `: ${progress}` : "…"}`,
63
- lost: "Skannern känner inte längre till skanningen, kanske efter en omstart. Skanna igen.",
63
+ incomplete: "Skanningen är ofullständig och kan ha missat något. Åtgärda det som står här och skanna igen:",
64
64
  failed: "Skanningen misslyckades:",
65
65
  done: (date, pages) => `Skannad ${date}, ${pages} sidor.`,
66
66
  groups: {
@@ -179,9 +179,9 @@ export function ScanPanel() {
179
179
  // The scanner knows first when a queued scan starts running.
180
180
  const current = active ? (live.status ?? scan?.status) : scan?.status;
181
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"
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, scan?.status === "failed" ? `${copy.failed} ${scan.error ?? ""}` : null, scan?.status === "done"
183
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"
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" && scan.summary?.problems?.length ? (_jsxs("div", { className: "consent-scan__error", children: [_jsx("p", { children: copy.incomplete }), _jsx("ul", { children: scan.summary.problems.map((problem) => (_jsx("li", { children: problem }, problem))) })] })) : null, scan?.status === "done"
185
185
  ? ["action", "unknown", "ok"].map((status) => {
186
186
  const rows = findings.filter((finding) => finding.status === status);
187
187
  if (!rows.length)
@@ -85,7 +85,18 @@ export type Finding = {
85
85
  };
86
86
  export type ScanSummary = Record<FindingStatus, number> & {
87
87
  new: number;
88
+ /** What kept the scan from being complete; a state with no pages proves nothing. */
89
+ problems?: string[];
88
90
  };
91
+ /**
92
+ * Why a finished scan may not show everything: a state the scanner did not return or that
93
+ * visited no pages, its errors, and sitemaps it could not read. Empty when the scan is complete.
94
+ */
95
+ export declare function scanProblems(args: {
96
+ states: ScanState[];
97
+ results: ScanResultState[];
98
+ pages?: unknown;
99
+ }): string[];
89
100
  /** `_ga_*` matches `_ga_ABC`; anything else must be equal. */
90
101
  export declare function matchesName(pattern: string, name: string): boolean;
91
102
  /** `googletagmanager.com` matches itself and `www.googletagmanager.com`. */
package/dist/evaluate.js CHANGED
@@ -1,3 +1,26 @@
1
+ /**
2
+ * Why a finished scan may not show everything: a state the scanner did not return or that
3
+ * visited no pages, its errors, and sitemaps it could not read. Empty when the scan is complete.
4
+ */
5
+ export function scanProblems(args) {
6
+ const problems = [];
7
+ for (const state of args.states) {
8
+ const result = args.results.find((candidate) => candidate.id === state.id);
9
+ if (!result)
10
+ problems.push(`${state.id}: not scanned`);
11
+ else if (!result.visited?.length)
12
+ problems.push(`${state.id}: no page could be visited`);
13
+ for (const error of result?.errors ?? [])
14
+ problems.push(`${state.id}: ${error}`);
15
+ }
16
+ const sitemapErrors = args.pages?.sitemapErrors;
17
+ for (const entry of Array.isArray(sitemapErrors) ? sitemapErrors : []) {
18
+ const { sitemap, error } = (entry ?? {});
19
+ problems.push(`Sitemap ${String(sitemap ?? "")}: ${String(error ?? "could not be read")}`);
20
+ }
21
+ // Kept short for the summary, the panel and the email.
22
+ return problems.slice(0, 20).map((problem) => problem.slice(0, 300));
23
+ }
1
24
  /** The banner's own storage; always necessary. */
2
25
  const OWN_STORAGE = /^c15t(-policy|-storage-test-key)?$/;
3
26
  /** `_ga_*` matches `_ga_ABC`; anything else must be equal. */
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: [
package/dist/global.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { manageAccess } from "./access.js";
1
2
  import { defaultTexts, isFormerSuggestion, OPTIONAL_CATEGORIES, } from "./defaults.js";
2
3
  import { CONSENT_GLOBAL } from "./types.js";
3
4
  export const categoryLabels = {
@@ -54,7 +55,10 @@ export function consentGlobal(options, { usersSlug, schedule }) {
54
55
  slug: CONSENT_GLOBAL,
55
56
  label: { en: "Cookies", sv: "Cookies" },
56
57
  admin: { group: options.group ?? { en: "Settings", sv: "Inställningar" } },
57
- access: { read: () => true, ...options.access },
58
+ access: {
59
+ read: options.access?.read ?? (() => true),
60
+ update: options.access?.update ?? manageAccess(options),
61
+ },
58
62
  fields: [
59
63
  {
60
64
  type: "tabs",
package/dist/notify.d.ts CHANGED
@@ -6,7 +6,10 @@ export type ScanOutcome = {
6
6
  error?: string | null;
7
7
  summary?: ScanSummary | null;
8
8
  };
9
- /** A scan worth an email: it failed, found something to handle, or found something new. */
9
+ /**
10
+ * A scan worth an email: it failed, could not see everything, found something to handle, or found
11
+ * something new.
12
+ */
10
13
  export declare function needsNotice(outcome: ScanOutcome): boolean;
11
14
  /**
12
15
  * Emails the users picked under Cookies → Scan about a finished scan, through the host's
package/dist/notify.js CHANGED
@@ -1,27 +1,35 @@
1
1
  import { CONSENT_GLOBAL } from "./types.js";
2
- /** A scan worth an email: it failed, found something to handle, or found something new. */
2
+ /**
3
+ * A scan worth an email: it failed, could not see everything, found something to handle, or found
4
+ * something new.
5
+ */
3
6
  export function needsNotice(outcome) {
4
7
  if (outcome.status === "failed")
5
8
  return true;
6
9
  const summary = outcome.summary;
7
- return Boolean(summary && (summary.action || summary.unknown || summary.new));
10
+ return Boolean(summary && (summary.action || summary.unknown || summary.new || summary.problems?.length));
8
11
  }
12
+ const problems = (outcome) => outcome.summary?.problems ?? [];
9
13
  const COPY = {
10
14
  en: {
11
15
  subject: (o, host) => o.status === "failed"
12
16
  ? `Cookie scan of ${host} failed`
13
- : `Cookie scan of ${host}: ${count(o.summary, "en")}`,
17
+ : `Cookie scan of ${host}${o.summary?.problems?.length ? " (incomplete)" : ""}: ${count(o.summary, "en")}`,
14
18
  failed: (o) => `The cookie scan of ${o.url} failed: ${o.error ?? "no reason given"}.`,
15
- done: (o) => `The cookie scan of ${o.url} found ${count(o.summary, "en")}.`,
19
+ done: (o) => `The cookie scan of ${o.url} found ${count(o.summary, "en")}.${problems(o).length
20
+ ? ` It is incomplete, so it may have missed something: ${problems(o).slice(0, 3).join("; ")}.`
21
+ : ""}`,
16
22
  open: "Open Cookies in Admin",
17
23
  why: "You get this because you are chosen under Cookies → Scan.",
18
24
  },
19
25
  sv: {
20
26
  subject: (o, host) => o.status === "failed"
21
27
  ? `Cookieskanningen av ${host} misslyckades`
22
- : `Cookieskanning av ${host}: ${count(o.summary, "sv")}`,
28
+ : `Cookieskanning av ${host}${o.summary?.problems?.length ? " (ofullständig)" : ""}: ${count(o.summary, "sv")}`,
23
29
  failed: (o) => `Cookieskanningen av ${o.url} misslyckades: ${o.error ?? "ingen orsak angiven"}.`,
24
- done: (o) => `Cookieskanningen av ${o.url} hittade ${count(o.summary, "sv")}.`,
30
+ done: (o) => `Cookieskanningen av ${o.url} hittade ${count(o.summary, "sv")}.${problems(o).length
31
+ ? ` Den är ofullständig och kan ha missat något: ${problems(o).slice(0, 3).join("; ")}.`
32
+ : ""}`,
25
33
  open: "Öppna Cookies i Admin",
26
34
  why: "Du får det här för att du är vald under Cookies → Skanning.",
27
35
  },
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Guards for the public consent-record endpoint. None of them stores anything about the visitor:
3
+ * the address is a key in this process's memory for a minute and is never written down.
4
+ */
5
+ /** A saved choice is a few hundred bytes; anything far larger is not one. */
6
+ export declare const MAX_RECORD_BYTES = 4096;
7
+ /**
8
+ * Browsers send `Origin` with every POST. The site's own pages post to it, so the origin must be
9
+ * the request's host, Payload's `serverURL` or one in its `csrf` list; a script elsewhere, or no
10
+ * origin at all, is refused.
11
+ */
12
+ export declare function allowedOrigin(args: {
13
+ origin: string | null;
14
+ host: string | null;
15
+ forwardedHost?: string | null;
16
+ serverURL?: string;
17
+ csrf?: string[];
18
+ }): boolean;
19
+ /** The visitor's address as the host's proxy reports it, only to count requests in memory. */
20
+ export declare function clientKey(headers: Headers): string;
21
+ /**
22
+ * At most `limit` records per key and window in this process. On serverless each instance counts
23
+ * on its own, so this slows a script down rather than stopping it outright.
24
+ */
25
+ export declare function createRateLimit(limit?: number, windowMs?: number, now?: () => number): (key: string) => boolean;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Guards for the public consent-record endpoint. None of them stores anything about the visitor:
3
+ * the address is a key in this process's memory for a minute and is never written down.
4
+ */
5
+ /** A saved choice is a few hundred bytes; anything far larger is not one. */
6
+ export const MAX_RECORD_BYTES = 4096;
7
+ /**
8
+ * Browsers send `Origin` with every POST. The site's own pages post to it, so the origin must be
9
+ * the request's host, Payload's `serverURL` or one in its `csrf` list; a script elsewhere, or no
10
+ * origin at all, is refused.
11
+ */
12
+ export function allowedOrigin(args) {
13
+ if (!args.origin)
14
+ return false;
15
+ let origin;
16
+ try {
17
+ origin = new URL(args.origin);
18
+ }
19
+ catch {
20
+ return false;
21
+ }
22
+ const hosts = [args.forwardedHost?.split(",")[0]?.trim(), args.host?.trim()].filter(Boolean);
23
+ if (hosts.includes(origin.host))
24
+ return true;
25
+ const trusted = [args.serverURL, ...(args.csrf ?? [])].filter(Boolean);
26
+ return trusted.some((value) => {
27
+ try {
28
+ return new URL(value).origin === origin.origin;
29
+ }
30
+ catch {
31
+ return false;
32
+ }
33
+ });
34
+ }
35
+ /** The visitor's address as the host's proxy reports it, only to count requests in memory. */
36
+ export function clientKey(headers) {
37
+ return (headers.get("x-forwarded-for")?.split(",")[0]?.trim() || headers.get("x-real-ip") || "unknown");
38
+ }
39
+ /**
40
+ * At most `limit` records per key and window in this process. On serverless each instance counts
41
+ * on its own, so this slows a script down rather than stopping it outright.
42
+ */
43
+ export function createRateLimit(limit = 20, windowMs = 60_000, now = () => Date.now()) {
44
+ const hits = new Map();
45
+ return (key) => {
46
+ const time = now();
47
+ // Forget finished windows, so the map does not grow with every address seen.
48
+ if (hits.size > 10_000) {
49
+ for (const [stored, entry] of hits) {
50
+ if (time - entry.start >= windowMs)
51
+ hits.delete(stored);
52
+ }
53
+ }
54
+ const entry = hits.get(key);
55
+ if (!entry || time - entry.start >= windowMs) {
56
+ hits.set(key, { count: 1, start: time });
57
+ return true;
58
+ }
59
+ entry.count += 1;
60
+ return entry.count <= limit;
61
+ };
62
+ }
package/dist/records.js CHANGED
@@ -1,7 +1,8 @@
1
+ import { manageAccess } from "./access.js";
1
2
  import { CATEGORIES } from "./defaults.js";
3
+ import { allowedOrigin, clientKey, createRateLimit, MAX_RECORD_BYTES } from "./record-guard.js";
2
4
  import { readConsent, toConsentConfig } from "./site-config.js";
3
5
  import { CONSENT_POLICIES, CONSENT_RECORDS, DEFAULT_RETENTION_DAYS, } from "./types.js";
4
- const signedIn = ({ req }) => Boolean(req.user);
5
6
  const nobody = () => false;
6
7
  /** Checks a posted record; returns why it is refused, or the record. */
7
8
  export function parseRecord(body) {
@@ -40,13 +41,43 @@ async function cleanUp(req, retentionDays) {
40
41
  overrideAccess: true,
41
42
  });
42
43
  }
43
- /** `POST /api/consent-records/record`: stores a visitor's choice and the policy it was given for. */
44
+ /** The same choice again within this time is not stored twice (a double save, a reload). */
45
+ const REPEAT_MS = 60_000;
46
+ /**
47
+ * `POST /api/consent-records/record`: stores a visitor's choice and the policy it was given for.
48
+ * Public, so it takes posts only from the site's own pages, of a choice's size, at a visitor's
49
+ * pace, and skips a choice the visitor just saved.
50
+ */
44
51
  function recordEndpoint(options) {
52
+ const withinLimit = createRateLimit();
45
53
  return {
46
54
  path: "/record",
47
55
  method: "post",
48
56
  handler: async (req) => {
49
- const body = req.json ? await req.json().catch(() => null) : null;
57
+ const headers = req.headers;
58
+ const { serverURL, csrf } = req.payload.config;
59
+ if (!allowedOrigin({
60
+ origin: headers.get("origin"),
61
+ host: headers.get("host"),
62
+ forwardedHost: headers.get("x-forwarded-host"),
63
+ serverURL,
64
+ csrf,
65
+ }))
66
+ return Response.json({ error: "Not from this site" }, { status: 403 });
67
+ if (Number(headers.get("content-length") ?? 0) > MAX_RECORD_BYTES)
68
+ return Response.json({ error: "Too large" }, { status: 413 });
69
+ if (!withinLimit(clientKey(headers)))
70
+ return Response.json({ error: "Too many choices" }, { status: 429 });
71
+ const text = req.text ? await req.text().catch(() => "") : "";
72
+ if (text.length > MAX_RECORD_BYTES)
73
+ return Response.json({ error: "Too large" }, { status: 413 });
74
+ let body = null;
75
+ try {
76
+ body = JSON.parse(text);
77
+ }
78
+ catch {
79
+ body = null;
80
+ }
50
81
  const record = parseRecord(body);
51
82
  if (typeof record === "string")
52
83
  return Response.json({ error: record }, { status: 400 });
@@ -96,6 +127,19 @@ function recordEndpoint(options) {
96
127
  overrideAccess: true,
97
128
  });
98
129
  const granted = config.categories.filter((category) => category === "necessary" || record.choices[category]);
130
+ const { docs: latest } = await req.payload.find({
131
+ collection: CONSENT_RECORDS,
132
+ where: { subjectId: { equals: record.subjectId } },
133
+ sort: "-createdAt",
134
+ limit: 1,
135
+ depth: 0,
136
+ overrideAccess: true,
137
+ });
138
+ const previous = latest[0];
139
+ if (previous?.policyVersion === record.policyVersion &&
140
+ Date.now() - new Date(previous.createdAt ?? 0).getTime() < REPEAT_MS &&
141
+ [...(previous.granted ?? [])].sort().join() === [...granted].sort().join())
142
+ return Response.json({ ok: true }, { status: 200 });
99
143
  await req.payload.create({
100
144
  collection: CONSENT_RECORDS,
101
145
  data: {
@@ -132,7 +176,7 @@ export function recordsCollection(options) {
132
176
  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.`,
133
177
  },
134
178
  },
135
- access: { read: signedIn, create: nobody, update: nobody, delete: nobody },
179
+ access: { read: manageAccess(options), create: nobody, update: nobody, delete: nobody },
136
180
  endpoints: [recordEndpoint(options)],
137
181
  timestamps: true,
138
182
  fields: [
@@ -180,7 +224,7 @@ export function policiesCollection(options) {
180
224
  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.",
181
225
  },
182
226
  },
183
- access: { read: signedIn, create: nobody, update: nobody, delete: nobody },
227
+ access: { read: manageAccess(options), create: nobody, update: nobody, delete: nobody },
184
228
  timestamps: true,
185
229
  fields: [
186
230
  {
package/dist/scans.d.ts CHANGED
@@ -27,6 +27,8 @@ export declare function startScan({ payload, options, url: given, trigger, req,
27
27
  trigger?: "manual" | "scheduled";
28
28
  req?: PayloadRequest;
29
29
  }): Promise<Started>;
30
+ /** Closes scans left queued or running for longer than the scanner keeps them. */
31
+ export declare function closeStaleScans(payload: Payload, now?: number): Promise<number>;
30
32
  /**
31
33
  * The monthly scan as a jobs task, scheduled from the site's address so sites spread over the
32
34
  * month. It runs when the host's cron calls Payload's `/api/payload-jobs/run`, and does nothing
package/dist/scans.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { timingSafeEqual } from "node:crypto";
2
- import { evaluateScan, } from "./evaluate.js";
2
+ import { canManage, manageAccess } from "./access.js";
3
+ import { evaluateScan, scanProblems, } from "./evaluate.js";
3
4
  import { evidenceEndpoint } from "./evidence.js";
4
5
  import { notifyScan } from "./notify.js";
5
6
  import { readConsent, toConsentConfig, } from "./site-config.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);
@@ -125,6 +125,37 @@ export async function startScan({ payload, options, url: given, trigger = "manua
125
125
  });
126
126
  return { id: scan.id };
127
127
  }
128
+ /** The scanner forgets a scan a day after it ends; one still open after that never returns. */
129
+ const STALE_MS = 26 * 60 * 60 * 1000;
130
+ const LOST = "The scanner lost the scan, perhaps after a restart. Scan again.";
131
+ /** Saves an open scan the scanner no longer knows as failed, and tells the chosen users. */
132
+ async function closeLostScan(payload, scan) {
133
+ await payload.update({
134
+ collection: CONSENT_SCANS,
135
+ id: scan.id,
136
+ data: { status: "failed", error: LOST },
137
+ overrideAccess: true,
138
+ });
139
+ await notifyScan(payload, { url: scan.url ?? "", status: "failed", error: LOST });
140
+ }
141
+ /** Closes scans left queued or running for longer than the scanner keeps them. */
142
+ export async function closeStaleScans(payload, now = Date.now()) {
143
+ const { docs } = await payload.find({
144
+ collection: CONSENT_SCANS,
145
+ where: {
146
+ and: [
147
+ { status: { in: ["queued", "running"] } },
148
+ { createdAt: { less_than: new Date(now - STALE_MS).toISOString() } },
149
+ ],
150
+ },
151
+ depth: 0,
152
+ limit: 50,
153
+ overrideAccess: true,
154
+ });
155
+ for (const scan of docs)
156
+ await closeLostScan(payload, scan);
157
+ return docs.length;
158
+ }
128
159
  /**
129
160
  * The monthly scan as a jobs task, scheduled from the site's address so sites spread over the
130
161
  * month. It runs when the host's cron calls Payload's `/api/payload-jobs/run`, and does nothing
@@ -146,6 +177,7 @@ export function scanTask(options, schedule) {
146
177
  depth: 0,
147
178
  overrideAccess: true,
148
179
  }));
180
+ await closeStaleScans(req.payload).catch((error) => req.payload.logger.error({ err: error, msg: "payload-consent: could not close old scans" }));
149
181
  if (global.scheduledScans === false)
150
182
  return { output: { skipped: "Scheduled scans are off" } };
151
183
  const started = await startScan({ payload: req.payload, options, trigger: "scheduled", req });
@@ -167,6 +199,8 @@ function endpoints(options) {
167
199
  handler: async (req) => {
168
200
  if (!req.user)
169
201
  return Response.json({ error: "Sign in" }, { status: 401 });
202
+ if (!(await canManage(options, req)))
203
+ return Response.json({ error: "Not allowed" }, { status: 403 });
170
204
  const body = (await req.json?.().catch(() => null));
171
205
  const started = await startScan({ payload: req.payload, options, url: body?.url, req });
172
206
  return "error" in started
@@ -204,6 +238,16 @@ function endpoints(options) {
204
238
  previousKeys: ((await latestDone(req, scan.id))?.findings ?? []).map((f) => f.key),
205
239
  })
206
240
  : undefined;
241
+ const problems = done
242
+ ? scanProblems({
243
+ states: scan.states ?? [],
244
+ results: result.states ?? [],
245
+ pages: result.pages,
246
+ })
247
+ : [];
248
+ const summary = evaluated
249
+ ? { ...evaluated.summary, ...(problems.length ? { problems } : {}) }
250
+ : null;
207
251
  await req.payload.update({
208
252
  collection: CONSENT_SCANS,
209
253
  id: scan.id,
@@ -215,7 +259,7 @@ function endpoints(options) {
215
259
  pages: result.pages,
216
260
  results: done ? result.states : null,
217
261
  findings: evaluated?.findings ?? null,
218
- summary: evaluated?.summary ?? null,
262
+ summary,
219
263
  },
220
264
  overrideAccess: true,
221
265
  req,
@@ -224,7 +268,7 @@ function endpoints(options) {
224
268
  url: scan.url ?? "",
225
269
  status: done ? "done" : "failed",
226
270
  error: done ? null : (result.error ?? "The scan failed"),
227
- summary: evaluated?.summary,
271
+ summary: (summary ?? undefined),
228
272
  });
229
273
  return Response.json({ ok: true });
230
274
  },
@@ -236,6 +280,8 @@ function endpoints(options) {
236
280
  handler: async (req) => {
237
281
  if (!req.user)
238
282
  return Response.json({ error: "Sign in" }, { status: 401 });
283
+ if (!(await canManage(options, req)))
284
+ return Response.json({ error: "Not allowed" }, { status: 403 });
239
285
  const scan = (await req.payload.findByID({
240
286
  collection: CONSENT_SCANS,
241
287
  id: req.routeParams?.id,
@@ -249,9 +295,14 @@ function endpoints(options) {
249
295
  signal: AbortSignal.timeout(10_000),
250
296
  }).catch(() => undefined);
251
297
  const live = (await response?.json().catch(() => undefined));
252
- if (!live?.status)
298
+ if (!live?.status) {
253
299
  // The scanner restarted or forgot the scan: it will never post a result.
254
- return Response.json({ status: scan.status, lost: response?.status === 404 });
300
+ if (response?.status === 404) {
301
+ await closeLostScan(req.payload, scan);
302
+ return Response.json({ status: "failed", error: LOST });
303
+ }
304
+ return Response.json({ status: scan.status });
305
+ }
255
306
  if (live.status === "running" && scan.status === "queued")
256
307
  await req.payload.update({
257
308
  collection: CONSENT_SCANS,
@@ -274,6 +325,8 @@ function endpoints(options) {
274
325
  handler: async (req) => {
275
326
  if (!req.user)
276
327
  return Response.json({ error: "Sign in" }, { status: 401 });
328
+ if (!(await canManage(options, req)))
329
+ return Response.json({ error: "Not allowed" }, { status: 403 });
277
330
  const body = (await req.json?.().catch(() => null));
278
331
  const kind = body?.kind;
279
332
  const name = body?.name?.trim();
@@ -362,7 +415,12 @@ export function scansCollection(options) {
362
415
  sv: "Varje skanning av den publicerade webbplatsen. Starta en under Cookies → Skanning.",
363
416
  },
364
417
  },
365
- access: { read: signedIn, create: () => false, update: () => false, delete: signedIn },
418
+ access: {
419
+ read: manageAccess(options),
420
+ create: () => false,
421
+ update: () => false,
422
+ delete: manageAccess(options),
423
+ },
366
424
  endpoints: endpoints(options),
367
425
  hooks: {
368
426
  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)],
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;
@@ -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";
@@ -9,6 +10,7 @@ const COPY = {
9
10
  none: "The site has not been scanned yet.",
10
11
  waiting: "A scan is waiting or running.",
11
12
  failed: "The latest scan failed",
13
+ incomplete: "Incomplete: it may have missed something",
12
14
  action: (n) => `${n} need${n === 1 ? "s" : ""} action`,
13
15
  unknown: (n) => `${n} not in the Cookie services`,
14
16
  allGood: "Everything found is in order",
@@ -24,6 +26,7 @@ const COPY = {
24
26
  none: "Webbplatsen har inte skannats än.",
25
27
  waiting: "En skanning väntar eller pågår.",
26
28
  failed: "Senaste skanningen misslyckades",
29
+ incomplete: "Ofullständig: den kan ha missat något",
27
30
  action: (n) => `${n} kräver åtgärd`,
28
31
  unknown: (n) => `${n} finns inte bland Cookietjänsterna`,
29
32
  allGood: "Allt som hittades är i ordning",
@@ -41,6 +44,10 @@ const COPY = {
41
44
  * collection, not a status.
42
45
  */
43
46
  export async function ConsentScanWidget({ req }) {
47
+ // Only for those who work with cookies: the scans are theirs to read.
48
+ const options = (req.payload.config.custom?.consent ?? {});
49
+ if (!(await canManage(options, req)))
50
+ return null;
44
51
  const language = req.i18n?.language === "sv" ? "sv" : "en";
45
52
  const copy = COPY[language];
46
53
  const [{ docs }, global] = await Promise.all([
@@ -66,7 +73,14 @@ export async function ConsentScanWidget({ req }) {
66
73
  const pending = scans[0]?.status === "queued" || scans[0]?.status === "running";
67
74
  const latest = scans.find((scan) => scan.status === "done" || scan.status === "failed");
68
75
  const summary = latest?.status === "done" ? latest.summary : undefined;
69
- const tone = summary ? (summary.action || summary.unknown ? "red" : "green") : "grey";
76
+ const incomplete = Boolean(summary?.problems?.length);
77
+ const tone = summary
78
+ ? summary.action || summary.unknown
79
+ ? "red"
80
+ : incomplete
81
+ ? "grey"
82
+ : "green"
83
+ : "grey";
70
84
  const format = (value) => value
71
85
  ? new Date(value).toLocaleDateString(language === "sv" ? "sv-SE" : "en-GB", {
72
86
  day: "numeric",
@@ -84,7 +98,8 @@ export async function ConsentScanWidget({ req }) {
84
98
  ? [
85
99
  ...(summary.action ? [copy.action(summary.action)] : []),
86
100
  ...(summary.unknown ? [copy.unknown(summary.unknown)] : []),
87
- ...(summary.action || summary.unknown ? [] : [copy.allGood]),
101
+ ...(incomplete ? [copy.incomplete] : []),
102
+ ...(summary.action || summary.unknown || incomplete ? [] : [copy.allGood]),
88
103
  ...(summary.new ? [copy.isNew(summary.new)] : []),
89
104
  ]
90
105
  : [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simmalugnt-se/payload-consent",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Cookie consent for Payload sites: banner texts, services and scans in Admin",
5
5
  "keywords": [
6
6
  "payload",