@consent-kit/audit 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.
- package/LICENSE +21 -0
- package/README.md +19 -2
- package/dist/bin.js +1789 -0
- package/dist/index.d.ts +348 -0
- package/dist/index.js +1843 -0
- package/package.json +58 -3
package/dist/bin.js
ADDED
|
@@ -0,0 +1,1789 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { resolve } from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { parseArgs } from 'node:util';
|
|
6
|
+
import { parseRegistry, describePresets } from '@consent-kit/presets';
|
|
7
|
+
import { contentSecurityPolicy, describeCspDeviations, guardManifest, policySnapshot } from '@consent-kit/compiler';
|
|
8
|
+
import { chromium } from 'playwright';
|
|
9
|
+
import { pathCovers } from '@consent-kit/schema';
|
|
10
|
+
|
|
11
|
+
var LIST_OF = {
|
|
12
|
+
cookie: "cookies",
|
|
13
|
+
localStorage: "localStorage",
|
|
14
|
+
sessionStorage: "sessionStorage",
|
|
15
|
+
indexedDB: "indexedDB",
|
|
16
|
+
script: "scripts",
|
|
17
|
+
iframe: "iframes",
|
|
18
|
+
request: "endpoints"
|
|
19
|
+
};
|
|
20
|
+
var URL_KINDS = /* @__PURE__ */ new Set(["script", "iframe", "request"]);
|
|
21
|
+
function isUrlKind(kind) {
|
|
22
|
+
return URL_KINDS.has(kind);
|
|
23
|
+
}
|
|
24
|
+
function declare(registry, siteUrl) {
|
|
25
|
+
return {
|
|
26
|
+
manifest: guardManifest(registry),
|
|
27
|
+
siteOrigin: new URL(siteUrl).origin,
|
|
28
|
+
consentCategories: registry.purposes.filter((p) => p.basis === "consent").map((p) => p.id),
|
|
29
|
+
registryIds: new Set(registry.artefacts.map((a) => a.id))
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
function parseUrl(value) {
|
|
33
|
+
try {
|
|
34
|
+
return new URL(value);
|
|
35
|
+
} catch {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function safeRegExp(source) {
|
|
40
|
+
try {
|
|
41
|
+
return new RegExp(source);
|
|
42
|
+
} catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function match(declared, kind, key) {
|
|
47
|
+
const entries = declared.manifest[LIST_OF[kind]] ?? [];
|
|
48
|
+
const all = [];
|
|
49
|
+
let entry = null;
|
|
50
|
+
if (isUrlKind(kind)) {
|
|
51
|
+
const url = parseUrl(key);
|
|
52
|
+
let bestLength = -1;
|
|
53
|
+
if (url && url.origin !== "null") {
|
|
54
|
+
for (const candidate of entries) {
|
|
55
|
+
if (candidate.pattern !== void 0 || candidate.name === void 0) continue;
|
|
56
|
+
const relative = candidate.name.startsWith("/") && !candidate.name.startsWith("//");
|
|
57
|
+
const prefix = parseUrl(relative ? declared.siteOrigin + candidate.name : candidate.name);
|
|
58
|
+
if (!prefix || prefix.origin !== url.origin || !pathCovers(prefix.pathname, url.pathname)) continue;
|
|
59
|
+
all.push(candidate);
|
|
60
|
+
if (prefix.pathname.length > bestLength) {
|
|
61
|
+
bestLength = prefix.pathname.length;
|
|
62
|
+
entry = candidate;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const target = url ? url.origin + url.pathname : key;
|
|
67
|
+
for (const candidate of entries) {
|
|
68
|
+
if (candidate.pattern === void 0 || !safeRegExp(candidate.pattern)?.test(target)) continue;
|
|
69
|
+
all.push(candidate);
|
|
70
|
+
entry ??= candidate;
|
|
71
|
+
}
|
|
72
|
+
return { entry, all };
|
|
73
|
+
}
|
|
74
|
+
for (const candidate of entries) {
|
|
75
|
+
if (candidate.pattern === void 0 && candidate.name === key) {
|
|
76
|
+
all.push(candidate);
|
|
77
|
+
entry ??= candidate;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
for (const candidate of entries) {
|
|
81
|
+
if (candidate.pattern !== void 0 && safeRegExp(candidate.pattern)?.test(key)) {
|
|
82
|
+
all.push(candidate);
|
|
83
|
+
entry ??= candidate;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return { entry, all };
|
|
87
|
+
}
|
|
88
|
+
function classify(declared, kind, key, granted) {
|
|
89
|
+
const { entry, all } = match(declared, kind, key);
|
|
90
|
+
if (!entry) {
|
|
91
|
+
if (isUrlKind(kind) && parseUrl(key)?.origin === declared.siteOrigin) return { status: "ignored" };
|
|
92
|
+
return { status: "undeclared" };
|
|
93
|
+
}
|
|
94
|
+
const grantedSet = new Set(granted);
|
|
95
|
+
return {
|
|
96
|
+
status: "declared",
|
|
97
|
+
entry,
|
|
98
|
+
exercised: all.map((e) => e.id),
|
|
99
|
+
missing: entry.categories.filter((category) => !grantedSet.has(category))
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
function declaredArtefacts(declared) {
|
|
103
|
+
const out = [];
|
|
104
|
+
for (const kind of Object.keys(LIST_OF)) {
|
|
105
|
+
for (const entry of declared.manifest[LIST_OF[kind]] ?? []) {
|
|
106
|
+
out.push({
|
|
107
|
+
id: entry.id,
|
|
108
|
+
kind,
|
|
109
|
+
label: entry.pattern !== void 0 ? `/${entry.pattern}/` : entry.name ?? entry.id,
|
|
110
|
+
categories: entry.categories
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return out;
|
|
115
|
+
}
|
|
116
|
+
function expectedFor(declared, category) {
|
|
117
|
+
return declaredArtefacts(declared).filter((a) => a.categories.length > 0 && a.categories.every((c) => c === category));
|
|
118
|
+
}
|
|
119
|
+
function boundTo(declared, category) {
|
|
120
|
+
return declaredArtefacts(declared).filter((a) => a.categories.includes(category));
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// src/analysis.ts
|
|
124
|
+
var DEFAULT_TOLERANCES = { size: 0.25, contrast: 0.25, expiry: 0.01 };
|
|
125
|
+
var DAY_MS = 864e5;
|
|
126
|
+
var HOUR_MS = 36e5;
|
|
127
|
+
var BROWSER_MAX_COOKIE_DAYS = 400;
|
|
128
|
+
var KIND_LABEL = {
|
|
129
|
+
cookie: "cookie",
|
|
130
|
+
localStorage: "localStorage key",
|
|
131
|
+
sessionStorage: "sessionStorage key",
|
|
132
|
+
indexedDB: "IndexedDB database",
|
|
133
|
+
script: "script",
|
|
134
|
+
iframe: "iframe",
|
|
135
|
+
request: "request to"
|
|
136
|
+
};
|
|
137
|
+
function describe(kind, key) {
|
|
138
|
+
return isUrlKind(kind) ? `${KIND_LABEL[kind]} ${key}` : `${KIND_LABEL[kind]} "${key}"`;
|
|
139
|
+
}
|
|
140
|
+
function seen(observation) {
|
|
141
|
+
const verb = observation.source === "request" ? observation.blockedBy === "csp" ? "was attempted (and blocked by the Content-Security-Policy)" : "was requested" : observation.source === "write" ? "was written" : "was present";
|
|
142
|
+
return `${verb} ${observation.phase} on ${observation.page}`;
|
|
143
|
+
}
|
|
144
|
+
function dedupe(findings) {
|
|
145
|
+
const keys = /* @__PURE__ */ new Set();
|
|
146
|
+
return findings.filter((finding) => {
|
|
147
|
+
const id = `${finding.code}|${finding.kind ?? ""}|${finding.key ?? ""}|${finding.artefact ?? ""}`;
|
|
148
|
+
if (keys.has(id)) return false;
|
|
149
|
+
keys.add(id);
|
|
150
|
+
return true;
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
function wrongPurpose(declared, observations) {
|
|
154
|
+
const findings = [];
|
|
155
|
+
for (const observation of observations) {
|
|
156
|
+
if (observation.blockedBy) continue;
|
|
157
|
+
const verdict = classify(declared, observation.kind, observation.key, observation.granted);
|
|
158
|
+
if (verdict.status !== "declared" || verdict.missing.length === 0) continue;
|
|
159
|
+
findings.push({
|
|
160
|
+
severity: "error",
|
|
161
|
+
code: "wrong-purpose",
|
|
162
|
+
message: `${describe(observation.kind, observation.key)} (artefact "${verdict.entry.id}") ${seen(observation)}; it needs consent to: ${verdict.missing.join(", ")}.`,
|
|
163
|
+
artefact: verdict.entry.id,
|
|
164
|
+
kind: observation.kind,
|
|
165
|
+
key: observation.key,
|
|
166
|
+
page: observation.page,
|
|
167
|
+
phase: observation.phase,
|
|
168
|
+
category: verdict.missing[0]
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
return dedupe(findings);
|
|
172
|
+
}
|
|
173
|
+
function undeclared(declared, observations) {
|
|
174
|
+
const findings = [];
|
|
175
|
+
const inJar = /* @__PURE__ */ new Map();
|
|
176
|
+
for (const observation of observations) {
|
|
177
|
+
if (observation.kind === "cookie" && observation.cookie && !inJar.has(observation.key)) inJar.set(observation.key, observation);
|
|
178
|
+
}
|
|
179
|
+
for (const observation of observations) {
|
|
180
|
+
if (classify(declared, observation.kind, observation.key, observation.granted).status !== "undeclared") continue;
|
|
181
|
+
const detailed = observation.kind === "cookie" ? inJar.get(observation.key) ?? observation : observation;
|
|
182
|
+
const registryEntry = suggestEntry(detailed, declared.siteOrigin);
|
|
183
|
+
findings.push({
|
|
184
|
+
severity: "error",
|
|
185
|
+
code: "undeclared",
|
|
186
|
+
message: `${describe(observation.kind, observation.key)} is not declared in the registry; it ${seen(observation)}. Remove it, or add to privacy.registry.yaml:
|
|
187
|
+
${registryEntry}`,
|
|
188
|
+
kind: observation.kind,
|
|
189
|
+
key: observation.key,
|
|
190
|
+
page: observation.page,
|
|
191
|
+
phase: observation.phase,
|
|
192
|
+
registryEntry
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
return dedupe(findings);
|
|
196
|
+
}
|
|
197
|
+
function exercisedIds(declared, observations) {
|
|
198
|
+
const ids = /* @__PURE__ */ new Set();
|
|
199
|
+
for (const observation of observations) {
|
|
200
|
+
if (observation.blockedBy) continue;
|
|
201
|
+
const verdict = classify(declared, observation.kind, observation.key, observation.granted);
|
|
202
|
+
if (verdict.status === "declared") for (const id of verdict.exercised) ids.add(id);
|
|
203
|
+
}
|
|
204
|
+
return ids;
|
|
205
|
+
}
|
|
206
|
+
function slug(key, fallback) {
|
|
207
|
+
const cleaned = key.replace(/^[a-z]+:\/\//i, "").replace(/[^a-zA-Z0-9]+/g, "-").replace(/^-+|-+$/g, "").toLowerCase();
|
|
208
|
+
const id = /^[a-z]/.test(cleaned) ? cleaned : cleaned ? `x-${cleaned}` : fallback;
|
|
209
|
+
return id.slice(0, 60);
|
|
210
|
+
}
|
|
211
|
+
function hostOf(origin) {
|
|
212
|
+
return new URL(origin).hostname;
|
|
213
|
+
}
|
|
214
|
+
function normaliseDomain(domain) {
|
|
215
|
+
return domain.replace(/^\./, "").toLowerCase();
|
|
216
|
+
}
|
|
217
|
+
function observedDuration(observation) {
|
|
218
|
+
const cookie = observation.cookie;
|
|
219
|
+
if (!cookie || cookie.expires < 0) return "session";
|
|
220
|
+
const days2 = Math.max(1, Math.round((cookie.expires * 1e3 - cookie.firstSeen) / DAY_MS));
|
|
221
|
+
return `${days2}d`;
|
|
222
|
+
}
|
|
223
|
+
function suggestEntry(observation, siteOrigin) {
|
|
224
|
+
const q = JSON.stringify;
|
|
225
|
+
const { kind, key } = observation;
|
|
226
|
+
const lines = [];
|
|
227
|
+
if (kind === "cookie") {
|
|
228
|
+
lines.push(`- id: ${slug(key, "cookie")}`, " kind: cookie", ` name: ${q(key)}`, ` duration: ${observedDuration(observation)}`);
|
|
229
|
+
const domain = observation.cookie ? normaliseDomain(observation.cookie.domain) : hostOf(siteOrigin);
|
|
230
|
+
if (domain !== hostOf(siteOrigin)) lines.push(` domain: ${domain}`, " processor: TODO");
|
|
231
|
+
if (observation.cookie) lines.push(` sameSite: ${observation.cookie.sameSite}`);
|
|
232
|
+
lines.push(" purposes: [TODO]");
|
|
233
|
+
} else if (isUrlKind(kind)) {
|
|
234
|
+
const url = new URL(key);
|
|
235
|
+
const sameOrigin = url.origin === siteOrigin;
|
|
236
|
+
const location2 = sameOrigin ? url.pathname : kind === "iframe" ? url.origin : url.origin + url.pathname;
|
|
237
|
+
const registryKind = kind === "request" ? REGISTRY_KIND_OF_RESOURCE[observation.resourceType ?? ""] ?? "endpoint" : kind;
|
|
238
|
+
lines.push(`- id: ${slug(url.host + url.pathname, registryKind)}`, ` kind: ${registryKind}`);
|
|
239
|
+
lines.push(` ${registryKind === "pixel" || registryKind === "endpoint" ? "url" : "src"}: ${q(location2)}`);
|
|
240
|
+
if (!sameOrigin) lines.push(" processor: TODO");
|
|
241
|
+
lines.push(" purposes: [TODO]");
|
|
242
|
+
} else {
|
|
243
|
+
const area = kind === "localStorage" ? "local" : kind === "sessionStorage" ? "session" : "indexeddb";
|
|
244
|
+
lines.push(`- id: ${slug(key, "storage")}`, " kind: storage", ` area: ${area}`, ` key: ${q(key)}`, " purposes: [TODO]");
|
|
245
|
+
}
|
|
246
|
+
return lines.join("\n");
|
|
247
|
+
}
|
|
248
|
+
var REGISTRY_KIND_OF_RESOURCE = {
|
|
249
|
+
image: "pixel",
|
|
250
|
+
stylesheet: "stylesheet",
|
|
251
|
+
font: "font",
|
|
252
|
+
media: "media"
|
|
253
|
+
};
|
|
254
|
+
var VIOLATION_WHAT = {
|
|
255
|
+
"style-src-attr": 'a style="\u2026" attribute',
|
|
256
|
+
"style-src-elem": "an inline <style> element",
|
|
257
|
+
"script-src-attr": 'an inline event handler (onclick="\u2026" and the like)',
|
|
258
|
+
"script-src-elem": "an inline <script> element"
|
|
259
|
+
};
|
|
260
|
+
function policyViolationFindings(violations, guard) {
|
|
261
|
+
const guardRefused = new Set(guard.filter((status) => status.present && !status.installed).map((status) => status.page));
|
|
262
|
+
const findings = [];
|
|
263
|
+
for (const violation of violations) {
|
|
264
|
+
if (violation.blocked === "inline" && violation.directive.startsWith("script-src") && guardRefused.has(violation.page)) continue;
|
|
265
|
+
const what = violation.blocked === "inline" ? VIOLATION_WHAT[violation.directive] ?? "inline code" : violation.blocked === "eval" || violation.blocked === "wasm-eval" ? "eval() or code built from a string" : `a ${violation.blocked}: resource`;
|
|
266
|
+
findings.push({
|
|
267
|
+
severity: "error",
|
|
268
|
+
code: "csp-violation",
|
|
269
|
+
message: `the Content-Security-Policy of ${violation.page} refused ${what} (${violation.directive}), ${violation.phase}. Something on the page does not work as built. Move it into a file served by the site, allow an inline <script> or <style> by its hash, or, if a third-party widget cannot be changed, loosen that one directive under "csp.allow" in privacy.registry.yaml with the reason.`,
|
|
270
|
+
key: `${violation.directive} ${violation.blocked}`,
|
|
271
|
+
page: violation.page,
|
|
272
|
+
phase: violation.phase
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
return dedupeBy(findings, (finding) => `${finding.page}|${finding.key}`).sort((a, b) => {
|
|
276
|
+
const order = (x, y) => x < y ? -1 : x > y ? 1 : 0;
|
|
277
|
+
return order(a.page ?? "", b.page ?? "") || order(a.key ?? "", b.key ?? "");
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
function dedupeBy(items, key) {
|
|
281
|
+
const seen2 = /* @__PURE__ */ new Set();
|
|
282
|
+
return items.filter((item) => !seen2.has(key(item)) && seen2.add(key(item)));
|
|
283
|
+
}
|
|
284
|
+
function days(ms) {
|
|
285
|
+
return `${Number((ms / DAY_MS).toFixed(1))} days`;
|
|
286
|
+
}
|
|
287
|
+
function attributeDrift(registry, declared, observations, tolerances = DEFAULT_TOLERANCES) {
|
|
288
|
+
const cookies = /* @__PURE__ */ new Map();
|
|
289
|
+
for (const artefact of registry.artefacts) if (artefact.kind === "cookie") cookies.set(artefact.id, artefact);
|
|
290
|
+
const siteHost = hostOf(declared.siteOrigin);
|
|
291
|
+
const findings = [];
|
|
292
|
+
for (const observation of observations) {
|
|
293
|
+
const observed = observation.cookie;
|
|
294
|
+
if (observation.kind !== "cookie" || !observed) continue;
|
|
295
|
+
const verdict = classify(declared, "cookie", observation.key, observation.granted);
|
|
296
|
+
if (verdict.status !== "declared") continue;
|
|
297
|
+
const artefact = cookies.get(verdict.entry.id);
|
|
298
|
+
if (!artefact) continue;
|
|
299
|
+
const drift = (attribute, detail) => findings.push({
|
|
300
|
+
severity: "error",
|
|
301
|
+
code: "attribute-drift",
|
|
302
|
+
message: `cookie "${observation.key}" (artefact "${artefact.id}"): ${detail}. Seen ${observation.phase} on ${observation.page}.`,
|
|
303
|
+
artefact: artefact.id,
|
|
304
|
+
kind: "cookie",
|
|
305
|
+
// Deduplicated per cookie and attribute.
|
|
306
|
+
key: `${observation.key} ${attribute}`,
|
|
307
|
+
page: observation.page,
|
|
308
|
+
phase: observation.phase
|
|
309
|
+
});
|
|
310
|
+
const persistent = observed.expires >= 0;
|
|
311
|
+
if (artefact.duration === "session") {
|
|
312
|
+
if (persistent) {
|
|
313
|
+
drift("duration", `it is declared as a session cookie but expires in ${days(observed.expires * 1e3 - observed.firstSeen)}`);
|
|
314
|
+
}
|
|
315
|
+
} else {
|
|
316
|
+
const declaredDays = Number(/^(\d+)d$/.exec(artefact.duration)?.[1]);
|
|
317
|
+
if (Number.isFinite(declaredDays)) {
|
|
318
|
+
if (!persistent) {
|
|
319
|
+
drift("duration", `it is declared to last ${declaredDays} days but is a session cookie`);
|
|
320
|
+
} else {
|
|
321
|
+
const expected = Math.min(declaredDays, BROWSER_MAX_COOKIE_DAYS) * DAY_MS;
|
|
322
|
+
const actual = observed.expires * 1e3 - observed.firstSeen;
|
|
323
|
+
const allowed = Math.max(HOUR_MS, expected * tolerances.expiry);
|
|
324
|
+
if (Math.abs(actual - expected) > allowed) {
|
|
325
|
+
drift(
|
|
326
|
+
"duration",
|
|
327
|
+
`it expires in ${days(actual)}, ${actual > expected ? "longer" : "shorter"} than the declared ${declaredDays} days`
|
|
328
|
+
);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
const expectedDomain = normaliseDomain(artefact.domain ?? siteHost);
|
|
334
|
+
if (normaliseDomain(observed.domain) !== expectedDomain) {
|
|
335
|
+
drift(
|
|
336
|
+
"domain",
|
|
337
|
+
`its domain is "${observed.domain}", but ${artefact.domain !== void 0 ? `"${artefact.domain}" is declared` : `no domain is declared, which means the site's host "${siteHost}"`}`
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
if (artefact.sameSite !== void 0 && artefact.sameSite !== observed.sameSite) {
|
|
341
|
+
drift("sameSite", `its SameSite is ${observed.sameSite}, but ${artefact.sameSite} is declared`);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
return dedupe(findings);
|
|
345
|
+
}
|
|
346
|
+
function unexercised(declared, exercised, strict) {
|
|
347
|
+
return declaredArtefacts(declared).filter((artefact) => declared.registryIds.has(artefact.id) && !exercised.has(artefact.id)).map((artefact) => ({
|
|
348
|
+
severity: strict ? "error" : "warning",
|
|
349
|
+
code: "unexercised",
|
|
350
|
+
message: `${describe(artefact.kind, artefact.label)} (artefact "${artefact.id}") is declared but was never observed. Either no audited page or interaction uses it (add the page, or an "exercise" step), or the declaration is stale.`,
|
|
351
|
+
artefact: artefact.id,
|
|
352
|
+
kind: artefact.kind,
|
|
353
|
+
key: artefact.label
|
|
354
|
+
}));
|
|
355
|
+
}
|
|
356
|
+
function guardNotInstalled(statuses) {
|
|
357
|
+
const findings = [];
|
|
358
|
+
const pages = /* @__PURE__ */ new Set();
|
|
359
|
+
for (const status of statuses) {
|
|
360
|
+
if (!status.present || status.installed || pages.has(status.page)) continue;
|
|
361
|
+
pages.add(status.page);
|
|
362
|
+
const why = status.inlineScriptBlocked ? `the browser refused to run it, because its text does not match the 'sha256-...' hash in the page's Content-Security-Policy` : `window.__ck_guard is not set and no Content-Security-Policy violation was seen, so the script was most likely altered or cut short and fails to run`;
|
|
363
|
+
findings.push({
|
|
364
|
+
severity: "error",
|
|
365
|
+
code: "guard-not-installed",
|
|
366
|
+
message: `the inline consent-kit guard is in the HTML of ${status.page} but did not install: ${why}. This page runs with no runtime guard. The guard must be inlined byte-for-byte: the content of the <script> element has to be exactly the generated guard.inline.js, including its trailing newline, with no added whitespace, re-indentation or minification. Run "consent-kit build" again and inline the file verbatim (or serve a CSP whose hash matches what you inline).`,
|
|
367
|
+
page: status.page,
|
|
368
|
+
phase: status.phase
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
return findings.sort((a, b) => (a.page ?? "") < (b.page ?? "") ? -1 : (a.page ?? "") > (b.page ?? "") ? 1 : 0);
|
|
372
|
+
}
|
|
373
|
+
function coverageOf(registry, declared, observations, options) {
|
|
374
|
+
const exercised = exercisedIds(declared, observations);
|
|
375
|
+
return {
|
|
376
|
+
exercised: [...exercised].sort(),
|
|
377
|
+
unexercised: unexercised(declared, exercised, options.strict).map((finding) => finding.artefact),
|
|
378
|
+
undeclared: undeclared(declared, observations),
|
|
379
|
+
wrongPurpose: wrongPurpose(declared, observations),
|
|
380
|
+
attributeDrift: attributeDrift(registry, declared, observations, options.tolerances)
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// src/banner.ts
|
|
385
|
+
var DEFAULT_SELECTORS = {
|
|
386
|
+
banner: "#cc-main .cm",
|
|
387
|
+
accept: '#cc-main .cm [data-role="all"]',
|
|
388
|
+
reject: '#cc-main .cm [data-role="necessary"]',
|
|
389
|
+
managePreferences: '#cc-main .cm [data-role="show"]',
|
|
390
|
+
preferencesModal: "#cc-main .pm",
|
|
391
|
+
preferencesLink: 'footer [data-cc="show-preferencesModal"], [role="contentinfo"] [data-cc="show-preferencesModal"]',
|
|
392
|
+
categoryToggle: '#cc-main .pm .pm__section-title-wrapper input.section__toggle[value="{category}"]',
|
|
393
|
+
save: '#cc-main .pm [data-role="save"]',
|
|
394
|
+
rejectInPreferences: '#cc-main .pm [data-role="necessary"]'
|
|
395
|
+
};
|
|
396
|
+
var DriveError = class extends Error {
|
|
397
|
+
};
|
|
398
|
+
var ConsentNotRecordedError = class extends Error {
|
|
399
|
+
};
|
|
400
|
+
function presenceTimeout(session) {
|
|
401
|
+
return Math.min(2e3, session.config.timeoutMs);
|
|
402
|
+
}
|
|
403
|
+
async function isVisible(session, selector, wait = true) {
|
|
404
|
+
const locator = session.page.locator(selector).first();
|
|
405
|
+
if (!wait) return locator.isVisible().catch(() => false);
|
|
406
|
+
return locator.waitFor({ state: "visible", timeout: presenceTimeout(session) }).then(() => true).catch(() => false);
|
|
407
|
+
}
|
|
408
|
+
async function click(session, selector, what) {
|
|
409
|
+
try {
|
|
410
|
+
await session.page.locator(selector).first().click();
|
|
411
|
+
} catch (error) {
|
|
412
|
+
throw new DriveError(`could not click ${what} (${selector}): ${error.message.split("\n")[0]}`);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
async function decided(session, banner, granted, action) {
|
|
416
|
+
const { ok, actual } = await session.waitForConsent(granted, banner.categories);
|
|
417
|
+
await session.page.waitForLoadState("load").catch(() => void 0);
|
|
418
|
+
await session.settle();
|
|
419
|
+
await session.snapshot();
|
|
420
|
+
if (!ok) {
|
|
421
|
+
throw new ConsentNotRecordedError(
|
|
422
|
+
`${action}, but the consent cookie "${session.config.consentCookieName}" ` + (actual === null ? "was not written" : `holds categories [${actual.join(", ")}]`) + `; expected exactly [${granted.join(", ")}] of the consent categories [${banner.categories.join(", ")}].`
|
|
423
|
+
);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
async function acceptAll(session, banner, phase) {
|
|
427
|
+
if (!await isVisible(session, banner.selectors.accept)) {
|
|
428
|
+
throw new DriveError(`no visible Accept button on the first layer (${banner.selectors.accept})`);
|
|
429
|
+
}
|
|
430
|
+
session.setPhase(phase, banner.categories);
|
|
431
|
+
await click(session, banner.selectors.accept, "Accept");
|
|
432
|
+
await decided(session, banner, banner.categories, "clicked Accept");
|
|
433
|
+
}
|
|
434
|
+
async function openPreferences(session, banner) {
|
|
435
|
+
const { selectors } = banner;
|
|
436
|
+
if (await isVisible(session, selectors.preferencesModal, false)) return;
|
|
437
|
+
if (await isVisible(session, selectors.managePreferences, false)) {
|
|
438
|
+
await click(session, selectors.managePreferences, `the banner's "manage preferences" button`);
|
|
439
|
+
} else if (await isVisible(session, selectors.preferencesLink)) {
|
|
440
|
+
await click(session, selectors.preferencesLink, "the preferences link");
|
|
441
|
+
} else {
|
|
442
|
+
throw new DriveError(
|
|
443
|
+
`no way to open the preferences: neither the banner's button (${selectors.managePreferences}) nor a preferences link (${selectors.preferencesLink}) is visible`
|
|
444
|
+
);
|
|
445
|
+
}
|
|
446
|
+
if (!await isVisible(session, selectors.preferencesModal)) {
|
|
447
|
+
throw new DriveError(`the preferences modal (${selectors.preferencesModal}) did not open`);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
async function setToggle(toggle, on) {
|
|
451
|
+
if (await toggle.isChecked() === on) return;
|
|
452
|
+
const label = toggle.locator("xpath=ancestor::label[1]");
|
|
453
|
+
if (await label.count() > 0) await label.click();
|
|
454
|
+
else await toggle.click({ force: true });
|
|
455
|
+
if (await toggle.isChecked() !== on) await toggle.setChecked(on, { force: true });
|
|
456
|
+
}
|
|
457
|
+
async function saveCategories(session, banner, granted, phase) {
|
|
458
|
+
await openPreferences(session, banner);
|
|
459
|
+
for (const category of banner.categories) {
|
|
460
|
+
const selector = banner.selectors.categoryToggle.replace("{category}", category);
|
|
461
|
+
const toggle = session.page.locator(selector).first();
|
|
462
|
+
if (await toggle.count() === 0) {
|
|
463
|
+
throw new DriveError(`the preferences modal has no toggle for the category "${category}" (${selector})`);
|
|
464
|
+
}
|
|
465
|
+
try {
|
|
466
|
+
await setToggle(toggle, granted.includes(category));
|
|
467
|
+
} catch (error) {
|
|
468
|
+
throw new DriveError(`could not switch the "${category}" toggle (${selector}): ${error.message.split("\n")[0]}`);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
session.setPhase(phase, granted);
|
|
472
|
+
await click(session, banner.selectors.save, 'the "save" button of the preferences modal');
|
|
473
|
+
await decided(session, banner, granted, `saved the preferences with [${granted.join(", ")}] switched on`);
|
|
474
|
+
}
|
|
475
|
+
async function rejectAll(session, banner, phase) {
|
|
476
|
+
const { selectors } = banner;
|
|
477
|
+
if (await isVisible(session, selectors.reject)) {
|
|
478
|
+
session.setPhase(phase, []);
|
|
479
|
+
await click(session, selectors.reject, "Reject");
|
|
480
|
+
await decided(session, banner, [], "clicked Reject");
|
|
481
|
+
return "first-layer";
|
|
482
|
+
}
|
|
483
|
+
await openPreferences(session, banner);
|
|
484
|
+
if (await isVisible(session, selectors.rejectInPreferences, false)) {
|
|
485
|
+
session.setPhase(phase, []);
|
|
486
|
+
await click(session, selectors.rejectInPreferences, 'the "reject" button of the preferences modal');
|
|
487
|
+
await decided(session, banner, [], "clicked Reject in the preferences modal");
|
|
488
|
+
} else {
|
|
489
|
+
await saveCategories(session, banner, [], phase);
|
|
490
|
+
}
|
|
491
|
+
return "preferences";
|
|
492
|
+
}
|
|
493
|
+
var FIELDS = ["consentId", "event", "accepted", "rejected", "policyHash", "revision", "timestamp"];
|
|
494
|
+
function expectedReceipt(registry, event, granted) {
|
|
495
|
+
const consent = registry.purposes.filter((purpose) => purpose.basis === "consent").sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
496
|
+
const entry = (purpose) => ({ purpose: purpose.id, version: purpose.version });
|
|
497
|
+
return {
|
|
498
|
+
event,
|
|
499
|
+
accepted: consent.filter((purpose) => granted.includes(purpose.id)).map(entry),
|
|
500
|
+
rejected: consent.filter((purpose) => !granted.includes(purpose.id)).map(entry),
|
|
501
|
+
policyHash: policySnapshot(registry).hash
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
var list = (value) => Array.isArray(value) ? `[${value.map((item) => typeof item === "object" && item !== null ? `${String(item.purpose)}@${String(item.version)}` : JSON.stringify(item)).join(", ")}]` : JSON.stringify(value);
|
|
505
|
+
function receiptProblems(body, expected) {
|
|
506
|
+
if (body === null || body === "") return ["it has no body"];
|
|
507
|
+
let parsed;
|
|
508
|
+
try {
|
|
509
|
+
parsed = JSON.parse(body);
|
|
510
|
+
} catch {
|
|
511
|
+
return ["its body is not JSON"];
|
|
512
|
+
}
|
|
513
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return ["its body is not a JSON object"];
|
|
514
|
+
const receipt = parsed;
|
|
515
|
+
const problems = [];
|
|
516
|
+
const extra = Object.keys(receipt).filter((key) => !FIELDS.includes(key)).sort();
|
|
517
|
+
if (extra.length > 0) problems.push(`it carries fields a receipt does not have: ${extra.join(", ")}`);
|
|
518
|
+
const missing = FIELDS.filter((key) => !Object.hasOwn(receipt, key));
|
|
519
|
+
if (missing.length > 0) problems.push(`it lacks ${missing.join(", ")}`);
|
|
520
|
+
const { consentId, event, accepted, rejected, policyHash, revision, timestamp } = receipt;
|
|
521
|
+
if (consentId !== void 0) {
|
|
522
|
+
if (typeof consentId !== "string" || consentId === "") problems.push(typeof consentId === "string" ? "consentId is empty" : "consentId is not a string");
|
|
523
|
+
else if (typeof expected.consentId === "string" && consentId !== expected.consentId) problems.push(`consentId is "${consentId}", but the consent cookie holds "${expected.consentId}"`);
|
|
524
|
+
}
|
|
525
|
+
if (event !== void 0 && event !== expected.event) problems.push(`event is ${JSON.stringify(event)}; expected "${expected.event}"`);
|
|
526
|
+
for (const [name, actual, wanted] of [
|
|
527
|
+
["accepted", accepted, expected.accepted],
|
|
528
|
+
["rejected", rejected, expected.rejected]
|
|
529
|
+
]) {
|
|
530
|
+
if (actual !== void 0 && JSON.stringify(actual) !== JSON.stringify(wanted)) problems.push(`${name} is ${list(actual)}; expected ${list(wanted)}`);
|
|
531
|
+
}
|
|
532
|
+
if (policyHash !== void 0 && policyHash !== expected.policyHash) {
|
|
533
|
+
problems.push(`policyHash is ${JSON.stringify(policyHash)}; expected "${expected.policyHash}", the hash of the audited registry`);
|
|
534
|
+
}
|
|
535
|
+
if (revision !== void 0 && !(Number.isSafeInteger(revision) && revision >= 0)) problems.push(`revision is ${JSON.stringify(revision)}; expected a non-negative integer`);
|
|
536
|
+
if (timestamp !== void 0 && !(typeof timestamp === "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d(:\d\d(\.\d+)?)?(Z|[+-]\d\d:\d\d)$/.test(timestamp) && !Number.isNaN(Date.parse(timestamp)))) {
|
|
537
|
+
problems.push(`timestamp is ${JSON.stringify(timestamp)}; expected an ISO 8601 date and time`);
|
|
538
|
+
}
|
|
539
|
+
return problems;
|
|
540
|
+
}
|
|
541
|
+
function receiptFindings(sent, expected, decision, endpoint) {
|
|
542
|
+
if (sent.length === 0) {
|
|
543
|
+
return [{ severity: "error", code: "receipt-missing", message: `${decision} sent no consent receipt to ${endpoint}; every decision must POST exactly one.` }];
|
|
544
|
+
}
|
|
545
|
+
const first = sent[0];
|
|
546
|
+
if (sent.length > 1) {
|
|
547
|
+
return [
|
|
548
|
+
{
|
|
549
|
+
severity: "error",
|
|
550
|
+
code: "receipt-duplicate",
|
|
551
|
+
message: `${decision} sent ${sent.length} consent receipts to ${endpoint}; every decision must POST exactly one.`,
|
|
552
|
+
page: first.page,
|
|
553
|
+
phase: first.phase
|
|
554
|
+
}
|
|
555
|
+
];
|
|
556
|
+
}
|
|
557
|
+
const problems = receiptProblems(first.body, expected);
|
|
558
|
+
if (problems.length === 0) return [];
|
|
559
|
+
return [
|
|
560
|
+
{
|
|
561
|
+
severity: "error",
|
|
562
|
+
code: "receipt-malformed",
|
|
563
|
+
message: `the consent receipt sent to ${endpoint} ${first.phase} does not have the documented shape: ${problems.join("; ")}.`,
|
|
564
|
+
page: first.page,
|
|
565
|
+
phase: first.phase
|
|
566
|
+
}
|
|
567
|
+
];
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
// src/session.ts
|
|
571
|
+
var BINDING = "__ckAuditRecord";
|
|
572
|
+
var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
|
|
573
|
+
function recorder(options) {
|
|
574
|
+
try {
|
|
575
|
+
Object.defineProperty(Navigator.prototype, "webdriver", { get: () => false, configurable: true });
|
|
576
|
+
} catch {
|
|
577
|
+
}
|
|
578
|
+
if (options.gpc) {
|
|
579
|
+
try {
|
|
580
|
+
Object.defineProperty(Navigator.prototype, "globalPrivacyControl", { get: () => true, configurable: true });
|
|
581
|
+
} catch {
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
if (window.top !== window) return;
|
|
585
|
+
const send = (entry) => {
|
|
586
|
+
try {
|
|
587
|
+
window[options.binding]?.(entry);
|
|
588
|
+
} catch {
|
|
589
|
+
}
|
|
590
|
+
};
|
|
591
|
+
const cookie = Object.getOwnPropertyDescriptor(Document.prototype, "cookie");
|
|
592
|
+
if (cookie?.set && cookie.get) {
|
|
593
|
+
const nativeSet = cookie.set;
|
|
594
|
+
Object.defineProperty(Document.prototype, "cookie", {
|
|
595
|
+
configurable: true,
|
|
596
|
+
enumerable: cookie.enumerable,
|
|
597
|
+
get: cookie.get,
|
|
598
|
+
set(value) {
|
|
599
|
+
try {
|
|
600
|
+
const parts = String(value).split(";");
|
|
601
|
+
const first = parts[0] ?? "";
|
|
602
|
+
const name = first.includes("=") ? first.slice(0, first.indexOf("=")).trim() : "";
|
|
603
|
+
let maxAge = null;
|
|
604
|
+
let expires = null;
|
|
605
|
+
for (const part of parts.slice(1)) {
|
|
606
|
+
const [rawName, ...rest] = part.split("=");
|
|
607
|
+
const attribute = (rawName ?? "").trim().toLowerCase();
|
|
608
|
+
const attributeValue = rest.join("=").trim();
|
|
609
|
+
if (attribute === "max-age" && /^-?\d+$/.test(attributeValue)) maxAge = Number(attributeValue);
|
|
610
|
+
if (attribute === "expires") expires = Date.parse(attributeValue);
|
|
611
|
+
}
|
|
612
|
+
const deletion = maxAge !== null ? maxAge <= 0 : expires !== null && expires <= Date.now();
|
|
613
|
+
if (!deletion) send({ t: "write", kind: "cookie", key: name });
|
|
614
|
+
} catch {
|
|
615
|
+
}
|
|
616
|
+
nativeSet.call(this, value);
|
|
617
|
+
}
|
|
618
|
+
});
|
|
619
|
+
}
|
|
620
|
+
const nativeSetItem = Storage.prototype.setItem;
|
|
621
|
+
Storage.prototype.setItem = function(key, value) {
|
|
622
|
+
try {
|
|
623
|
+
let kind = null;
|
|
624
|
+
try {
|
|
625
|
+
kind = this === window.localStorage ? "localStorage" : this === window.sessionStorage ? "sessionStorage" : null;
|
|
626
|
+
} catch {
|
|
627
|
+
}
|
|
628
|
+
if (kind) send({ t: "write", kind, key: String(key) });
|
|
629
|
+
} catch {
|
|
630
|
+
}
|
|
631
|
+
nativeSetItem.call(this, key, value);
|
|
632
|
+
};
|
|
633
|
+
document.addEventListener("securitypolicyviolation", (event) => {
|
|
634
|
+
send({ t: "csp", url: event.blockedURI, directive: event.effectiveDirective });
|
|
635
|
+
});
|
|
636
|
+
}
|
|
637
|
+
function originOf(url) {
|
|
638
|
+
try {
|
|
639
|
+
const origin = new URL(url).origin;
|
|
640
|
+
return origin === "null" ? null : origin;
|
|
641
|
+
} catch {
|
|
642
|
+
return null;
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
function stripQuery(url) {
|
|
646
|
+
try {
|
|
647
|
+
const parsed = new URL(url);
|
|
648
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
|
|
649
|
+
return parsed.origin + parsed.pathname;
|
|
650
|
+
} catch {
|
|
651
|
+
return null;
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
var Session = class _Session {
|
|
655
|
+
observations = [];
|
|
656
|
+
guardBlocked = [];
|
|
657
|
+
/** One entry per snapshot: was the page's guard running? */
|
|
658
|
+
guardStatus = [];
|
|
659
|
+
/** Every POST the context sent, with its body: what the consent-receipts check reads. */
|
|
660
|
+
posts = [];
|
|
661
|
+
/** What the page's Content-Security-Policy refused that is not a request: inline styles and scripts, eval, data: and blob:. */
|
|
662
|
+
policyViolations = [];
|
|
663
|
+
/** Pathnames of pages on which the CSP refused an inline script. */
|
|
664
|
+
inlineBlocked = /* @__PURE__ */ new Set();
|
|
665
|
+
/** The most recent snapshot. */
|
|
666
|
+
latest = /* @__PURE__ */ new Set();
|
|
667
|
+
phase = "before any decision";
|
|
668
|
+
granted = [];
|
|
669
|
+
path = "/";
|
|
670
|
+
inflight = 0;
|
|
671
|
+
lastActivity = Date.now();
|
|
672
|
+
firstSeen = /* @__PURE__ */ new Map();
|
|
673
|
+
byRequest = /* @__PURE__ */ new WeakMap();
|
|
674
|
+
siteOrigin;
|
|
675
|
+
context;
|
|
676
|
+
page;
|
|
677
|
+
config;
|
|
678
|
+
// No parameter properties: this file also runs under Node's type stripping.
|
|
679
|
+
constructor(context, page, config) {
|
|
680
|
+
this.context = context;
|
|
681
|
+
this.page = page;
|
|
682
|
+
this.config = config;
|
|
683
|
+
this.siteOrigin = new URL(config.siteUrl).origin;
|
|
684
|
+
}
|
|
685
|
+
static async open(browser, config, options = {}) {
|
|
686
|
+
const gpc = options.gpc === true;
|
|
687
|
+
const context = await browser.newContext(gpc ? { extraHTTPHeaders: { "Sec-GPC": "1" } } : {});
|
|
688
|
+
context.setDefaultTimeout(config.timeoutMs);
|
|
689
|
+
context.setDefaultNavigationTimeout(config.timeoutMs);
|
|
690
|
+
const page = await context.newPage();
|
|
691
|
+
const session = new _Session(context, page, config);
|
|
692
|
+
await context.exposeBinding(BINDING, (source, entry) => {
|
|
693
|
+
if (source.frame === page.mainFrame()) session.record(entry);
|
|
694
|
+
});
|
|
695
|
+
await context.addInitScript(recorder, { gpc, binding: BINDING });
|
|
696
|
+
context.on("request", (request) => session.onRequest(request));
|
|
697
|
+
context.on("requestfinished", () => session.onRequestDone());
|
|
698
|
+
context.on("requestfailed", (request) => {
|
|
699
|
+
session.onRequestDone();
|
|
700
|
+
const observation = session.byRequest.get(request);
|
|
701
|
+
if (observation && request.failure()?.errorText === "csp") observation.blockedBy = "csp";
|
|
702
|
+
});
|
|
703
|
+
return session;
|
|
704
|
+
}
|
|
705
|
+
/** Labels what follows. Call it just before the click that changes the consent state. */
|
|
706
|
+
setPhase(phase, granted) {
|
|
707
|
+
this.phase = phase;
|
|
708
|
+
this.granted = [...granted];
|
|
709
|
+
}
|
|
710
|
+
/** Index into `observations`: everything from here on happened after this call. */
|
|
711
|
+
mark() {
|
|
712
|
+
return this.observations.length;
|
|
713
|
+
}
|
|
714
|
+
push(observation) {
|
|
715
|
+
const full = { ...observation, page: this.path, phase: this.phase, granted: [...this.granted] };
|
|
716
|
+
this.observations.push(full);
|
|
717
|
+
return full;
|
|
718
|
+
}
|
|
719
|
+
record(entry) {
|
|
720
|
+
this.lastActivity = Date.now();
|
|
721
|
+
if (entry.t === "write" && entry.kind && typeof entry.key === "string") {
|
|
722
|
+
this.push({ kind: entry.kind, key: entry.key, source: "write" });
|
|
723
|
+
return;
|
|
724
|
+
}
|
|
725
|
+
if (entry.t === "csp" && !/^https?:\/\//i.test(entry.url ?? "")) {
|
|
726
|
+
const directive = entry.directive ?? "";
|
|
727
|
+
const blocked = entry.url || "inline";
|
|
728
|
+
if (blocked === "inline" && directive.startsWith("script-src")) this.inlineBlocked.add(this.path);
|
|
729
|
+
this.policyViolations.push({ page: this.path, phase: this.phase, directive, blocked });
|
|
730
|
+
return;
|
|
731
|
+
}
|
|
732
|
+
if (entry.t === "csp" && entry.url) {
|
|
733
|
+
const key = stripQuery(entry.url);
|
|
734
|
+
if (!key) return;
|
|
735
|
+
const known = this.observations.some((o) => o.blockedBy === "csp" && o.key === key);
|
|
736
|
+
if (known) return;
|
|
737
|
+
const directive = entry.directive ?? "";
|
|
738
|
+
const kind = directive.startsWith("script-src") ? "script" : /^(frame|child)-src/.test(directive) ? "iframe" : "request";
|
|
739
|
+
const resourceType = /^style-src/.test(directive) ? "stylesheet" : /^font-src/.test(directive) ? "font" : /^media-src/.test(directive) ? "media" : /^img-src/.test(directive) ? "image" : void 0;
|
|
740
|
+
this.push({ kind, key, source: "request", blockedBy: "csp", ...resourceType === void 0 ? {} : { resourceType } });
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
onRequestDone() {
|
|
744
|
+
this.inflight = Math.max(0, this.inflight - 1);
|
|
745
|
+
this.lastActivity = Date.now();
|
|
746
|
+
}
|
|
747
|
+
onRequest(request) {
|
|
748
|
+
this.inflight += 1;
|
|
749
|
+
this.lastActivity = Date.now();
|
|
750
|
+
const key = stripQuery(request.url());
|
|
751
|
+
if (!key) return;
|
|
752
|
+
if (request.method() === "POST") this.posts.push({ url: request.url(), body: request.postData(), page: this.path, phase: this.phase });
|
|
753
|
+
let frame = null;
|
|
754
|
+
try {
|
|
755
|
+
frame = request.frame();
|
|
756
|
+
} catch {
|
|
757
|
+
}
|
|
758
|
+
let kind;
|
|
759
|
+
let initiator = frame;
|
|
760
|
+
if (request.isNavigationRequest()) {
|
|
761
|
+
if (!frame || frame.parentFrame() === null) return;
|
|
762
|
+
kind = "iframe";
|
|
763
|
+
initiator = frame.parentFrame();
|
|
764
|
+
} else {
|
|
765
|
+
kind = request.resourceType() === "script" ? "script" : "request";
|
|
766
|
+
}
|
|
767
|
+
while (initiator && initiator.parentFrame() !== null && originOf(initiator.url()) === null) initiator = initiator.parentFrame();
|
|
768
|
+
if (initiator && initiator.parentFrame() !== null && originOf(initiator.url()) !== this.siteOrigin) return;
|
|
769
|
+
this.byRequest.set(request, this.push({ kind, key, source: "request", resourceType: request.resourceType() }));
|
|
770
|
+
}
|
|
771
|
+
/** Waits until no request has started or finished for `settleMs` (at most `timeoutMs`). */
|
|
772
|
+
async settle() {
|
|
773
|
+
const deadline = Date.now() + this.config.timeoutMs;
|
|
774
|
+
const stuckAfter = Math.max(1500, this.config.settleMs * 4);
|
|
775
|
+
for (; ; ) {
|
|
776
|
+
const quiet = Date.now() - this.lastActivity;
|
|
777
|
+
if (quiet >= this.config.settleMs && (this.inflight === 0 || quiet >= stuckAfter)) return;
|
|
778
|
+
if (Date.now() >= deadline) return;
|
|
779
|
+
await sleep(25);
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
async evaluateStable(fn) {
|
|
783
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
784
|
+
try {
|
|
785
|
+
return await this.page.evaluate(fn);
|
|
786
|
+
} catch {
|
|
787
|
+
await this.page.waitForLoadState("load").catch(() => void 0);
|
|
788
|
+
await this.settle();
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
return null;
|
|
792
|
+
}
|
|
793
|
+
/** Reads the browser's own view and records every cookie, storage key and database it holds. */
|
|
794
|
+
async snapshot() {
|
|
795
|
+
const snapshot = /* @__PURE__ */ new Set();
|
|
796
|
+
const now = Date.now();
|
|
797
|
+
for (const cookie of await this.context.cookies()) {
|
|
798
|
+
const identity = `${cookie.name}|${cookie.domain}|${cookie.path}|${cookie.expires}`;
|
|
799
|
+
if (!this.firstSeen.has(identity)) this.firstSeen.set(identity, now);
|
|
800
|
+
const observed = {
|
|
801
|
+
domain: cookie.domain,
|
|
802
|
+
path: cookie.path,
|
|
803
|
+
expires: cookie.expires,
|
|
804
|
+
sameSite: cookie.sameSite,
|
|
805
|
+
httpOnly: cookie.httpOnly,
|
|
806
|
+
secure: cookie.secure,
|
|
807
|
+
firstSeen: this.firstSeen.get(identity)
|
|
808
|
+
};
|
|
809
|
+
this.push({ kind: "cookie", key: cookie.name, source: "cookie-jar", cookie: observed });
|
|
810
|
+
snapshot.add(`cookie|${cookie.name}`);
|
|
811
|
+
}
|
|
812
|
+
const store = await this.evaluateStable(async () => {
|
|
813
|
+
const keys = (read) => {
|
|
814
|
+
try {
|
|
815
|
+
return Object.keys(read());
|
|
816
|
+
} catch {
|
|
817
|
+
return [];
|
|
818
|
+
}
|
|
819
|
+
};
|
|
820
|
+
let databases = [];
|
|
821
|
+
try {
|
|
822
|
+
databases = (await indexedDB.databases()).map((db) => db.name ?? "").filter(Boolean);
|
|
823
|
+
} catch {
|
|
824
|
+
}
|
|
825
|
+
const guard = window.__ck_observed;
|
|
826
|
+
return {
|
|
827
|
+
// The guard's own text names its install marker, whether or not the browser ran it.
|
|
828
|
+
guardPresent: Array.from(document.scripts).some((script) => !script.src && (script.textContent ?? "").includes("__ck_guard")),
|
|
829
|
+
guardInstalled: typeof window.__ck_guard === "object" && window.__ck_guard !== null,
|
|
830
|
+
localStorage: keys(() => localStorage),
|
|
831
|
+
sessionStorage: keys(() => sessionStorage),
|
|
832
|
+
indexedDB: databases,
|
|
833
|
+
blocked: Array.isArray(guard) ? guard.filter((o) => o.outcome === "blocked").map((o) => ({ kind: o.kind, key: o.key, artefact: o.artefact })) : []
|
|
834
|
+
};
|
|
835
|
+
});
|
|
836
|
+
if (store) {
|
|
837
|
+
this.guardStatus.push({
|
|
838
|
+
page: this.path,
|
|
839
|
+
phase: this.phase,
|
|
840
|
+
present: store.guardPresent,
|
|
841
|
+
installed: store.guardInstalled,
|
|
842
|
+
inlineScriptBlocked: this.inlineBlocked.has(this.path)
|
|
843
|
+
});
|
|
844
|
+
for (const kind of ["localStorage", "sessionStorage", "indexedDB"]) {
|
|
845
|
+
for (const key of store[kind]) {
|
|
846
|
+
this.push({ kind, key, source: "storage" });
|
|
847
|
+
snapshot.add(`${kind}|${key}`);
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
for (const blocked of store.blocked) {
|
|
851
|
+
const known = this.guardBlocked.some((b) => b.kind === blocked.kind && b.key === blocked.key && b.phase === this.phase);
|
|
852
|
+
if (!known) this.guardBlocked.push({ ...blocked, page: this.path, phase: this.phase });
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
this.latest = snapshot;
|
|
856
|
+
return snapshot;
|
|
857
|
+
}
|
|
858
|
+
/** Loads a page, lets it settle, runs the project's `exercise` step and takes a snapshot. */
|
|
859
|
+
async visit(path) {
|
|
860
|
+
const url = new URL(path, this.config.siteUrl);
|
|
861
|
+
this.path = url.pathname;
|
|
862
|
+
await this.page.goto(url.href, { waitUntil: "load" });
|
|
863
|
+
if (this.config.exercise) {
|
|
864
|
+
await this.config.exercise(this.page, { path: this.path, phase: this.phase, granted: [...this.granted] });
|
|
865
|
+
}
|
|
866
|
+
await this.settle();
|
|
867
|
+
return this.snapshot();
|
|
868
|
+
}
|
|
869
|
+
/** CookieConsent's consent cookie, parsed, or null when there is no (readable) cookie. */
|
|
870
|
+
async consentCookie() {
|
|
871
|
+
const cookies = await this.context.cookies(this.config.siteUrl);
|
|
872
|
+
const cookie = cookies.find((c) => c.name === this.config.consentCookieName);
|
|
873
|
+
if (!cookie) return null;
|
|
874
|
+
try {
|
|
875
|
+
const value = JSON.parse(decodeURIComponent(cookie.value));
|
|
876
|
+
return typeof value === "object" && value !== null ? value : null;
|
|
877
|
+
} catch {
|
|
878
|
+
return null;
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
/** The categories in CookieConsent's consent cookie, or null when there is no (readable) cookie. */
|
|
882
|
+
async consentCategories() {
|
|
883
|
+
const value = await this.consentCookie();
|
|
884
|
+
return value && Array.isArray(value.categories) ? value.categories.filter((c) => typeof c === "string") : null;
|
|
885
|
+
}
|
|
886
|
+
/** The `consentId` in CookieConsent's consent cookie, or null. */
|
|
887
|
+
async consentId() {
|
|
888
|
+
const value = await this.consentCookie();
|
|
889
|
+
return typeof value?.consentId === "string" ? value.consentId : null;
|
|
890
|
+
}
|
|
891
|
+
/**
|
|
892
|
+
* Waits for the consent cookie to say exactly `granted` among `consentCategories`.
|
|
893
|
+
* Returns what the cookie held when the wait ended.
|
|
894
|
+
*/
|
|
895
|
+
async waitForConsent(granted, consentCategories) {
|
|
896
|
+
const deadline = Date.now() + this.config.timeoutMs;
|
|
897
|
+
let actual = null;
|
|
898
|
+
for (; ; ) {
|
|
899
|
+
actual = await this.consentCategories();
|
|
900
|
+
if (actual !== null) {
|
|
901
|
+
const held = actual;
|
|
902
|
+
if (consentCategories.every((category) => held.includes(category) === granted.includes(category))) return { ok: true, actual };
|
|
903
|
+
}
|
|
904
|
+
if (Date.now() >= deadline) return { ok: false, actual };
|
|
905
|
+
await sleep(50);
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
async close() {
|
|
909
|
+
await this.context.close().catch(() => void 0);
|
|
910
|
+
}
|
|
911
|
+
};
|
|
912
|
+
|
|
913
|
+
// src/ux.ts
|
|
914
|
+
var WHITE = { r: 255, g: 255, b: 255, a: 1 };
|
|
915
|
+
function parseColor(css) {
|
|
916
|
+
const value = css.trim().toLowerCase();
|
|
917
|
+
if (value === "transparent") return { r: 0, g: 0, b: 0, a: 0 };
|
|
918
|
+
const hex = /^#([0-9a-f]{3,8})$/.exec(value)?.[1];
|
|
919
|
+
if (hex && [3, 4, 6, 8].includes(hex.length)) {
|
|
920
|
+
const full = hex.length <= 4 ? [...hex].map((c) => c + c).join("") : hex;
|
|
921
|
+
const channel = (at) => parseInt(full.slice(at, at + 2), 16);
|
|
922
|
+
return { r: channel(0), g: channel(2), b: channel(4), a: full.length === 8 ? channel(6) / 255 : 1 };
|
|
923
|
+
}
|
|
924
|
+
const rgb = /^rgba?\(([^)]+)\)$/.exec(value)?.[1];
|
|
925
|
+
if (!rgb) return null;
|
|
926
|
+
const parts = rgb.split(/[\s,/]+/).filter(Boolean);
|
|
927
|
+
if (parts.length < 3) return null;
|
|
928
|
+
const number = (part, scale) => part.endsWith("%") ? parseFloat(part) / 100 * scale : parseFloat(part);
|
|
929
|
+
const [r, g, b] = [number(parts[0], 255), number(parts[1], 255), number(parts[2], 255)];
|
|
930
|
+
const a = parts[3] === void 0 ? 1 : number(parts[3], 1);
|
|
931
|
+
if (![r, g, b, a].every(Number.isFinite)) return null;
|
|
932
|
+
return { r, g, b, a: Math.min(1, Math.max(0, a)) };
|
|
933
|
+
}
|
|
934
|
+
function composite(top, bottom) {
|
|
935
|
+
const mix = (t, b) => t * top.a + b * (1 - top.a);
|
|
936
|
+
return { r: mix(top.r, bottom.r), g: mix(top.g, bottom.g), b: mix(top.b, bottom.b), a: 1 };
|
|
937
|
+
}
|
|
938
|
+
function effectiveBackground(layers) {
|
|
939
|
+
let colour = WHITE;
|
|
940
|
+
for (const layer of [...layers].reverse()) {
|
|
941
|
+
const parsed = parseColor(layer);
|
|
942
|
+
if (parsed) colour = composite(parsed, colour);
|
|
943
|
+
}
|
|
944
|
+
return colour;
|
|
945
|
+
}
|
|
946
|
+
function luminance(colour) {
|
|
947
|
+
const channel = (value) => {
|
|
948
|
+
const s = value / 255;
|
|
949
|
+
return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
|
|
950
|
+
};
|
|
951
|
+
return 0.2126 * channel(colour.r) + 0.7152 * channel(colour.g) + 0.0722 * channel(colour.b);
|
|
952
|
+
}
|
|
953
|
+
function contrastRatio(a, b) {
|
|
954
|
+
const [light, dark] = [luminance(a), luminance(b)].sort((x, y) => y - x);
|
|
955
|
+
return (light + 0.05) / (dark + 0.05);
|
|
956
|
+
}
|
|
957
|
+
function weightMetrics(button) {
|
|
958
|
+
const surround = effectiveBackground(button.backgrounds.slice(1));
|
|
959
|
+
const own = parseColor(button.backgrounds[0] ?? "transparent") ?? { r: 0, g: 0, b: 0, a: 0 };
|
|
960
|
+
const background = composite({ ...own, a: own.a * button.opacity }, surround);
|
|
961
|
+
const text = parseColor(button.color) ?? { r: 0, g: 0, b: 0, a: 1 };
|
|
962
|
+
return {
|
|
963
|
+
area: button.width * button.height,
|
|
964
|
+
height: button.height,
|
|
965
|
+
fontSize: button.fontSize,
|
|
966
|
+
textContrast: contrastRatio(composite({ ...text, a: text.a * button.opacity }, background), background),
|
|
967
|
+
prominence: contrastRatio(background, surround)
|
|
968
|
+
};
|
|
969
|
+
}
|
|
970
|
+
function compareWeight(accept, reject, tolerances) {
|
|
971
|
+
const a = weightMetrics(accept);
|
|
972
|
+
const r = weightMetrics(reject);
|
|
973
|
+
const differences = [];
|
|
974
|
+
const check = (name, x, y, tolerance, format) => {
|
|
975
|
+
const [low, high] = x <= y ? [x, y] : [y, x];
|
|
976
|
+
if (high > 0 && low / high < 1 - tolerance) {
|
|
977
|
+
differences.push(
|
|
978
|
+
`${name}: "${accept.label}" ${format(x)} vs "${reject.label}" ${format(y)} (ratio ${(low / high).toFixed(2)}, must be at least ${(1 - tolerance).toFixed(2)})`
|
|
979
|
+
);
|
|
980
|
+
}
|
|
981
|
+
};
|
|
982
|
+
const px = (value) => `${Math.round(value)}px`;
|
|
983
|
+
const ratio = (value) => `${value.toFixed(2)}:1`;
|
|
984
|
+
check("area", a.area, r.area, tolerances.size, (value) => `${Math.round(value)}px\xB2`);
|
|
985
|
+
check("height", a.height, r.height, tolerances.size, px);
|
|
986
|
+
check("font size", a.fontSize, r.fontSize, tolerances.size, px);
|
|
987
|
+
check("label contrast", a.textContrast, r.textContrast, tolerances.contrast, ratio);
|
|
988
|
+
check("contrast against the banner", a.prominence, r.prominence, tolerances.contrast, ratio);
|
|
989
|
+
return { equal: differences.length === 0, differences, accept: a, reject: r };
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
// src/checks.ts
|
|
993
|
+
var NOTHING_TO_CONSENT = "no purpose asks for consent";
|
|
994
|
+
var BEFORE = "before any decision";
|
|
995
|
+
function driveFinding(error, context, category) {
|
|
996
|
+
if (error instanceof ConsentNotRecordedError) {
|
|
997
|
+
return { severity: "error", code: "consent-not-recorded", message: `${context}: ${error.message}`, category };
|
|
998
|
+
}
|
|
999
|
+
if (error instanceof DriveError) {
|
|
1000
|
+
return { severity: "error", code: "cannot-drive", message: `${context}: ${error.message}`, category };
|
|
1001
|
+
}
|
|
1002
|
+
throw error;
|
|
1003
|
+
}
|
|
1004
|
+
function guardWarnings(session) {
|
|
1005
|
+
return session.guardBlocked.map((blocked) => ({
|
|
1006
|
+
severity: "warning",
|
|
1007
|
+
code: "guard-blocked",
|
|
1008
|
+
message: `the runtime guard blocked ${blocked.kind} "${blocked.key}"` + (blocked.artefact ? ` (artefact "${blocked.artefact}")` : "") + ` ${blocked.phase} on ${blocked.page}: the page tried to use it without consent.`,
|
|
1009
|
+
artefact: blocked.artefact ?? void 0,
|
|
1010
|
+
key: blocked.key,
|
|
1011
|
+
page: blocked.page,
|
|
1012
|
+
phase: blocked.phase
|
|
1013
|
+
}));
|
|
1014
|
+
}
|
|
1015
|
+
function withSession(env, seen2, options, run2) {
|
|
1016
|
+
return env.limit(async () => {
|
|
1017
|
+
const session = await Session.open(env.browser, env.session, options);
|
|
1018
|
+
try {
|
|
1019
|
+
return await run2(session);
|
|
1020
|
+
} finally {
|
|
1021
|
+
seen2.observations.push(...session.observations);
|
|
1022
|
+
seen2.guard.push(...session.guardStatus);
|
|
1023
|
+
seen2.violations.push(...session.policyViolations);
|
|
1024
|
+
await session.close();
|
|
1025
|
+
}
|
|
1026
|
+
});
|
|
1027
|
+
}
|
|
1028
|
+
async function perSession(env, items, run2) {
|
|
1029
|
+
const seen2 = { observations: [], guard: [], violations: [] };
|
|
1030
|
+
const findings = await Promise.all(items.map((item) => withSession(env, seen2, {}, (session) => run2(item, session))));
|
|
1031
|
+
return { findings: findings.flat(), ...seen2 };
|
|
1032
|
+
}
|
|
1033
|
+
async function oneSession(env, options, run2) {
|
|
1034
|
+
const seen2 = { observations: [], guard: [], violations: [] };
|
|
1035
|
+
const findings = await withSession(env, seen2, options, run2);
|
|
1036
|
+
return { findings, ...seen2 };
|
|
1037
|
+
}
|
|
1038
|
+
function preConsentSilence(env) {
|
|
1039
|
+
return perSession(env, env.pages, async (page, session) => {
|
|
1040
|
+
session.setPhase(BEFORE, []);
|
|
1041
|
+
await session.visit(page);
|
|
1042
|
+
return [...wrongPurpose(env.declared, session.observations), ...guardWarnings(session)];
|
|
1043
|
+
});
|
|
1044
|
+
}
|
|
1045
|
+
function rejectMeansReject(env) {
|
|
1046
|
+
if (env.declared.consentCategories.length === 0) return Promise.resolve({ findings: [], ...NO_SESSIONS, note: NOTHING_TO_CONSENT });
|
|
1047
|
+
return oneSession(env, {}, async (session) => {
|
|
1048
|
+
const [first, ...rest] = env.pages;
|
|
1049
|
+
session.setPhase(BEFORE, []);
|
|
1050
|
+
await session.visit(first);
|
|
1051
|
+
const mark = session.mark();
|
|
1052
|
+
try {
|
|
1053
|
+
await rejectAll(session, env.banner, "after rejecting");
|
|
1054
|
+
} catch (error) {
|
|
1055
|
+
return [driveFinding(error, "could not reject")];
|
|
1056
|
+
}
|
|
1057
|
+
for (const page of rest.length > 0 ? [...rest, first] : [first]) await session.visit(page);
|
|
1058
|
+
return [...wrongPurpose(env.declared, session.observations.slice(mark)), ...guardWarnings(session)];
|
|
1059
|
+
});
|
|
1060
|
+
}
|
|
1061
|
+
async function grantOnly(env, session, category) {
|
|
1062
|
+
const [first, ...rest] = env.pages;
|
|
1063
|
+
session.setPhase(BEFORE, []);
|
|
1064
|
+
const baseline = await session.visit(first);
|
|
1065
|
+
const mark = session.mark();
|
|
1066
|
+
await saveCategories(session, env.banner, [category], `after granting only "${category}"`);
|
|
1067
|
+
for (const page of rest) await session.visit(page);
|
|
1068
|
+
return { baseline, mark };
|
|
1069
|
+
}
|
|
1070
|
+
function grantActivatesDeclared(env) {
|
|
1071
|
+
return perSession(env, env.declared.consentCategories, async (category, session) => {
|
|
1072
|
+
let granted;
|
|
1073
|
+
try {
|
|
1074
|
+
granted = await grantOnly(env, session, category);
|
|
1075
|
+
} catch (error) {
|
|
1076
|
+
return [driveFinding(error, `could not grant "${category}"`, category)];
|
|
1077
|
+
}
|
|
1078
|
+
const after = session.observations.slice(granted.mark);
|
|
1079
|
+
const fresh = after.filter((o) => o.source === "request" || o.source === "write" || !granted.baseline.has(`${o.kind}|${o.key}`));
|
|
1080
|
+
const findings = [];
|
|
1081
|
+
for (const finding of wrongPurpose(env.declared, fresh)) {
|
|
1082
|
+
findings.push({
|
|
1083
|
+
...finding,
|
|
1084
|
+
message: `extra: granting only "${category}" also activated ${describe(finding.kind ?? "request", finding.key ?? "")} (artefact "${finding.artefact}"), which needs consent to: ${finding.category}.`,
|
|
1085
|
+
category
|
|
1086
|
+
});
|
|
1087
|
+
}
|
|
1088
|
+
const seen2 = exercisedIds(env.declared, after);
|
|
1089
|
+
for (const artefact of expectedFor(env.declared, category)) {
|
|
1090
|
+
if (seen2.has(artefact.id)) continue;
|
|
1091
|
+
findings.push({
|
|
1092
|
+
severity: "error",
|
|
1093
|
+
code: "missing",
|
|
1094
|
+
message: `missing: ${describe(artefact.kind, artefact.label)} (artefact "${artefact.id}") is declared for "${category}" but was not observed after granting it on ${env.pages.join(", ")}.`,
|
|
1095
|
+
artefact: artefact.id,
|
|
1096
|
+
kind: artefact.kind,
|
|
1097
|
+
key: artefact.label,
|
|
1098
|
+
category
|
|
1099
|
+
});
|
|
1100
|
+
}
|
|
1101
|
+
return findings;
|
|
1102
|
+
});
|
|
1103
|
+
}
|
|
1104
|
+
var STORED_KINDS = /* @__PURE__ */ new Set(["cookie", "localStorage", "sessionStorage", "indexedDB"]);
|
|
1105
|
+
function withdrawalCleansUp(env) {
|
|
1106
|
+
const stored = (category) => boundTo(env.declared, category).filter((artefact) => STORED_KINDS.has(artefact.kind));
|
|
1107
|
+
const categories = env.declared.consentCategories.filter((category) => stored(category).length > 0);
|
|
1108
|
+
return perSession(env, categories, async (category, session) => {
|
|
1109
|
+
const targets = stored(category);
|
|
1110
|
+
const targetIds = new Set(targets.map((artefact) => artefact.id));
|
|
1111
|
+
const present = (snapshot) => {
|
|
1112
|
+
const found = /* @__PURE__ */ new Map();
|
|
1113
|
+
for (const item of snapshot) {
|
|
1114
|
+
const separator = item.indexOf("|");
|
|
1115
|
+
const kind = item.slice(0, separator);
|
|
1116
|
+
const key = item.slice(separator + 1);
|
|
1117
|
+
const verdict = classify(env.declared, kind, key, []);
|
|
1118
|
+
if (verdict.status === "declared" && targetIds.has(verdict.entry.id)) found.set(verdict.entry.id, describe(kind, key));
|
|
1119
|
+
}
|
|
1120
|
+
return found;
|
|
1121
|
+
};
|
|
1122
|
+
const findings = [];
|
|
1123
|
+
try {
|
|
1124
|
+
await grantOnly(env, session, category);
|
|
1125
|
+
} catch (error) {
|
|
1126
|
+
return [driveFinding(error, `could not grant "${category}"`, category)];
|
|
1127
|
+
}
|
|
1128
|
+
const whileGranted = present(session.latest);
|
|
1129
|
+
for (const artefact of targets) {
|
|
1130
|
+
if (whileGranted.has(artefact.id)) continue;
|
|
1131
|
+
findings.push({
|
|
1132
|
+
severity: "warning",
|
|
1133
|
+
code: "not-verified",
|
|
1134
|
+
message: `${describe(artefact.kind, artefact.label)} (artefact "${artefact.id}") was never set while "${category}" was granted, so its cleanup could not be verified.`,
|
|
1135
|
+
artefact: artefact.id,
|
|
1136
|
+
category
|
|
1137
|
+
});
|
|
1138
|
+
}
|
|
1139
|
+
const phase = `after withdrawing "${category}"`;
|
|
1140
|
+
let withdrawnOn = env.pages[env.pages.length - 1];
|
|
1141
|
+
try {
|
|
1142
|
+
const candidates = [withdrawnOn, ...env.pages.filter((page) => page !== withdrawnOn)];
|
|
1143
|
+
for (const [index, page] of candidates.entries()) {
|
|
1144
|
+
if (index > 0) await session.visit(page);
|
|
1145
|
+
withdrawnOn = page;
|
|
1146
|
+
if (await isVisible(session, env.banner.selectors.preferencesLink, index === candidates.length - 1)) break;
|
|
1147
|
+
}
|
|
1148
|
+
await saveCategories(session, env.banner, [], phase);
|
|
1149
|
+
} catch (error) {
|
|
1150
|
+
return [...findings, driveFinding(error, `could not withdraw "${category}"`, category)];
|
|
1151
|
+
}
|
|
1152
|
+
const leftBehind = present(session.latest);
|
|
1153
|
+
const afterReload = present(await session.visit(withdrawnOn));
|
|
1154
|
+
for (const artefact of targets) {
|
|
1155
|
+
const stillThere = leftBehind.get(artefact.id);
|
|
1156
|
+
const backAgain = afterReload.get(artefact.id);
|
|
1157
|
+
if (stillThere === void 0 && backAgain === void 0) continue;
|
|
1158
|
+
findings.push({
|
|
1159
|
+
severity: "error",
|
|
1160
|
+
code: "not-cleaned",
|
|
1161
|
+
message: `${stillThere ?? backAgain} (artefact "${artefact.id}") ` + (stillThere !== void 0 ? `was still present after withdrawing "${category}"` : `came back on the next page load after withdrawing "${category}"`) + `. Declared cookies and storage keys must be removed on withdrawal.`,
|
|
1162
|
+
artefact: artefact.id,
|
|
1163
|
+
kind: artefact.kind,
|
|
1164
|
+
key: artefact.label,
|
|
1165
|
+
category,
|
|
1166
|
+
phase
|
|
1167
|
+
});
|
|
1168
|
+
}
|
|
1169
|
+
return findings;
|
|
1170
|
+
});
|
|
1171
|
+
}
|
|
1172
|
+
function gpcHonoured(env) {
|
|
1173
|
+
return oneSession(env, { gpc: true }, async (session) => {
|
|
1174
|
+
session.setPhase("with the GPC signal set", []);
|
|
1175
|
+
for (const page of env.pages) await session.visit(page);
|
|
1176
|
+
return [...wrongPurpose(env.declared, session.observations), ...guardWarnings(session)];
|
|
1177
|
+
});
|
|
1178
|
+
}
|
|
1179
|
+
function undeclaredDrift(env) {
|
|
1180
|
+
return oneSession(env, {}, async (session) => {
|
|
1181
|
+
const findings = [];
|
|
1182
|
+
session.setPhase(BEFORE, []);
|
|
1183
|
+
for (const page of env.pages) await session.visit(page);
|
|
1184
|
+
if (env.declared.consentCategories.length === 0) return undeclared(env.declared, session.observations);
|
|
1185
|
+
try {
|
|
1186
|
+
await acceptAll(session, env.banner, "after accepting all");
|
|
1187
|
+
for (const page of env.pages) await session.visit(page);
|
|
1188
|
+
} catch (error) {
|
|
1189
|
+
const finding = driveFinding(error, "could not accept all, so only the journey before a decision was checked");
|
|
1190
|
+
findings.push({ ...finding, severity: "warning" });
|
|
1191
|
+
}
|
|
1192
|
+
return [...findings, ...undeclared(env.declared, session.observations)];
|
|
1193
|
+
});
|
|
1194
|
+
}
|
|
1195
|
+
async function noBannerWanted(env) {
|
|
1196
|
+
const outcome = await oneSession(env, {}, async (session) => {
|
|
1197
|
+
const findings = [];
|
|
1198
|
+
session.setPhase(BEFORE, []);
|
|
1199
|
+
for (const page of env.pages) {
|
|
1200
|
+
await session.visit(page);
|
|
1201
|
+
if (await isVisible(session, env.banner.selectors.banner)) {
|
|
1202
|
+
findings.push({
|
|
1203
|
+
severity: "error",
|
|
1204
|
+
code: "banner-without-consent",
|
|
1205
|
+
message: `a consent banner (${env.banner.selectors.banner}) is visible on ${page}, but no purpose in the registry asks for consent. Remove the banner, or declare the purpose it asks about.`,
|
|
1206
|
+
page
|
|
1207
|
+
});
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
return findings;
|
|
1211
|
+
});
|
|
1212
|
+
return { ...outcome, note: NOTHING_TO_CONSENT };
|
|
1213
|
+
}
|
|
1214
|
+
async function measure(session, selector) {
|
|
1215
|
+
return session.page.locator(selector).first().evaluate((element) => {
|
|
1216
|
+
const rect = element.getBoundingClientRect();
|
|
1217
|
+
const style = getComputedStyle(element);
|
|
1218
|
+
const backgrounds = [];
|
|
1219
|
+
for (let node = element; node; node = node.parentElement) backgrounds.push(getComputedStyle(node).backgroundColor);
|
|
1220
|
+
return {
|
|
1221
|
+
label: (element.textContent ?? "").trim(),
|
|
1222
|
+
width: rect.width,
|
|
1223
|
+
height: rect.height,
|
|
1224
|
+
fontSize: parseFloat(style.fontSize),
|
|
1225
|
+
color: style.color,
|
|
1226
|
+
backgrounds,
|
|
1227
|
+
opacity: parseFloat(style.opacity)
|
|
1228
|
+
};
|
|
1229
|
+
});
|
|
1230
|
+
}
|
|
1231
|
+
function bannerUx(env) {
|
|
1232
|
+
const { selectors } = env.banner;
|
|
1233
|
+
if (env.declared.consentCategories.length === 0) return noBannerWanted(env);
|
|
1234
|
+
return oneSession(env, {}, async (session) => {
|
|
1235
|
+
const findings = [];
|
|
1236
|
+
const [first] = env.pages;
|
|
1237
|
+
session.setPhase(BEFORE, []);
|
|
1238
|
+
await session.visit(first);
|
|
1239
|
+
if (!await isVisible(session, selectors.banner)) {
|
|
1240
|
+
findings.push({
|
|
1241
|
+
severity: "error",
|
|
1242
|
+
code: "banner-missing",
|
|
1243
|
+
message: `no consent banner (${selectors.banner}) is visible on ${first} for a visitor who has not decided yet.`,
|
|
1244
|
+
page: first
|
|
1245
|
+
});
|
|
1246
|
+
} else {
|
|
1247
|
+
const hasAccept = await isVisible(session, selectors.accept);
|
|
1248
|
+
const hasReject = await isVisible(session, selectors.reject);
|
|
1249
|
+
for (const [present, name, selector] of [
|
|
1250
|
+
[hasAccept, "Accept", selectors.accept],
|
|
1251
|
+
[hasReject, "Reject", selectors.reject]
|
|
1252
|
+
]) {
|
|
1253
|
+
if (present) continue;
|
|
1254
|
+
findings.push({
|
|
1255
|
+
severity: "error",
|
|
1256
|
+
code: "button-missing",
|
|
1257
|
+
message: `the first layer of the banner has no visible ${name} button (${selector}). Accept and Reject must both be one click away.`,
|
|
1258
|
+
page: first
|
|
1259
|
+
});
|
|
1260
|
+
}
|
|
1261
|
+
if (hasAccept && hasReject) {
|
|
1262
|
+
const comparison = compareWeight(await measure(session, selectors.accept), await measure(session, selectors.reject), env.tolerances);
|
|
1263
|
+
if (!comparison.equal) {
|
|
1264
|
+
findings.push({
|
|
1265
|
+
severity: "error",
|
|
1266
|
+
code: "unequal-weight",
|
|
1267
|
+
message: `Accept and Reject do not have equal visual weight: ${comparison.differences.join("; ")}.`,
|
|
1268
|
+
page: first
|
|
1269
|
+
});
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
try {
|
|
1274
|
+
await rejectAll(session, env.banner, "after rejecting");
|
|
1275
|
+
} catch {
|
|
1276
|
+
await acceptAll(session, env.banner, "after accepting all").catch(() => void 0);
|
|
1277
|
+
}
|
|
1278
|
+
for (const page of env.pages) {
|
|
1279
|
+
await session.visit(page);
|
|
1280
|
+
let reason = null;
|
|
1281
|
+
if (!await isVisible(session, selectors.preferencesLink)) {
|
|
1282
|
+
reason = `no visible preferences link (${selectors.preferencesLink})`;
|
|
1283
|
+
} else {
|
|
1284
|
+
const opened = await session.page.locator(selectors.preferencesLink).first().click().then(() => isVisible(session, selectors.preferencesModal)).catch(() => false);
|
|
1285
|
+
if (!opened) reason = `clicking the preferences link (${selectors.preferencesLink}) did not open the preferences modal (${selectors.preferencesModal})`;
|
|
1286
|
+
}
|
|
1287
|
+
if (reason === null) continue;
|
|
1288
|
+
findings.push({
|
|
1289
|
+
severity: "error",
|
|
1290
|
+
code: "preferences-unreachable",
|
|
1291
|
+
message: `the privacy preferences cannot be reopened from the footer of ${page}: ${reason}.`,
|
|
1292
|
+
page
|
|
1293
|
+
});
|
|
1294
|
+
}
|
|
1295
|
+
return findings;
|
|
1296
|
+
});
|
|
1297
|
+
}
|
|
1298
|
+
var NO_SESSIONS = { observations: [], guard: [], violations: [] };
|
|
1299
|
+
function consentReceipts(env) {
|
|
1300
|
+
const receipts = env.registry.receipts;
|
|
1301
|
+
const categories = env.declared.consentCategories;
|
|
1302
|
+
if (receipts === void 0) {
|
|
1303
|
+
if (categories.length === 0) return Promise.resolve({ findings: [], ...NO_SESSIONS });
|
|
1304
|
+
return Promise.resolve({
|
|
1305
|
+
findings: [
|
|
1306
|
+
{
|
|
1307
|
+
severity: "error",
|
|
1308
|
+
code: "receipts-not-stated",
|
|
1309
|
+
message: `the registry asks for consent (${categories.join(", ")}) but has no "receipts" section, so nothing says where the proof of a decision goes. "consent-kit check" refuses such a registry.`
|
|
1310
|
+
}
|
|
1311
|
+
],
|
|
1312
|
+
...NO_SESSIONS
|
|
1313
|
+
});
|
|
1314
|
+
}
|
|
1315
|
+
if ("optOut" in receipts) {
|
|
1316
|
+
return Promise.resolve({
|
|
1317
|
+
findings: [
|
|
1318
|
+
{
|
|
1319
|
+
severity: "warning",
|
|
1320
|
+
code: "receipts-opted-out",
|
|
1321
|
+
message: `NOT CHECKED: the registry opts out of consent receipts, so no visitor's decision is recorded beyond the consent cookie in their browser. Reason given: ${receipts.optOut.reason}`
|
|
1322
|
+
}
|
|
1323
|
+
],
|
|
1324
|
+
...NO_SESSIONS
|
|
1325
|
+
});
|
|
1326
|
+
}
|
|
1327
|
+
const endpoint = new URL(receipts.endpoint, env.session.siteUrl);
|
|
1328
|
+
const target = endpoint.origin + endpoint.pathname;
|
|
1329
|
+
const toEndpoint = (session, from) => session.posts.slice(from).filter((post) => {
|
|
1330
|
+
const url = new URL(post.url);
|
|
1331
|
+
return url.origin + url.pathname === target;
|
|
1332
|
+
});
|
|
1333
|
+
const judge = async (session, decision, event, granted, decide) => {
|
|
1334
|
+
const from = session.posts.length;
|
|
1335
|
+
try {
|
|
1336
|
+
await decide();
|
|
1337
|
+
} catch (error) {
|
|
1338
|
+
return [driveFinding(error, `could not ${decision}`)];
|
|
1339
|
+
}
|
|
1340
|
+
const deadline = Date.now() + env.session.timeoutMs;
|
|
1341
|
+
while (toEndpoint(session, from).length === 0 && Date.now() < deadline) await new Promise((resolve2) => setTimeout(resolve2, 50));
|
|
1342
|
+
await new Promise((resolve2) => setTimeout(resolve2, env.session.settleMs));
|
|
1343
|
+
await session.settle();
|
|
1344
|
+
const expected = { ...expectedReceipt(env.registry, event, granted), consentId: await session.consentId() };
|
|
1345
|
+
return receiptFindings(toEndpoint(session, from), expected, decision, target);
|
|
1346
|
+
};
|
|
1347
|
+
return perSession(env, ["accept", "reject"], async (journey, session) => {
|
|
1348
|
+
const [first] = env.pages;
|
|
1349
|
+
session.setPhase(BEFORE, []);
|
|
1350
|
+
await session.visit(first);
|
|
1351
|
+
if (journey === "reject") return judge(session, "rejecting all", "first", [], () => rejectAll(session, env.banner, "after rejecting"));
|
|
1352
|
+
const accepted = await judge(session, "accepting all", "first", categories, () => acceptAll(session, env.banner, "after accepting all"));
|
|
1353
|
+
if (accepted.some((finding) => finding.code === "cannot-drive" || finding.code === "consent-not-recorded")) return accepted;
|
|
1354
|
+
const withdrawn = await judge(
|
|
1355
|
+
session,
|
|
1356
|
+
"withdrawing everything after accepting it",
|
|
1357
|
+
"change",
|
|
1358
|
+
[],
|
|
1359
|
+
() => saveCategories(session, env.banner, [], "after withdrawing everything")
|
|
1360
|
+
);
|
|
1361
|
+
return [...accepted, ...withdrawn];
|
|
1362
|
+
});
|
|
1363
|
+
}
|
|
1364
|
+
var AUDIT_TEST_DOMAIN = "consent-kit.invalid";
|
|
1365
|
+
var MAX_LINKS_FOLLOWED = 25;
|
|
1366
|
+
function subjectRequestsReachable(env) {
|
|
1367
|
+
const section = env.registry.subjectRequests;
|
|
1368
|
+
if (section === void 0) return Promise.resolve({ findings: [], ...NO_SESSIONS, note: "the registry declares no subject requests" });
|
|
1369
|
+
const site = new URL(env.session.siteUrl);
|
|
1370
|
+
const endpoint = new URL(section.endpoint, site);
|
|
1371
|
+
const target = endpoint.origin + endpoint.pathname;
|
|
1372
|
+
return oneSession(env, {}, async (session) => {
|
|
1373
|
+
session.setPhase(BEFORE, []);
|
|
1374
|
+
const findForm = () => session.page.evaluate((path) => {
|
|
1375
|
+
for (const form2 of Array.from(document.forms)) {
|
|
1376
|
+
const action = new URL(form2.getAttribute("action") ?? "", location.href);
|
|
1377
|
+
if (action.pathname !== path) continue;
|
|
1378
|
+
form2.setAttribute("data-consent-kit-audit", "subject-request");
|
|
1379
|
+
return { action: action.origin + action.pathname, origin: action.origin, method: (form2.getAttribute("method") ?? "get").toLowerCase() };
|
|
1380
|
+
}
|
|
1381
|
+
return null;
|
|
1382
|
+
}, endpoint.pathname);
|
|
1383
|
+
const sameOriginLinks = () => session.page.evaluate((origin) => Array.from(document.querySelectorAll("a[href]"), (a) => new URL(a.href)).filter((url) => url.origin === origin).map((url) => url.pathname + url.search), site.origin);
|
|
1384
|
+
let found;
|
|
1385
|
+
const links = [];
|
|
1386
|
+
for (const page2 of env.pages) {
|
|
1387
|
+
await session.visit(page2);
|
|
1388
|
+
const form2 = await findForm();
|
|
1389
|
+
if (form2) {
|
|
1390
|
+
found = { page: page2, form: form2 };
|
|
1391
|
+
break;
|
|
1392
|
+
}
|
|
1393
|
+
for (const link of await sameOriginLinks()) if (!links.includes(link) && !env.pages.includes(link)) links.push(link);
|
|
1394
|
+
}
|
|
1395
|
+
for (const link of links.slice(0, MAX_LINKS_FOLLOWED)) {
|
|
1396
|
+
if (found) break;
|
|
1397
|
+
await session.visit(link);
|
|
1398
|
+
const form2 = await findForm();
|
|
1399
|
+
if (form2) found = { page: link, form: form2 };
|
|
1400
|
+
}
|
|
1401
|
+
if (!found) {
|
|
1402
|
+
return [
|
|
1403
|
+
{
|
|
1404
|
+
severity: "error",
|
|
1405
|
+
code: "subject-request-form-missing",
|
|
1406
|
+
message: `no audited page has a form that posts to ${section.endpoint}, nor links to a page that has one (${Math.min(links.length, MAX_LINKS_FOLLOWED)} same-origin link(s) followed). Embed consent-kit's subject-request-form.<locale>.html, and link its page from every page, e.g. next to the privacy policy.`
|
|
1407
|
+
}
|
|
1408
|
+
];
|
|
1409
|
+
}
|
|
1410
|
+
const { page, form } = found;
|
|
1411
|
+
if (form.origin !== site.origin || form.method !== "post") {
|
|
1412
|
+
return [
|
|
1413
|
+
{
|
|
1414
|
+
severity: "error",
|
|
1415
|
+
code: "subject-request-form-foreign",
|
|
1416
|
+
message: `the request form on ${page} ${form.origin !== site.origin ? `posts to ${form.action}, another origin than the site's (${site.origin}), so the browser would not send its consent cookie` : `uses method "${form.method}" instead of POST`}.`,
|
|
1417
|
+
page
|
|
1418
|
+
}
|
|
1419
|
+
];
|
|
1420
|
+
}
|
|
1421
|
+
const network = (o) => o.kind === "request" || o.kind === "script" || o.kind === "iframe";
|
|
1422
|
+
const foreign = (o) => network(o) && originOfKey(o.key) !== site.origin;
|
|
1423
|
+
const baseline = new Set(session.observations.filter((o) => o.page === new URL(page, site).pathname && foreign(o)).map((o) => o.key));
|
|
1424
|
+
const selector = 'form[data-consent-kit-audit="subject-request"]';
|
|
1425
|
+
const address = `audit-${Date.now().toString(36)}@${AUDIT_TEST_DOMAIN}`;
|
|
1426
|
+
if (await session.page.locator(`${selector} [name="email"]`).count() === 0 || await session.page.locator(`${selector} [type="submit"]`).count() === 0) {
|
|
1427
|
+
return [{ severity: "error", code: "subject-request-not-accepted", message: `the request form on ${page} has no "email" field or no submit button, so nobody can send it.`, page }];
|
|
1428
|
+
}
|
|
1429
|
+
await session.page.fill(`${selector} [name="email"]`, address);
|
|
1430
|
+
const type = session.page.locator(`${selector} [name="type"]`).first();
|
|
1431
|
+
if (await type.getAttribute("type") === "radio") await type.check();
|
|
1432
|
+
const from = session.mark();
|
|
1433
|
+
const answered = session.page.waitForResponse((response2) => response2.request().method() === "POST" && stripped(response2.url()) === target, { timeout: env.session.timeoutMs }).catch(() => null);
|
|
1434
|
+
await session.page.locator(`${selector} [type="submit"]`).first().click();
|
|
1435
|
+
const response = await answered;
|
|
1436
|
+
await session.page.waitForLoadState("load").catch(() => void 0);
|
|
1437
|
+
await session.settle();
|
|
1438
|
+
const findings = [];
|
|
1439
|
+
if (response === null || response.status() !== 303) {
|
|
1440
|
+
findings.push({
|
|
1441
|
+
severity: "error",
|
|
1442
|
+
code: "subject-request-not-accepted",
|
|
1443
|
+
message: `submitting the request form on ${page} (as ${address}) was ${response === null ? "never answered by" : `answered ${response.status()} by`} ${target}; the endpoint answers an accepted request with 303 See Other.`,
|
|
1444
|
+
page
|
|
1445
|
+
});
|
|
1446
|
+
}
|
|
1447
|
+
const contacted = [...new Set(session.observations.slice(from).filter(foreign).map((o) => o.key))].filter((key) => !baseline.has(key));
|
|
1448
|
+
for (const key of contacted) {
|
|
1449
|
+
findings.push({
|
|
1450
|
+
severity: "error",
|
|
1451
|
+
code: "subject-request-third-party",
|
|
1452
|
+
message: `submitting the request form on ${page} made the browser contact ${key}, a third party: a request (and the requester's address) must stay on the site's own domain.`,
|
|
1453
|
+
page,
|
|
1454
|
+
key
|
|
1455
|
+
});
|
|
1456
|
+
}
|
|
1457
|
+
return findings;
|
|
1458
|
+
});
|
|
1459
|
+
}
|
|
1460
|
+
function originOfKey(key) {
|
|
1461
|
+
try {
|
|
1462
|
+
return new URL(key).origin;
|
|
1463
|
+
} catch {
|
|
1464
|
+
return null;
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
function stripped(url) {
|
|
1468
|
+
const parsed = new URL(url);
|
|
1469
|
+
return parsed.origin + parsed.pathname;
|
|
1470
|
+
}
|
|
1471
|
+
var BROWSER_CHECKS = {
|
|
1472
|
+
"pre-consent-silence": preConsentSilence,
|
|
1473
|
+
"reject-means-reject": rejectMeansReject,
|
|
1474
|
+
"grant-activates-declared": grantActivatesDeclared,
|
|
1475
|
+
"withdrawal-cleans-up": withdrawalCleansUp,
|
|
1476
|
+
"gpc-honoured": gpcHonoured,
|
|
1477
|
+
"undeclared-drift": undeclaredDrift,
|
|
1478
|
+
"banner-ux": bannerUx,
|
|
1479
|
+
"consent-receipts": consentReceipts,
|
|
1480
|
+
"subject-requests": subjectRequestsReachable
|
|
1481
|
+
};
|
|
1482
|
+
|
|
1483
|
+
// src/types.ts
|
|
1484
|
+
var CHECK_IDS = [
|
|
1485
|
+
"pre-consent-silence",
|
|
1486
|
+
"reject-means-reject",
|
|
1487
|
+
"grant-activates-declared",
|
|
1488
|
+
"withdrawal-cleans-up",
|
|
1489
|
+
"gpc-honoured",
|
|
1490
|
+
"undeclared-drift",
|
|
1491
|
+
"banner-ux",
|
|
1492
|
+
"consent-receipts",
|
|
1493
|
+
"subject-requests",
|
|
1494
|
+
"attribute-drift",
|
|
1495
|
+
"unexercised",
|
|
1496
|
+
"guard-installed",
|
|
1497
|
+
"csp-violations"
|
|
1498
|
+
];
|
|
1499
|
+
var CHECK_TITLES = {
|
|
1500
|
+
"pre-consent-silence": "1. Pre-consent silence",
|
|
1501
|
+
"reject-means-reject": "2. Reject means reject",
|
|
1502
|
+
"grant-activates-declared": "3. Grant activates exactly what is declared",
|
|
1503
|
+
"withdrawal-cleans-up": "4. Withdrawal cleans up",
|
|
1504
|
+
"gpc-honoured": "5. GPC honoured",
|
|
1505
|
+
"undeclared-drift": "6. Undeclared drift",
|
|
1506
|
+
"banner-ux": "7. Banner UX",
|
|
1507
|
+
"consent-receipts": "Consent receipts: one per decision",
|
|
1508
|
+
"subject-requests": "Subject requests reachable",
|
|
1509
|
+
"attribute-drift": "Coverage: attribute drift",
|
|
1510
|
+
unexercised: "Coverage: unexercised declarations",
|
|
1511
|
+
"guard-installed": "Setup: runtime guard installed",
|
|
1512
|
+
"csp-violations": "Setup: no Content-Security-Policy violations in the page itself"
|
|
1513
|
+
};
|
|
1514
|
+
|
|
1515
|
+
// src/audit.ts
|
|
1516
|
+
var DEFAULTS = { concurrency: 6, settleMs: 300, timeoutMs: 8e3, consentCookieName: "cc_cookie" };
|
|
1517
|
+
function statusOf(findings) {
|
|
1518
|
+
if (findings.some((finding) => finding.severity === "error")) return "fail";
|
|
1519
|
+
return findings.length > 0 ? "warn" : "pass";
|
|
1520
|
+
}
|
|
1521
|
+
function limiter(max) {
|
|
1522
|
+
let active = 0;
|
|
1523
|
+
const waiting = [];
|
|
1524
|
+
return async (task) => {
|
|
1525
|
+
if (active >= max) await new Promise((resolve2) => waiting.push(resolve2));
|
|
1526
|
+
active += 1;
|
|
1527
|
+
try {
|
|
1528
|
+
return await task();
|
|
1529
|
+
} finally {
|
|
1530
|
+
active -= 1;
|
|
1531
|
+
waiting.shift()?.();
|
|
1532
|
+
}
|
|
1533
|
+
};
|
|
1534
|
+
}
|
|
1535
|
+
async function runAudit(options) {
|
|
1536
|
+
const started = Date.now();
|
|
1537
|
+
const site = new URL(options.url);
|
|
1538
|
+
if (site.protocol !== "http:" && site.protocol !== "https:") throw new Error(`consent-kit audit: "${options.url}" is not an http(s) URL`);
|
|
1539
|
+
const pages = options.pages && options.pages.length > 0 ? [...options.pages] : ["/"];
|
|
1540
|
+
for (const page of pages) {
|
|
1541
|
+
if (new URL(page, site).origin !== site.origin) throw new Error(`consent-kit audit: page "${page}" is not on ${site.origin}`);
|
|
1542
|
+
}
|
|
1543
|
+
const selected = new Set(options.checks ?? CHECK_IDS);
|
|
1544
|
+
for (const id of selected) if (!CHECK_IDS.includes(id)) throw new Error(`consent-kit audit: unknown check "${String(id)}"`);
|
|
1545
|
+
const strict = options.strict === true;
|
|
1546
|
+
const tolerances = { ...DEFAULT_TOLERANCES, ...options.tolerances };
|
|
1547
|
+
const declared = declare(options.registry, site.href);
|
|
1548
|
+
const ownBrowser = options.browser === void 0;
|
|
1549
|
+
const browser = options.browser ?? await chromium.launch({ headless: options.headless ?? true });
|
|
1550
|
+
const env = {
|
|
1551
|
+
browser,
|
|
1552
|
+
registry: options.registry,
|
|
1553
|
+
declared,
|
|
1554
|
+
banner: { selectors: { ...DEFAULT_SELECTORS, ...options.selectors }, categories: declared.consentCategories },
|
|
1555
|
+
session: {
|
|
1556
|
+
siteUrl: site.href,
|
|
1557
|
+
settleMs: options.settleMs ?? DEFAULTS.settleMs,
|
|
1558
|
+
timeoutMs: options.timeoutMs ?? DEFAULTS.timeoutMs,
|
|
1559
|
+
consentCookieName: options.consentCookieName ?? DEFAULTS.consentCookieName,
|
|
1560
|
+
exercise: options.exercise
|
|
1561
|
+
},
|
|
1562
|
+
pages,
|
|
1563
|
+
tolerances,
|
|
1564
|
+
limit: limiter(Math.max(1, options.concurrency ?? DEFAULTS.concurrency))
|
|
1565
|
+
};
|
|
1566
|
+
const results = /* @__PURE__ */ new Map();
|
|
1567
|
+
const observations = [];
|
|
1568
|
+
const guardStatuses = [];
|
|
1569
|
+
const violations = [];
|
|
1570
|
+
const elsewhere = [];
|
|
1571
|
+
try {
|
|
1572
|
+
const ids = Object.keys(BROWSER_CHECKS).filter((id) => selected.has(id));
|
|
1573
|
+
const outcomes = await Promise.all(
|
|
1574
|
+
ids.map(async (id) => {
|
|
1575
|
+
const checkStarted = Date.now();
|
|
1576
|
+
let outcome;
|
|
1577
|
+
try {
|
|
1578
|
+
outcome = await BROWSER_CHECKS[id](env);
|
|
1579
|
+
} catch (error) {
|
|
1580
|
+
const message = error instanceof Error ? error.message.split("\n")[0] : String(error);
|
|
1581
|
+
outcome = { findings: [{ severity: "error", code: "check-error", message: `the check could not complete: ${message}` }], observations: [], guard: [], violations: [] };
|
|
1582
|
+
}
|
|
1583
|
+
return { id, outcome, durationMs: Date.now() - checkStarted };
|
|
1584
|
+
})
|
|
1585
|
+
);
|
|
1586
|
+
for (const { id, outcome, durationMs } of outcomes) {
|
|
1587
|
+
observations.push(...outcome.observations);
|
|
1588
|
+
guardStatuses.push(...outcome.guard);
|
|
1589
|
+
violations.push(...outcome.violations);
|
|
1590
|
+
if (id !== "undeclared-drift") elsewhere.push(...outcome.observations);
|
|
1591
|
+
results.set(id, { id, title: CHECK_TITLES[id], status: statusOf(outcome.findings), findings: outcome.findings, durationMs, ...outcome.note ? { note: outcome.note } : {} });
|
|
1592
|
+
}
|
|
1593
|
+
} finally {
|
|
1594
|
+
if (ownBrowser) await browser.close();
|
|
1595
|
+
}
|
|
1596
|
+
const drift = results.get("undeclared-drift");
|
|
1597
|
+
if (drift) {
|
|
1598
|
+
const known = new Set(drift.findings.map((finding) => `${finding.kind}|${finding.key}`));
|
|
1599
|
+
drift.findings.push(...undeclared(declared, elsewhere).filter((finding) => !known.has(`${finding.kind}|${finding.key}`)));
|
|
1600
|
+
drift.status = statusOf(drift.findings);
|
|
1601
|
+
}
|
|
1602
|
+
if (selected.has("attribute-drift")) {
|
|
1603
|
+
const findings = attributeDrift(options.registry, declared, observations, tolerances);
|
|
1604
|
+
results.set("attribute-drift", { id: "attribute-drift", title: CHECK_TITLES["attribute-drift"], status: statusOf(findings), findings, durationMs: 0 });
|
|
1605
|
+
}
|
|
1606
|
+
if (selected.has("unexercised")) {
|
|
1607
|
+
const findings = unexercised(declared, exercisedIds(declared, observations), strict);
|
|
1608
|
+
results.set("unexercised", { id: "unexercised", title: CHECK_TITLES.unexercised, status: statusOf(findings), findings, durationMs: 0 });
|
|
1609
|
+
}
|
|
1610
|
+
if (selected.has("guard-installed")) {
|
|
1611
|
+
const findings = guardNotInstalled(guardStatuses);
|
|
1612
|
+
results.set("guard-installed", { id: "guard-installed", title: CHECK_TITLES["guard-installed"], status: statusOf(findings), findings, durationMs: 0 });
|
|
1613
|
+
}
|
|
1614
|
+
if (selected.has("csp-violations")) {
|
|
1615
|
+
const findings = policyViolationFindings(violations, guardStatuses);
|
|
1616
|
+
results.set("csp-violations", { id: "csp-violations", title: CHECK_TITLES["csp-violations"], status: statusOf(findings), findings, durationMs: 0 });
|
|
1617
|
+
}
|
|
1618
|
+
const { level, deviations } = contentSecurityPolicy(options.registry);
|
|
1619
|
+
const checks = CHECK_IDS.map(
|
|
1620
|
+
(id) => results.get(id) ?? { id, title: CHECK_TITLES[id], status: "skipped", findings: [], durationMs: 0 }
|
|
1621
|
+
);
|
|
1622
|
+
const count = (status) => checks.filter((check) => check.status === status).length;
|
|
1623
|
+
return {
|
|
1624
|
+
ok: count("fail") === 0,
|
|
1625
|
+
url: site.href,
|
|
1626
|
+
pages,
|
|
1627
|
+
strict,
|
|
1628
|
+
startedAt: new Date(started).toISOString(),
|
|
1629
|
+
durationMs: Date.now() - started,
|
|
1630
|
+
checks,
|
|
1631
|
+
coverage: coverageOf(options.registry, declared, observations, { strict, tolerances }),
|
|
1632
|
+
summary: { passed: count("pass"), warned: count("warn"), failed: count("fail"), skipped: count("skipped") },
|
|
1633
|
+
csp: { level, deviations },
|
|
1634
|
+
receipts: options.registry.receipts ?? null,
|
|
1635
|
+
...options.presets && options.presets.applied.length > 0 ? { presets: { applied: options.presets.applied, overrides: options.presets.overrides } } : {}
|
|
1636
|
+
};
|
|
1637
|
+
}
|
|
1638
|
+
var LABEL = { pass: "PASS", warn: "WARN", fail: "FAIL", skipped: "SKIP" };
|
|
1639
|
+
function plural(count, noun) {
|
|
1640
|
+
return `${count} ${noun}${count === 1 ? "" : "s"}`;
|
|
1641
|
+
}
|
|
1642
|
+
function renderReport(report) {
|
|
1643
|
+
const lines = [`consent-kit audit of ${report.url}`, `Pages: ${report.pages.join(", ")}${report.strict ? " (strict)" : ""}`, ""];
|
|
1644
|
+
const receipts = report.receipts;
|
|
1645
|
+
if (receipts && "optOut" in receipts) {
|
|
1646
|
+
lines.push(`CONSENT RECEIPTS NOT KEPT: the registry opts out. Reason given: ${receipts.optOut.reason}`, "");
|
|
1647
|
+
}
|
|
1648
|
+
for (const check of report.checks) {
|
|
1649
|
+
lines.push(`${LABEL[check.status]} ${check.title}${check.note ? ` (${check.note})` : ""}`);
|
|
1650
|
+
for (const finding of check.findings) {
|
|
1651
|
+
const [first, ...rest] = finding.message.split("\n");
|
|
1652
|
+
lines.push(` ${finding.severity === "error" ? "error " : "warning"} ${first}`);
|
|
1653
|
+
for (const line of rest) lines.push(` ${line}`);
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
const { coverage, summary } = report;
|
|
1657
|
+
const declared = coverage.exercised.length + coverage.unexercised.length;
|
|
1658
|
+
lines.push(
|
|
1659
|
+
"",
|
|
1660
|
+
`Coverage: ${coverage.exercised.length} of ${plural(declared, "declared artefact")} observed; ${coverage.undeclared.length} undeclared; ${coverage.wrongPurpose.length} used without consent; ${coverage.attributeDrift.length} with attribute drift.`
|
|
1661
|
+
);
|
|
1662
|
+
if (coverage.unexercised.length > 0) lines.push(`Unexercised: ${coverage.unexercised.join(", ")}`);
|
|
1663
|
+
const deviations = describeCspDeviations(report.csp?.deviations ?? []);
|
|
1664
|
+
lines.push(
|
|
1665
|
+
"",
|
|
1666
|
+
deviations.length === 0 ? "Content-Security-Policy (as generated from the registry): strict." : `Content-Security-Policy (as generated from the registry): ${plural(deviations.length, "deviation")} from strict`,
|
|
1667
|
+
...deviations.map((line) => ` ${line}`)
|
|
1668
|
+
);
|
|
1669
|
+
if (report.presets) {
|
|
1670
|
+
const presets = describePresets({ ...report.presets, warnings: [] });
|
|
1671
|
+
if (presets.length > 0) lines.push("", ...presets);
|
|
1672
|
+
}
|
|
1673
|
+
const parts = [plural(summary.passed, "check") + " passed"];
|
|
1674
|
+
if (summary.warned > 0) parts.push(`${summary.warned} with warnings`);
|
|
1675
|
+
if (summary.failed > 0) parts.push(`${summary.failed} failed`);
|
|
1676
|
+
if (summary.skipped > 0) parts.push(`${summary.skipped} skipped`);
|
|
1677
|
+
lines.push("", `${report.ok ? "Audit passed" : "Audit FAILED"}: ${parts.join(", ")} (${(report.durationMs / 1e3).toFixed(1)}s).`);
|
|
1678
|
+
return lines;
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
// src/cli.ts
|
|
1682
|
+
var EXIT_OK = 0;
|
|
1683
|
+
var EXIT_FAILED = 1;
|
|
1684
|
+
var EXIT_USAGE = 2;
|
|
1685
|
+
var DEFAULT_PROGRAM = "consent-kit-audit";
|
|
1686
|
+
function helpText(program = DEFAULT_PROGRAM, defaultRegistry) {
|
|
1687
|
+
const usage = defaultRegistry === void 0 ? `${program} <url> --registry <path> [options]` : `${program} <url> [options]`;
|
|
1688
|
+
const registry = defaultRegistry === void 0 ? "(required)" : `(default: ${defaultRegistry})`;
|
|
1689
|
+
return `${program}: check a running site against its privacy registry
|
|
1690
|
+
|
|
1691
|
+
Usage: ${usage}
|
|
1692
|
+
|
|
1693
|
+
Options:
|
|
1694
|
+
--registry <path> privacy.registry.yaml of the site ${registry}
|
|
1695
|
+
--page <path> Page to audit; repeat for several (default: /)
|
|
1696
|
+
--strict Declared-but-never-observed artefacts fail instead of warn
|
|
1697
|
+
--json Print the report as JSON
|
|
1698
|
+
--check <id> Run only this check; repeat for several
|
|
1699
|
+
(${CHECK_IDS.join(", ")})
|
|
1700
|
+
--exercise <file> ES module whose default export, (page, context) => Promise,
|
|
1701
|
+
runs after every page load (click a theme toggle, fill a form)
|
|
1702
|
+
--headed Show the browser
|
|
1703
|
+
-h, --help Show this help
|
|
1704
|
+
|
|
1705
|
+
Exit codes: 0 all checks passed, 1 a check failed, 2 usage or unreadable registry.
|
|
1706
|
+
`;
|
|
1707
|
+
}
|
|
1708
|
+
async function run(argv, io = {}) {
|
|
1709
|
+
const stdout = io.stdout ?? process.stdout;
|
|
1710
|
+
const stderr = io.stderr ?? process.stderr;
|
|
1711
|
+
const cwd = io.cwd ?? process.cwd();
|
|
1712
|
+
const program = io.programName ?? DEFAULT_PROGRAM;
|
|
1713
|
+
const usage = (message) => {
|
|
1714
|
+
stderr.write(`${program}: ${message}. Run "${program} --help" for usage.
|
|
1715
|
+
`);
|
|
1716
|
+
return EXIT_USAGE;
|
|
1717
|
+
};
|
|
1718
|
+
let parsed;
|
|
1719
|
+
try {
|
|
1720
|
+
parsed = parseArgs({
|
|
1721
|
+
args: [...argv],
|
|
1722
|
+
allowPositionals: true,
|
|
1723
|
+
options: {
|
|
1724
|
+
registry: { type: "string" },
|
|
1725
|
+
page: { type: "string", multiple: true },
|
|
1726
|
+
check: { type: "string", multiple: true },
|
|
1727
|
+
exercise: { type: "string" },
|
|
1728
|
+
strict: { type: "boolean" },
|
|
1729
|
+
json: { type: "boolean" },
|
|
1730
|
+
headed: { type: "boolean" },
|
|
1731
|
+
help: { type: "boolean", short: "h" }
|
|
1732
|
+
}
|
|
1733
|
+
});
|
|
1734
|
+
} catch (error) {
|
|
1735
|
+
return usage(error.message.replace(/\.$/, ""));
|
|
1736
|
+
}
|
|
1737
|
+
const { values, positionals } = parsed;
|
|
1738
|
+
if (values.help) {
|
|
1739
|
+
stdout.write(helpText(program, io.defaultRegistry));
|
|
1740
|
+
return EXIT_OK;
|
|
1741
|
+
}
|
|
1742
|
+
const [url, ...extra] = positionals;
|
|
1743
|
+
if (url === void 0) return usage("expected the URL of the site to audit");
|
|
1744
|
+
if (extra.length > 0) return usage(`unexpected argument "${extra[0]}"`);
|
|
1745
|
+
if (!/^https?:\/\//i.test(url)) return usage(`"${url}" is not an http(s) URL`);
|
|
1746
|
+
const registryPath = values.registry ?? io.defaultRegistry;
|
|
1747
|
+
if (registryPath === void 0) return usage("--registry <path> is required");
|
|
1748
|
+
const unknown = (values.check ?? []).find((id) => !CHECK_IDS.includes(id));
|
|
1749
|
+
if (unknown !== void 0) return usage(`unknown check "${unknown}"; expected one of ${CHECK_IDS.join(", ")}`);
|
|
1750
|
+
let yaml;
|
|
1751
|
+
try {
|
|
1752
|
+
yaml = readFileSync(resolve(cwd, registryPath), "utf8");
|
|
1753
|
+
} catch (error) {
|
|
1754
|
+
stderr.write(`${program}: cannot read ${registryPath}: ${error.message}
|
|
1755
|
+
`);
|
|
1756
|
+
return EXIT_USAGE;
|
|
1757
|
+
}
|
|
1758
|
+
const registry = parseRegistry(yaml);
|
|
1759
|
+
if (!registry.ok) {
|
|
1760
|
+
for (const error of registry.errors) stderr.write(`${registryPath}${error.line !== void 0 ? `:${error.line}` : ""} ${error.rule} ${error.message}
|
|
1761
|
+
`);
|
|
1762
|
+
stderr.write(`${program}: ${registryPath} is not a valid registry; run "consent-kit check"
|
|
1763
|
+
`);
|
|
1764
|
+
return EXIT_USAGE;
|
|
1765
|
+
}
|
|
1766
|
+
let exercise;
|
|
1767
|
+
if (values.exercise !== void 0) {
|
|
1768
|
+
const module = await import(pathToFileURL(resolve(cwd, values.exercise)).href);
|
|
1769
|
+
if (typeof module.default !== "function") return usage(`${values.exercise} has no default-exported function`);
|
|
1770
|
+
exercise = module.default;
|
|
1771
|
+
}
|
|
1772
|
+
const report = await (io.audit ?? runAudit)({
|
|
1773
|
+
url,
|
|
1774
|
+
registry: registry.registry,
|
|
1775
|
+
presets: registry.presets,
|
|
1776
|
+
pages: values.page,
|
|
1777
|
+
strict: values.strict === true,
|
|
1778
|
+
checks: values.check,
|
|
1779
|
+
headless: values.headed !== true,
|
|
1780
|
+
exercise
|
|
1781
|
+
});
|
|
1782
|
+
stdout.write(values.json ? `${JSON.stringify(report, null, 2)}
|
|
1783
|
+
` : `${renderReport(report).join("\n")}
|
|
1784
|
+
`);
|
|
1785
|
+
return report.ok ? EXIT_OK : EXIT_FAILED;
|
|
1786
|
+
}
|
|
1787
|
+
|
|
1788
|
+
// src/bin.ts
|
|
1789
|
+
process.exitCode = await run(process.argv.slice(2));
|