@simmalugnt-se/payload-consent 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,32 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.1
4
+
5
+ - What a visitor was shown is kept when it changes: a reworded banner text or a service's new
6
+ purpose saves a new snapshot under Consent policies with the next choice, and a record's
7
+ snapshot is the latest saved before it. Before, only the first snapshot per policy version and
8
+ language was kept. The policy version still changes only with categories and cookies, so a text
9
+ alone asks nobody again.
10
+ - An integration ID is checked when a service is saved (letters, digits and dashes; Hotjar's a
11
+ number other than 0), an ID saved before that is left out of the site, and an integration c15t
12
+ refuses is skipped in the browser instead of breaking the page.
13
+
14
+ ## 0.5.0
15
+
16
+ - A scan that could not see everything says so: a state the scanner did not return or that
17
+ visited no pages, the scanner's errors and unreadable sitemaps are kept in the summary
18
+ (`summary.problems`), shown on the Scan tab, named in the email and marked incomplete in the
19
+ dashboard widget instead of "in order". Before, a scan whose "reject all" state failed looked
20
+ clean.
21
+ - A scan the scanner has forgotten (after a restart) is saved as failed when the Scan tab asks
22
+ about it, and the monthly job closes scans left queued or running for more than 26 hours; both
23
+ email the chosen users. Before, they stayed queued.
24
+
25
+ - The public `POST /api/consent-records/record` takes choices only from the site's own pages (the
26
+ request's host, `serverURL` or Payload's `csrf` list), up to 4 kB, and at most 20 a minute from
27
+ one address per server process; the address is only counted in memory, never stored. The same
28
+ choice from the same visitor within a minute is not stored twice; a changed choice is.
29
+
3
30
  ## 0.4.0
4
31
 
5
32
  - `access.manage` says who works with cookies in Admin: the texts and services, the consent log,
@@ -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. */
@@ -57,11 +57,16 @@ const factories = {
57
57
  * advanced mode), which sends data about the visit before the visitor has chosen.
58
58
  */
59
59
  export function integrationScripts(config) {
60
- return config.integrations.map(({ key, id, category }) => ({
61
- ...factories[key](id, category),
62
- category,
63
- alwaysLoad: false,
64
- }));
60
+ return config.integrations.flatMap(({ key, id, category }) => {
61
+ // One integration c15t refuses must not take the site's layout down with it.
62
+ try {
63
+ return [{ ...factories[key](id, category), category, alwaysLoad: false }];
64
+ }
65
+ catch (error) {
66
+ console.error(`payload-consent: the ${key} integration could not be loaded`, error);
67
+ return [];
68
+ }
69
+ });
65
70
  }
66
71
  const ConfigContext = createContext(null);
67
72
  /** The banner, the settings dialog and c15t's consent state around the site. */
@@ -38,3 +38,9 @@ export declare const INTEGRATIONS: readonly [{
38
38
  }];
39
39
  export type IntegrationKey = (typeof INTEGRATIONS)[number]["key"];
40
40
  export declare const isIntegration: (value: unknown) => value is IntegrationKey;
41
+ /**
42
+ * Why an integration's ID cannot be used, or undefined when it can. The providers' IDs are
43
+ * letters, digits and dashes (GTM-…, G-…, numbers); anything else would end up in a script URL.
44
+ * Hotjar's loader throws on "0", which would take the site's layout down with it.
45
+ */
46
+ export declare function integrationIdProblem(key: unknown, id: unknown): string | undefined;
@@ -30,3 +30,18 @@ export const INTEGRATIONS = [
30
30
  { key: "hotjar", label: "Hotjar", idLabel: "Site ID" },
31
31
  ];
32
32
  export const isIntegration = (value) => INTEGRATIONS.some((integration) => integration.key === value);
33
+ /**
34
+ * Why an integration's ID cannot be used, or undefined when it can. The providers' IDs are
35
+ * letters, digits and dashes (GTM-…, G-…, numbers); anything else would end up in a script URL.
36
+ * Hotjar's loader throws on "0", which would take the site's layout down with it.
37
+ */
38
+ export function integrationIdProblem(key, id) {
39
+ const value = typeof id === "string" ? id.trim() : "";
40
+ if (!value)
41
+ return "Enter the integration's ID";
42
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(value))
43
+ return "The ID has only letters, digits and dashes, as the provider shows it";
44
+ if (key === "hotjar" && !/^[1-9][0-9]*$/.test(value))
45
+ return "Hotjar's Site ID is a number";
46
+ return undefined;
47
+ }
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.d.ts CHANGED
@@ -11,5 +11,10 @@ export type ConsentRecordInput = {
11
11
  };
12
12
  /** Checks a posted record; returns why it is refused, or the record. */
13
13
  export declare function parseRecord(body: unknown): ConsentRecordInput | string;
14
+ /**
15
+ * JSON with object keys in order and undefined values left out, so a snapshot read back from the
16
+ * database (Postgres' jsonb reorders keys) compares equal to the same one built anew.
17
+ */
18
+ export declare function stableJson(value: unknown): string;
14
19
  export declare function recordsCollection(options: ConsentPluginOptions): CollectionConfig;
15
20
  export declare function policiesCollection(options: ConsentPluginOptions): CollectionConfig;
package/dist/records.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { manageAccess } from "./access.js";
2
2
  import { CATEGORIES } from "./defaults.js";
3
+ import { allowedOrigin, clientKey, createRateLimit, MAX_RECORD_BYTES } from "./record-guard.js";
3
4
  import { readConsent, toConsentConfig } from "./site-config.js";
4
5
  import { CONSENT_POLICIES, CONSENT_RECORDS, DEFAULT_RETENTION_DAYS, } from "./types.js";
5
6
  const nobody = () => false;
@@ -27,6 +28,15 @@ export function parseRecord(body) {
27
28
  }
28
29
  return { subjectId, choices: parsed, policyVersion, locale, path };
29
30
  }
31
+ /**
32
+ * JSON with object keys in order and undefined values left out, so a snapshot read back from the
33
+ * database (Postgres' jsonb reorders keys) compares equal to the same one built anew.
34
+ */
35
+ export function stableJson(value) {
36
+ return JSON.stringify(value, (_key, entry) => entry && typeof entry === "object" && !Array.isArray(entry)
37
+ ? Object.fromEntries(Object.entries(entry).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
38
+ : entry);
39
+ }
30
40
  let lastCleanup = 0;
31
41
  /** Deletes records older than the retention period, at most once a day per server process. */
32
42
  async function cleanUp(req, retentionDays) {
@@ -40,13 +50,43 @@ async function cleanUp(req, retentionDays) {
40
50
  overrideAccess: true,
41
51
  });
42
52
  }
43
- /** `POST /api/consent-records/record`: stores a visitor's choice and the policy it was given for. */
53
+ /** The same choice again within this time is not stored twice (a double save, a reload). */
54
+ const REPEAT_MS = 60_000;
55
+ /**
56
+ * `POST /api/consent-records/record`: stores a visitor's choice and the policy it was given for.
57
+ * Public, so it takes posts only from the site's own pages, of a choice's size, at a visitor's
58
+ * pace, and skips a choice the visitor just saved.
59
+ */
44
60
  function recordEndpoint(options) {
61
+ const withinLimit = createRateLimit();
45
62
  return {
46
63
  path: "/record",
47
64
  method: "post",
48
65
  handler: async (req) => {
49
- const body = req.json ? await req.json().catch(() => null) : null;
66
+ const headers = req.headers;
67
+ const { serverURL, csrf } = req.payload.config;
68
+ if (!allowedOrigin({
69
+ origin: headers.get("origin"),
70
+ host: headers.get("host"),
71
+ forwardedHost: headers.get("x-forwarded-host"),
72
+ serverURL,
73
+ csrf,
74
+ }))
75
+ return Response.json({ error: "Not from this site" }, { status: 403 });
76
+ if (Number(headers.get("content-length") ?? 0) > MAX_RECORD_BYTES)
77
+ return Response.json({ error: "Too large" }, { status: 413 });
78
+ if (!withinLimit(clientKey(headers)))
79
+ return Response.json({ error: "Too many choices" }, { status: 429 });
80
+ const text = req.text ? await req.text().catch(() => "") : "";
81
+ if (text.length > MAX_RECORD_BYTES)
82
+ return Response.json({ error: "Too large" }, { status: 413 });
83
+ let body = null;
84
+ try {
85
+ body = JSON.parse(text);
86
+ }
87
+ catch {
88
+ body = null;
89
+ }
50
90
  const record = parseRecord(body);
51
91
  if (typeof record === "string")
52
92
  return Response.json({ error: record }, { status: 400 });
@@ -58,7 +98,27 @@ function recordEndpoint(options) {
58
98
  const unknown = Object.keys(record.choices).filter((name) => !config.categories.includes(name));
59
99
  if (unknown.length)
60
100
  return Response.json({ error: `Not in the policy: ${unknown.join(", ")}` }, { status: 400 });
61
- const existing = await req.payload.count({
101
+ // What this visitor was shown. A new snapshot whenever it changes (a reworded text, a
102
+ // service's new purpose), so the one in force for a record is the latest created before it.
103
+ const snapshot = {
104
+ categories: config.categories,
105
+ messages: config.messages,
106
+ services: services.map((service) => ({
107
+ name: service.name,
108
+ provider: service.provider,
109
+ category: service.category,
110
+ purpose: service.purpose,
111
+ loading: service.loading,
112
+ integration: service.loading === "integration" ? service.integration : undefined,
113
+ storage: (service.storage ?? []).map(({ name, type, duration, thirdParty }) => ({
114
+ name,
115
+ type,
116
+ duration,
117
+ thirdParty,
118
+ })),
119
+ })),
120
+ };
121
+ const { docs: shown } = await req.payload.find({
62
122
  collection: CONSENT_POLICIES,
63
123
  where: {
64
124
  and: [
@@ -66,36 +126,32 @@ function recordEndpoint(options) {
66
126
  { locale: { equals: record.locale } },
67
127
  ],
68
128
  },
129
+ sort: "-createdAt",
130
+ limit: 1,
131
+ depth: 0,
69
132
  overrideAccess: true,
70
133
  });
71
- if (!existing.totalDocs)
134
+ const shownBefore = shown[0]?.snapshot;
135
+ if (stableJson(shownBefore) !== stableJson(snapshot))
72
136
  await req.payload.create({
73
137
  collection: CONSENT_POLICIES,
74
- data: {
75
- version: record.policyVersion,
76
- locale: record.locale,
77
- snapshot: {
78
- categories: config.categories,
79
- messages: config.messages,
80
- services: services.map((service) => ({
81
- name: service.name,
82
- provider: service.provider,
83
- category: service.category,
84
- purpose: service.purpose,
85
- loading: service.loading,
86
- integration: service.loading === "integration" ? service.integration : undefined,
87
- storage: (service.storage ?? []).map(({ name, type, duration, thirdParty }) => ({
88
- name,
89
- type,
90
- duration,
91
- thirdParty,
92
- })),
93
- })),
94
- },
95
- },
138
+ data: { version: record.policyVersion, locale: record.locale, snapshot },
96
139
  overrideAccess: true,
97
140
  });
98
141
  const granted = config.categories.filter((category) => category === "necessary" || record.choices[category]);
142
+ const { docs: latest } = await req.payload.find({
143
+ collection: CONSENT_RECORDS,
144
+ where: { subjectId: { equals: record.subjectId } },
145
+ sort: "-createdAt",
146
+ limit: 1,
147
+ depth: 0,
148
+ overrideAccess: true,
149
+ });
150
+ const previous = latest[0];
151
+ if (previous?.policyVersion === record.policyVersion &&
152
+ Date.now() - new Date(previous.createdAt ?? 0).getTime() < REPEAT_MS &&
153
+ [...(previous.granted ?? [])].sort().join() === [...granted].sort().join())
154
+ return Response.json({ ok: true }, { status: 200 });
99
155
  await req.payload.create({
100
156
  collection: CONSENT_RECORDS,
101
157
  data: {
@@ -176,8 +232,8 @@ export function policiesCollection(options) {
176
232
  group: false,
177
233
  defaultColumns: ["version", "locale", "createdAt"],
178
234
  description: {
179
- en: "What visitors were shown, per policy version and language: categories, services and texts. Saved with the first choice for each version.",
180
- sv: "Det besökarna fick se, per policyversion och språk: kategorier, tjänster och texter. Sparas med det första valet för varje version.",
235
+ en: "What visitors were shown, per policy version and language: categories, services and texts. Saved with the first choice after it changes; a record's is the latest saved before it.",
236
+ sv: "Det besökarna fick se, per policyversion och språk: kategorier, tjänster och texter. Sparas med det första valet efter en ändring; en posts är den senaste som sparades före den.",
181
237
  },
182
238
  },
183
239
  access: { read: manageAccess(options), create: nobody, update: nobody, delete: nobody },
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,6 +1,6 @@
1
1
  import { timingSafeEqual } from "node:crypto";
2
2
  import { canManage, manageAccess } from "./access.js";
3
- import { evaluateScan, } from "./evaluate.js";
3
+ import { evaluateScan, scanProblems, } from "./evaluate.js";
4
4
  import { evidenceEndpoint } from "./evidence.js";
5
5
  import { notifyScan } from "./notify.js";
6
6
  import { readConsent, toConsentConfig, } from "./site-config.js";
@@ -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 });
@@ -206,6 +238,16 @@ function endpoints(options) {
206
238
  previousKeys: ((await latestDone(req, scan.id))?.findings ?? []).map((f) => f.key),
207
239
  })
208
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;
209
251
  await req.payload.update({
210
252
  collection: CONSENT_SCANS,
211
253
  id: scan.id,
@@ -217,7 +259,7 @@ function endpoints(options) {
217
259
  pages: result.pages,
218
260
  results: done ? result.states : null,
219
261
  findings: evaluated?.findings ?? null,
220
- summary: evaluated?.summary ?? null,
262
+ summary,
221
263
  },
222
264
  overrideAccess: true,
223
265
  req,
@@ -226,7 +268,7 @@ function endpoints(options) {
226
268
  url: scan.url ?? "",
227
269
  status: done ? "done" : "failed",
228
270
  error: done ? null : (result.error ?? "The scan failed"),
229
- summary: evaluated?.summary,
271
+ summary: (summary ?? undefined),
230
272
  });
231
273
  return Response.json({ ok: true });
232
274
  },
@@ -253,9 +295,14 @@ function endpoints(options) {
253
295
  signal: AbortSignal.timeout(10_000),
254
296
  }).catch(() => undefined);
255
297
  const live = (await response?.json().catch(() => undefined));
256
- if (!live?.status)
298
+ if (!live?.status) {
257
299
  // The scanner restarted or forgot the scan: it will never post a result.
258
- 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
+ }
259
306
  if (live.status === "running" && scan.status === "queued")
260
307
  await req.payload.update({
261
308
  collection: CONSENT_SCANS,
package/dist/services.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { manageAccess } from "./access.js";
2
2
  import { CATEGORIES, OPTIONAL_CATEGORIES } from "./defaults.js";
3
3
  import { categoryLabels } from "./global.js";
4
- import { INTEGRATIONS } from "./integrations.js";
4
+ import { INTEGRATIONS, integrationIdProblem } from "./integrations.js";
5
5
  import { CONSENT_GLOBAL, CONSENT_SERVICES } from "./types.js";
6
6
  /**
7
7
  * Keeps the global's categories in step with the services, for the Banner tab's conditions. A bulk
@@ -172,8 +172,8 @@ export function servicesCollection(options) {
172
172
  },
173
173
  },
174
174
  validate: (value, { siblingData }) => siblingData?.loading !== "integration" ||
175
- (typeof value === "string" && value.trim() !== "") ||
176
- "Enter the integration's ID",
175
+ integrationIdProblem(siblingData?.integration, value) ||
176
+ true,
177
177
  },
178
178
  ],
179
179
  },
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { CATEGORIES, defaultTexts, isFormerSuggestion, OPTIONAL_CATEGORIES, } from "./defaults.js";
3
- import { isIntegration } from "./integrations.js";
3
+ import { integrationIdProblem, isIntegration } from "./integrations.js";
4
4
  import { consentDays, DEFAULT_CONSENT_MONTHS } from "./renewal.js";
5
5
  import { CONSENT_GLOBAL, CONSENT_RECORDS, CONSENT_SERVICES, POLICY_COOKIE, } from "./types.js";
6
6
  const isDoc = (value) => Boolean(value) && typeof value === "object";
@@ -49,6 +49,8 @@ export function toConsentConfig(doc, services, options) {
49
49
  const integrations = services.flatMap((service) => service.loading === "integration" &&
50
50
  isIntegration(service.integration) &&
51
51
  service.integrationId?.trim() &&
52
+ // An ID saved before it was checked never reaches the visitor's browser.
53
+ !integrationIdProblem(service.integration, service.integrationId) &&
52
54
  isCategory(service.category)
53
55
  ? [{ key: service.integration, id: service.integrationId.trim(), category: service.category }]
54
56
  : []);
@@ -10,6 +10,7 @@ const COPY = {
10
10
  none: "The site has not been scanned yet.",
11
11
  waiting: "A scan is waiting or running.",
12
12
  failed: "The latest scan failed",
13
+ incomplete: "Incomplete: it may have missed something",
13
14
  action: (n) => `${n} need${n === 1 ? "s" : ""} action`,
14
15
  unknown: (n) => `${n} not in the Cookie services`,
15
16
  allGood: "Everything found is in order",
@@ -25,6 +26,7 @@ const COPY = {
25
26
  none: "Webbplatsen har inte skannats än.",
26
27
  waiting: "En skanning väntar eller pågår.",
27
28
  failed: "Senaste skanningen misslyckades",
29
+ incomplete: "Ofullständig: den kan ha missat något",
28
30
  action: (n) => `${n} kräver åtgärd`,
29
31
  unknown: (n) => `${n} finns inte bland Cookietjänsterna`,
30
32
  allGood: "Allt som hittades är i ordning",
@@ -71,7 +73,14 @@ export async function ConsentScanWidget({ req }) {
71
73
  const pending = scans[0]?.status === "queued" || scans[0]?.status === "running";
72
74
  const latest = scans.find((scan) => scan.status === "done" || scan.status === "failed");
73
75
  const summary = latest?.status === "done" ? latest.summary : undefined;
74
- 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";
75
84
  const format = (value) => value
76
85
  ? new Date(value).toLocaleDateString(language === "sv" ? "sv-SE" : "en-GB", {
77
86
  day: "numeric",
@@ -89,7 +98,8 @@ export async function ConsentScanWidget({ req }) {
89
98
  ? [
90
99
  ...(summary.action ? [copy.action(summary.action)] : []),
91
100
  ...(summary.unknown ? [copy.unknown(summary.unknown)] : []),
92
- ...(summary.action || summary.unknown ? [] : [copy.allGood]),
101
+ ...(incomplete ? [copy.incomplete] : []),
102
+ ...(summary.action || summary.unknown || incomplete ? [] : [copy.allGood]),
93
103
  ...(summary.new ? [copy.isNew(summary.new)] : []),
94
104
  ]
95
105
  : [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simmalugnt-se/payload-consent",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "description": "Cookie consent for Payload sites: banner texts, services and scans in Admin",
5
5
  "keywords": [
6
6
  "payload",