@simmalugnt-se/payload-consent 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0
4
+
5
+ - `scanner.pages` sends the site's published pages from Payload with a scan, in place of its
6
+ sitemaps, so a site with search indexing off and empty sitemaps is scanned beyond its start page.
7
+ Needs a `consent-scanner` that takes `pages`; an older one ignores them and reads the sitemaps.
8
+
9
+ ## 0.5.2
10
+
11
+ - Adding a scan's finding to a service keeps what the scan could not see (`summary.problems`):
12
+ judging the scan again wrote over it, so an incomplete scan looked complete (0.5.0).
13
+ - Adding a finding to a service writes as the editor, so a project's own access on the services
14
+ applies, in one of the site's languages, and with a known category (`necessary` otherwise).
15
+ - Evidence larger than 8 MB is refused before it is read; the scanner sends files up to 4 MB.
16
+
3
17
  ## 0.5.1
4
18
 
5
19
  - What a visitor was shown is kept when it changes: a reworded banner text or a service's new
package/README.md CHANGED
@@ -124,10 +124,20 @@ consentPlugin({
124
124
  token: process.env.CONSENT_SCANNER_TOKEN,
125
125
  // Only when the scanner cannot reach serverURL, e.g. Docker beside a dev server:
126
126
  // callbackBaseUrl: 'http://host.docker.internal:3000',
127
+ // Optional: the pages to scan, in place of the site's sitemaps.
128
+ pages: [{ collection: 'pages', url: (doc) => (doc.slug === 'home' ? '/' : `/${doc.slug}`) }],
127
129
  },
128
130
  })
129
131
  ```
130
132
 
133
+ The scanner picks the pages to visit from the site's sitemaps. A site with search indexing off
134
+ often serves empty ones, and then only the start page is scanned. With `scanner.pages`, a scan
135
+ sends the published documents of those collections instead: read as a visitor would, in the
136
+ default locale, each turned into a path or address by `url` (return nothing to leave one out).
137
+ Paths are taken relative to the scanned address, and addresses on another origin are left out;
138
+ more than 500 are thinned evenly. The scanner picks from them as from one sitemap. Without the
139
+ option, or when no page is left, the scanner reads the sitemaps.
140
+
131
141
  Scan now scans the site's address (the field above the button, or `serverURL`) as a new visitor,
132
142
  after rejecting, after accepting and, with several optional categories, with each one alone. The
133
143
  plugin presets c15t's cookie for each state, so no click is needed. The scanner posts the result
@@ -8,5 +8,7 @@ import { type ConsentPluginOptions } from "./types.ts";
8
8
  export declare function evidenceCollection(options: ConsentPluginOptions): CollectionConfig;
9
9
  /** Deletes the evidence of all but the latest `keep` finished scans, and any without a scan. */
10
10
  export declare function pruneEvidence(payload: Payload, keep: number): Promise<void>;
11
+ /** The scanner sends files up to 4 MB; anything far larger is not its evidence. */
12
+ export declare const MAX_EVIDENCE_BYTES: number;
11
13
  /** The scanner posts each evidence file here after the result, one file per request. */
12
14
  export declare function evidenceEndpoint(options: ConsentPluginOptions, checkToken: (req: PayloadRequest) => boolean): Endpoint;
package/dist/evidence.js CHANGED
@@ -69,6 +69,8 @@ export async function pruneEvidence(payload, keep) {
69
69
  overrideAccess: true,
70
70
  });
71
71
  }
72
+ /** The scanner sends files up to 4 MB; anything far larger is not its evidence. */
73
+ export const MAX_EVIDENCE_BYTES = 8 * 1024 * 1024;
72
74
  /** The scanner posts each evidence file here after the result, one file per request. */
73
75
  export function evidenceEndpoint(options, checkToken) {
74
76
  return {
@@ -95,9 +97,13 @@ export function evidenceEndpoint(options, checkToken) {
95
97
  return Response.json({ error: "Unknown scan" }, { status: 404 });
96
98
  if (scan.status !== "done")
97
99
  return Response.json({ error: "The scan has no result yet" }, { status: 409 });
100
+ if (Number(req.headers.get("content-length") ?? 0) > MAX_EVIDENCE_BYTES)
101
+ return Response.json({ error: "Too large" }, { status: 413 });
98
102
  const data = Buffer.from((await req.arrayBuffer?.()) ?? new ArrayBuffer(0));
99
103
  if (!data.length)
100
104
  return Response.json({ error: "Empty file" }, { status: 400 });
105
+ if (data.length > MAX_EVIDENCE_BYTES)
106
+ return Response.json({ error: "Too large" }, { status: 413 });
101
107
  const [, state, , extension] = match;
102
108
  const pdf = extension === "pdf";
103
109
  const doc = await req.payload.create({
package/dist/index.js CHANGED
@@ -39,6 +39,9 @@ export function consentPlugin(options = {}) {
39
39
  if (options.legalPages &&
40
40
  !config.collections?.some((collection) => collection.slug === options.legalPages?.collection))
41
41
  throw new Error(`Unknown legal pages collection: ${options.legalPages.collection}`);
42
+ for (const { collection } of options.scanner?.pages ?? [])
43
+ if (!config.collections?.some(({ slug }) => slug === collection))
44
+ throw new Error(`Unknown scanner pages collection: ${collection}`);
42
45
  // The site's own address spreads monthly scans over the month; the secret when it has none.
43
46
  const schedule = scanSchedule(config.serverURL || config.secret || CONSENT_GLOBAL);
44
47
  const usersSlug = config.admin?.user ?? "users";
package/dist/scans.d.ts CHANGED
@@ -9,6 +9,13 @@ import { type ConsentPluginOptions } from "./types.ts";
9
9
  * writes it, and the policy cookie, so the banner treats it as a choice already made.
10
10
  */
11
11
  export declare function scanStates(config: Pick<ConsentConfig, "categories" | "policyVersion">, now?: number): ScanState[];
12
+ /**
13
+ * The published pages of `scanner.pages` as addresses on the scanned site, read as a visitor would
14
+ * (`overrideAccess: false`) in the default locale. Paths are taken relative to `url`; addresses on
15
+ * another origin are left out, since the scanner refuses them. More than `MAX_SCAN_PAGES` are
16
+ * thinned evenly. `undefined` without any, so the scanner reads the sitemaps.
17
+ */
18
+ export declare function scanPages(payload: Payload, options: ConsentPluginOptions, url: string): Promise<string[] | undefined>;
12
19
  type Started = {
13
20
  id: number | string;
14
21
  } | {
package/dist/scans.js CHANGED
@@ -1,10 +1,11 @@
1
1
  import { timingSafeEqual } from "node:crypto";
2
2
  import { canManage, manageAccess } from "./access.js";
3
+ import { CATEGORIES } from "./defaults.js";
3
4
  import { evaluateScan, scanProblems, } from "./evaluate.js";
4
5
  import { evidenceEndpoint } from "./evidence.js";
5
6
  import { notifyScan } from "./notify.js";
6
7
  import { readConsent, toConsentConfig, } from "./site-config.js";
7
- import { CONSENT_GLOBAL, CONSENT_SCAN_EVIDENCE, CONSENT_SCANS, CONSENT_SERVICES, POLICY_COOKIE, SCAN_TASK, } from "./types.js";
8
+ import { CONSENT_GLOBAL, CONSENT_SCAN_EVIDENCE, CONSENT_SCANS, CONSENT_SERVICES, MAX_SCAN_PAGES, POLICY_COOKIE, SCAN_TASK, } from "./types.js";
8
9
  /**
9
10
  * The states a scan runs: a new visitor, rejecting, accepting everything and, with more than one
10
11
  * optional category, each category on its own. Each state presets c15t's cookie as c15t 2.2.1
@@ -35,6 +36,49 @@ export function scanStates(config, now = Date.now()) {
35
36
  states.push(state(`only-${category}`, [category]));
36
37
  return states;
37
38
  }
39
+ /**
40
+ * The published pages of `scanner.pages` as addresses on the scanned site, read as a visitor would
41
+ * (`overrideAccess: false`) in the default locale. Paths are taken relative to `url`; addresses on
42
+ * another origin are left out, since the scanner refuses them. More than `MAX_SCAN_PAGES` are
43
+ * thinned evenly. `undefined` without any, so the scanner reads the sitemaps.
44
+ */
45
+ export async function scanPages(payload, options, url) {
46
+ const site = new URL(url);
47
+ const localization = payload.config.localization;
48
+ const locale = localization ? localization.defaultLocale : undefined;
49
+ const found = new Set();
50
+ for (const { collection, url: toUrl } of options.scanner?.pages ?? []) {
51
+ const drafts = Boolean(payload.config.collections.find(({ slug }) => slug === collection)?.versions?.drafts);
52
+ const { docs } = await payload.find({
53
+ collection: collection,
54
+ depth: 0,
55
+ draft: false,
56
+ pagination: false,
57
+ overrideAccess: false,
58
+ ...(drafts ? { where: { _status: { equals: "published" } } } : {}),
59
+ });
60
+ for (const doc of docs) {
61
+ let address;
62
+ try {
63
+ const path = toUrl(doc, locale);
64
+ if (!path)
65
+ continue;
66
+ address = new URL(path, site);
67
+ }
68
+ catch {
69
+ continue;
70
+ }
71
+ if (address.origin !== site.origin)
72
+ continue;
73
+ address.hash = "";
74
+ found.add(address.href);
75
+ }
76
+ }
77
+ const pages = [...found].sort();
78
+ if (pages.length <= MAX_SCAN_PAGES)
79
+ return pages.length ? pages : undefined;
80
+ return Array.from({ length: MAX_SCAN_PAGES }, (_, index) => pages[Math.round((index * (pages.length - 1)) / (MAX_SCAN_PAGES - 1))]);
81
+ }
38
82
  function sameToken(given, expected) {
39
83
  const a = Buffer.from(given);
40
84
  const b = Buffer.from(expected);
@@ -84,6 +128,11 @@ export async function startScan({ payload, options, url: given, trigger = "manua
84
128
  return { error: "Enter the site's address, starting with https://", status: 400 };
85
129
  const { doc, services } = await readConsent({ payload });
86
130
  const states = scanStates(toConsentConfig(doc, services, { locale: "en" }));
131
+ // A page list that cannot be read leaves the scanner to the sitemaps rather than stop the scan.
132
+ const pages = await scanPages(payload, options, url).catch((error) => {
133
+ payload.logger.error({ err: error, msg: "payload-consent: could not list the pages to scan" });
134
+ return undefined;
135
+ });
87
136
  const base = `${scanner.callbackBaseUrl ?? payload.config.serverURL}${payload.config.routes.api}/${CONSENT_SCANS}`;
88
137
  const response = await fetch(new URL("/scans", scanner.url), {
89
138
  method: "POST",
@@ -92,6 +141,7 @@ export async function startScan({ payload, options, url: given, trigger = "manua
92
141
  url,
93
142
  callbackUrl: `${base}/result`,
94
143
  ...(scanner.keepEvidence === 0 ? {} : { evidenceUrl: `${base}/evidence` }),
144
+ ...(pages ? { pages } : {}),
95
145
  states: states.map(({ id, cookies }) => ({ id, cookies })),
96
146
  }),
97
147
  signal: AbortSignal.timeout(20_000),
@@ -335,14 +385,25 @@ function endpoints(options) {
335
385
  !serviceName ||
336
386
  (kind !== "cookie" && kind !== "localStorage" && kind !== "host"))
337
387
  return Response.json({ error: "Name the finding and the service" }, { status: 400 });
338
- const locale = body?.locale;
388
+ // The site's own languages only; anything else writes the default one.
389
+ const localization = req.payload.config.localization;
390
+ const locale = localization &&
391
+ localization.localeCodes.includes(String(body?.locale)) &&
392
+ typeof body?.locale === "string"
393
+ ? body.locale
394
+ : undefined;
395
+ const category = CATEGORIES.includes(body?.category)
396
+ ? body?.category
397
+ : "necessary";
398
+ // As the editor: a project's own access on the services still applies.
399
+ const asEditor = { overrideAccess: false, user: req.user, req };
339
400
  const existing = (await req.payload.find({
340
401
  collection: CONSENT_SERVICES,
341
402
  where: { name: { equals: serviceName } },
342
403
  limit: 1,
343
404
  depth: 0,
344
405
  locale: locale,
345
- req,
406
+ ...asEditor,
346
407
  })).docs[0];
347
408
  const entry = kind === "host"
348
409
  ? { hosts: [...(existing?.hosts ?? []), { host: name }] }
@@ -358,21 +419,21 @@ function endpoints(options) {
358
419
  id: existing.id,
359
420
  data: entry,
360
421
  locale: locale,
361
- req,
422
+ ...asEditor,
362
423
  })
363
424
  : await req.payload.create({
364
425
  collection: CONSENT_SERVICES,
365
426
  data: {
366
427
  name: serviceName,
367
428
  provider: body?.provider || undefined,
368
- category: body?.category || "necessary",
429
+ category,
369
430
  purpose: body?.purpose || serviceName,
370
431
  policyUrl: body?.policyUrl || undefined,
371
432
  loading: "code",
372
433
  ...entry,
373
434
  },
374
435
  locale: locale,
375
- req,
436
+ ...asEditor,
376
437
  });
377
438
  const latest = await latestDone(req);
378
439
  if (latest) {
@@ -384,10 +445,15 @@ function endpoints(options) {
384
445
  services: await allServices(req),
385
446
  previousKeys: (previous?.findings ?? []).map((f) => f.key),
386
447
  });
448
+ // Judged again against the services; what the scan could not see stays as it was.
449
+ const problems = latest.summary?.problems;
387
450
  await req.payload.update({
388
451
  collection: CONSENT_SCANS,
389
452
  id: latest.id,
390
- data: { findings: evaluated.findings, summary: evaluated.summary },
453
+ data: {
454
+ findings: evaluated.findings,
455
+ summary: { ...evaluated.summary, ...(problems?.length ? { problems } : {}) },
456
+ },
391
457
  overrideAccess: true,
392
458
  req,
393
459
  });
package/dist/types.d.ts CHANGED
@@ -54,6 +54,16 @@ export type ConsentPluginOptions = {
54
54
  * `consent-scan-evidence`. Defaults to 12; `0` asks the scanner for none.
55
55
  */
56
56
  keepEvidence?: number;
57
+ /**
58
+ * Collections whose published documents are the site's pages; `url` turns a document into its
59
+ * path or address, as in `legalPages`, or returns nothing to leave it out. A scan sends these
60
+ * pages to the scanner in place of the site's sitemaps, which a site with search indexing off
61
+ * leaves empty. Without it, the scanner reads the sitemaps.
62
+ */
63
+ pages?: {
64
+ collection: CollectionSlug;
65
+ url: (doc: Record<string, unknown>, locale: string | undefined) => string | null | undefined;
66
+ }[];
57
67
  };
58
68
  /** Change the services collection, for example to add hooks that revalidate the site's cache. */
59
69
  overrideServices?: (collection: CollectionConfig) => CollectionConfig;
@@ -75,3 +85,5 @@ export declare const POLICY_COOKIE = "c15t-policy";
75
85
  /** Three years, unless the host sets `records.retentionDays`. */
76
86
  export declare const DEFAULT_RETENTION_DAYS: number;
77
87
  export declare const DEFAULT_KEEP_EVIDENCE = 12;
88
+ /** The most pages a scan sends; the scanner takes up to 500. */
89
+ export declare const MAX_SCAN_PAGES = 500;
package/dist/types.js CHANGED
@@ -15,3 +15,5 @@ export const POLICY_COOKIE = "c15t-policy";
15
15
  /** Three years, unless the host sets `records.retentionDays`. */
16
16
  export const DEFAULT_RETENTION_DAYS = 3 * 365;
17
17
  export const DEFAULT_KEEP_EVIDENCE = 12;
18
+ /** The most pages a scan sends; the scanner takes up to 500. */
19
+ export const MAX_SCAN_PAGES = 500;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simmalugnt-se/payload-consent",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "Cookie consent for Payload sites: banner texts, services and scans in Admin",
5
5
  "keywords": [
6
6
  "payload",