@simmalugnt-se/payload-consent 0.4.0 → 0.5.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 +16 -0
- package/dist/admin/ScanPanel.js +4 -4
- package/dist/evaluate.d.ts +11 -0
- package/dist/evaluate.js +23 -0
- package/dist/notify.d.ts +4 -1
- package/dist/notify.js +14 -6
- package/dist/record-guard.d.ts +25 -0
- package/dist/record-guard.js +62 -0
- package/dist/records.js +46 -2
- package/dist/scans.d.ts +2 -0
- package/dist/scans.js +52 -5
- package/dist/widget/ConsentScanWidget.js +12 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.5.0
|
|
4
|
+
|
|
5
|
+
- A scan that could not see everything says so: a state the scanner did not return or that
|
|
6
|
+
visited no pages, the scanner's errors and unreadable sitemaps are kept in the summary
|
|
7
|
+
(`summary.problems`), shown on the Scan tab, named in the email and marked incomplete in the
|
|
8
|
+
dashboard widget instead of "in order". Before, a scan whose "reject all" state failed looked
|
|
9
|
+
clean.
|
|
10
|
+
- A scan the scanner has forgotten (after a restart) is saved as failed when the Scan tab asks
|
|
11
|
+
about it, and the monthly job closes scans left queued or running for more than 26 hours; both
|
|
12
|
+
email the chosen users. Before, they stayed queued.
|
|
13
|
+
|
|
14
|
+
- The public `POST /api/consent-records/record` takes choices only from the site's own pages (the
|
|
15
|
+
request's host, `serverURL` or Payload's `csrf` list), up to 4 kB, and at most 20 a minute from
|
|
16
|
+
one address per server process; the address is only counted in memory, never stored. The same
|
|
17
|
+
choice from the same visitor within a minute is not stored twice; a changed choice is.
|
|
18
|
+
|
|
3
19
|
## 0.4.0
|
|
4
20
|
|
|
5
21
|
- `access.manage` says who works with cookies in Admin: the texts and services, the consent log,
|
package/dist/admin/ScanPanel.js
CHANGED
|
@@ -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
|
-
|
|
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,
|
|
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)
|
package/dist/evaluate.d.ts
CHANGED
|
@@ -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. */
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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.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;
|
|
@@ -40,13 +41,43 @@ async function cleanUp(req, retentionDays) {
|
|
|
40
41
|
overrideAccess: true,
|
|
41
42
|
});
|
|
42
43
|
}
|
|
43
|
-
/**
|
|
44
|
+
/** The same choice again within this time is not stored twice (a double save, a reload). */
|
|
45
|
+
const REPEAT_MS = 60_000;
|
|
46
|
+
/**
|
|
47
|
+
* `POST /api/consent-records/record`: stores a visitor's choice and the policy it was given for.
|
|
48
|
+
* Public, so it takes posts only from the site's own pages, of a choice's size, at a visitor's
|
|
49
|
+
* pace, and skips a choice the visitor just saved.
|
|
50
|
+
*/
|
|
44
51
|
function recordEndpoint(options) {
|
|
52
|
+
const withinLimit = createRateLimit();
|
|
45
53
|
return {
|
|
46
54
|
path: "/record",
|
|
47
55
|
method: "post",
|
|
48
56
|
handler: async (req) => {
|
|
49
|
-
const
|
|
57
|
+
const headers = req.headers;
|
|
58
|
+
const { serverURL, csrf } = req.payload.config;
|
|
59
|
+
if (!allowedOrigin({
|
|
60
|
+
origin: headers.get("origin"),
|
|
61
|
+
host: headers.get("host"),
|
|
62
|
+
forwardedHost: headers.get("x-forwarded-host"),
|
|
63
|
+
serverURL,
|
|
64
|
+
csrf,
|
|
65
|
+
}))
|
|
66
|
+
return Response.json({ error: "Not from this site" }, { status: 403 });
|
|
67
|
+
if (Number(headers.get("content-length") ?? 0) > MAX_RECORD_BYTES)
|
|
68
|
+
return Response.json({ error: "Too large" }, { status: 413 });
|
|
69
|
+
if (!withinLimit(clientKey(headers)))
|
|
70
|
+
return Response.json({ error: "Too many choices" }, { status: 429 });
|
|
71
|
+
const text = req.text ? await req.text().catch(() => "") : "";
|
|
72
|
+
if (text.length > MAX_RECORD_BYTES)
|
|
73
|
+
return Response.json({ error: "Too large" }, { status: 413 });
|
|
74
|
+
let body = null;
|
|
75
|
+
try {
|
|
76
|
+
body = JSON.parse(text);
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
body = null;
|
|
80
|
+
}
|
|
50
81
|
const record = parseRecord(body);
|
|
51
82
|
if (typeof record === "string")
|
|
52
83
|
return Response.json({ error: record }, { status: 400 });
|
|
@@ -96,6 +127,19 @@ function recordEndpoint(options) {
|
|
|
96
127
|
overrideAccess: true,
|
|
97
128
|
});
|
|
98
129
|
const granted = config.categories.filter((category) => category === "necessary" || record.choices[category]);
|
|
130
|
+
const { docs: latest } = await req.payload.find({
|
|
131
|
+
collection: CONSENT_RECORDS,
|
|
132
|
+
where: { subjectId: { equals: record.subjectId } },
|
|
133
|
+
sort: "-createdAt",
|
|
134
|
+
limit: 1,
|
|
135
|
+
depth: 0,
|
|
136
|
+
overrideAccess: true,
|
|
137
|
+
});
|
|
138
|
+
const previous = latest[0];
|
|
139
|
+
if (previous?.policyVersion === record.policyVersion &&
|
|
140
|
+
Date.now() - new Date(previous.createdAt ?? 0).getTime() < REPEAT_MS &&
|
|
141
|
+
[...(previous.granted ?? [])].sort().join() === [...granted].sort().join())
|
|
142
|
+
return Response.json({ ok: true }, { status: 200 });
|
|
99
143
|
await req.payload.create({
|
|
100
144
|
collection: CONSENT_RECORDS,
|
|
101
145
|
data: {
|
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
|
|
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:
|
|
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
|
-
|
|
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,
|
|
@@ -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
|
|
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
|
-
...(
|
|
101
|
+
...(incomplete ? [copy.incomplete] : []),
|
|
102
|
+
...(summary.action || summary.unknown || incomplete ? [] : [copy.allGood]),
|
|
93
103
|
...(summary.new ? [copy.isNew(summary.new)] : []),
|
|
94
104
|
]
|
|
95
105
|
: [];
|