@simmalugnt-se/payload-consent 0.5.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,16 @@
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
+
3
14
  ## 0.5.0
4
15
 
5
16
  - A scan that could not see everything says so: a state the scanner did not return or that
@@ -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/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.1",
4
4
  "description": "Cookie consent for Payload sites: banner texts, services and scans in Admin",
5
5
  "keywords": [
6
6
  "payload",