@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
package/README.md CHANGED
@@ -1,3 +1,99 @@
1
- # Temporary Holding Version
1
+ # goose-tools
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Check your site for search, AI answers and security. From the terminal, or from your AI agent.
4
+
5
+ The check finds what keeps search engines and AI answers out: crawlers refused in robots.txt (ChatGPT, Claude,
6
+ Perplexity, Bing, Google), a noindex, a page that is empty until JavaScript runs, a missing sitemap. It also finds
7
+ missing security headers and secret keys in the page's JavaScript. Each finding comes with the fix for your stack.
8
+
9
+ ## Check a page
10
+
11
+ ```
12
+ npx @goosetools/goose-tools check yourproduct.dev
13
+ npx @goosetools/goose-tools check yourproduct.dev --json
14
+ ```
15
+
16
+ The exit code is 1 when anything is urgent, so you can run it after a deploy.
17
+
18
+ ## Let your AI agent check it
19
+
20
+ Claude Code:
21
+
22
+ ```
23
+ claude mcp add goose-tools -- npx -y @goosetools/goose-tools mcp
24
+ ```
25
+
26
+ Cursor, in `.cursor/mcp.json`:
27
+
28
+ ```json
29
+ {
30
+ "mcpServers": {
31
+ "goose-tools": {
32
+ "command": "npx",
33
+ "args": ["-y", "@goosetools/goose-tools", "mcp"]
34
+ }
35
+ }
36
+ }
37
+ ```
38
+
39
+ Then ask: "Check yourproduct.dev and fix anything urgent." The agent gets each finding with its fix, edits your code,
40
+ and checks again after you deploy.
41
+
42
+ The server has one tool, `check_site`. It is read-only.
43
+
44
+ ## Add the dashboard to your site
45
+
46
+ A private dashboard at `/_gt/` shows your visits, where they come from and how fast your pages load for real
47
+ visitors. No cookies for visitors and no visitor IDs. The data stays in your site.
48
+
49
+ ```
50
+ npm install @goosetools/goose-tools
51
+ npx goose-tools setup
52
+ ```
53
+
54
+ Setup shows each change before it writes it. On Next.js (App Router), it adds one route file and the script tag. On
55
+ Express and other Node servers, it writes the steps to GOOSE-TOOLS-SETUP.md for your coding agent.
56
+
57
+ Then deploy your site. Open `/_gt/` on the live site and enter the setup code. Pick a password and add your
58
+ authenticator app.
59
+
60
+ - The data goes in a SQLite file on your server, or in your own Postgres database on hosts with no persistent
61
+ disk, such as Vercel. See where it runs below.
62
+ - If your site has Next.js middleware (called proxy in Next.js 16), leave `/_gt/` out of its matcher.
63
+
64
+ Lost your password, or the data file? Run `npx goose-tools setup --new-code` and deploy. Sign in at `/_gt/` with the
65
+ new code. It replaces your password and two-factor sign-in.
66
+
67
+ ### Where it runs
68
+
69
+ **On a server with a disk.** The data is a SQLite file, `.goose-tools/data.sqlite`, on a persistent local disk.
70
+ Network file shares don't work. This covers your own server or VPS (AWS EC2 and Lightsail, Azure
71
+ Virtual Machines, Google Compute Engine, DigitalOcean Droplets, Hetzner and others), Docker with a volume, Render
72
+ with a persistent disk, Railway with a volume, and Fly.io with a volume on one machine. If your site runs on several
73
+ servers, each keeps its own file, so run one instance for full totals.
74
+
75
+ **On Vercel, with your own Postgres database.** Add a database such as Supabase or Neon from your project's Storage
76
+ tab, then run setup. Setup finds your Postgres client and writes the route.
77
+ - The data stays in your database, in its own `goose_tools` tables with row level security on, so Supabase's public
78
+ key can't read them.
79
+ - Give each site its own database, since two sites on one database share one sign-in. To keep Goose Tools apart from
80
+ your app's data, set `GOOSE_TOOLS_DATABASE_URL`, which the route uses first.
81
+ - Counting stops at 10,000 views a day and starts again at midnight UTC, so a free hosting plan isn't used up. You
82
+ can change the limit (`dailyLimit`) in the route file.
83
+
84
+ **Planned**
85
+ - Setup for other hosts with no persistent disk: AWS Lambda, Amplify and App Runner, Google Cloud Run and App Engine,
86
+ Azure App Service, Heroku and DigitalOcean App Platform.
87
+ - The Cloudflare plugin, for Cloudflare Workers.
88
+
89
+ ## What it reads
90
+
91
+ Only public files, the same ones any browser can get: the page, robots.txt, sitemap.xml, llms.txt and the page's
92
+ own scripts (only to look for secret keys). The check runs on your machine. Nothing is sent to goosetools.app.
93
+ Requests name the check in their User-Agent (`GooseToolsCheck/1.0`). It never poses as a crawler.
94
+
95
+ It reads public addresses only. localhost and private networks are refused.
96
+
97
+ No install scripts. No dependencies. Node.js 22.13 or later.
98
+
99
+ The same check runs free at [goosetools.app/check](https://goosetools.app/check).
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env node
2
+ // goose-tools command line. Commands:
3
+ // goose-tools check <url> [--json] Run the free check on one page from this machine.
4
+ // goose-tools mcp Serve the check to an AI agent over MCP (stdio).
5
+ // goose-tools setup [--yes] [--new-code] Add the /_gt/ dashboard to this site; --new-code replaces the setup code.
6
+ // goose-tools --version | --help
7
+ import fs from 'node:fs';
8
+
9
+ const { version } = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
10
+
11
+ const HELP = `goose-tools ${version}
12
+
13
+ Usage:
14
+ npx @goosetools/goose-tools check <url> Check one page for search, AI answers and security.
15
+ npx @goosetools/goose-tools check <url> --json The same result as JSON, for scripts and agents.
16
+ npx @goosetools/goose-tools mcp Let an AI agent run the check (MCP server over stdio).
17
+ npx goose-tools setup Add the private dashboard at /_gt/ to this site.
18
+ npx goose-tools setup --new-code Get a new setup code, if you lost your password or your data file.
19
+
20
+ Add it to Claude Code:
21
+ claude mcp add goose-tools -- npx -y @goosetools/goose-tools mcp
22
+
23
+ The check reads only public files, the same ones any browser can get. It runs on this
24
+ machine and changes nothing. Nothing is sent to goosetools.app.
25
+ `;
26
+
27
+ const [cmd, ...rest] = process.argv.slice(2);
28
+
29
+ if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') {
30
+ process.stdout.write(HELP);
31
+ } else if (cmd === '--version' || cmd === '-v') {
32
+ process.stdout.write(version + '\n');
33
+ } else if (cmd === 'setup') {
34
+ const { runSetup } = await import('../src/setup.js');
35
+ process.exitCode = await runSetup({ yes: rest.includes('--yes') || rest.includes('-y'), newCode: rest.includes('--new-code') });
36
+ } else if (cmd === 'mcp') {
37
+ const { serveStdio } = await import('../src/mcp.js');
38
+ serveStdio(version);
39
+ } else if (cmd === 'check') {
40
+ const json = rest.includes('--json');
41
+ const url = rest.find((a) => !a.startsWith('--'));
42
+ if (!url) {
43
+ process.stderr.write('Add the page to check, for example: npx @goosetools/goose-tools check yourproduct.dev\n');
44
+ process.exit(2);
45
+ }
46
+ const [{ checkPage }, { forAgent, asText }, { addressProblem }] = await Promise.all([import('../src/local.js'), import('../lib/check/src/agent.js'), import('../lib/check/src/copy.js')]);
47
+ try {
48
+ const result = forAgent(await checkPage(url), version);
49
+ process.stdout.write((json ? JSON.stringify(result, null, 2) : asText(result)) + '\n');
50
+ // Exit code for scripts and CI: 1 when anything is urgent, otherwise 0.
51
+ process.exitCode = result.counts.urgent > 0 ? 1 : 0;
52
+ } catch (e) {
53
+ const text = e && e.name === 'CheckError' ? addressProblem(e.code) : `The check could not run: ${(e && e.message) || e}`;
54
+ if (json) process.stdout.write(JSON.stringify({ error: { code: (e && e.code) || 'error', message: text } }, null, 2) + '\n');
55
+ else process.stderr.write(text + '\n');
56
+ process.exitCode = 2;
57
+ }
58
+ } else {
59
+ process.stderr.write(`Unknown command: ${cmd}\n\n${HELP}`);
60
+ process.exitCode = 2;
61
+ }
@@ -0,0 +1,90 @@
1
+ // The check's result for an agent or a script: plain JSON with every finding, why it matters and its fix for the
2
+ // detected stack as Markdown, plus what passed. Built from the same view the check page shows (check/src/view.js),
3
+ // so the words and fixes are the approved ones.
4
+ import { scanRows } from './scan.js';
5
+
6
+ const LEVEL = { risk: 'urgent', attention: 'recommended', unknown: 'couldnt_check' };
7
+ const ORDER = { urgent: 0, recommended: 1, couldnt_check: 2 };
8
+
9
+ const unescape = (s) => s.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, '&');
10
+
11
+ /**
12
+ * A fix's HTML (check/src/fixes.js markup) as Markdown: numbered steps, code blocks with their file name, and
13
+ * "Option 1: Vercel" before each way to fix when there are several.
14
+ * @param {string} html
15
+ * @returns {string}
16
+ */
17
+ export function fixMarkdown(html) {
18
+ if (!html) return '';
19
+ const blocks = [];
20
+ let s = html.replace(/<div class="gt-code"><div class="gt-code__bar"><span>([\s\S]*?)<\/span><button[^>]*>Copy<\/button><\/div><pre><code>([\s\S]*?)<\/code><\/pre><\/div>/g, (_, file, text) => {
21
+ blocks.push(`\n\n${unescape(file)}:\n\`\`\`\n${unescape(text)}\n\`\`\`\n\n`);
22
+ return `\u0000${blocks.length - 1}\u0000`;
23
+ });
24
+ const labels = [];
25
+ s = s.replace(/<div class="gs-toggle[^"]*" role="tablist"[^>]*>([\s\S]*?)<\/div>/g, (_, buttons) => {
26
+ for (const m of buttons.matchAll(/<button[^>]*>([\s\S]*?)<\/button>/g)) labels.push(unescape(m[1]));
27
+ return '';
28
+ });
29
+ let option = 0;
30
+ s = s.replace(/<div role="tabpanel"[^>]*>([\s\S]*?)<\/div>/g, (_, body) => `\n\nOption ${option + 1}: ${labels[option++] ?? ''}\n\n${body}`);
31
+ s = s.replace(/<ol class="gt-steps">([\s\S]*?)<\/ol>/g, (_, items) => {
32
+ let n = 0;
33
+ return '\n\n' + items.replace(/<li>([\s\S]*?)<\/li>/g, (__, li) => `${++n}. ${li.replace(/<\/p>\s*<p[^>]*>/g, ' ').trim()}\n`) + '\n';
34
+ });
35
+ s = s
36
+ .replace(/<span class="gt-mono">([\s\S]*?)<\/span>/g, '`$1`')
37
+ .replace(/<\/p>/g, '\n\n')
38
+ .replace(/<[^>]+>/g, '');
39
+ s = unescape(s).replace(/\u0000(\d+)\u0000/g, (_, i) => blocks[Number(i)]);
40
+ return s.replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim();
41
+ }
42
+
43
+ /**
44
+ * @param {ReturnType<typeof import('./view.js').view>} v
45
+ * @param {string} version The package version.
46
+ */
47
+ export function forAgent(v, version) {
48
+ const { counts } = scanRows(v);
49
+ const area = (name, a) =>
50
+ v[a].fixes.map((f) => ({
51
+ id: f.id,
52
+ area: name,
53
+ level: LEVEL[f.state],
54
+ title: f.title,
55
+ why: f.verdict ?? null,
56
+ found: f.found ?? null,
57
+ fix: f.code ? fixMarkdown(f.code) : null,
58
+ }));
59
+ const findings = v.unreadable ? [] : [...area('seo', 'seo'), ...area('security', 'security')].sort((a, b) => ORDER[a.level] - ORDER[b.level]);
60
+ const passed = v.unreadable
61
+ ? []
62
+ : ['seo', 'security'].flatMap((a) => v[a].groups.flatMap((g) => g.items.map(([check, detail]) => ({ area: a, group: g.name, check, detail }))));
63
+ return {
64
+ checker: { name: 'goose-tools', version },
65
+ url: v.page.url,
66
+ host: v.page.host,
67
+ checkedAt: new Date(v.page.checkedAt * 1000).toISOString(),
68
+ stack: v.page.stack,
69
+ unreadable: v.unreadable,
70
+ counts: { urgent: counts.urgent, recommended: counts.recommended, couldntCheck: counts.unchecked, passed: v.unreadable ? 0 : counts.passed },
71
+ headlines: v.unreadable ? null : { seo: v.seo.headline.text, security: v.security.headline.text },
72
+ findings,
73
+ passed,
74
+ info: v.unreadable ? [] : v.seo.info.map((i) => ({ title: i.title, detail: i.line })),
75
+ next: findings.length ? 'Apply each fix in the code, deploy, then run the check again to confirm.' : 'Nothing to fix on this page.',
76
+ };
77
+ }
78
+
79
+ /**
80
+ * The same result as readable Markdown, for a person in a terminal or an agent that reads text.
81
+ * @param {ReturnType<typeof forAgent>} r
82
+ */
83
+ export function asText(r) {
84
+ if (r.unreadable) return `# ${r.url}\n\nCouldn't check this page. ${r.unreadable}\n\nOpen the address in a browser. Make sure the page loads. If the site uses bot protection, it may refuse this check. Allow it, or check another page. Then check again.`;
85
+ const c = r.counts;
86
+ const head = [`# ${r.url}`, `Checked ${r.checkedAt}${r.stack.length ? ` · ${r.stack.join(', ')}` : ''}`, `${c.urgent} urgent · ${c.recommended} recommended · ${c.couldntCheck} couldn't check · ${c.passed} passed`, `SEO/AEO: ${r.headlines.seo}`, `Security: ${r.headlines.security}`];
87
+ const label = { urgent: 'Urgent', recommended: 'Recommended', couldnt_check: "Couldn't check" };
88
+ const items = r.findings.map((f, i) => [`## ${i + 1}. ${f.title} (${label[f.level]})`, f.why, f.found, f.fix].filter(Boolean).join('\n\n'));
89
+ return [...head, ...items, r.next].join('\n\n');
90
+ }
@@ -0,0 +1,311 @@
1
+ /**
2
+ * The free check: what the Worker fetched, turned into findings. Runs in the visitor's browser.
3
+ *
4
+ * Structured results only. Sentences live in the copy file and are approved by the owner, so this
5
+ * module returns ids, levels and the values a sentence needs.
6
+ *
7
+ * Levels (spec/standalone.md section 3), the WordPress plugin's own:
8
+ * - urgent: a key leaked in public JavaScript; noindex on the page; search or answer crawlers
9
+ * refused by robots.txt.
10
+ * - recommended: a page empty without JavaScript; no sitemap; missing security headers;
11
+ * Strict-Transport-Security missing, invalid or too short; robots.txt, Content-Signal and llms.txt
12
+ * disagreeing; text hidden from visitors or addressed to AI.
13
+ * - unchecked: Couldn't check, with the reason.
14
+ * - info (no level): training crawlers refused (the owner's choice); llms.txt.
15
+ *
16
+ * The free check claims only what it tested: it reads robots.txt and the page, so a crawler is
17
+ * "refused by robots.txt", never "can't read". Firewalls are tested only in the full report.
18
+ */
19
+ import * as robotsTxt from '../../engine/src/robots.js';
20
+ import * as reach from '../../engine/src/reach.js';
21
+ import * as directives from '../../engine/src/directives.js';
22
+ import * as bots from '../../engine/src/bots.js';
23
+ import * as signals from '../../engine/src/signals.js';
24
+ import * as hiddenText from '../../engine/src/hidden-text.js';
25
+ import { securityHeaders } from '../../engine/src/headers.js';
26
+ import { emptyPage, hsts, frontendKeys } from '../../engine/src/frontend.js';
27
+ import { parse, elements, attr, hasAttr } from '../../engine/src/html.js';
28
+ import { text } from './frame.js';
29
+ import { MAX_SCRIPTS, sameSite } from './worker.js';
30
+ import { detect } from './stack.js';
31
+
32
+ /** Harm order for the headline and What to do (spec section 3). */
33
+ export const ORDER = ['key_leaked', 'empty_page', 'crawlers_refused', 'noindex', 'sitemap_missing', 'hsts', 'headers_missing', 'signals_disagree', 'hidden_text'];
34
+ const LEVEL_RANK = { urgent: 0, recommended: 1, unchecked: 2, info: 3 };
35
+
36
+ /** Areas, in the order the scorecards show them. */
37
+ export const AREAS = ['reach', 'text', 'robots', 'https', 'headers', 'keys'];
38
+
39
+ /**
40
+ * @typedef {object} Finding
41
+ * @property {string} id
42
+ * @property {'urgent'|'recommended'|'unchecked'|'info'} level
43
+ * @property {string} area
44
+ * @property {Record<string, unknown>} data Values for the sentence.
45
+ *
46
+ * @typedef {object} Pass
47
+ * @property {string} id
48
+ * @property {string} area
49
+ * @property {Record<string, unknown>} data
50
+ *
51
+ * @typedef {object} Result
52
+ * @property {'ok'|'unchecked'} state unchecked when the page itself could not be read.
53
+ * @property {string} url The page's final URL.
54
+ * @property {string} host
55
+ * @property {{framework: string|null, host: string|null}} stack
56
+ * @property {Finding[]} findings Worst first.
57
+ * @property {Pass[]} passed
58
+ * @property {Record<string, {passed: number, total: number}>} areas
59
+ */
60
+
61
+ /** The page's text and tree, read once: scriptUrls() and analyze() both need them. */
62
+ /** @type {WeakMap<object, {html: string, doc: ReturnType<typeof parse>}>} */
63
+ const pages = new WeakMap();
64
+
65
+ /**
66
+ * @param {import('./frame.js').Part} page
67
+ * @returns {{html: string, doc: ReturnType<typeof parse>}}
68
+ */
69
+ function readPage(page) {
70
+ let r = pages.get(page);
71
+ if (!r) {
72
+ const html = text(page);
73
+ r = { html, doc: parse(html) };
74
+ pages.set(page, r);
75
+ }
76
+ return r;
77
+ }
78
+
79
+ /**
80
+ * The scripts to ask the Worker for: same-site external scripts and module preloads, in page
81
+ * order, at most 8.
82
+ * @param {import('./frame.js').Part} page
83
+ * @returns {string[]}
84
+ */
85
+ export function scriptUrls(page) {
86
+ if (!page || page.error || !page.bytes) return [];
87
+ const base = new URL(page.url);
88
+ const { doc } = readPage(page);
89
+ if (!doc) return [];
90
+ const out = [];
91
+ const add = (src) => {
92
+ try {
93
+ const u = new URL(src, base);
94
+ if ((u.protocol === 'https:' || u.protocol === 'http:') && sameSite(u, base) && !out.includes(u.href)) out.push(u.href);
95
+ } catch {
96
+ // not a URL
97
+ }
98
+ };
99
+ for (const el of elements(doc, 'script')) if (hasAttr(el, 'src')) add(attr(el, 'src'));
100
+ for (const el of elements(doc, 'link')) {
101
+ if (/\bmodulepreload\b/i.test(attr(el, 'rel')) && hasAttr(el, 'href')) add(attr(el, 'href'));
102
+ }
103
+ return out.slice(0, MAX_SCRIPTS);
104
+ }
105
+
106
+ /**
107
+ * Run the free check.
108
+ * @param {import('./frame.js').Part[]} site The page, robots.txt, sitemap.xml and llms.txt.
109
+ * @param {import('./frame.js').Part[] | null} scripts The scripts, or null when that call failed.
110
+ * @returns {Result}
111
+ */
112
+ export function analyze(site, scripts) {
113
+ const byName = Object.fromEntries(site.map((p) => [p.name, p]));
114
+ const page = byName.page;
115
+ /** @type {Finding[]} */
116
+ const findings = [];
117
+ /** @type {Pass[]} */
118
+ const passed = [];
119
+ const flag = (id, level, area, data = {}) => findings.push({ id, level, area, data });
120
+ const pass = (id, area, data = {}) => passed.push({ id, area, data });
121
+
122
+ const url = page && !page.error ? page.url : page ? page.url : '';
123
+ const host = url ? new URL(url).hostname : '';
124
+ const pageProblem = problem(page, true);
125
+ if (pageProblem) {
126
+ flag('page_unreadable', 'unchecked', 'reach', pageProblem);
127
+ return finish({ state: 'unchecked', url, host, stack: { framework: null, host: null }, findings, passed });
128
+ }
129
+
130
+ const headers = new Headers(page.headers);
131
+ const { html, doc } = readPage(page);
132
+ const stack = detect(html, headers);
133
+ const path = (() => {
134
+ const u = new URL(url);
135
+ return u.pathname + u.search;
136
+ })();
137
+
138
+ // robots.txt: a 4xx means there is none (everything allowed); an error or 5xx is Couldn't check.
139
+ const robotsPart = byName.robots;
140
+ const robotsProblem = problem(robotsPart, false);
141
+ const robotsFound = !robotsProblem && robotsPart.status >= 200 && robotsPart.status < 300;
142
+ const robots = robotsTxt.parse(robotsFound ? text(robotsPart) : '');
143
+
144
+ // --- Reach: search and answer crawlers, by robots.txt and noindex.
145
+ if (robotsProblem) {
146
+ flag('robots_unreadable', 'unchecked', 'reach', robotsProblem);
147
+ } else {
148
+ const result = reach.evaluate(robots, [{ label: 'This page', path, status: page.status, headers: directives.headerValues(headers), metas: directives.metas(doc ?? html) }]);
149
+ const refused = result.engines.filter((e) => e.blocked.length).map((e) => ({ token: e.token, feeds: e.feeds, rule: e.rule }));
150
+ const noindexed = result.engines.filter((e) => e.noindex.length).map((e) => ({ token: e.token, feeds: e.feeds }));
151
+ if (refused.length) flag('crawlers_refused', 'urgent', 'reach', { engines: refused, total: result.engines.length });
152
+ if (noindexed.length) {
153
+ const inHeader = directives.headerValues(headers).some((v) => /noindex|\bnone\b/i.test(v));
154
+ flag('noindex', 'urgent', 'reach', { engines: noindexed, total: result.engines.length, where: inHeader ? 'header' : 'meta' });
155
+ }
156
+ for (const e of result.engines) {
157
+ if (!e.blocked.length && !e.noindex.length) pass('engine_allowed', 'reach', { token: e.token, feeds: e.feeds, path });
158
+ }
159
+ const users = bots.tokens(bots.USER);
160
+ const usersOk = users.filter((t) => robotsTxt.allowed(robots, t, path));
161
+ pass('user_fetchers', 'reach', { allowed: usersOk, refused: users.filter((t) => !usersOk.includes(t)), info: true });
162
+ }
163
+
164
+ // --- Text without JavaScript.
165
+ const empty = emptyPage(doc ?? html);
166
+ if (empty) flag('empty_page', 'recommended', 'text', { chars: empty.chars, root: emptyRoot(doc) });
167
+ else pass('page_text', 'text', {});
168
+ const hidden = hiddenText.scan(html);
169
+ if (hidden.length) flag('hidden_text', 'recommended', 'text', { items: hidden.map((h) => ({ kind: h.kind, how: h.how, text: h.text, phrase: h.phrase })) });
170
+ else pass('no_hidden_text', 'text', {});
171
+
172
+ // --- robots.txt, sitemap and AI signals.
173
+ if (!robotsProblem) {
174
+ const listed = robotsTxt.sitemaps(robots);
175
+ const sm = byName.sitemap;
176
+ const atDefault = sm && !sm.error && sm.status >= 200 && sm.status < 300 && /<(urlset|sitemapindex)\b/i.test(text(sm).slice(0, 4096));
177
+ if (listed.length) pass('sitemap', 'robots', { listed, atDefault: Boolean(atDefault) });
178
+ else if (atDefault) pass('sitemap', 'robots', { listed: [], atDefault: true });
179
+ else flag('sitemap_missing', 'recommended', 'robots', { robots: robotsFound, defaultStatus: sm && !sm.error ? sm.status : null, defaultError: sm && sm.error ? sm.error.code : null });
180
+
181
+ const llmsPart = byName.llms;
182
+ const llms = !llmsPart || llmsPart.error || llmsPart.status >= 500 ? false : llmsPart.status >= 200 && llmsPart.status < 300 ? text(llmsPart) : null;
183
+ const disagree = signals.check(robots, llms).filter((f) => f.level === 'recommended');
184
+ if (disagree.length) flag('signals_disagree', 'recommended', 'robots', { ids: disagree.map((f) => f.id), values: robotsTxt.generalSignals(robots) });
185
+ else pass('signals_agree', 'robots', { contentSignal: Object.keys(robotsTxt.generalSignals(robots)).length > 0, llms: typeof llms === 'string' });
186
+
187
+ const training = bots.tokens(bots.TRAINING);
188
+ const refusedTraining = training.filter((t) => !robotsTxt.allowed(robots, t, '/'));
189
+ if (refusedTraining.length) {
190
+ const searchOk = !findings.some((f) => f.id === 'crawlers_refused');
191
+ const ai = robotsTxt.generalSignals(robots)['ai-train'] === 'no';
192
+ flag('training_refused', 'info', 'robots', { tokens: refusedTraining, total: training.length, searchOk, contentSignal: ai });
193
+ }
194
+ flag('llms', 'info', 'robots', { found: typeof llms === 'string', unchecked: llms === false });
195
+ }
196
+
197
+ // --- Security headers, read from the page's final answer.
198
+ if (new URL(url).protocol === 'https:') {
199
+ const h = hsts(headers);
200
+ if (h) flag('hsts', 'recommended', 'https', { reason: h.reason, maxAge: h.maxAge });
201
+ else pass('hsts', 'https', { value: headers.get('strict-transport-security') });
202
+ } else {
203
+ flag('hsts', 'unchecked', 'https', { reason: 'http' });
204
+ }
205
+ const sec = securityHeaders(headers);
206
+ if (sec.missing.length) flag('headers_missing', 'recommended', 'headers', { missing: sec.missing });
207
+ for (const name of ['X-Content-Type-Options', 'X-Frame-Options', 'Referrer-Policy']) {
208
+ if (!sec.missing.includes(name)) pass('header', 'headers', { name, value: headers.get(name) ?? '', viaCsp: name === 'X-Frame-Options' && !headers.get(name) });
209
+ }
210
+
211
+ // --- Keys in public JavaScript: inline scripts and the scripts the Worker fetched.
212
+ const sources = [{ url, body: inlineScripts(doc) }];
213
+ const unread = [];
214
+ let bytes = 0;
215
+ if (scripts === null) {
216
+ if (scriptUrls(page).length) unread.push({ url: '', code: 'fetch_failed' });
217
+ } else {
218
+ for (const s of scripts) {
219
+ const p = problem(s, true);
220
+ if (p) unread.push({ url: s.url, code: p.code });
221
+ else {
222
+ sources.push({ url: s.url, body: text(s) });
223
+ bytes += s.bytes.byteLength;
224
+ }
225
+ }
226
+ }
227
+ const leaks = [];
228
+ for (const s of sources) for (const k of frontendKeys(s.body)) leaks.push({ ...k, script: s.url });
229
+ for (const k of leaks) flag('key_leaked', 'urgent', 'keys', k);
230
+ const read = sources.length - 1;
231
+ if (unread.length) flag('scripts_unread', 'unchecked', 'keys', { unread, read });
232
+ // With scripts unread, a missing key proves nothing: no pass is claimed.
233
+ if (!unread.length) {
234
+ for (const type of ['supabase_service_role', 'openai', 'stripe']) {
235
+ if (!leaks.some((k) => k.type === type)) pass('no_key', 'keys', { type, scripts: read, bytes, inline: sources[0].body.trim() !== '' });
236
+ }
237
+ }
238
+
239
+ return finish({ state: 'ok', url, host, stack, findings, passed });
240
+ }
241
+
242
+ /**
243
+ * Sort worst first, then by harm order, and count each area for the scorecards. Info items do not
244
+ * count; Couldn't check counts as not passed.
245
+ * @param {Omit<Result, 'areas'>} r
246
+ * @returns {Result}
247
+ */
248
+ function finish(r) {
249
+ const rank = (f) => LEVEL_RANK[f.level] * 100 + (ORDER.includes(f.id) ? ORDER.indexOf(f.id) : 50);
250
+ r.findings.sort((a, b) => rank(a) - rank(b));
251
+ /** @type {Record<string, {passed: number, total: number}>} */
252
+ const areas = {};
253
+ for (const a of AREAS) {
254
+ const ok = r.passed.filter((p) => p.area === a && !p.data.info).length;
255
+ const bad = r.findings.filter((f) => f.area === a && f.level !== 'info').length;
256
+ areas[a] = { passed: ok, total: ok + bad };
257
+ }
258
+ return { ...r, areas };
259
+ }
260
+
261
+ /**
262
+ * Why a part cannot be read, or null. A page must answer 2xx with HTML; a site file may also
263
+ * answer 4xx (there is none).
264
+ * @param {import('./frame.js').Part | undefined} part
265
+ * @param {boolean} needOk
266
+ * @returns {{code: string, status?: number} | null}
267
+ */
268
+ function problem(part, needOk) {
269
+ if (!part) return { code: 'missing' };
270
+ if (part.error) return { code: part.error.code };
271
+ if (part.status >= 500) return { code: 'server_error', status: part.status };
272
+ if (needOk && (part.status < 200 || part.status >= 300)) return { code: 'status', status: part.status };
273
+ if (needOk && part.name === 'page') {
274
+ const type = (new Headers(part.headers).get('content-type') || '').toLowerCase();
275
+ if (type && !type.includes('html')) return { code: 'not_html' };
276
+ }
277
+ return null;
278
+ }
279
+
280
+ /**
281
+ * The empty root element an app mounts into, for the fix sentence: "root", "app", "__next" or null.
282
+ * @param {import('../../engine/src/html.js').Document | null} doc
283
+ * @returns {string | null}
284
+ */
285
+ function emptyRoot(doc) {
286
+ if (!doc) return null;
287
+ for (const el of elements(doc, 'div')) {
288
+ const id = attr(el, 'id');
289
+ if (['root', 'app', '__next', '__nuxt', 'svelte'].includes(id)) return id;
290
+ }
291
+ return null;
292
+ }
293
+
294
+ /**
295
+ * Inline script text: JSON data blocks and code alike, since keys show up in both.
296
+ * @param {import('../../engine/src/html.js').Document | null} doc
297
+ * @returns {string}
298
+ */
299
+ function inlineScripts(doc) {
300
+ if (!doc) return '';
301
+ return elements(doc, 'script')
302
+ .filter((el) => !hasAttr(el, 'src'))
303
+ .map((el) => textOf(el))
304
+ .join('\n');
305
+ }
306
+
307
+ /** @param {any} node */
308
+ function textOf(node) {
309
+ if (node.type === 3 || node.type === 4) return node.data;
310
+ return node.type === 1 ? node.children.map(textOf).join('') : '';
311
+ }