@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.
- package/README.md +98 -2
- package/bin/goose-tools.js +61 -0
- package/lib/check/src/agent.js +90 -0
- package/lib/check/src/analyze.js +311 -0
- package/lib/check/src/client.js +136 -0
- package/lib/check/src/copy.js +355 -0
- package/lib/check/src/fixes.js +153 -0
- package/lib/check/src/frame.js +92 -0
- package/lib/check/src/guard.js +441 -0
- package/lib/check/src/index.js +18 -0
- package/lib/check/src/mcp-http.js +169 -0
- package/lib/check/src/mcp.js +153 -0
- package/lib/check/src/scan.js +55 -0
- package/lib/check/src/stack.js +61 -0
- package/lib/check/src/tlds.js +3 -0
- package/lib/check/src/view.js +130 -0
- package/lib/check/src/worker.js +257 -0
- package/lib/engine/src/bots.js +146 -0
- package/lib/engine/src/directives.js +131 -0
- package/lib/engine/src/exposure.js +70 -0
- package/lib/engine/src/frontend.js +157 -0
- package/lib/engine/src/headers.js +76 -0
- package/lib/engine/src/hidden-text.js +425 -0
- package/lib/engine/src/html.js +794 -0
- package/lib/engine/src/index.js +20 -0
- package/lib/engine/src/php.js +316 -0
- package/lib/engine/src/policies.js +234 -0
- package/lib/engine/src/reach.js +199 -0
- package/lib/engine/src/robots.js +275 -0
- package/lib/engine/src/secrets.js +142 -0
- package/lib/engine/src/signals.js +144 -0
- package/lib/rules/data/bots.json.js +1 -0
- package/lib/rules/data/exposure.json.js +1 -0
- package/lib/rules/data/frontend.json.js +1 -0
- package/lib/rules/data/headers.json.js +1 -0
- package/lib/rules/data/secrets.json.js +1 -0
- package/lib/ui/LICENSE-Inter.txt +93 -0
- package/lib/ui/assets.js +5 -0
- package/package.json +37 -4
- package/src/local.js +61 -0
- package/src/mcp.js +61 -0
- package/src/setup.js +395 -0
- package/src/site/auth.js +287 -0
- package/src/site/beacon.js +462 -0
- package/src/site/collect.js +484 -0
- package/src/site/handler.js +405 -0
- package/src/site/index.js +88 -0
- package/src/site/limits.js +48 -0
- package/src/site/pages.js +75 -0
- package/src/site/qr.js +318 -0
- package/src/site/reports.js +1117 -0
- package/src/site/source.js +68 -0
- package/src/site/store-pg.js +225 -0
- package/src/site/store.js +249 -0
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The check Worker: `POST /check/fetch`. The same Worker serves the check page at /check/ (static assets).
|
|
3
|
+
*
|
|
4
|
+
* The check page sends a URL. The Worker fetches what the page cannot fetch itself (other sites
|
|
5
|
+
* do not allow it across origins) and returns the bytes as fetched. The page runs every check.
|
|
6
|
+
* Nothing from a check is stored, apart from the 10-minute cache below.
|
|
7
|
+
*
|
|
8
|
+
* Two calls make one check:
|
|
9
|
+
* 1. `{ "url": "https://site.example/" }`: the page, then robots.txt, sitemap.xml and llms.txt
|
|
10
|
+
* from the origin the page ended on.
|
|
11
|
+
* 2. `{ "url": "<the page's final URL>", "scripts": ["https://site.example/assets/app.js", ...] }`:
|
|
12
|
+
* up to 8 scripts the page loads from its own host, to look for keys in public JavaScript.
|
|
13
|
+
*
|
|
14
|
+
* Limits (spec/standalone.md section 3), on top of check/src/guard.js for every hop:
|
|
15
|
+
* - a per-visitor rate limit when the RATE_LIMITER binding is present (Workers Rate Limiting API,
|
|
16
|
+
* approximate and per Cloudflare location; whether the Free plan has it is confirmed by the
|
|
17
|
+
* deployed test, risk 3 in the spec);
|
|
18
|
+
* - 45 subrequests a call, under the Free plan's 50;
|
|
19
|
+
* - a 10-minute cache per request (Cache API, per data center, custom domains only).
|
|
20
|
+
*
|
|
21
|
+
* The User-Agent names the check and links to it. Crawler identities (GPTBot and others) are never
|
|
22
|
+
* sent from here: a site the visitor has not proved is theirs must not see them.
|
|
23
|
+
*
|
|
24
|
+
* Response: application/octet-stream in the frame format of check/src/frame.js, or JSON
|
|
25
|
+
* `{ error: { code, reason } }` with a 4xx status.
|
|
26
|
+
*/
|
|
27
|
+
import { guardedFetch, validateTarget, GuardError } from './guard.js';
|
|
28
|
+
import { frame } from './frame.js';
|
|
29
|
+
|
|
30
|
+
export const USER_AGENT = 'GooseToolsCheck/1.0 (+https://goosetools.app/check)';
|
|
31
|
+
export const MAX_SCRIPTS = 8;
|
|
32
|
+
export const MAX_SUBREQUESTS = 45;
|
|
33
|
+
export const CACHE_SECONDS = 600;
|
|
34
|
+
export const FETCH_PATH = '/check/fetch';
|
|
35
|
+
const MAX_REQUEST_BYTES = 16 * 1024;
|
|
36
|
+
const SITE_FILES = /** @type {const} */ ([
|
|
37
|
+
['robots', '/robots.txt'],
|
|
38
|
+
['sitemap', '/sitemap.xml'],
|
|
39
|
+
['llms', '/llms.txt'],
|
|
40
|
+
]);
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* @typedef {object} Env
|
|
44
|
+
* @property {{limit: (o: {key: string}) => Promise<{success: boolean}>}} [RATE_LIMITER]
|
|
45
|
+
* @property {string} [ALLOWED_ORIGINS] Comma-separated origins allowed to call across origins,
|
|
46
|
+
* for local development. The check page itself is same-origin and needs none.
|
|
47
|
+
*/
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* @typedef {object} Deps For tests. Production passes none.
|
|
51
|
+
* @property {typeof fetch} [fetchImpl]
|
|
52
|
+
* @property {(url: string | URL) => any} [validate]
|
|
53
|
+
* @property {Cache | null} [cache]
|
|
54
|
+
* @property {number} [pageMaxBytes] Read at most this much of the page (the chat-app server's limit, plus one byte
|
|
55
|
+
* so a page over it shows as larger). Default 2 MB.
|
|
56
|
+
* @property {number} [scriptMaxBytes] Read at most this much of each script. Default 2 MB.
|
|
57
|
+
*/
|
|
58
|
+
|
|
59
|
+
export default {
|
|
60
|
+
/**
|
|
61
|
+
* @param {Request} request
|
|
62
|
+
* @param {Env} env
|
|
63
|
+
* @param {{waitUntil?: (p: Promise<unknown>) => void}} [ctx]
|
|
64
|
+
*/
|
|
65
|
+
fetch(request, env, ctx) {
|
|
66
|
+
return handle(request, env, ctx);
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* @param {Request} request
|
|
72
|
+
* @param {Env} env
|
|
73
|
+
* @param {{waitUntil?: (p: Promise<unknown>) => void}} [ctx]
|
|
74
|
+
* @param {Deps} [deps]
|
|
75
|
+
* @returns {Promise<Response>}
|
|
76
|
+
*/
|
|
77
|
+
export async function handle(request, env = {}, ctx = {}, deps = {}) {
|
|
78
|
+
const url = new URL(request.url);
|
|
79
|
+
const cors = corsHeaders(request, env);
|
|
80
|
+
if (url.pathname !== FETCH_PATH) return fail(404, 'not_found', 'Not found.', cors);
|
|
81
|
+
if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers: cors });
|
|
82
|
+
if (request.method !== 'POST') return fail(405, 'method', 'Use POST.', { ...cors, allow: 'POST, OPTIONS' });
|
|
83
|
+
|
|
84
|
+
/** @type {{url?: unknown, scripts?: unknown}} */
|
|
85
|
+
let input;
|
|
86
|
+
try {
|
|
87
|
+
const raw = await request.text();
|
|
88
|
+
if (raw.length > MAX_REQUEST_BYTES) return fail(413, 'too_large', 'The request is too large.', cors);
|
|
89
|
+
input = JSON.parse(raw);
|
|
90
|
+
} catch {
|
|
91
|
+
return fail(400, 'bad_request', 'Send JSON with a url.', cors);
|
|
92
|
+
}
|
|
93
|
+
if (!input || typeof input.url !== 'string') return fail(400, 'bad_request', 'Send JSON with a url.', cors);
|
|
94
|
+
|
|
95
|
+
const target = validateTarget(input.url.trim());
|
|
96
|
+
if (!target.ok) return fail(400, target.code, target.reason, cors);
|
|
97
|
+
|
|
98
|
+
/** @type {URL[] | null} */
|
|
99
|
+
let scripts = null;
|
|
100
|
+
if (input.scripts !== undefined) {
|
|
101
|
+
if (!Array.isArray(input.scripts) || input.scripts.length === 0 || input.scripts.length > MAX_SCRIPTS) {
|
|
102
|
+
return fail(400, 'bad_request', `Send 1 to ${MAX_SCRIPTS} script URLs.`, cors);
|
|
103
|
+
}
|
|
104
|
+
scripts = [];
|
|
105
|
+
for (const s of input.scripts) {
|
|
106
|
+
const check = typeof s === 'string' ? validateTarget(s) : null;
|
|
107
|
+
if (!check || !check.ok || !sameSite(check.url, target.url)) {
|
|
108
|
+
return fail(400, 'bad_script', 'Scripts must be on the same site as the page.', cors);
|
|
109
|
+
}
|
|
110
|
+
scripts.push(check.url);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (env.RATE_LIMITER) {
|
|
115
|
+
const who = request.headers.get('cf-connecting-ip') || 'unknown';
|
|
116
|
+
const { success } = await env.RATE_LIMITER.limit({ key: who });
|
|
117
|
+
if (!success) return fail(429, 'rate_limited', 'Too many checks in a minute. Wait a minute, then check again.', { ...cors, 'retry-after': '60' });
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const cache = deps.cache !== undefined ? deps.cache : globalThis.caches ? /** @type {any} */ (caches).default : null;
|
|
121
|
+
const key = cache ? await cacheKey(url, target.url, scripts) : null;
|
|
122
|
+
if (cache && key) {
|
|
123
|
+
const hit = await cache.match(key).catch(() => undefined);
|
|
124
|
+
if (hit) return withHeaders(hit, { ...cors, 'x-gt-cache': 'hit' });
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const budget = counted(deps.fetchImpl ?? globalThis.fetch.bind(globalThis), MAX_SUBREQUESTS);
|
|
128
|
+
const opts = { headers: { 'user-agent': USER_AGENT, accept: '*/*' }, fetchImpl: budget, ...(deps.validate ? { validate: deps.validate } : {}) };
|
|
129
|
+
|
|
130
|
+
const parts = scripts
|
|
131
|
+
? await fetchScripts(scripts, deps.scriptMaxBytes ? { ...opts, maxBytes: deps.scriptMaxBytes } : opts)
|
|
132
|
+
: await fetchSite(target.url, opts, deps.pageMaxBytes);
|
|
133
|
+
const body = frame(parts);
|
|
134
|
+
const res = new Response(body, {
|
|
135
|
+
status: 200,
|
|
136
|
+
headers: { 'content-type': 'application/octet-stream', 'cache-control': `private, max-age=${CACHE_SECONDS}` },
|
|
137
|
+
});
|
|
138
|
+
if (cache && key) {
|
|
139
|
+
const put = cache.put(key, new Response(body, { headers: { 'content-type': 'application/octet-stream', 'cache-control': `max-age=${CACHE_SECONDS}` } })).catch(() => {});
|
|
140
|
+
if (ctx.waitUntil) ctx.waitUntil(put);
|
|
141
|
+
}
|
|
142
|
+
return withHeaders(res, { ...cors, 'x-gt-cache': 'miss' });
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The page first, then the three site files from the origin the page ended on.
|
|
147
|
+
* @param {URL} url
|
|
148
|
+
* @param {object} opts
|
|
149
|
+
* @param {number} [pageMaxBytes]
|
|
150
|
+
*/
|
|
151
|
+
async function fetchSite(url, opts, pageMaxBytes) {
|
|
152
|
+
const page = await one('page', url.href, pageMaxBytes ? { ...opts, maxBytes: pageMaxBytes } : opts);
|
|
153
|
+
const origin = new URL(page.head.error ? url.href : page.head.url).origin;
|
|
154
|
+
const files = await Promise.all(SITE_FILES.map(([name, path]) => one(name, origin + path, opts)));
|
|
155
|
+
return [page, ...files];
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Scripts, fetched at the same time (the platform allows six open at once), 2 MB each.
|
|
160
|
+
* @param {URL[]} scripts
|
|
161
|
+
* @param {object} opts
|
|
162
|
+
*/
|
|
163
|
+
function fetchScripts(scripts, opts) {
|
|
164
|
+
return Promise.all(scripts.map((s) => one('script', s.href, opts)));
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* @param {string} name
|
|
169
|
+
* @param {string} url
|
|
170
|
+
* @param {object} opts
|
|
171
|
+
* @returns {Promise<{head: import('./frame.js').PartHead, body?: Uint8Array}>}
|
|
172
|
+
*/
|
|
173
|
+
async function one(name, url, opts) {
|
|
174
|
+
try {
|
|
175
|
+
const r = await guardedFetch(url, opts);
|
|
176
|
+
/** @type {[string, string][]} */
|
|
177
|
+
const headers = [];
|
|
178
|
+
r.headers.forEach((v, k) => {
|
|
179
|
+
if (k !== 'set-cookie') headers.push([k, v]);
|
|
180
|
+
});
|
|
181
|
+
return { head: { name, url: r.url, status: r.status, headers, truncated: r.truncated, redirects: r.redirects }, body: r.body };
|
|
182
|
+
} catch (err) {
|
|
183
|
+
const e = err instanceof GuardError ? err : new GuardError('fetch_failed', 'The site could not be reached.');
|
|
184
|
+
return { head: { name, url, error: { code: e.code, reason: e.message } } };
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* A fetch that refuses past a number of calls, so one check stays under the subrequest limit.
|
|
190
|
+
* @param {typeof fetch} f
|
|
191
|
+
* @param {number} max
|
|
192
|
+
* @returns {typeof fetch}
|
|
193
|
+
*/
|
|
194
|
+
function counted(f, max) {
|
|
195
|
+
let n = 0;
|
|
196
|
+
return /** @type {typeof fetch} */ (
|
|
197
|
+
(input, init) => {
|
|
198
|
+
if (++n > max) return Promise.reject(new Error('subrequest budget'));
|
|
199
|
+
return f(input, init);
|
|
200
|
+
}
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Same host, or a host under the page's domain (www stripped): app.js on cdn.site.example is
|
|
206
|
+
* allowed for www.site.example. Other sites' scripts are not fetched.
|
|
207
|
+
* @param {URL} script
|
|
208
|
+
* @param {URL} page
|
|
209
|
+
*/
|
|
210
|
+
export function sameSite(script, page) {
|
|
211
|
+
const base = page.hostname.replace(/^www\./, '');
|
|
212
|
+
return script.hostname === page.hostname || script.hostname === base || script.hostname.endsWith('.' + base);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* @param {URL} self
|
|
217
|
+
* @param {URL} target
|
|
218
|
+
* @param {URL[] | null} scripts
|
|
219
|
+
*/
|
|
220
|
+
async function cacheKey(self, target, scripts) {
|
|
221
|
+
const raw = JSON.stringify([target.href, scripts ? scripts.map((s) => s.href) : null]);
|
|
222
|
+
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(raw));
|
|
223
|
+
const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
|
|
224
|
+
return new Request(new URL(FETCH_PATH + '/cache/' + hex, self.origin).href, { method: 'GET' });
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* @param {Request} request
|
|
229
|
+
* @param {Env} env
|
|
230
|
+
* @returns {Record<string, string>}
|
|
231
|
+
*/
|
|
232
|
+
function corsHeaders(request, env) {
|
|
233
|
+
const origin = request.headers.get('origin');
|
|
234
|
+
const allowed = (env.ALLOWED_ORIGINS || '').split(',').map((s) => s.trim()).filter(Boolean);
|
|
235
|
+
if (!origin || !allowed.includes(origin)) return {};
|
|
236
|
+
return { 'access-control-allow-origin': origin, 'access-control-allow-methods': 'POST, OPTIONS', 'access-control-allow-headers': 'content-type', vary: 'origin' };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* @param {number} status
|
|
241
|
+
* @param {string} code
|
|
242
|
+
* @param {string} reason
|
|
243
|
+
* @param {Record<string, string>} headers
|
|
244
|
+
*/
|
|
245
|
+
function fail(status, code, reason, headers) {
|
|
246
|
+
return new Response(JSON.stringify({ error: { code, reason } }), { status, headers: { 'content-type': 'application/json', ...headers } });
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* @param {Response} res
|
|
251
|
+
* @param {Record<string, string>} extra
|
|
252
|
+
*/
|
|
253
|
+
function withHeaders(res, extra) {
|
|
254
|
+
const out = new Response(res.body, res);
|
|
255
|
+
for (const [k, v] of Object.entries(extra)) out.headers.set(k, v);
|
|
256
|
+
return out;
|
|
257
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The AI crawlers and fetchers Goose Tools recognizes, what each is for, and where its provider
|
|
3
|
+
* publishes its addresses (port of Crawlers/Bots.php). The facts live in rules/data/bots.json,
|
|
4
|
+
* which goose-tools checks against the PHP (RulesDataTest).
|
|
5
|
+
*
|
|
6
|
+
* Purposes: training (content may train models), search (builds the index an engine answers
|
|
7
|
+
* from), user (fetches a page because a person asked; may ignore robots.txt). Googlebot and
|
|
8
|
+
* Bingbot are search crawlers that the purpose switches never touch.
|
|
9
|
+
*/
|
|
10
|
+
import data from '../../rules/data/bots.json.js' ;
|
|
11
|
+
import { str } from './php.js';
|
|
12
|
+
|
|
13
|
+
export const TRAINING = 'training';
|
|
14
|
+
export const SEARCH = 'search';
|
|
15
|
+
export const USER = 'user';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @typedef {object} Bot
|
|
19
|
+
* @property {string} provider
|
|
20
|
+
* @property {string} purpose training, search or user.
|
|
21
|
+
* @property {RegExp | null} pattern What identifies it in a user agent; null for a robots.txt token only.
|
|
22
|
+
* @property {string} token Its robots.txt token.
|
|
23
|
+
* @property {string} list Key of its address list, or ''.
|
|
24
|
+
* @property {boolean} switch Whether the purpose switch applies to it.
|
|
25
|
+
* @property {boolean} robots Whether its provider says it follows robots.txt.
|
|
26
|
+
* @property {string} doc Provider documentation.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
/** @type {Record<string, Bot>} */
|
|
30
|
+
const BOTS = Object.fromEntries(
|
|
31
|
+
Object.entries(data.bots).map(([name, b]) => [
|
|
32
|
+
name,
|
|
33
|
+
Object.freeze({ ...b, pattern: b.pattern ? new RegExp(b.pattern.source, b.pattern.flags) : null }),
|
|
34
|
+
]),
|
|
35
|
+
);
|
|
36
|
+
|
|
37
|
+
/** The cheap first test a user agent must pass before the patterns are tried. */
|
|
38
|
+
const PREFILTER = new RegExp(data.prefilter.source, data.prefilter.flags);
|
|
39
|
+
|
|
40
|
+
/** Address lists: key => URL. */
|
|
41
|
+
export const LISTS = Object.freeze({ ...data.lists.urls });
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The catalog, in match order.
|
|
45
|
+
* @returns {Record<string, Bot>}
|
|
46
|
+
*/
|
|
47
|
+
export function all() {
|
|
48
|
+
return BOTS;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The cheap first look: whether a user agent could name one of the crawlers at all.
|
|
53
|
+
* @param {string} ua
|
|
54
|
+
* @returns {boolean}
|
|
55
|
+
*/
|
|
56
|
+
export function maybe(ua) {
|
|
57
|
+
const s = str(ua);
|
|
58
|
+
return s !== '' && PREFILTER.test(s);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The crawler a user agent claims to be (a claim until its address is checked), or null.
|
|
63
|
+
* @param {string} ua
|
|
64
|
+
* @returns {string | null} Bot name, a key of all().
|
|
65
|
+
*/
|
|
66
|
+
export function match(ua) {
|
|
67
|
+
if (!maybe(ua)) return null;
|
|
68
|
+
const s = str(ua);
|
|
69
|
+
for (const [name, b] of Object.entries(BOTS)) {
|
|
70
|
+
if (b.pattern !== null && b.pattern.test(s)) return name;
|
|
71
|
+
}
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* A crawler's entry, or null.
|
|
77
|
+
* @param {string} name
|
|
78
|
+
* @returns {Bot | null}
|
|
79
|
+
*/
|
|
80
|
+
export function get(name) {
|
|
81
|
+
return Object.hasOwn(BOTS, name) ? BOTS[name] : null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* A crawler's purpose ('' when unknown).
|
|
86
|
+
* @param {string} name
|
|
87
|
+
* @returns {string}
|
|
88
|
+
*/
|
|
89
|
+
export function purpose(name) {
|
|
90
|
+
const b = get(name);
|
|
91
|
+
return b === null ? '' : b.purpose;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Robots.txt tokens a purpose switch covers.
|
|
96
|
+
* @param {string} p training, search or user.
|
|
97
|
+
* @returns {string[]}
|
|
98
|
+
*/
|
|
99
|
+
export function tokens(p) {
|
|
100
|
+
return Object.values(BOTS)
|
|
101
|
+
.filter((b) => b.switch && b.purpose === p)
|
|
102
|
+
.map((b) => b.token);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Purposes, in display order.
|
|
107
|
+
* @returns {string[]}
|
|
108
|
+
*/
|
|
109
|
+
export function purposes() {
|
|
110
|
+
return [...data.purposes];
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** @type {Record<string, string>} */
|
|
114
|
+
const LABELS = { training: 'training', search: 'search', user: 'user request' };
|
|
115
|
+
|
|
116
|
+
/** @type {Record<string, string>} */
|
|
117
|
+
const NAMES = { training: 'AI training crawlers', search: 'AI search crawlers', user: 'User-requested AI fetchers' };
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Plain label for a purpose.
|
|
121
|
+
* @param {string} p
|
|
122
|
+
* @returns {string}
|
|
123
|
+
*/
|
|
124
|
+
export function purposeLabel(p) {
|
|
125
|
+
return Object.hasOwn(LABELS, p) ? LABELS[p] : '';
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Plain name for the crawlers a purpose switch covers ("AI training crawlers").
|
|
130
|
+
* @param {string} p
|
|
131
|
+
* @returns {string}
|
|
132
|
+
*/
|
|
133
|
+
export function purposeName(p) {
|
|
134
|
+
return Object.hasOwn(NAMES, p) ? NAMES[p] : '';
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Bot names that share an address list (Anthropic publishes one for its three crawlers).
|
|
139
|
+
* @param {string} listKey
|
|
140
|
+
* @returns {string[]}
|
|
141
|
+
*/
|
|
142
|
+
export function onList(listKey) {
|
|
143
|
+
return Object.entries(BOTS)
|
|
144
|
+
.filter(([, b]) => b.list === listKey)
|
|
145
|
+
.map(([name]) => name);
|
|
146
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Robots directives on a page, from X-Robots-Tag headers and robots meta tags, as they apply to
|
|
3
|
+
* one crawler (port of Crawlers/Directives.php).
|
|
4
|
+
*
|
|
5
|
+
* - X-Robots-Tag: "noindex", "noindex, nofollow", or for one crawler "googlebot: noindex". A name
|
|
6
|
+
* before a colon is a crawler unless it is a directive: one that takes a value (max-snippet,
|
|
7
|
+
* max-image-preview, max-video-preview, unavailable_after) or one of NAMED ("all: noindex" is
|
|
8
|
+
* all and noindex for every crawler). Google:
|
|
9
|
+
* https://developers.google.com/search/docs/crawling-indexing/robots-meta-tag.
|
|
10
|
+
* - Meta tags: <meta name="robots"> applies to all crawlers, <meta name="googlebot"> (or another
|
|
11
|
+
* token) to that one.
|
|
12
|
+
*/
|
|
13
|
+
import { trim, lower, str, isArray, isset, values, WS } from './php.js';
|
|
14
|
+
import { parse, headElements, attr } from './html.js';
|
|
15
|
+
|
|
16
|
+
/** Directives that take a value after a colon. */
|
|
17
|
+
export const VALUED = ['max-snippet', 'max-image-preview', 'max-video-preview', 'unavailable_after'];
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Directives without a value. Before a colon they are never a crawler name: "all: noindex" is all
|
|
21
|
+
* and noindex for every crawler. Google ignores noarchive and nocache, but they are still names.
|
|
22
|
+
*/
|
|
23
|
+
export const NAMED = ['all', 'none', 'noindex', 'nofollow', 'nosnippet', 'indexifembedded', 'notranslate', 'noimageindex', 'noarchive', 'nocache'];
|
|
24
|
+
|
|
25
|
+
/** "name: rest" in one header part. PHP's "$" also matches before a final newline. */
|
|
26
|
+
const SCOPED = new RegExp(`^([a-z0-9_-]+)${WS}*:${WS}*([^\\n]*)\\n?$`);
|
|
27
|
+
/** Spaces around a colon, removed: "max-snippet : 10" is "max-snippet:10". */
|
|
28
|
+
const COLON = new RegExp(`${WS}*:${WS}*`, 'g');
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @typedef {object} Meta
|
|
32
|
+
* @property {string} [name]
|
|
33
|
+
* @property {string} [content]
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Directives that apply to a crawler.
|
|
38
|
+
* @param {unknown[]} headers X-Robots-Tag header values.
|
|
39
|
+
* @param {unknown[]} metas Robots meta tags: {name, content}.
|
|
40
|
+
* @param {string} token Crawler token, for example "Googlebot".
|
|
41
|
+
* @returns {string[]} Lower-case directives, for example noindex, nosnippet, max-snippet:0.
|
|
42
|
+
*/
|
|
43
|
+
export function forBot(headers, metas, token) {
|
|
44
|
+
const t = lower(str(token));
|
|
45
|
+
/** @type {string[]} */
|
|
46
|
+
const out = [];
|
|
47
|
+
for (const value of values(headers)) {
|
|
48
|
+
let bot = '';
|
|
49
|
+
for (let part of str(value).split(',')) {
|
|
50
|
+
part = lower(trim(part));
|
|
51
|
+
const m = SCOPED.exec(part);
|
|
52
|
+
if (m && !VALUED.includes(m[1])) {
|
|
53
|
+
if (NAMED.includes(m[1])) {
|
|
54
|
+
if (bot === '' || bot === t) out.push(m[1]);
|
|
55
|
+
} else {
|
|
56
|
+
bot = m[1];
|
|
57
|
+
}
|
|
58
|
+
part = trim(m[2]);
|
|
59
|
+
}
|
|
60
|
+
if (part !== '' && (bot === '' || bot === t)) out.push(part.replace(COLON, ':'));
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
for (const meta of values(metas)) {
|
|
64
|
+
const name = lower(trim(isset(meta, 'name') ? str(/** @type {Meta} */ (meta).name) : ''));
|
|
65
|
+
if (name !== 'robots' && name !== t) continue;
|
|
66
|
+
const content = isset(meta, 'content') ? str(/** @type {Meta} */ (meta).content) : '';
|
|
67
|
+
for (let part of content.split(',')) {
|
|
68
|
+
part = lower(trim(part));
|
|
69
|
+
if (part !== '') out.push(part.replace(COLON, ':'));
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return [...new Set(out)];
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Whether the directives keep the page out of the index.
|
|
77
|
+
* @param {string[]} directives
|
|
78
|
+
* @returns {boolean}
|
|
79
|
+
*/
|
|
80
|
+
export function noindex(directives) {
|
|
81
|
+
return directives.includes('noindex') || directives.includes('none');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Whether the directives keep text snippets out of results (nosnippet, or max-snippet:0).
|
|
86
|
+
* @param {string[]} directives
|
|
87
|
+
* @returns {boolean}
|
|
88
|
+
*/
|
|
89
|
+
export function nosnippet(directives) {
|
|
90
|
+
return directives.includes('nosnippet') || directives.includes('max-snippet:0');
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* X-Robots-Tag values from response headers.
|
|
95
|
+
* @param {Record<string, unknown> | Headers} headers Header name => value or values (any case), or a
|
|
96
|
+
* fetch Headers object.
|
|
97
|
+
* @returns {string[]}
|
|
98
|
+
*/
|
|
99
|
+
export function headerValues(headers) {
|
|
100
|
+
if (typeof Headers !== 'undefined' && headers instanceof Headers) {
|
|
101
|
+
const v = headers.get('x-robots-tag');
|
|
102
|
+
return v === null ? [] : [v];
|
|
103
|
+
}
|
|
104
|
+
/** @type {string[]} */
|
|
105
|
+
const out = [];
|
|
106
|
+
if (!isArray(headers)) return out;
|
|
107
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
108
|
+
if (lower(name) !== 'x-robots-tag') continue;
|
|
109
|
+
for (const v of Array.isArray(value) ? value : [value]) out.push(str(v));
|
|
110
|
+
}
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Robots meta tags in a page's head (name robots or a crawler's token).
|
|
116
|
+
* @param {string | import('./html.js').Document | null} html The page, or a tree from html.parse().
|
|
117
|
+
* @returns {{name: string, content: string}[]}
|
|
118
|
+
*/
|
|
119
|
+
export function metas(html) {
|
|
120
|
+
const doc = typeof html === 'string' ? parse(html) : html;
|
|
121
|
+
if (!doc) return [];
|
|
122
|
+
/** @type {{name: string, content: string}[]} */
|
|
123
|
+
const out = [];
|
|
124
|
+
for (const m of headElements(doc, 'meta')) {
|
|
125
|
+
const name = lower(trim(attr(m, 'name')));
|
|
126
|
+
if (name !== '' && /^(robots|[a-z0-9_-]*bot[a-z0-9_-]*|[a-z0-9_-]+-(user|extended))$/.test(name)) {
|
|
127
|
+
out.push({ name, content: attr(m, 'content') });
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Exposed-file detection (port of Signals/Exposure.php): does a public response really contain the
|
|
3
|
+
* sensitive file? Content tests avoid false alarms from sites that answer every address with a
|
|
4
|
+
* page (soft 404). The tests live in rules/data/exposure.json as small expressions, which
|
|
5
|
+
* goose-tools checks against the PHP (RulesDataTest).
|
|
6
|
+
*
|
|
7
|
+
* The PHP regexes have no u flag, so the body is tested as a byte string: \s is ASCII and the
|
|
8
|
+
* 1024-byte window for "looks like HTML" counts bytes.
|
|
9
|
+
*/
|
|
10
|
+
import data from '../../rules/data/exposure.json.js' ;
|
|
11
|
+
import { int, str, lower, toBytes, phpRegex } from './php.js';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @typedef {{regex: {source: string, flags: string}} | {contains: string} | {contains_ci: string} |
|
|
15
|
+
* {not_html: true} | {all: Expr[]} | {any: Expr[]}} Expr
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** Statuses whose body can expose a file. */
|
|
19
|
+
const STATUSES = new Set(data.statuses.list);
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* A PHP regex from the data.
|
|
23
|
+
* @param {{source: string, flags: string}} r
|
|
24
|
+
* @returns {RegExp}
|
|
25
|
+
*/
|
|
26
|
+
function regex(r) {
|
|
27
|
+
return phpRegex(r.source, r.flags);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const HTML = regex(data.html);
|
|
31
|
+
|
|
32
|
+
/** @type {Map<object, RegExp>} */
|
|
33
|
+
const compiled = new Map();
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Evaluate one expression on a body.
|
|
37
|
+
* @param {Expr} e
|
|
38
|
+
* @param {string} body Byte string.
|
|
39
|
+
* @returns {boolean}
|
|
40
|
+
*/
|
|
41
|
+
function test(e, body) {
|
|
42
|
+
if ('all' in e) return e.all.every((x) => test(x, body));
|
|
43
|
+
if ('any' in e) return e.any.some((x) => test(x, body));
|
|
44
|
+
if ('regex' in e) {
|
|
45
|
+
let re = compiled.get(e);
|
|
46
|
+
if (!re) {
|
|
47
|
+
re = regex(e.regex);
|
|
48
|
+
compiled.set(e, re);
|
|
49
|
+
}
|
|
50
|
+
return re.test(body);
|
|
51
|
+
}
|
|
52
|
+
if ('contains' in e) return body.includes(e.contains);
|
|
53
|
+
if ('contains_ci' in e) return lower(body).includes(lower(e.contains_ci));
|
|
54
|
+
if ('not_html' in e) return !HTML.test(body.slice(0, data.html.first_bytes));
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Whether a response exposes the file.
|
|
60
|
+
* @param {string} type log, config_backup, env, git, sql, phpinfo or listing.
|
|
61
|
+
* @param {number} status HTTP status.
|
|
62
|
+
* @param {string} body First bytes of the body.
|
|
63
|
+
* @returns {boolean}
|
|
64
|
+
*/
|
|
65
|
+
export function exposed(type, status, body) {
|
|
66
|
+
if (!STATUSES.has(int(status))) return false;
|
|
67
|
+
const types = /** @type {Record<string, Expr>} */ (data.types);
|
|
68
|
+
if (!Object.hasOwn(types, type)) return false;
|
|
69
|
+
return test(types[type], toBytes(str(body)));
|
|
70
|
+
}
|