@simmalugnt-se/payload-consent 0.5.0 → 0.5.2

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,24 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.2
4
+
5
+ - Adding a scan's finding to a service keeps what the scan could not see (`summary.problems`):
6
+ judging the scan again wrote over it, so an incomplete scan looked complete (0.5.0).
7
+ - Adding a finding to a service writes as the editor, so a project's own access on the services
8
+ applies, in one of the site's languages, and with a known category (`necessary` otherwise).
9
+ - Evidence larger than 8 MB is refused before it is read; the scanner sends files up to 4 MB.
10
+
11
+ ## 0.5.1
12
+
13
+ - What a visitor was shown is kept when it changes: a reworded banner text or a service's new
14
+ purpose saves a new snapshot under Consent policies with the next choice, and a record's
15
+ snapshot is the latest saved before it. Before, only the first snapshot per policy version and
16
+ language was kept. The policy version still changes only with categories and cookies, so a text
17
+ alone asks nobody again.
18
+ - An integration ID is checked when a service is saved (letters, digits and dashes; Hotjar's a
19
+ number other than 0), an ID saved before that is left out of the site, and an integration c15t
20
+ refuses is skipped in the browser instead of breaking the page.
21
+
3
22
  ## 0.5.0
4
23
 
5
24
  - A scan that could not see everything says so: a state the scanner did not return or that
@@ -8,5 +8,7 @@ import { type ConsentPluginOptions } from "./types.ts";
8
8
  export declare function evidenceCollection(options: ConsentPluginOptions): CollectionConfig;
9
9
  /** Deletes the evidence of all but the latest `keep` finished scans, and any without a scan. */
10
10
  export declare function pruneEvidence(payload: Payload, keep: number): Promise<void>;
11
+ /** The scanner sends files up to 4 MB; anything far larger is not its evidence. */
12
+ export declare const MAX_EVIDENCE_BYTES: number;
11
13
  /** The scanner posts each evidence file here after the result, one file per request. */
12
14
  export declare function evidenceEndpoint(options: ConsentPluginOptions, checkToken: (req: PayloadRequest) => boolean): Endpoint;
package/dist/evidence.js CHANGED
@@ -69,6 +69,8 @@ export async function pruneEvidence(payload, keep) {
69
69
  overrideAccess: true,
70
70
  });
71
71
  }
72
+ /** The scanner sends files up to 4 MB; anything far larger is not its evidence. */
73
+ export const MAX_EVIDENCE_BYTES = 8 * 1024 * 1024;
72
74
  /** The scanner posts each evidence file here after the result, one file per request. */
73
75
  export function evidenceEndpoint(options, checkToken) {
74
76
  return {
@@ -95,9 +97,13 @@ export function evidenceEndpoint(options, checkToken) {
95
97
  return Response.json({ error: "Unknown scan" }, { status: 404 });
96
98
  if (scan.status !== "done")
97
99
  return Response.json({ error: "The scan has no result yet" }, { status: 409 });
100
+ if (Number(req.headers.get("content-length") ?? 0) > MAX_EVIDENCE_BYTES)
101
+ return Response.json({ error: "Too large" }, { status: 413 });
98
102
  const data = Buffer.from((await req.arrayBuffer?.()) ?? new ArrayBuffer(0));
99
103
  if (!data.length)
100
104
  return Response.json({ error: "Empty file" }, { status: 400 });
105
+ if (data.length > MAX_EVIDENCE_BYTES)
106
+ return Response.json({ error: "Too large" }, { status: 413 });
101
107
  const [, state, , extension] = match;
102
108
  const pdf = extension === "pdf";
103
109
  const doc = await req.payload.create({
@@ -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/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
@@ -28,6 +28,15 @@ export function parseRecord(body) {
28
28
  }
29
29
  return { subjectId, choices: parsed, policyVersion, locale, path };
30
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
+ }
31
40
  let lastCleanup = 0;
32
41
  /** Deletes records older than the retention period, at most once a day per server process. */
33
42
  async function cleanUp(req, retentionDays) {
@@ -89,7 +98,27 @@ function recordEndpoint(options) {
89
98
  const unknown = Object.keys(record.choices).filter((name) => !config.categories.includes(name));
90
99
  if (unknown.length)
91
100
  return Response.json({ error: `Not in the policy: ${unknown.join(", ")}` }, { status: 400 });
92
- 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({
93
122
  collection: CONSENT_POLICIES,
94
123
  where: {
95
124
  and: [
@@ -97,33 +126,16 @@ function recordEndpoint(options) {
97
126
  { locale: { equals: record.locale } },
98
127
  ],
99
128
  },
129
+ sort: "-createdAt",
130
+ limit: 1,
131
+ depth: 0,
100
132
  overrideAccess: true,
101
133
  });
102
- if (!existing.totalDocs)
134
+ const shownBefore = shown[0]?.snapshot;
135
+ if (stableJson(shownBefore) !== stableJson(snapshot))
103
136
  await req.payload.create({
104
137
  collection: CONSENT_POLICIES,
105
- data: {
106
- version: record.policyVersion,
107
- locale: record.locale,
108
- snapshot: {
109
- categories: config.categories,
110
- messages: config.messages,
111
- services: services.map((service) => ({
112
- name: service.name,
113
- provider: service.provider,
114
- category: service.category,
115
- purpose: service.purpose,
116
- loading: service.loading,
117
- integration: service.loading === "integration" ? service.integration : undefined,
118
- storage: (service.storage ?? []).map(({ name, type, duration, thirdParty }) => ({
119
- name,
120
- type,
121
- duration,
122
- thirdParty,
123
- })),
124
- })),
125
- },
126
- },
138
+ data: { version: record.policyVersion, locale: record.locale, snapshot },
127
139
  overrideAccess: true,
128
140
  });
129
141
  const granted = config.categories.filter((category) => category === "necessary" || record.choices[category]);
@@ -220,8 +232,8 @@ export function policiesCollection(options) {
220
232
  group: false,
221
233
  defaultColumns: ["version", "locale", "createdAt"],
222
234
  description: {
223
- en: "What visitors were shown, per policy version and language: categories, services and texts. Saved with the first choice for each version.",
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.",
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.",
225
237
  },
226
238
  },
227
239
  access: { read: manageAccess(options), create: nobody, update: nobody, delete: nobody },
package/dist/scans.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { timingSafeEqual } from "node:crypto";
2
2
  import { canManage, manageAccess } from "./access.js";
3
+ import { CATEGORIES } from "./defaults.js";
3
4
  import { evaluateScan, scanProblems, } from "./evaluate.js";
4
5
  import { evidenceEndpoint } from "./evidence.js";
5
6
  import { notifyScan } from "./notify.js";
@@ -335,14 +336,25 @@ function endpoints(options) {
335
336
  !serviceName ||
336
337
  (kind !== "cookie" && kind !== "localStorage" && kind !== "host"))
337
338
  return Response.json({ error: "Name the finding and the service" }, { status: 400 });
338
- const locale = body?.locale;
339
+ // The site's own languages only; anything else writes the default one.
340
+ const localization = req.payload.config.localization;
341
+ const locale = localization &&
342
+ localization.localeCodes.includes(String(body?.locale)) &&
343
+ typeof body?.locale === "string"
344
+ ? body.locale
345
+ : undefined;
346
+ const category = CATEGORIES.includes(body?.category)
347
+ ? body?.category
348
+ : "necessary";
349
+ // As the editor: a project's own access on the services still applies.
350
+ const asEditor = { overrideAccess: false, user: req.user, req };
339
351
  const existing = (await req.payload.find({
340
352
  collection: CONSENT_SERVICES,
341
353
  where: { name: { equals: serviceName } },
342
354
  limit: 1,
343
355
  depth: 0,
344
356
  locale: locale,
345
- req,
357
+ ...asEditor,
346
358
  })).docs[0];
347
359
  const entry = kind === "host"
348
360
  ? { hosts: [...(existing?.hosts ?? []), { host: name }] }
@@ -358,21 +370,21 @@ function endpoints(options) {
358
370
  id: existing.id,
359
371
  data: entry,
360
372
  locale: locale,
361
- req,
373
+ ...asEditor,
362
374
  })
363
375
  : await req.payload.create({
364
376
  collection: CONSENT_SERVICES,
365
377
  data: {
366
378
  name: serviceName,
367
379
  provider: body?.provider || undefined,
368
- category: body?.category || "necessary",
380
+ category,
369
381
  purpose: body?.purpose || serviceName,
370
382
  policyUrl: body?.policyUrl || undefined,
371
383
  loading: "code",
372
384
  ...entry,
373
385
  },
374
386
  locale: locale,
375
- req,
387
+ ...asEditor,
376
388
  });
377
389
  const latest = await latestDone(req);
378
390
  if (latest) {
@@ -384,10 +396,15 @@ function endpoints(options) {
384
396
  services: await allServices(req),
385
397
  previousKeys: (previous?.findings ?? []).map((f) => f.key),
386
398
  });
399
+ // Judged again against the services; what the scan could not see stays as it was.
400
+ const problems = latest.summary?.problems;
387
401
  await req.payload.update({
388
402
  collection: CONSENT_SCANS,
389
403
  id: latest.id,
390
- data: { findings: evaluated.findings, summary: evaluated.summary },
404
+ data: {
405
+ findings: evaluated.findings,
406
+ summary: { ...evaluated.summary, ...(problems?.length ? { problems } : {}) },
407
+ },
391
408
  overrideAccess: true,
392
409
  req,
393
410
  });
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
  : []);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simmalugnt-se/payload-consent",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "Cookie consent for Payload sites: banner texts, services and scans in Admin",
5
5
  "keywords": [
6
6
  "payload",