@simmalugnt-se/payload-consent 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/LICENSE +21 -0
  3. package/README.md +238 -2
  4. package/dist/admin/ScanPanel.d.ts +3 -0
  5. package/dist/admin/ScanPanel.js +232 -0
  6. package/dist/block.d.ts +6 -0
  7. package/dist/block.js +27 -0
  8. package/dist/defaults.d.ts +56 -0
  9. package/dist/defaults.js +137 -0
  10. package/dist/evaluate.d.ts +106 -0
  11. package/dist/evaluate.js +101 -0
  12. package/dist/evidence.d.ts +12 -0
  13. package/dist/evidence.js +113 -0
  14. package/dist/exports/admin.d.ts +1 -0
  15. package/dist/exports/admin.js +1 -0
  16. package/dist/exports/client.d.ts +37 -0
  17. package/dist/exports/client.js +177 -0
  18. package/dist/exports/rsc.d.ts +1 -0
  19. package/dist/exports/rsc.js +1 -0
  20. package/dist/global.d.ts +14 -0
  21. package/dist/global.js +272 -0
  22. package/dist/index.d.ts +13 -0
  23. package/dist/index.js +75 -0
  24. package/dist/integrations.d.ts +40 -0
  25. package/dist/integrations.js +32 -0
  26. package/dist/notify.d.ts +15 -0
  27. package/dist/notify.js +86 -0
  28. package/dist/records.d.ts +15 -0
  29. package/dist/records.js +197 -0
  30. package/dist/scans.d.ts +37 -0
  31. package/dist/scans.js +423 -0
  32. package/dist/schedule.d.ts +17 -0
  33. package/dist/schedule.js +18 -0
  34. package/dist/services.d.ts +8 -0
  35. package/dist/services.js +257 -0
  36. package/dist/site-config.d.ts +128 -0
  37. package/dist/site-config.js +204 -0
  38. package/dist/styles/admin.css +144 -0
  39. package/dist/styles/consent.css +296 -0
  40. package/dist/types.d.ts +65 -0
  41. package/dist/types.js +17 -0
  42. package/dist/widget/ConsentScanWidget.d.ts +8 -0
  43. package/dist/widget/ConsentScanWidget.js +99 -0
  44. package/package.json +76 -3
package/dist/notify.js ADDED
@@ -0,0 +1,86 @@
1
+ import { CONSENT_GLOBAL } from "./types.js";
2
+ /** A scan worth an email: it failed, found something to handle, or found something new. */
3
+ export function needsNotice(outcome) {
4
+ if (outcome.status === "failed")
5
+ return true;
6
+ const summary = outcome.summary;
7
+ return Boolean(summary && (summary.action || summary.unknown || summary.new));
8
+ }
9
+ const COPY = {
10
+ en: {
11
+ subject: (o, host) => o.status === "failed"
12
+ ? `Cookie scan of ${host} failed`
13
+ : `Cookie scan of ${host}: ${count(o.summary, "en")}`,
14
+ 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")}.`,
16
+ open: "Open Cookies in Admin",
17
+ why: "You get this because you are chosen under Cookies → Scan.",
18
+ },
19
+ sv: {
20
+ subject: (o, host) => o.status === "failed"
21
+ ? `Cookieskanningen av ${host} misslyckades`
22
+ : `Cookieskanning av ${host}: ${count(o.summary, "sv")}`,
23
+ failed: (o) => `Cookieskanningen av ${o.url} misslyckades: ${o.error ?? "ingen orsak angiven"}.`,
24
+ done: (o) => `Cookieskanningen av ${o.url} hittade ${count(o.summary, "sv")}.`,
25
+ open: "Öppna Cookies i Admin",
26
+ why: "Du får det här för att du är vald under Cookies → Skanning.",
27
+ },
28
+ };
29
+ function count(summary, language) {
30
+ const s = summary ?? { action: 0, unknown: 0, ok: 0, new: 0 };
31
+ const parts = language === "sv"
32
+ ? [
33
+ s.action && `${s.action} som kräver åtgärd`,
34
+ s.unknown && `${s.unknown} som inte finns bland Cookietjänsterna`,
35
+ s.new && `${s.new} nya sedan förra skanningen`,
36
+ ]
37
+ : [
38
+ s.action && `${s.action} needing action`,
39
+ s.unknown && `${s.unknown} not in the Cookie services`,
40
+ s.new && `${s.new} new since the last scan`,
41
+ ];
42
+ return (parts.filter(Boolean).join(", ") ||
43
+ (language === "sv" ? "inget att åtgärda" : "nothing to handle"));
44
+ }
45
+ const escape = (value) => value.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c] ?? c);
46
+ /**
47
+ * Emails the users picked under Cookies → Scan about a finished scan, through the host's
48
+ * email adapter, when it needs a look. Admin's default language picks the text.
49
+ */
50
+ export async function notifyScan(payload, outcome) {
51
+ if (!needsNotice(outcome))
52
+ return;
53
+ const global = (await payload.findGlobal({
54
+ slug: CONSENT_GLOBAL,
55
+ depth: 1,
56
+ overrideAccess: true,
57
+ }));
58
+ const to = (global.notify ?? [])
59
+ .map((user) => (typeof user === "object" ? user?.email : undefined))
60
+ .filter((email) => Boolean(email));
61
+ if (!to.length)
62
+ return;
63
+ const language = payload.config.i18n.fallbackLanguage === "sv" ? "sv" : "en";
64
+ const copy = COPY[language];
65
+ const host = (() => {
66
+ try {
67
+ return new URL(outcome.url).host;
68
+ }
69
+ catch {
70
+ return outcome.url;
71
+ }
72
+ })();
73
+ const text = outcome.status === "failed" ? copy.failed(outcome) : copy.done(outcome);
74
+ const link = `${payload.config.serverURL}${payload.config.routes.admin}/globals/${CONSENT_GLOBAL}`;
75
+ try {
76
+ await payload.sendEmail({
77
+ to,
78
+ subject: copy.subject(outcome, host),
79
+ text: `${text}\n\n${copy.open}: ${link}\n\n${copy.why}`,
80
+ html: `<p>${escape(text)}</p><p><a href="${escape(link)}">${copy.open}</a></p><p><small>${copy.why}</small></p>`,
81
+ });
82
+ }
83
+ catch (error) {
84
+ payload.logger.error({ err: error, msg: "payload-consent: could not email the scan result" });
85
+ }
86
+ }
@@ -0,0 +1,15 @@
1
+ import type { CollectionConfig } from "payload";
2
+ import { type Category } from "./defaults.ts";
3
+ import { type ConsentPluginOptions } from "./types.ts";
4
+ /** What the site posts after a visitor saves a choice. */
5
+ export type ConsentRecordInput = {
6
+ subjectId: string;
7
+ choices: Partial<Record<Category, boolean>>;
8
+ policyVersion: string;
9
+ locale: string;
10
+ path?: string;
11
+ };
12
+ /** Checks a posted record; returns why it is refused, or the record. */
13
+ export declare function parseRecord(body: unknown): ConsentRecordInput | string;
14
+ export declare function recordsCollection(options: ConsentPluginOptions): CollectionConfig;
15
+ export declare function policiesCollection(options: ConsentPluginOptions): CollectionConfig;
@@ -0,0 +1,197 @@
1
+ import { CATEGORIES } from "./defaults.js";
2
+ import { readConsent, toConsentConfig } from "./site-config.js";
3
+ import { CONSENT_POLICIES, CONSENT_RECORDS, DEFAULT_RETENTION_DAYS, } from "./types.js";
4
+ const signedIn = ({ req }) => Boolean(req.user);
5
+ const nobody = () => false;
6
+ /** Checks a posted record; returns why it is refused, or the record. */
7
+ export function parseRecord(body) {
8
+ if (!body || typeof body !== "object")
9
+ return "Expected a JSON object";
10
+ const { subjectId, choices, policyVersion, locale, path } = body;
11
+ if (typeof subjectId !== "string" || !/^sub_[A-Za-z0-9]{8,64}$/.test(subjectId))
12
+ return "Invalid subjectId";
13
+ if (typeof policyVersion !== "string" || !/^[a-f0-9]{16}$/.test(policyVersion))
14
+ return "Invalid policyVersion";
15
+ if (typeof locale !== "string" || !/^[A-Za-z-]{2,16}$/.test(locale))
16
+ return "Invalid locale";
17
+ if (path !== undefined &&
18
+ (typeof path !== "string" || !path.startsWith("/") || path.length > 512))
19
+ return "Invalid path";
20
+ if (!choices || typeof choices !== "object" || Array.isArray(choices))
21
+ return "Invalid choices";
22
+ const parsed = {};
23
+ for (const [name, value] of Object.entries(choices)) {
24
+ if (!CATEGORIES.includes(name) || typeof value !== "boolean")
25
+ return `Invalid choice: ${name}`;
26
+ parsed[name] = value;
27
+ }
28
+ return { subjectId, choices: parsed, policyVersion, locale, path };
29
+ }
30
+ let lastCleanup = 0;
31
+ /** Deletes records older than the retention period, at most once a day per server process. */
32
+ async function cleanUp(req, retentionDays) {
33
+ if (Date.now() - lastCleanup < 24 * 60 * 60 * 1000)
34
+ return;
35
+ lastCleanup = Date.now();
36
+ const before = new Date(Date.now() - retentionDays * 24 * 60 * 60 * 1000).toISOString();
37
+ await req.payload.delete({
38
+ collection: CONSENT_RECORDS,
39
+ where: { createdAt: { less_than: before } },
40
+ overrideAccess: true,
41
+ });
42
+ }
43
+ /** `POST /api/consent-records/record`: stores a visitor's choice and the policy it was given for. */
44
+ function recordEndpoint(options) {
45
+ return {
46
+ path: "/record",
47
+ method: "post",
48
+ handler: async (req) => {
49
+ const body = req.json ? await req.json().catch(() => null) : null;
50
+ const record = parseRecord(body);
51
+ if (typeof record === "string")
52
+ return Response.json({ error: record }, { status: 400 });
53
+ // Only the current policy can be consented to; this also keeps made-up records out.
54
+ const { doc, services } = await readConsent({ payload: req.payload, locale: record.locale });
55
+ const config = toConsentConfig(doc, services, { locale: record.locale });
56
+ if (record.policyVersion !== config.policyVersion)
57
+ return Response.json({ error: "Outdated policy" }, { status: 409 });
58
+ const unknown = Object.keys(record.choices).filter((name) => !config.categories.includes(name));
59
+ if (unknown.length)
60
+ return Response.json({ error: `Not in the policy: ${unknown.join(", ")}` }, { status: 400 });
61
+ const existing = await req.payload.count({
62
+ collection: CONSENT_POLICIES,
63
+ where: {
64
+ and: [
65
+ { version: { equals: record.policyVersion } },
66
+ { locale: { equals: record.locale } },
67
+ ],
68
+ },
69
+ overrideAccess: true,
70
+ });
71
+ if (!existing.totalDocs)
72
+ await req.payload.create({
73
+ collection: CONSENT_POLICIES,
74
+ data: {
75
+ version: record.policyVersion,
76
+ locale: record.locale,
77
+ snapshot: {
78
+ categories: config.categories,
79
+ messages: config.messages,
80
+ googleConsentMode: config.googleConsentMode,
81
+ services: services.map((service) => ({
82
+ name: service.name,
83
+ provider: service.provider,
84
+ category: service.category,
85
+ purpose: service.purpose,
86
+ loading: service.loading,
87
+ integration: service.loading === "integration" ? service.integration : undefined,
88
+ storage: (service.storage ?? []).map(({ name, type, duration, thirdParty }) => ({
89
+ name,
90
+ type,
91
+ duration,
92
+ thirdParty,
93
+ })),
94
+ })),
95
+ },
96
+ },
97
+ overrideAccess: true,
98
+ });
99
+ const granted = config.categories.filter((category) => category === "necessary" || record.choices[category]);
100
+ await req.payload.create({
101
+ collection: CONSENT_RECORDS,
102
+ data: {
103
+ subjectId: record.subjectId,
104
+ granted,
105
+ choices: record.choices,
106
+ policyVersion: record.policyVersion,
107
+ locale: record.locale,
108
+ path: record.path,
109
+ },
110
+ overrideAccess: true,
111
+ });
112
+ const retention = (options.records || undefined)?.retentionDays ?? DEFAULT_RETENTION_DAYS;
113
+ await cleanUp(req, retention).catch((error) => req.payload.logger.error({ err: error, msg: "Could not delete old consent records" }));
114
+ return Response.json({ ok: true }, { status: 201 });
115
+ },
116
+ };
117
+ }
118
+ const group = (options) => options.group ?? { en: "Settings", sv: "Inställningar" };
119
+ export function recordsCollection(options) {
120
+ const retention = (options.records || undefined)?.retentionDays ?? DEFAULT_RETENTION_DAYS;
121
+ return {
122
+ slug: CONSENT_RECORDS,
123
+ labels: {
124
+ singular: { en: "Consent record", sv: "Samtycke" },
125
+ plural: { en: "Consent records", sv: "Samtyckeslogg" },
126
+ },
127
+ admin: {
128
+ useAsTitle: "subjectId",
129
+ group: group(options),
130
+ defaultColumns: ["subjectId", "granted", "policyVersion", "createdAt"],
131
+ description: {
132
+ en: `Every choice a visitor saved, with the policy it was given for. Identified only by the random ID in the visitor's c15t cookie; no IP address or browser details. Kept for ${retention} days.`,
133
+ 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.`,
134
+ },
135
+ },
136
+ access: { read: signedIn, create: nobody, update: nobody, delete: nobody },
137
+ endpoints: [recordEndpoint(options)],
138
+ timestamps: true,
139
+ fields: [
140
+ {
141
+ name: "subjectId",
142
+ type: "text",
143
+ required: true,
144
+ index: true,
145
+ label: { en: "Visitor ID", sv: "Besökar-ID" },
146
+ },
147
+ {
148
+ name: "granted",
149
+ type: "select",
150
+ hasMany: true,
151
+ label: { en: "Allowed", sv: "Tillåtna" },
152
+ options: CATEGORIES.map((value) => ({ value, label: value })),
153
+ },
154
+ { name: "choices", type: "json", label: { en: "Choices", sv: "Val" } },
155
+ {
156
+ name: "policyVersion",
157
+ type: "text",
158
+ required: true,
159
+ index: true,
160
+ label: { en: "Policy version", sv: "Policyversion" },
161
+ },
162
+ { name: "locale", type: "text", label: { en: "Language", sv: "Språk" } },
163
+ { name: "path", type: "text", label: { en: "Page", sv: "Sida" } },
164
+ ],
165
+ };
166
+ }
167
+ export function policiesCollection(options) {
168
+ return {
169
+ slug: CONSENT_POLICIES,
170
+ labels: {
171
+ singular: { en: "Consent policy", sv: "Samtyckespolicy" },
172
+ plural: { en: "Consent policies", sv: "Samtyckespolicyer" },
173
+ },
174
+ admin: {
175
+ useAsTitle: "version",
176
+ group: group(options),
177
+ defaultColumns: ["version", "locale", "createdAt"],
178
+ 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.",
181
+ },
182
+ },
183
+ access: { read: signedIn, create: nobody, update: nobody, delete: nobody },
184
+ timestamps: true,
185
+ fields: [
186
+ {
187
+ name: "version",
188
+ type: "text",
189
+ required: true,
190
+ index: true,
191
+ label: { en: "Version", sv: "Version" },
192
+ },
193
+ { name: "locale", type: "text", required: true, label: { en: "Language", sv: "Språk" } },
194
+ { name: "snapshot", type: "json", label: { en: "Shown", sv: "Visades" } },
195
+ ],
196
+ };
197
+ }
@@ -0,0 +1,37 @@
1
+ import type { CollectionConfig, Payload, PayloadRequest, TaskConfig } from "payload";
2
+ import { type ScanState } from "./evaluate.ts";
3
+ import type { ScanSchedule } from "./schedule.ts";
4
+ import { type ConsentConfig } from "./site-config.ts";
5
+ import { type ConsentPluginOptions } from "./types.ts";
6
+ /**
7
+ * The states a scan runs: a new visitor, rejecting, accepting everything and, with more than one
8
+ * optional category, each category on its own. Each state presets c15t's cookie as c15t 2.2.1
9
+ * writes it, and the policy cookie, so the banner treats it as a choice already made.
10
+ */
11
+ export declare function scanStates(config: Pick<ConsentConfig, "categories" | "policyVersion">, now?: number): ScanState[];
12
+ type Started = {
13
+ id: number | string;
14
+ } | {
15
+ error: string;
16
+ status: number;
17
+ };
18
+ /**
19
+ * Asks the scanner to scan the site in every consent state and records the scan as queued. The
20
+ * address is the one given (the Scan tab's field, saved or not), then the saved one, then the
21
+ * site's own. Scan now and the monthly task both start here.
22
+ */
23
+ export declare function startScan({ payload, options, url: given, trigger, req, }: {
24
+ payload: Payload;
25
+ options: ConsentPluginOptions;
26
+ url?: string;
27
+ trigger?: "manual" | "scheduled";
28
+ req?: PayloadRequest;
29
+ }): Promise<Started>;
30
+ /**
31
+ * The monthly scan as a jobs task, scheduled from the site's address so sites spread over the
32
+ * month. It runs when the host's cron calls Payload's `/api/payload-jobs/run`, and does nothing
33
+ * while Cookies → Scan has the monthly scan turned off.
34
+ */
35
+ export declare function scanTask(options: ConsentPluginOptions, schedule: ScanSchedule): TaskConfig;
36
+ export declare function scansCollection(options: ConsentPluginOptions): CollectionConfig;
37
+ export {};