@goosetools/goose-tools 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +98 -2
  2. package/bin/goose-tools.js +61 -0
  3. package/lib/check/src/agent.js +90 -0
  4. package/lib/check/src/analyze.js +311 -0
  5. package/lib/check/src/client.js +136 -0
  6. package/lib/check/src/copy.js +355 -0
  7. package/lib/check/src/fixes.js +153 -0
  8. package/lib/check/src/frame.js +92 -0
  9. package/lib/check/src/guard.js +441 -0
  10. package/lib/check/src/index.js +18 -0
  11. package/lib/check/src/mcp-http.js +169 -0
  12. package/lib/check/src/mcp.js +153 -0
  13. package/lib/check/src/scan.js +55 -0
  14. package/lib/check/src/stack.js +61 -0
  15. package/lib/check/src/tlds.js +3 -0
  16. package/lib/check/src/view.js +130 -0
  17. package/lib/check/src/worker.js +257 -0
  18. package/lib/engine/src/bots.js +146 -0
  19. package/lib/engine/src/directives.js +131 -0
  20. package/lib/engine/src/exposure.js +70 -0
  21. package/lib/engine/src/frontend.js +157 -0
  22. package/lib/engine/src/headers.js +76 -0
  23. package/lib/engine/src/hidden-text.js +425 -0
  24. package/lib/engine/src/html.js +794 -0
  25. package/lib/engine/src/index.js +20 -0
  26. package/lib/engine/src/php.js +316 -0
  27. package/lib/engine/src/policies.js +234 -0
  28. package/lib/engine/src/reach.js +199 -0
  29. package/lib/engine/src/robots.js +275 -0
  30. package/lib/engine/src/secrets.js +142 -0
  31. package/lib/engine/src/signals.js +144 -0
  32. package/lib/rules/data/bots.json.js +1 -0
  33. package/lib/rules/data/exposure.json.js +1 -0
  34. package/lib/rules/data/frontend.json.js +1 -0
  35. package/lib/rules/data/headers.json.js +1 -0
  36. package/lib/rules/data/secrets.json.js +1 -0
  37. package/lib/ui/LICENSE-Inter.txt +93 -0
  38. package/lib/ui/assets.js +5 -0
  39. package/package.json +37 -4
  40. package/src/local.js +61 -0
  41. package/src/mcp.js +61 -0
  42. package/src/setup.js +395 -0
  43. package/src/site/auth.js +287 -0
  44. package/src/site/beacon.js +462 -0
  45. package/src/site/collect.js +484 -0
  46. package/src/site/handler.js +405 -0
  47. package/src/site/index.js +88 -0
  48. package/src/site/limits.js +48 -0
  49. package/src/site/pages.js +75 -0
  50. package/src/site/qr.js +318 -0
  51. package/src/site/reports.js +1117 -0
  52. package/src/site/source.js +68 -0
  53. package/src/site/store-pg.js +225 -0
  54. package/src/site/store.js +249 -0
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Checks for standalone sites with no PHP equivalent. Facts and sentences live in
3
+ * rules/data/frontend.json, which only the JavaScript reads.
4
+ *
5
+ * - emptyPage(): the page shows almost no text before JavaScript runs.
6
+ * - hsts(): Strict-Transport-Security is missing, invalid or shorter than 180 days.
7
+ * - frontendKeys(): secret keys in public JavaScript (Supabase service_role JWTs, OpenAI keys,
8
+ * Stripe live secret keys), masked like Secrets::mask().
9
+ */
10
+ import data from '../../rules/data/frontend.json.js' ;
11
+ import secretsData from '../../rules/data/secrets.json.js' ;
12
+ import { trim, lower, str, sprintf, phpRegex } from './php.js';
13
+ import { parse, bodyText } from './html.js';
14
+ import { headerList } from './headers.js';
15
+ import { mask } from './secrets.js';
16
+
17
+ /**
18
+ * @typedef {object} Finding
19
+ * @property {string} id
20
+ * @property {string} level Always recommended: a check that passes returns null.
21
+ * @property {string} sentence
22
+ */
23
+
24
+ /**
25
+ * A page that shows almost no text until JavaScript runs.
26
+ * @param {string | import('./html.js').Document | null} html Raw HTML as fetched, or a tree from html.parse().
27
+ * @returns {(Finding & {chars: number}) | null} Null when the page has enough text.
28
+ */
29
+ export function emptyPage(html) {
30
+ const doc = typeof html === 'string' ? parse(html) : html;
31
+ const chars = doc ? [...bodyText(doc)].length : 0;
32
+ const e = data.empty_page;
33
+ if (chars >= e.min_chars) return null;
34
+ return { id: e.id, level: 'recommended', sentence: e.sentence, chars };
35
+ }
36
+
37
+ /**
38
+ * A max-age as the sentence shows it: whole days, or hours, minutes or seconds under a day.
39
+ * @param {number} seconds
40
+ * @returns {string}
41
+ */
42
+ function days(seconds) {
43
+ for (const [unit, size] of /** @type {const} */ ([['day', 86400], ['hour', 3600], ['minute', 60]])) {
44
+ const n = Math.floor(seconds / size);
45
+ if (n >= 1) return n === 1 ? `1 ${unit}` : `${n} ${unit}s`;
46
+ }
47
+ return seconds === 1 ? '1 second' : `${seconds} seconds`;
48
+ }
49
+
50
+ /**
51
+ * Strict-Transport-Security on an HTTPS response.
52
+ * @param {import('./headers.js').HeaderSource} headers Response headers.
53
+ * @returns {(Finding & {reason: string, maxAge: number | null}) | null} Null when max-age is at
54
+ * least 180 days. reason is missing, invalid or short.
55
+ */
56
+ export function hsts(headers) {
57
+ const h = data.hsts;
58
+ // Sent more than once, the first value counts. A Headers object joins them with ", ".
59
+ const first = trim(str(headerList(headers, h.header)[0] ?? '').split(',')[0]);
60
+ /**
61
+ * @param {string} reason
62
+ * @param {number | null} maxAge
63
+ */
64
+ const flag = (reason, maxAge) => ({
65
+ id: h.id,
66
+ level: 'recommended',
67
+ sentence: sprintf(/** @type {Record<string, string>} */ (h.sentences)[reason], maxAge === null ? '' : days(maxAge)),
68
+ reason,
69
+ maxAge,
70
+ });
71
+ if (first === '') return flag('missing', null);
72
+ /** @type {string | null} */
73
+ let age = null;
74
+ for (const directive of first.split(';')) {
75
+ const eq = directive.indexOf('=');
76
+ const name = lower(trim(eq < 0 ? directive : directive.slice(0, eq)));
77
+ if (name !== 'max-age') continue;
78
+ if (age !== null) return flag('invalid', null); // max-age twice
79
+ age = trim(eq < 0 ? '' : directive.slice(eq + 1)).replace(/^"(.*)"$/, '$1');
80
+ }
81
+ if (age === null || !/^\d+$/.test(age)) return flag('invalid', null);
82
+ const seconds = Number(age);
83
+ return seconds < h.min_max_age ? flag('short', seconds) : null;
84
+ }
85
+
86
+ /**
87
+ * @typedef {object} KeyFinding
88
+ * @property {number} line Line number, from 1.
89
+ * @property {string} type supabase_service_role, openai or stripe.
90
+ * @property {string} label
91
+ * @property {string} masked
92
+ */
93
+
94
+ const EXAMPLE = phpRegex(secretsData.example_filter.source, secretsData.example_filter.flags);
95
+
96
+ /** The key patterns, with Stripe taken from secrets.json. */
97
+ const KEYS = data.keys.list.map((k) => {
98
+ const from = 'from_secrets' in k ? secretsData.patterns.list.find((p) => p.type === k.from_secrets) : null;
99
+ const src = from ?? /** @type {{source: string, flags: string}} */ (k);
100
+ const re = phpRegex(src.source, src.flags);
101
+ return { type: k.type, label: k.label, jwtRole: 'jwt_role' in k ? k.jwt_role : null, re: new RegExp(re.source, re.flags + 'g') };
102
+ });
103
+
104
+ /**
105
+ * The payload of a JWT, or null when it does not decode to a JSON object.
106
+ * @param {string} token
107
+ * @returns {Record<string, unknown> | null}
108
+ */
109
+ function jwtPayload(token) {
110
+ const part = token.split('.')[1] ?? '';
111
+ try {
112
+ const b64 = part.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(part.length / 4) * 4, '=');
113
+ const bin = atob(b64);
114
+ const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));
115
+ const value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
116
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : null;
117
+ } catch {
118
+ return null;
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Secret keys in public JavaScript, in the order they appear. Each value is reported once.
124
+ * @param {string} js Script text as served.
125
+ * @returns {KeyFinding[]}
126
+ */
127
+ export function frontendKeys(js) {
128
+ const text = str(js);
129
+ /** @type {{at: number, finding: KeyFinding}[]} */
130
+ const found = [];
131
+ const seen = new Set();
132
+ /** Start offset of each line (lines end at \r\n, \r or \n, as in Secrets::scan()). */
133
+ const starts = [0];
134
+ for (const m of text.matchAll(/\r\n|\r|\n/g)) starts.push(/** @type {number} */ (m.index) + m[0].length);
135
+ /** @param {number} at */
136
+ const lineOf = (at) => {
137
+ let lo = 0;
138
+ let hi = starts.length - 1;
139
+ while (lo < hi) {
140
+ const mid = (lo + hi + 1) >> 1;
141
+ if (starts[mid] <= at) lo = mid;
142
+ else hi = mid - 1;
143
+ }
144
+ return lo + 1;
145
+ };
146
+ for (const k of KEYS) {
147
+ for (const m of text.matchAll(k.re)) {
148
+ const value = m[0];
149
+ if (EXAMPLE.test(value) || seen.has(value)) continue;
150
+ if (k.jwtRole !== null && jwtPayload(value)?.role !== k.jwtRole) continue;
151
+ seen.add(value);
152
+ const at = /** @type {number} */ (m.index);
153
+ found.push({ at, finding: { line: lineOf(at), type: k.type, label: k.label, masked: mask(value) } });
154
+ }
155
+ }
156
+ return found.sort((a, b) => a.at - b.at).map((f) => f.finding);
157
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Response headers: reading them from any source, and the basic security header rule from
3
+ * rules/data/headers.json (Report/ConfigurationArea.php in goose-tools). That rule has no golden
4
+ * cases because it runs inside WordPress; this port follows the data file.
5
+ */
6
+ import data from '../../rules/data/headers.json.js' ;
7
+ import { lower, str, empty, isArray } from './php.js';
8
+
9
+ /**
10
+ * Headers as a fetch Headers object, or a plain record of name => value or list of values in any
11
+ * case.
12
+ * @typedef {Headers | Record<string, unknown>} HeaderSource
13
+ */
14
+
15
+ /**
16
+ * Every value of a header, in order. A Headers object joins repeated headers with ", ".
17
+ * @param {HeaderSource} headers
18
+ * @param {string} name
19
+ * @returns {string[]}
20
+ */
21
+ export function headerList(headers, name) {
22
+ const want = lower(name);
23
+ if (typeof Headers !== 'undefined' && headers instanceof Headers) {
24
+ const v = headers.get(want);
25
+ return v === null ? [] : [v];
26
+ }
27
+ /** @type {string[]} */
28
+ const out = [];
29
+ if (!isArray(headers)) return out;
30
+ for (const [k, v] of Object.entries(headers)) {
31
+ if (lower(k) !== want) continue;
32
+ for (const x of Array.isArray(v) ? v : [v]) out.push(str(x));
33
+ }
34
+ return out;
35
+ }
36
+
37
+ /**
38
+ * A header's value, repeated headers joined with ", " (as Wp/Probe.php reads them), or ''.
39
+ * @param {HeaderSource} headers
40
+ * @param {string} name
41
+ * @returns {string}
42
+ */
43
+ export function header(headers, name) {
44
+ return headerList(headers, name).join(data.headers_read.join);
45
+ }
46
+
47
+ /**
48
+ * @typedef {object} HeaderCheck
49
+ * @property {string} id configuration.headers
50
+ * @property {string} level ok or attention.
51
+ * @property {string[]} missing Header names, in the data file's order.
52
+ * @property {string} evidence "Missing: ..." or ''.
53
+ */
54
+
55
+ /**
56
+ * The basic security headers check on the home page.
57
+ * @param {HeaderSource} headers
58
+ * @returns {HeaderCheck}
59
+ */
60
+ export function securityHeaders(headers) {
61
+ /** @type {string[]} */
62
+ const missing = [];
63
+ for (const h of data.list) {
64
+ if (!empty(header(headers, h.header))) continue;
65
+ const unless = 'unless' in h ? h.unless : null;
66
+ if (unless && lower(header(headers, unless.header)).includes(lower(unless.contains_ci))) continue;
67
+ missing.push(h.name);
68
+ }
69
+ const r = data.result;
70
+ return {
71
+ id: r.id,
72
+ level: missing.length ? 'attention' : 'ok',
73
+ missing,
74
+ evidence: missing.length ? r.missing_prefix + missing.join(r.missing_join) : '',
75
+ };
76
+ }
@@ -0,0 +1,425 @@
1
+ /**
2
+ * Hidden text and text addressed to AI in content (port of Crawlers/HiddenText.php). Agents treat
3
+ * instructions found on pages as untrusted, so they may read such text as prompt injection, and
4
+ * Google's spam policies cover hidden text. Findings are recommendations; content is never changed.
5
+ *
6
+ * Hidden: the hidden attribute, display:none, visibility:hidden, opacity:0, a font size of 0 or
7
+ * 1px, text moved far off screen (a negative offset or text-indent of 500px or more), and text the
8
+ * same color as its background (inline styles or block editor color classes). White text with no
9
+ * background anywhere up the tree is "white text without a background", since most pages are
10
+ * white. Hidden text under 20 bytes is left alone unless it addresses AI, and accessibility text
11
+ * (screen-reader-text, sr-only, visually-hidden) is left alone unless it addresses AI.
12
+ *
13
+ * Addressed to AI (hidden or not, and in HTML comments other than block markers): phrases such as
14
+ * "ignore previous instructions", "if you are an AI", "note to AI agents", a sentence starting
15
+ * with "AI agents:" or "LLM:" (not a bare "AI:"), and "when summarizing this page". Visible text is
16
+ * read block by block (paragraph, list item, heading, cell), so a phrase split by bold text is found.
17
+ *
18
+ * The page is read with the libxml rules in html.js. The PHP regexes have no u flag, so \s and \b
19
+ * are ASCII here too; lengths are UTF-8 bytes; the excerpt is cut at 120 characters.
20
+ */
21
+ import { trim, rtrim, lower, byteLength, sprintf, str, WS, NWS, UWS } from './php.js';
22
+ import { parse, bodyTextNodes, attr, hasAttr } from './html.js';
23
+
24
+ /** Hidden text shorter than this many bytes is not reported unless it addresses AI. */
25
+ export const MIN_HIDDEN = 20;
26
+
27
+ /** Characters of text kept in a finding. */
28
+ export const EXCERPT = 120;
29
+
30
+ const AI =
31
+ '(?:ai|a\\.i\\.|llms?|large language models?|language models?|ai (?:agents?|assistants?|models?|crawlers?|bots?|systems?|tools?)|chatbots?|chatgpt|assistants?)';
32
+
33
+ /** Phrases that address AI or try to instruct it (HiddenText::phrases(), \s written as ASCII). */
34
+ const PHRASES = [
35
+ `\\b(?:ignore|disregard|forget|override)${WS}+(?:all${WS}+|any${WS}+)?(?:of${WS}+)?(?:the${WS}+|your${WS}+)?(?:previous|prior|above|earlier|preceding|former|system)${WS}+(?:instructions?|prompts?|directions?|messages?|rules)\\b`,
36
+ `(?:^|[.!?\\n]${WS}*)(?:llms?|large language models?|language models?|ai (?:agents?|assistants?|models?|crawlers?|bots?|systems?))${WS}*:${WS}+${NWS}`,
37
+ `\\b(?:note|message|instructions?|attention|notice)${WS}+(?:to|for)${WS}+(?:all${WS}+|any${WS}+)?${AI}\\b`,
38
+ `\\bif${WS}+you${WS}+are${WS}+(?:an?${WS}+)?${AI}\\b`,
39
+ `\\bwhen${WS}+(?:you${WS}+)?(?:summari[sz]e|summari[sz]ing|answer|answering|describe|describing|recommend|recommending)${WS}+(?:this|the)${WS}+(?:page|site|article|post|product|company|business|content|website)\\b`,
40
+ `\\b(?:system prompt|new instructions${WS}*:)`,
41
+ `\\bdo${WS}+not${WS}+(?:tell|reveal${WS}+to|inform|show)${WS}+the${WS}+user\\b`,
42
+ ].map((s) => new RegExp(s, 'i'));
43
+
44
+ /** Block elements: visible text is grouped by the nearest one. */
45
+ const BLOCKS = new Set(
46
+ 'p li h1 h2 h3 h4 h5 h6 td th dt dd blockquote figcaption pre div section article aside header footer details summary'.split(' '),
47
+ );
48
+
49
+ /** Elements whose text is never shown as content. */
50
+ const SKIPPED = new Set(['script', 'style', 'template', 'noscript', 'svg']);
51
+
52
+ const SQUASH = new RegExp(`${UWS}+`, 'g');
53
+ const CLASS_SPACES = new RegExp(`${WS}+`, 'g');
54
+ const A11Y = / (screen-reader-text|sr-only|visually-hidden|screen-reader-only) /;
55
+ const OFFSET = /^-(\d+(?:\.\d+)?)(px|em|rem)?$/;
56
+ const CLIP = new RegExp(`^rect\\(${WS}*0(px)?[\\t\\n\\v\\f\\r ,]+0(px)?[\\t\\n\\v\\f\\r ,]+0(px)?[\\t\\n\\v\\f\\r ,]+0(px)?${WS}*\\)$`);
57
+ const RGB = new RegExp(`^rgba?\\(${WS}*(\\d{1,3})[\\t\\n\\v\\f\\r ,]+(\\d{1,3})[\\t\\n\\v\\f\\r ,]+(\\d{1,3})${WS}*(?:[,/]${WS}*(1|1\\.0+|100%))?${WS}*\\)$`);
58
+
59
+ /**
60
+ * @typedef {object} Finding
61
+ * @property {string} kind hidden (hidden text), hidden_ai (hidden text addressed to AI), ai
62
+ * (visible text addressed to AI), comment (an HTML comment addressed to AI).
63
+ * @property {string} how How it is hidden, "visible text" or "HTML comment".
64
+ * @property {string} text
65
+ * @property {string} phrase The AI phrase, or ''.
66
+ *
67
+ * @typedef {import('./html.js').Element} Element
68
+ * @typedef {{style: Record<string, string>, classes: string}} Look
69
+ */
70
+
71
+ /**
72
+ * Whether text addresses AI.
73
+ * @param {string} text
74
+ * @returns {string} The phrase found, or ''.
75
+ */
76
+ export function addressed(text) {
77
+ const t = str(text);
78
+ for (const re of PHRASES) {
79
+ const m = re.exec(t);
80
+ if (m) return trim(m[0], ' \t\n\r.!?');
81
+ }
82
+ return '';
83
+ }
84
+
85
+ /**
86
+ * Scan one item's content.
87
+ * @param {string} html Content (block markup or HTML).
88
+ * @returns {Finding[]}
89
+ */
90
+ export function scan(html) {
91
+ const h = str(html);
92
+ /** @type {Finding[]} */
93
+ const out = [];
94
+ if (trim(h) === '') return out;
95
+ // HTML comments that are not block markers.
96
+ for (const m of h.matchAll(/<!--([\s\S]*?)-->/g)) {
97
+ const c = trim(m[1]);
98
+ if (/^\/?wp:/.test(c)) continue;
99
+ const phrase = addressed(c);
100
+ if (phrase !== '') out.push(finding('comment', 'HTML comment', c, phrase));
101
+ }
102
+ const doc = parse('<html><body>' + h + '</body></html>');
103
+ if (!doc) return out;
104
+ /** Hiding element => {how, a11y, parts}, in the order first found. */
105
+ /** @type {Map<Element, {how: string, a11y: boolean, parts: string[]}>} */
106
+ const groups = new Map();
107
+ /** Block element (or null for none) => text. */
108
+ /** @type {Map<Element | null, string>} */
109
+ const visible = new Map();
110
+ const memo = newMemo();
111
+ for (const t of bodyTextNodes(doc)) {
112
+ if (inSkipped(t, memo)) continue;
113
+ const why = hiddenBy(t, memo);
114
+ if (why === null) {
115
+ const b = block(t, memo);
116
+ visible.set(b, visible.has(b) ? visible.get(b) + ' ' + t.data : t.data);
117
+ continue;
118
+ }
119
+ let g = groups.get(why.element);
120
+ if (!g) {
121
+ g = { how: why.how, a11y: why.a11y, parts: [] };
122
+ groups.set(why.element, g);
123
+ }
124
+ g.parts.push(t.data);
125
+ }
126
+ for (const g of groups.values()) {
127
+ const text = squash(g.parts.join(' '));
128
+ const phrase = addressed(text);
129
+ if (phrase !== '') out.push(finding('hidden_ai', g.how, text, phrase));
130
+ else if (!g.a11y && byteLength(text) >= MIN_HIDDEN) out.push(finding('hidden', g.how, text, ''));
131
+ }
132
+ // Visible text, block by block, so a phrase is reported once with its own sentence around it.
133
+ for (const v of visible.values()) {
134
+ const text = squash(v);
135
+ const phrase = addressed(text);
136
+ if (phrase !== '') out.push(finding('ai', 'visible text', text, phrase));
137
+ }
138
+ return out;
139
+ }
140
+
141
+ /**
142
+ * What the walks up the tree learn about each element, kept for the rest of one scan. Text nodes
143
+ * share their ancestors, so each element is read once instead of once per text node under it.
144
+ * @typedef {{how: string, element: Element, a11y: boolean} | null} Why
145
+ * @typedef {{kind: 'hide', why: Why} | {kind: 'background', value: string} | {kind: 'end'}} Above
146
+ * @typedef {{looks: Map<Element, Look>, block: Map<Element, Element | null>, skipped: Map<Element, boolean>, why: Map<Element, Why>, above: Map<Element, Above>}} Memo
147
+ * @returns {Memo}
148
+ */
149
+ function newMemo() {
150
+ return { looks: new Map(), block: new Map(), skipped: new Map(), why: new Map(), above: new Map() };
151
+ }
152
+
153
+ /** @param {any} n */
154
+ const isElement = (n) => Boolean(n) && n.type === 1;
155
+
156
+ /**
157
+ * The nearest block element around a node, or null.
158
+ * @param {import('./html.js').Node} node
159
+ * @param {Memo} memo
160
+ * @returns {Element | null}
161
+ */
162
+ function block(node, memo) {
163
+ return blockFrom(node.parent, memo);
164
+ }
165
+
166
+ /**
167
+ * @param {any} n
168
+ * @param {Memo} memo
169
+ * @returns {Element | null}
170
+ */
171
+ function blockFrom(n, memo) {
172
+ if (!isElement(n) || n.name === 'body') return null;
173
+ if (memo.block.has(n)) return /** @type {Element | null} */ (memo.block.get(n));
174
+ const b = BLOCKS.has(n.name) ? n : blockFrom(n.parent, memo);
175
+ memo.block.set(n, b);
176
+ return b;
177
+ }
178
+
179
+ /**
180
+ * Whether a text node sits in an element whose text is never shown as content.
181
+ * @param {import('./html.js').Node} node
182
+ * @param {Memo} memo
183
+ * @returns {boolean}
184
+ */
185
+ function inSkipped(node, memo) {
186
+ return skippedFrom(node.parent, memo);
187
+ }
188
+
189
+ /**
190
+ * @param {any} n
191
+ * @param {Memo} memo
192
+ * @returns {boolean}
193
+ */
194
+ function skippedFrom(n, memo) {
195
+ if (!isElement(n)) return false;
196
+ const known = memo.skipped.get(n);
197
+ if (known !== undefined) return known;
198
+ const s = SKIPPED.has(n.name) || skippedFrom(n.parent, memo);
199
+ memo.skipped.set(n, s);
200
+ return s;
201
+ }
202
+
203
+ /**
204
+ * An element's declarations and padded class list, parsed once per scan.
205
+ * @param {Element} el
206
+ * @param {Memo} memo
207
+ * @returns {Look}
208
+ */
209
+ function look(el, memo) {
210
+ let l = memo.looks.get(el);
211
+ if (!l) {
212
+ l = { style: style(attr(el, 'style')), classes: ' ' + lower(attr(el, 'class').replace(CLASS_SPACES, ' ')) + ' ' };
213
+ memo.looks.set(el, l);
214
+ }
215
+ return l;
216
+ }
217
+
218
+ /**
219
+ * How an element hides its text, including text for screen readers only ('' when it does not).
220
+ * @param {Element} n
221
+ * @param {Look} l
222
+ * @returns {Why}
223
+ */
224
+ function hiddenHere(n, l) {
225
+ const how = hides(n, l.style);
226
+ if (how !== '') return { how, element: n, a11y: false };
227
+ if (A11Y.test(l.classes)) return { how: 'text for screen readers only', element: n, a11y: true };
228
+ return null;
229
+ }
230
+
231
+ /**
232
+ * Why a text node is hidden, or null. Read from the nearest element up to body: the first element
233
+ * that hides it decides; the nearest background ends the walk, and text the same color as that
234
+ * background is hidden; white text with no background up the tree is reported as such.
235
+ * @param {import('./html.js').Node} node Text node.
236
+ * @param {Memo} memo
237
+ * @returns {Why}
238
+ */
239
+ function hiddenBy(node, memo) {
240
+ return whyFrom(node.parent, memo);
241
+ }
242
+
243
+ /**
244
+ * hiddenBy for text whose nearest element is n, with no text color set below n.
245
+ * @param {any} n
246
+ * @param {Memo} memo
247
+ * @returns {Why}
248
+ */
249
+ function whyFrom(n, memo) {
250
+ if (!isElement(n) || n.name === 'body') return null;
251
+ if (memo.why.has(n)) return /** @type {Why} */ (memo.why.get(n));
252
+ const l = look(n, memo);
253
+ let why = hiddenHere(n, l);
254
+ if (why === null) {
255
+ const c = textColor(l.style, l.classes);
256
+ const bg = backgroundOf(l.style, l.classes);
257
+ if (c !== '') {
258
+ if (bg !== null) why = bg !== '' && bg === c ? { how: 'same color as its background', element: n, a11y: false } : null;
259
+ else why = withColor(n.parent, c, n, memo);
260
+ } else if (bg === null) why = whyFrom(n.parent, memo);
261
+ }
262
+ memo.why.set(n, why);
263
+ return why;
264
+ }
265
+
266
+ /**
267
+ * The rest of the walk once a text color is known.
268
+ * @param {any} n The next element up.
269
+ * @param {string} c The text color.
270
+ * @param {Element} colored The element that set it.
271
+ * @param {Memo} memo
272
+ * @returns {Why}
273
+ */
274
+ function withColor(n, c, colored, memo) {
275
+ const a = aboveFrom(n, memo);
276
+ if (a.kind === 'hide') return a.why;
277
+ if (a.kind === 'background') return a.value !== '' && a.value === c ? { how: 'same color as its background', element: colored, a11y: false } : null;
278
+ return c === '#ffffff' || c === 'white' ? { how: 'white text without a background', element: colored, a11y: false } : null;
279
+ }
280
+
281
+ /**
282
+ * The first thing up the tree from n that ends a walk, text colors aside: an element that hides,
283
+ * the nearest background, or body.
284
+ * @param {any} n
285
+ * @param {Memo} memo
286
+ * @returns {Above}
287
+ */
288
+ function aboveFrom(n, memo) {
289
+ if (!isElement(n) || n.name === 'body') return { kind: 'end' };
290
+ const known = memo.above.get(n);
291
+ if (known) return known;
292
+ const l = look(n, memo);
293
+ const why = hiddenHere(n, l);
294
+ /** @type {Above} */
295
+ let a;
296
+ if (why !== null) a = { kind: 'hide', why };
297
+ else {
298
+ const bg = backgroundOf(l.style, l.classes);
299
+ a = bg !== null ? { kind: 'background', value: bg } : aboveFrom(n.parent, memo);
300
+ }
301
+ memo.above.set(n, a);
302
+ return a;
303
+ }
304
+
305
+ /**
306
+ * How an element hides its content ('' when it does not).
307
+ * @param {Element} el
308
+ * @param {Record<string, string>} st Declarations.
309
+ * @returns {string}
310
+ */
311
+ function hides(el, st) {
312
+ if (hasAttr(el, 'hidden')) return 'hidden attribute';
313
+ if (Object.hasOwn(st, 'display') && st.display === 'none') return 'display: none';
314
+ if (Object.hasOwn(st, 'visibility') && (st.visibility === 'hidden' || st.visibility === 'collapse')) return 'visibility: hidden';
315
+ // An empty or invalid value is ignored by browsers, so it hides nothing.
316
+ if (Object.hasOwn(st, 'opacity') && /^(0+(\.0+)?|\.0+)$/.test(st.opacity)) return 'opacity: 0';
317
+ if (Object.hasOwn(st, 'font-size') && /^(0+(\.0+)?([a-z%]+)?|0*1px)$/.test(st['font-size'])) return 'font size of zero';
318
+ for (const prop of ['left', 'top', 'right', 'margin-left', 'margin-top', 'text-indent']) {
319
+ if (!Object.hasOwn(st, prop)) continue;
320
+ const m = OFFSET.exec(st[prop]);
321
+ if (m) {
322
+ const px = parseFloat(m[1]) * (m[2] === 'em' || m[2] === 'rem' ? 16 : 1);
323
+ if (px >= 500) return 'moved off screen';
324
+ }
325
+ }
326
+ if (Object.hasOwn(st, 'clip') && CLIP.test(st.clip)) return 'clipped to nothing';
327
+ return '';
328
+ }
329
+
330
+ /**
331
+ * Inline style declarations, lower-case, without !important. A later declaration wins.
332
+ * @param {string} css Style attribute.
333
+ * @returns {Record<string, string>}
334
+ */
335
+ function style(css) {
336
+ /** @type {Record<string, string>} */
337
+ const out = Object.create(null);
338
+ for (const decl of lower(css).split(';')) {
339
+ const colon = decl.indexOf(':');
340
+ if (colon < 0) continue;
341
+ out[trim(decl.slice(0, colon))] = trim(decl.slice(colon + 1).replaceAll('!important', ''));
342
+ }
343
+ return out;
344
+ }
345
+
346
+ /**
347
+ * Text color an element sets ('' when none).
348
+ * @param {Record<string, string>} st Declarations.
349
+ * @param {string} classes Class list, padded with spaces.
350
+ * @returns {string} Normalized color (#rrggbb) or a block editor color name.
351
+ */
352
+ function textColor(st, classes) {
353
+ if (Object.hasOwn(st, 'color')) return color(st.color);
354
+ // Any class order: has-text-color, has-link-color and background and border classes are skipped.
355
+ for (const m of classes.matchAll(/(?<= )has-([a-z0-9-]+)-color(?= )/g)) {
356
+ const slug = m[1];
357
+ if (slug !== 'text' && slug !== 'link' && slug !== 'border' && !/-(background|border)$/.test(slug)) return color(slug);
358
+ }
359
+ return '';
360
+ }
361
+
362
+ /**
363
+ * Background an element sets: a color, '' for a background of unknown color, or null for none.
364
+ * @param {Record<string, string>} st Declarations.
365
+ * @param {string} classes Class list, padded with spaces.
366
+ * @returns {string | null}
367
+ */
368
+ function backgroundOf(st, classes) {
369
+ for (const prop of ['background-color', 'background']) {
370
+ if (!Object.hasOwn(st, prop)) continue;
371
+ const v = st[prop];
372
+ if (v !== '' && !['none', 'transparent', 'inherit', 'initial', 'unset'].includes(v)) return color(v);
373
+ }
374
+ const m = / has-([a-z0-9-]+)-background-color /.exec(classes);
375
+ if (m) return color(m[1]);
376
+ if (/ (has-background|wp-block-cover|wp-block-cover__background|has-[a-z0-9-]+-gradient-background) /.test(classes)) return '';
377
+ return null;
378
+ }
379
+
380
+ /**
381
+ * A color in a comparable form: #rrggbb for hex, rgb() and the names white and black; other
382
+ * values as written.
383
+ * @param {string} value CSS value or block editor color slug.
384
+ * @returns {string}
385
+ */
386
+ export function color(value) {
387
+ const v = lower(trim(str(value)));
388
+ let m = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(v);
389
+ if (m) return '#' + m[1] + m[1] + m[2] + m[2] + m[3] + m[3];
390
+ if (/^#[0-9a-f]{6}$/.test(v)) return v;
391
+ m = RGB.exec(v);
392
+ if (m) {
393
+ const hex = (/** @type {string} */ d) => Math.min(255, Number(d)).toString(16).padStart(2, '0');
394
+ return sprintf('#%s%s%s', hex(m[1]), hex(m[2]), hex(m[3]));
395
+ }
396
+ if (v === 'white') return '#ffffff';
397
+ if (v === 'black') return '#000000';
398
+ return v;
399
+ }
400
+
401
+ /**
402
+ * Collapse whitespace (PHP /\s+/u, Unicode spaces included).
403
+ * @param {string} s
404
+ * @returns {string}
405
+ */
406
+ function squash(s) {
407
+ return trim(s.replace(SQUASH, ' '));
408
+ }
409
+
410
+ /**
411
+ * A finding, with the text cut to EXCERPT characters when it is longer than EXCERPT bytes.
412
+ * @param {string} kind
413
+ * @param {string} how
414
+ * @param {string} text
415
+ * @param {string} phrase
416
+ * @returns {Finding}
417
+ */
418
+ function finding(kind, how, text, phrase) {
419
+ let t = squash(text);
420
+ if (byteLength(t) > EXCERPT) {
421
+ const head = [...t].slice(0, EXCERPT).join('');
422
+ if (head !== t) t = rtrim(head) + '...';
423
+ }
424
+ return { kind, how, text: t, phrase };
425
+ }