@simmalugnt-se/payload-consent 0.0.0-stage → 0.2.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 +46 -0
- package/LICENSE +21 -0
- package/README.md +242 -2
- package/dist/admin/ScanPanel.d.ts +3 -0
- package/dist/admin/ScanPanel.js +232 -0
- package/dist/admin/ServicesPanel.d.ts +11 -0
- package/dist/admin/ServicesPanel.js +136 -0
- package/dist/block.d.ts +6 -0
- package/dist/block.js +27 -0
- package/dist/defaults.d.ts +56 -0
- package/dist/defaults.js +137 -0
- package/dist/evaluate.d.ts +106 -0
- package/dist/evaluate.js +101 -0
- package/dist/evidence.d.ts +12 -0
- package/dist/evidence.js +114 -0
- package/dist/exports/admin.d.ts +2 -0
- package/dist/exports/admin.js +2 -0
- package/dist/exports/client.d.ts +37 -0
- package/dist/exports/client.js +180 -0
- package/dist/exports/rsc.d.ts +1 -0
- package/dist/exports/rsc.js +1 -0
- package/dist/global.d.ts +14 -0
- package/dist/global.js +317 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +75 -0
- package/dist/integrations.d.ts +40 -0
- package/dist/integrations.js +32 -0
- package/dist/notify.d.ts +15 -0
- package/dist/notify.js +86 -0
- package/dist/records.d.ts +15 -0
- package/dist/records.js +198 -0
- package/dist/scans.d.ts +37 -0
- package/dist/scans.js +424 -0
- package/dist/schedule.d.ts +17 -0
- package/dist/schedule.js +18 -0
- package/dist/services.d.ts +8 -0
- package/dist/services.js +258 -0
- package/dist/site-config.d.ts +128 -0
- package/dist/site-config.js +204 -0
- package/dist/styles/admin.css +202 -0
- package/dist/styles/consent.css +301 -0
- package/dist/types.d.ts +65 -0
- package/dist/types.js +17 -0
- package/dist/widget/ConsentScanWidget.d.ts +8 -0
- package/dist/widget/ConsentScanWidget.js +99 -0
- package/package.json +76 -3
package/dist/records.js
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
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
|
+
export function recordsCollection(options) {
|
|
119
|
+
const retention = (options.records || undefined)?.retentionDays ?? DEFAULT_RETENTION_DAYS;
|
|
120
|
+
return {
|
|
121
|
+
slug: CONSENT_RECORDS,
|
|
122
|
+
labels: {
|
|
123
|
+
singular: { en: "Consent record", sv: "Samtycke" },
|
|
124
|
+
plural: { en: "Consent records", sv: "Samtyckeslogg" },
|
|
125
|
+
},
|
|
126
|
+
admin: {
|
|
127
|
+
useAsTitle: "subjectId",
|
|
128
|
+
// Out of the navigation and dashboard: the Cookies global links here.
|
|
129
|
+
group: false,
|
|
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
|
+
// Out of the navigation and dashboard: the Cookies global links here.
|
|
177
|
+
group: false,
|
|
178
|
+
defaultColumns: ["version", "locale", "createdAt"],
|
|
179
|
+
description: {
|
|
180
|
+
en: "What visitors were shown, per policy version and language: categories, services and texts. Saved with the first choice for each version.",
|
|
181
|
+
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.",
|
|
182
|
+
},
|
|
183
|
+
},
|
|
184
|
+
access: { read: signedIn, create: nobody, update: nobody, delete: nobody },
|
|
185
|
+
timestamps: true,
|
|
186
|
+
fields: [
|
|
187
|
+
{
|
|
188
|
+
name: "version",
|
|
189
|
+
type: "text",
|
|
190
|
+
required: true,
|
|
191
|
+
index: true,
|
|
192
|
+
label: { en: "Version", sv: "Version" },
|
|
193
|
+
},
|
|
194
|
+
{ name: "locale", type: "text", required: true, label: { en: "Language", sv: "Språk" } },
|
|
195
|
+
{ name: "snapshot", type: "json", label: { en: "Shown", sv: "Visades" } },
|
|
196
|
+
],
|
|
197
|
+
};
|
|
198
|
+
}
|
package/dist/scans.d.ts
ADDED
|
@@ -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 {};
|
package/dist/scans.js
ADDED
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
import { timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { evaluateScan, } from "./evaluate.js";
|
|
3
|
+
import { evidenceEndpoint } from "./evidence.js";
|
|
4
|
+
import { notifyScan } from "./notify.js";
|
|
5
|
+
import { readConsent, toConsentConfig, } from "./site-config.js";
|
|
6
|
+
import { CONSENT_GLOBAL, CONSENT_SCAN_EVIDENCE, CONSENT_SCANS, CONSENT_SERVICES, POLICY_COOKIE, SCAN_TASK, } from "./types.js";
|
|
7
|
+
/**
|
|
8
|
+
* The states a scan runs: a new visitor, rejecting, accepting everything and, with more than one
|
|
9
|
+
* optional category, each category on its own. Each state presets c15t's cookie as c15t 2.2.1
|
|
10
|
+
* writes it, and the policy cookie, so the banner treats it as a choice already made.
|
|
11
|
+
*/
|
|
12
|
+
export function scanStates(config, now = Date.now()) {
|
|
13
|
+
const optional = config.categories.filter((category) => category !== "necessary");
|
|
14
|
+
const state = (id, allowed) => ({
|
|
15
|
+
id,
|
|
16
|
+
allowed: ["necessary", ...allowed],
|
|
17
|
+
cookies: [
|
|
18
|
+
{
|
|
19
|
+
name: "c15t",
|
|
20
|
+
value: [
|
|
21
|
+
...config.categories.map((category) => `c.${category}:${category === "necessary" || allowed.includes(category) ? 1 : 0}`),
|
|
22
|
+
`i.t:${now}`,
|
|
23
|
+
].join(","),
|
|
24
|
+
},
|
|
25
|
+
{ name: POLICY_COOKIE, value: config.policyVersion },
|
|
26
|
+
],
|
|
27
|
+
});
|
|
28
|
+
const states = [{ id: "no-choice", allowed: ["necessary"], cookies: [] }];
|
|
29
|
+
if (!optional.length)
|
|
30
|
+
return states;
|
|
31
|
+
states.push(state("reject-all", []), state("accept-all", optional));
|
|
32
|
+
if (optional.length > 1)
|
|
33
|
+
for (const category of optional)
|
|
34
|
+
states.push(state(`only-${category}`, [category]));
|
|
35
|
+
return states;
|
|
36
|
+
}
|
|
37
|
+
const signedIn = ({ req }) => Boolean(req.user);
|
|
38
|
+
function sameToken(given, expected) {
|
|
39
|
+
const a = Buffer.from(given);
|
|
40
|
+
const b = Buffer.from(expected);
|
|
41
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
42
|
+
}
|
|
43
|
+
async function latestDone(req, before) {
|
|
44
|
+
const { docs } = await req.payload.find({
|
|
45
|
+
collection: CONSENT_SCANS,
|
|
46
|
+
where: {
|
|
47
|
+
and: [{ status: { equals: "done" } }, ...(before ? [{ id: { not_equals: before } }] : [])],
|
|
48
|
+
},
|
|
49
|
+
sort: "-createdAt",
|
|
50
|
+
limit: 1,
|
|
51
|
+
depth: 0,
|
|
52
|
+
overrideAccess: true,
|
|
53
|
+
req,
|
|
54
|
+
});
|
|
55
|
+
return docs[0];
|
|
56
|
+
}
|
|
57
|
+
async function allServices(req) {
|
|
58
|
+
const { docs } = await req.payload.find({
|
|
59
|
+
collection: CONSENT_SERVICES,
|
|
60
|
+
depth: 0,
|
|
61
|
+
limit: 0,
|
|
62
|
+
pagination: false,
|
|
63
|
+
overrideAccess: true,
|
|
64
|
+
req,
|
|
65
|
+
});
|
|
66
|
+
return docs;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Asks the scanner to scan the site in every consent state and records the scan as queued. The
|
|
70
|
+
* address is the one given (the Scan tab's field, saved or not), then the saved one, then the
|
|
71
|
+
* site's own. Scan now and the monthly task both start here.
|
|
72
|
+
*/
|
|
73
|
+
export async function startScan({ payload, options, url: given, trigger = "manual", req, }) {
|
|
74
|
+
const scanner = options.scanner;
|
|
75
|
+
if (!scanner)
|
|
76
|
+
return { error: "No scanner configured", status: 409 };
|
|
77
|
+
const global = (await payload.findGlobal({
|
|
78
|
+
slug: CONSENT_GLOBAL,
|
|
79
|
+
depth: 0,
|
|
80
|
+
overrideAccess: true,
|
|
81
|
+
}));
|
|
82
|
+
const url = given?.trim() || global.scanUrl?.trim() || payload.config.serverURL;
|
|
83
|
+
if (!url || !/^https?:\/\//.test(url))
|
|
84
|
+
return { error: "Enter the site's address, starting with https://", status: 400 };
|
|
85
|
+
const { doc, services } = await readConsent({ payload });
|
|
86
|
+
const states = scanStates(toConsentConfig(doc, services, { locale: "en" }));
|
|
87
|
+
const base = `${scanner.callbackBaseUrl ?? payload.config.serverURL}${payload.config.routes.api}/${CONSENT_SCANS}`;
|
|
88
|
+
const response = await fetch(new URL("/scans", scanner.url), {
|
|
89
|
+
method: "POST",
|
|
90
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${scanner.token}` },
|
|
91
|
+
body: JSON.stringify({
|
|
92
|
+
url,
|
|
93
|
+
callbackUrl: `${base}/result`,
|
|
94
|
+
...(scanner.keepEvidence === 0 ? {} : { evidenceUrl: `${base}/evidence` }),
|
|
95
|
+
states: states.map(({ id, cookies }) => ({ id, cookies })),
|
|
96
|
+
}),
|
|
97
|
+
signal: AbortSignal.timeout(20_000),
|
|
98
|
+
}).catch((error) => error);
|
|
99
|
+
const answer = response instanceof Error
|
|
100
|
+
? undefined
|
|
101
|
+
: (await response.json().catch(() => ({})));
|
|
102
|
+
const error = response instanceof Error
|
|
103
|
+
? `The scanner did not answer: ${response.message}`
|
|
104
|
+
: !response.ok || !answer?.id
|
|
105
|
+
? (answer?.error ?? `The scanner answered ${response.status}`)
|
|
106
|
+
: undefined;
|
|
107
|
+
if (error) {
|
|
108
|
+
// Nobody watches a scheduled scan start: keep the failure where the widget and email show it.
|
|
109
|
+
if (trigger === "scheduled") {
|
|
110
|
+
await payload.create({
|
|
111
|
+
collection: CONSENT_SCANS,
|
|
112
|
+
data: { url, status: "failed", error, trigger, states },
|
|
113
|
+
overrideAccess: true,
|
|
114
|
+
req,
|
|
115
|
+
});
|
|
116
|
+
await notifyScan(payload, { url, status: "failed", error });
|
|
117
|
+
}
|
|
118
|
+
return { error, status: 502 };
|
|
119
|
+
}
|
|
120
|
+
const scan = await payload.create({
|
|
121
|
+
collection: CONSENT_SCANS,
|
|
122
|
+
data: { scanId: answer?.id, url, status: "queued", trigger, states },
|
|
123
|
+
overrideAccess: true,
|
|
124
|
+
req,
|
|
125
|
+
});
|
|
126
|
+
return { id: scan.id };
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* The monthly scan as a jobs task, scheduled from the site's address so sites spread over the
|
|
130
|
+
* month. It runs when the host's cron calls Payload's `/api/payload-jobs/run`, and does nothing
|
|
131
|
+
* while Cookies → Scan has the monthly scan turned off.
|
|
132
|
+
*/
|
|
133
|
+
export function scanTask(options, schedule) {
|
|
134
|
+
return {
|
|
135
|
+
slug: SCAN_TASK,
|
|
136
|
+
label: "Monthly cookie scan",
|
|
137
|
+
schedule: [{ cron: schedule.cron, queue: "default" }],
|
|
138
|
+
retries: 0,
|
|
139
|
+
outputSchema: [
|
|
140
|
+
{ name: "scan", type: "text" },
|
|
141
|
+
{ name: "skipped", type: "text" },
|
|
142
|
+
],
|
|
143
|
+
handler: async ({ req }) => {
|
|
144
|
+
const global = (await req.payload.findGlobal({
|
|
145
|
+
slug: CONSENT_GLOBAL,
|
|
146
|
+
depth: 0,
|
|
147
|
+
overrideAccess: true,
|
|
148
|
+
}));
|
|
149
|
+
if (global.scheduledScans === false)
|
|
150
|
+
return { output: { skipped: "Scheduled scans are off" } };
|
|
151
|
+
const started = await startScan({ payload: req.payload, options, trigger: "scheduled", req });
|
|
152
|
+
return "error" in started
|
|
153
|
+
? { output: { skipped: started.error } }
|
|
154
|
+
: { output: { scan: String(started.id) } };
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
function endpoints(options) {
|
|
159
|
+
const scanner = options.scanner;
|
|
160
|
+
const hasToken = (req) => Boolean(scanner &&
|
|
161
|
+
sameToken((req.headers.get("authorization") ?? "").replace(/^Bearer /, ""), scanner.token));
|
|
162
|
+
return [
|
|
163
|
+
{
|
|
164
|
+
// Starts a scan of the published site in every consent state.
|
|
165
|
+
path: "/start",
|
|
166
|
+
method: "post",
|
|
167
|
+
handler: async (req) => {
|
|
168
|
+
if (!req.user)
|
|
169
|
+
return Response.json({ error: "Sign in" }, { status: 401 });
|
|
170
|
+
const body = (await req.json?.().catch(() => null));
|
|
171
|
+
const started = await startScan({ payload: req.payload, options, url: body?.url, req });
|
|
172
|
+
return "error" in started
|
|
173
|
+
? Response.json({ error: started.error }, { status: started.status })
|
|
174
|
+
: Response.json({ id: started.id }, { status: 201 });
|
|
175
|
+
},
|
|
176
|
+
},
|
|
177
|
+
{
|
|
178
|
+
// The scanner posts the result here, with the token it was given.
|
|
179
|
+
path: "/result",
|
|
180
|
+
method: "post",
|
|
181
|
+
handler: async (req) => {
|
|
182
|
+
if (!hasToken(req))
|
|
183
|
+
return Response.json({ error: "Unknown token" }, { status: 401 });
|
|
184
|
+
const result = (await req.json?.().catch(() => null));
|
|
185
|
+
if (!result?.id)
|
|
186
|
+
return Response.json({ error: "Expected a result" }, { status: 400 });
|
|
187
|
+
const { docs } = await req.payload.find({
|
|
188
|
+
collection: CONSENT_SCANS,
|
|
189
|
+
where: { scanId: { equals: result.id } },
|
|
190
|
+
limit: 1,
|
|
191
|
+
depth: 0,
|
|
192
|
+
overrideAccess: true,
|
|
193
|
+
req,
|
|
194
|
+
});
|
|
195
|
+
const scan = docs[0];
|
|
196
|
+
if (!scan)
|
|
197
|
+
return Response.json({ error: "Unknown scan" }, { status: 404 });
|
|
198
|
+
const done = result.status === "done" && Array.isArray(result.states);
|
|
199
|
+
const evaluated = done
|
|
200
|
+
? evaluateScan({
|
|
201
|
+
states: scan.states ?? [],
|
|
202
|
+
results: result.states ?? [],
|
|
203
|
+
services: await allServices(req),
|
|
204
|
+
previousKeys: ((await latestDone(req, scan.id))?.findings ?? []).map((f) => f.key),
|
|
205
|
+
})
|
|
206
|
+
: undefined;
|
|
207
|
+
await req.payload.update({
|
|
208
|
+
collection: CONSENT_SCANS,
|
|
209
|
+
id: scan.id,
|
|
210
|
+
data: {
|
|
211
|
+
status: done ? "done" : "failed",
|
|
212
|
+
error: done ? null : (result.error ?? "The scan failed"),
|
|
213
|
+
startedAt: result.startedAt,
|
|
214
|
+
finishedAt: result.finishedAt,
|
|
215
|
+
pages: result.pages,
|
|
216
|
+
results: done ? result.states : null,
|
|
217
|
+
findings: evaluated?.findings ?? null,
|
|
218
|
+
summary: evaluated?.summary ?? null,
|
|
219
|
+
},
|
|
220
|
+
overrideAccess: true,
|
|
221
|
+
req,
|
|
222
|
+
});
|
|
223
|
+
await notifyScan(req.payload, {
|
|
224
|
+
url: scan.url ?? "",
|
|
225
|
+
status: done ? "done" : "failed",
|
|
226
|
+
error: done ? null : (result.error ?? "The scan failed"),
|
|
227
|
+
summary: evaluated?.summary,
|
|
228
|
+
});
|
|
229
|
+
return Response.json({ ok: true });
|
|
230
|
+
},
|
|
231
|
+
},
|
|
232
|
+
{
|
|
233
|
+
// The scanner's queue position and progress while a scan waits or runs.
|
|
234
|
+
path: "/:id/status",
|
|
235
|
+
method: "get",
|
|
236
|
+
handler: async (req) => {
|
|
237
|
+
if (!req.user)
|
|
238
|
+
return Response.json({ error: "Sign in" }, { status: 401 });
|
|
239
|
+
const scan = (await req.payload.findByID({
|
|
240
|
+
collection: CONSENT_SCANS,
|
|
241
|
+
id: req.routeParams?.id,
|
|
242
|
+
depth: 0,
|
|
243
|
+
req,
|
|
244
|
+
}));
|
|
245
|
+
if (!scanner || !scan.scanId || (scan.status !== "queued" && scan.status !== "running"))
|
|
246
|
+
return Response.json({ status: scan.status, error: scan.error });
|
|
247
|
+
const response = await fetch(new URL(`/scans/${scan.scanId}`, scanner.url), {
|
|
248
|
+
headers: { authorization: `Bearer ${scanner.token}` },
|
|
249
|
+
signal: AbortSignal.timeout(10_000),
|
|
250
|
+
}).catch(() => undefined);
|
|
251
|
+
const live = (await response?.json().catch(() => undefined));
|
|
252
|
+
if (!live?.status)
|
|
253
|
+
// The scanner restarted or forgot the scan: it will never post a result.
|
|
254
|
+
return Response.json({ status: scan.status, lost: response?.status === 404 });
|
|
255
|
+
if (live.status === "running" && scan.status === "queued")
|
|
256
|
+
await req.payload.update({
|
|
257
|
+
collection: CONSENT_SCANS,
|
|
258
|
+
id: scan.id,
|
|
259
|
+
data: { status: "running" },
|
|
260
|
+
overrideAccess: true,
|
|
261
|
+
req,
|
|
262
|
+
});
|
|
263
|
+
return Response.json({
|
|
264
|
+
status: live.status,
|
|
265
|
+
position: live.position,
|
|
266
|
+
progress: live.progress,
|
|
267
|
+
});
|
|
268
|
+
},
|
|
269
|
+
},
|
|
270
|
+
{
|
|
271
|
+
// Makes a finding part of a service, new or existing, and judges the latest scan again.
|
|
272
|
+
path: "/classify",
|
|
273
|
+
method: "post",
|
|
274
|
+
handler: async (req) => {
|
|
275
|
+
if (!req.user)
|
|
276
|
+
return Response.json({ error: "Sign in" }, { status: 401 });
|
|
277
|
+
const body = (await req.json?.().catch(() => null));
|
|
278
|
+
const kind = body?.kind;
|
|
279
|
+
const name = body?.name?.trim();
|
|
280
|
+
const serviceName = body?.service?.trim();
|
|
281
|
+
if (!name ||
|
|
282
|
+
!serviceName ||
|
|
283
|
+
(kind !== "cookie" && kind !== "localStorage" && kind !== "host"))
|
|
284
|
+
return Response.json({ error: "Name the finding and the service" }, { status: 400 });
|
|
285
|
+
const locale = body?.locale;
|
|
286
|
+
const existing = (await req.payload.find({
|
|
287
|
+
collection: CONSENT_SERVICES,
|
|
288
|
+
where: { name: { equals: serviceName } },
|
|
289
|
+
limit: 1,
|
|
290
|
+
depth: 0,
|
|
291
|
+
locale: locale,
|
|
292
|
+
req,
|
|
293
|
+
})).docs[0];
|
|
294
|
+
const entry = kind === "host"
|
|
295
|
+
? { hosts: [...(existing?.hosts ?? []), { host: name }] }
|
|
296
|
+
: {
|
|
297
|
+
storage: [
|
|
298
|
+
...(existing?.storage ?? []),
|
|
299
|
+
{ name, type: kind, duration: body?.duration || undefined, thirdParty: false },
|
|
300
|
+
],
|
|
301
|
+
};
|
|
302
|
+
const service = existing
|
|
303
|
+
? await req.payload.update({
|
|
304
|
+
collection: CONSENT_SERVICES,
|
|
305
|
+
id: existing.id,
|
|
306
|
+
data: entry,
|
|
307
|
+
locale: locale,
|
|
308
|
+
req,
|
|
309
|
+
})
|
|
310
|
+
: await req.payload.create({
|
|
311
|
+
collection: CONSENT_SERVICES,
|
|
312
|
+
data: {
|
|
313
|
+
name: serviceName,
|
|
314
|
+
provider: body?.provider || undefined,
|
|
315
|
+
category: body?.category || "necessary",
|
|
316
|
+
purpose: body?.purpose || serviceName,
|
|
317
|
+
policyUrl: body?.policyUrl || undefined,
|
|
318
|
+
loading: "code",
|
|
319
|
+
...entry,
|
|
320
|
+
},
|
|
321
|
+
locale: locale,
|
|
322
|
+
req,
|
|
323
|
+
});
|
|
324
|
+
const latest = await latestDone(req);
|
|
325
|
+
if (latest) {
|
|
326
|
+
const previous = await latestDone(req, latest.id);
|
|
327
|
+
const evaluated = evaluateScan({
|
|
328
|
+
states: latest.states ?? [],
|
|
329
|
+
results: (latest.results ??
|
|
330
|
+
[]),
|
|
331
|
+
services: await allServices(req),
|
|
332
|
+
previousKeys: (previous?.findings ?? []).map((f) => f.key),
|
|
333
|
+
});
|
|
334
|
+
await req.payload.update({
|
|
335
|
+
collection: CONSENT_SCANS,
|
|
336
|
+
id: latest.id,
|
|
337
|
+
data: { findings: evaluated.findings, summary: evaluated.summary },
|
|
338
|
+
overrideAccess: true,
|
|
339
|
+
req,
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
return Response.json({ service: service.id });
|
|
343
|
+
},
|
|
344
|
+
},
|
|
345
|
+
evidenceEndpoint(options, hasToken),
|
|
346
|
+
];
|
|
347
|
+
}
|
|
348
|
+
export function scansCollection(options) {
|
|
349
|
+
return {
|
|
350
|
+
slug: CONSENT_SCANS,
|
|
351
|
+
labels: {
|
|
352
|
+
singular: { en: "Cookie scan", sv: "Cookieskanning" },
|
|
353
|
+
plural: { en: "Cookie scans", sv: "Cookieskanningar" },
|
|
354
|
+
},
|
|
355
|
+
admin: {
|
|
356
|
+
useAsTitle: "url",
|
|
357
|
+
// Out of the navigation and dashboard: the Cookies global links here.
|
|
358
|
+
group: false,
|
|
359
|
+
defaultColumns: ["url", "status", "summary", "createdAt"],
|
|
360
|
+
description: {
|
|
361
|
+
en: "Each scan of the published site. Start one from Cookies → Scan.",
|
|
362
|
+
sv: "Varje skanning av den publicerade webbplatsen. Starta en under Cookies → Skanning.",
|
|
363
|
+
},
|
|
364
|
+
},
|
|
365
|
+
access: { read: signedIn, create: () => false, update: () => false, delete: signedIn },
|
|
366
|
+
endpoints: endpoints(options),
|
|
367
|
+
hooks: {
|
|
368
|
+
beforeDelete: [
|
|
369
|
+
// A scan's evidence goes with it; afterwards the database has already unlinked it.
|
|
370
|
+
async ({ id, req }) => {
|
|
371
|
+
await req.payload.delete({
|
|
372
|
+
collection: CONSENT_SCAN_EVIDENCE,
|
|
373
|
+
where: { scan: { equals: id } },
|
|
374
|
+
overrideAccess: true,
|
|
375
|
+
req,
|
|
376
|
+
});
|
|
377
|
+
},
|
|
378
|
+
],
|
|
379
|
+
},
|
|
380
|
+
timestamps: true,
|
|
381
|
+
fields: [
|
|
382
|
+
{ name: "url", type: "text", label: { en: "Address", sv: "Adress" } },
|
|
383
|
+
{
|
|
384
|
+
name: "status",
|
|
385
|
+
type: "select",
|
|
386
|
+
label: { en: "Status", sv: "Status" },
|
|
387
|
+
options: ["queued", "running", "done", "failed"].map((value) => ({ value, label: value })),
|
|
388
|
+
},
|
|
389
|
+
{
|
|
390
|
+
name: "trigger",
|
|
391
|
+
type: "select",
|
|
392
|
+
label: { en: "Started", sv: "Startad" },
|
|
393
|
+
options: [
|
|
394
|
+
{ value: "manual", label: { en: "From Admin", sv: "Från Admin" } },
|
|
395
|
+
{ value: "scheduled", label: { en: "Monthly", sv: "Månatligen" } },
|
|
396
|
+
],
|
|
397
|
+
},
|
|
398
|
+
{ name: "scanId", type: "text", index: true, admin: { hidden: true } },
|
|
399
|
+
{ name: "error", type: "text", label: { en: "Error", sv: "Fel" } },
|
|
400
|
+
{ name: "startedAt", type: "date", admin: { date: { pickerAppearance: "dayAndTime" } } },
|
|
401
|
+
{ name: "finishedAt", type: "date", admin: { date: { pickerAppearance: "dayAndTime" } } },
|
|
402
|
+
{ name: "summary", type: "json", label: { en: "Summary", sv: "Sammanfattning" } },
|
|
403
|
+
{ name: "findings", type: "json", label: { en: "Findings", sv: "Fynd" } },
|
|
404
|
+
{ name: "states", type: "json", label: { en: "States", sv: "Lägen" } },
|
|
405
|
+
{ name: "pages", type: "json", label: { en: "Pages", sv: "Sidor" } },
|
|
406
|
+
{ name: "results", type: "json", label: { en: "Scanner results", sv: "Skannerns resultat" } },
|
|
407
|
+
{
|
|
408
|
+
name: "evidence",
|
|
409
|
+
type: "join",
|
|
410
|
+
collection: CONSENT_SCAN_EVIDENCE,
|
|
411
|
+
on: "scan",
|
|
412
|
+
label: { en: "Evidence", sv: "Underlag" },
|
|
413
|
+
admin: {
|
|
414
|
+
allowCreate: false,
|
|
415
|
+
defaultColumns: ["filename", "state", "kind", "filesize"],
|
|
416
|
+
description: {
|
|
417
|
+
en: "WEC's report (PDF) and network traffic (HAR) per consent state.",
|
|
418
|
+
sv: "WEC:s rapport (PDF) och nätverkstrafik (HAR) per samtyckesläge.",
|
|
419
|
+
},
|
|
420
|
+
},
|
|
421
|
+
},
|
|
422
|
+
],
|
|
423
|
+
};
|
|
424
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* When a site's monthly scan runs: one fixed time per site, spread over the month. Payload reads
|
|
3
|
+
* the cron in the server's time zone (UTC on Vercel).
|
|
4
|
+
*/
|
|
5
|
+
export type ScanSchedule = {
|
|
6
|
+
day: number;
|
|
7
|
+
hour: number;
|
|
8
|
+
minute: number;
|
|
9
|
+
cron: string;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Picks a day from 1 to 28 and a time between 01:00 and 04:59 from the site's address, so
|
|
13
|
+
* sites sharing a scanner do not all queue on the 1st.
|
|
14
|
+
*/
|
|
15
|
+
export declare function scanSchedule(seed: string): ScanSchedule;
|
|
16
|
+
/** The next time the schedule comes round after `now`, taking the server's time as UTC. */
|
|
17
|
+
export declare function nextScan(schedule: ScanSchedule, now?: Date): Date;
|