@cobola/dsh-geo 0.0.0-stage → 0.2.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/.github/workflows/publish.yml +59 -0
- package/CHANGELOG.md +27 -0
- package/CONTRIBUTING.md +86 -0
- package/LICENSE +176 -0
- package/NOTICE +14 -0
- package/README.md +194 -2
- package/SECURITY.md +46 -0
- package/bin/dsh-geo.js +378 -0
- package/client.js +695 -0
- package/cordis.patch.yml +4 -0
- package/docs/CI.md +118 -0
- package/docs/GOOGLE.md +57 -0
- package/docs/NPM-TRUSTED-PUBLISHING.md +69 -0
- package/docs/PROFILES.md +40 -0
- package/docs/RULES.md +108 -0
- package/icon.svg +8 -0
- package/index.js +376 -0
- package/lib/audit.js +62 -0
- package/lib/fetch.js +650 -0
- package/lib/html.js +649 -0
- package/lib/profiles.js +62 -0
- package/lib/report.js +353 -0
- package/lib/robots.js +198 -0
- package/lib/rules.js +939 -0
- package/lib/scan.js +602 -0
- package/lib/score.js +143 -0
- package/lib/store.js +277 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +66 -4
package/lib/scan.js
ADDED
|
@@ -0,0 +1,602 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deterministic site scanner.
|
|
3
|
+
*
|
|
4
|
+
* Produces the artifact the rubric scores: robots decisions, sitemap contents,
|
|
5
|
+
* llms.txt, and a bounded set of raw-HTML page fact sheets. No rendering, no
|
|
6
|
+
* LLM calls, no wall-clock values inside page facts, so the same site (with the
|
|
7
|
+
* same `now`) always yields the same artifact.
|
|
8
|
+
*
|
|
9
|
+
* Safety: destination validation, per-hop redirect checks, body caps, timeouts
|
|
10
|
+
* and per-host rate limits all come from lib/fetch.js; this module also honours
|
|
11
|
+
* robots.txt for every request it makes.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { analyzeHtml } from './html.js';
|
|
15
|
+
import { createTransport, DEFAULT_USER_AGENT, FetchError } from './fetch.js';
|
|
16
|
+
import { aiCrawlerPolicy, blocksEverything, crawlDelayMs, googlebotAccess, isAllowed, parseRobots } from './robots.js';
|
|
17
|
+
|
|
18
|
+
export const SCAN_VERSION = 'scan@1';
|
|
19
|
+
|
|
20
|
+
export const SCAN_DEFAULTS = {
|
|
21
|
+
respectRobots: true,
|
|
22
|
+
allowPrivate: false,
|
|
23
|
+
insecureTls: false,
|
|
24
|
+
maxPages: 6,
|
|
25
|
+
maxBytes: 1_500_000,
|
|
26
|
+
robotsMaxBytes: 256_000,
|
|
27
|
+
sitemapMaxBytes: 512_000,
|
|
28
|
+
llmsMaxBytes: 64_000,
|
|
29
|
+
timeoutMs: 10_000,
|
|
30
|
+
rateLimitMs: 250,
|
|
31
|
+
maxRedirects: 5,
|
|
32
|
+
userAgent: DEFAULT_USER_AGENT,
|
|
33
|
+
now: null,
|
|
34
|
+
signal: null,
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const SITEMAP_URL_LIMIT = 2000;
|
|
38
|
+
const LLMS_TEXT_LIMIT = 4000;
|
|
39
|
+
const ROBOTS_TEXT_LIMIT = 16_000;
|
|
40
|
+
const PAGE_TEXT_LIMIT = 20_000;
|
|
41
|
+
const HTML_ASSET = /\.(?:png|jpe?g|gif|svg|webp|avif|ico|css|js|mjs|json|xml|txt|pdf|zip|gz|tgz|tar|mp4|webm|mov|mp3|wav|ogg|woff2?|ttf|eot|wasm|map)$/i;
|
|
42
|
+
|
|
43
|
+
const ROBOTS_HEADER_KEYS = [
|
|
44
|
+
'content-type',
|
|
45
|
+
'x-robots-tag',
|
|
46
|
+
'strict-transport-security',
|
|
47
|
+
'content-security-policy',
|
|
48
|
+
'x-content-type-options',
|
|
49
|
+
'referrer-policy',
|
|
50
|
+
'permissions-policy',
|
|
51
|
+
'link',
|
|
52
|
+
'last-modified',
|
|
53
|
+
'cache-control',
|
|
54
|
+
'vary',
|
|
55
|
+
];
|
|
56
|
+
|
|
57
|
+
function pickHeaders(headers) {
|
|
58
|
+
const picked = {};
|
|
59
|
+
for (const key of ROBOTS_HEADER_KEYS) {
|
|
60
|
+
if (headers[key] !== undefined) picked[key] = String(headers[key]).slice(0, 1000);
|
|
61
|
+
}
|
|
62
|
+
return picked;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function canonicalize(rawUrl) {
|
|
66
|
+
try {
|
|
67
|
+
const url = new URL(rawUrl);
|
|
68
|
+
url.hash = '';
|
|
69
|
+
if (url.pathname.endsWith('/index.html')) url.pathname = url.pathname.slice(0, -'index.html'.length);
|
|
70
|
+
return url.href;
|
|
71
|
+
} catch {
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function looksLikeHtml(contentType, body) {
|
|
77
|
+
if (/html|xhtml/i.test(contentType ?? '')) return true;
|
|
78
|
+
if (contentType) return false;
|
|
79
|
+
return /^\s*<(!doctype\s+html|html[\s>])/i.test(String(body ?? '').slice(0, 500));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function parseLocUrls(xml) {
|
|
83
|
+
const urls = [];
|
|
84
|
+
const pattern = /<loc>\s*([^<]+?)\s*<\/loc>/gi;
|
|
85
|
+
let match = pattern.exec(xml);
|
|
86
|
+
while (match && urls.length < SITEMAP_URL_LIMIT) {
|
|
87
|
+
const value = match[1].replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').trim();
|
|
88
|
+
if (/^https?:\/\//i.test(value)) urls.push(value);
|
|
89
|
+
match = pattern.exec(xml);
|
|
90
|
+
}
|
|
91
|
+
return urls;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function parseLlms(text) {
|
|
95
|
+
const body = String(text ?? '');
|
|
96
|
+
const lines = body.split(/\r?\n/);
|
|
97
|
+
const firstLine = lines.find((line) => line.trim().length > 0) ?? '';
|
|
98
|
+
const sections = lines.filter((line) => /^##\s+\S/.test(line));
|
|
99
|
+
const links = body.match(/\[[^\]]+\]\([^)]+\)/g) ?? [];
|
|
100
|
+
const bullets = lines.filter((line) => /^\s*[-*]\s+\S/.test(line));
|
|
101
|
+
return {
|
|
102
|
+
valid: /^#\s+\S/.test(firstLine.trim()) && (sections.length > 0 || links.length > 0),
|
|
103
|
+
hasTitle: /^#\s+\S/.test(firstLine.trim()),
|
|
104
|
+
sectionCount: sections.length,
|
|
105
|
+
linkCount: links.length,
|
|
106
|
+
bulletCount: bullets.length,
|
|
107
|
+
text: body.slice(0, LLMS_TEXT_LIMIT),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* A redirect may legitimately move a site to HTTPS or to its `www` host. It
|
|
113
|
+
* must not widen the audit to an unrelated domain: that both amplifies
|
|
114
|
+
* requests against third parties and makes the artifact's origin ambiguous.
|
|
115
|
+
*/
|
|
116
|
+
export function isSameSiteRedirect(fromOrigin, toOrigin) {
|
|
117
|
+
const from = new URL(fromOrigin);
|
|
118
|
+
const to = new URL(toOrigin);
|
|
119
|
+
const strip = (hostname) => hostname.toLowerCase().replace(/^www\./, '');
|
|
120
|
+
if (strip(from.hostname) !== strip(to.hostname)) return false;
|
|
121
|
+
if (from.port !== to.port) {
|
|
122
|
+
const isDefaultPort = (port) => port === '' || port === '80' || port === '443';
|
|
123
|
+
if (!isDefaultPort(from.port) || !isDefaultPort(to.port)) return false;
|
|
124
|
+
}
|
|
125
|
+
if (from.protocol === 'https:' && to.protocol === 'http:') return false;
|
|
126
|
+
return true;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Scan one site.
|
|
131
|
+
*
|
|
132
|
+
* @param {string} input Absolute http(s) URL of the site root or entry page.
|
|
133
|
+
* @param {object} [options] Overrides for SCAN_DEFAULTS plus `transport`.
|
|
134
|
+
* @returns {Promise<object>} JSON-serialisable scan artifact.
|
|
135
|
+
*/
|
|
136
|
+
export async function scanSite(input, options = {}) {
|
|
137
|
+
const settings = { ...SCAN_DEFAULTS, ...options };
|
|
138
|
+
// Defensive clamps: a bad option must not turn into an unbounded crawl.
|
|
139
|
+
settings.userAgent = settings.userAgent || SCAN_DEFAULTS.userAgent;
|
|
140
|
+
settings.maxPages = Math.max(1, Math.min(Math.trunc(Number(settings.maxPages) || SCAN_DEFAULTS.maxPages), 50));
|
|
141
|
+
settings.maxBytes = Math.max(1024, Math.trunc(Number(settings.maxBytes) || SCAN_DEFAULTS.maxBytes));
|
|
142
|
+
settings.timeoutMs = Math.max(100, Math.trunc(Number(settings.timeoutMs) || SCAN_DEFAULTS.timeoutMs));
|
|
143
|
+
const rateLimit = Number(settings.rateLimitMs);
|
|
144
|
+
settings.rateLimitMs = Math.max(0, Math.trunc(Number.isFinite(rateLimit) ? rateLimit : SCAN_DEFAULTS.rateLimitMs));
|
|
145
|
+
const startedAt = settings.now ? new Date(settings.now) : new Date();
|
|
146
|
+
if (!Number.isFinite(startedAt.getTime())) {
|
|
147
|
+
throw new Error(`scanSite received an invalid reference time: ${String(settings.now)}`);
|
|
148
|
+
}
|
|
149
|
+
const transport = options.transport ?? createTransport({
|
|
150
|
+
allowPrivate: settings.allowPrivate,
|
|
151
|
+
insecureTls: settings.insecureTls,
|
|
152
|
+
userAgent: settings.userAgent,
|
|
153
|
+
timeoutMs: settings.timeoutMs,
|
|
154
|
+
maxBytes: settings.maxBytes,
|
|
155
|
+
rateLimitMs: settings.rateLimitMs,
|
|
156
|
+
maxRedirects: settings.maxRedirects,
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
const errors = [];
|
|
160
|
+
const requested = { count: 0 };
|
|
161
|
+
|
|
162
|
+
const request = async (url, overrides = {}) => {
|
|
163
|
+
requested.count += 1;
|
|
164
|
+
try {
|
|
165
|
+
return await transport.fetch(url, { ...overrides, signal: settings.signal });
|
|
166
|
+
} catch (error) {
|
|
167
|
+
errors.push({ url, code: error?.code ?? 'FETCH_ERROR', message: error?.message ?? String(error) });
|
|
168
|
+
throw error;
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
const startUrl = canonicalize(input);
|
|
173
|
+
if (!startUrl) {
|
|
174
|
+
throw new Error(`scanSite needs an absolute http(s) URL, got: ${String(input)}`);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
let origin = new URL(startUrl).origin;
|
|
178
|
+
let robotsUrl = new URL('/robots.txt', origin).href;
|
|
179
|
+
let robotsText = '';
|
|
180
|
+
let robots = null;
|
|
181
|
+
let robotsFound = false;
|
|
182
|
+
let robotsStatus = 0;
|
|
183
|
+
let crawlDelay = settings.rateLimitMs;
|
|
184
|
+
|
|
185
|
+
async function loadRobots(targetOrigin) {
|
|
186
|
+
const url = new URL('/robots.txt', targetOrigin).href;
|
|
187
|
+
try {
|
|
188
|
+
const response = await request(url, { maxBytes: settings.robotsMaxBytes });
|
|
189
|
+
const isHtml = /html/i.test(response.contentType ?? '');
|
|
190
|
+
// An empty 200 robots.txt is valid and means "allow everything".
|
|
191
|
+
const usable = response.status === 200 && !isHtml;
|
|
192
|
+
return {
|
|
193
|
+
url,
|
|
194
|
+
status: response.status,
|
|
195
|
+
found: usable,
|
|
196
|
+
text: usable ? response.body.slice(0, ROBOTS_TEXT_LIMIT) : '',
|
|
197
|
+
parsed: usable ? parseRobots(response.body) : parseRobots(''),
|
|
198
|
+
contentType: response.contentType,
|
|
199
|
+
};
|
|
200
|
+
} catch {
|
|
201
|
+
return { url, status: 0, found: false, text: '', parsed: parseRobots(''), contentType: '' };
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
let loaded = await loadRobots(origin);
|
|
206
|
+
robotsUrl = loaded.url;
|
|
207
|
+
robotsStatus = loaded.status;
|
|
208
|
+
robotsFound = loaded.found;
|
|
209
|
+
robotsText = loaded.text;
|
|
210
|
+
robots = loaded.parsed;
|
|
211
|
+
crawlDelay = Math.max(settings.rateLimitMs, crawlDelayMs(robots, settings.userAgent));
|
|
212
|
+
|
|
213
|
+
// RFC 9309: a robots.txt that cannot be served (5xx) must be treated as a
|
|
214
|
+
// full disallow rather than as "no restrictions".
|
|
215
|
+
const robotsUnreachable = settings.respectRobots && (robotsStatus === 0 || robotsStatus >= 500);
|
|
216
|
+
const startAllowed = !settings.respectRobots
|
|
217
|
+
|| (!robotsUnreachable && isAllowed(robots, startUrl, settings.userAgent));
|
|
218
|
+
|
|
219
|
+
const artifact = {
|
|
220
|
+
version: SCAN_VERSION,
|
|
221
|
+
scannedAt: startedAt.toISOString(),
|
|
222
|
+
startUrl,
|
|
223
|
+
origin,
|
|
224
|
+
policy: {
|
|
225
|
+
respectRobots: settings.respectRobots,
|
|
226
|
+
maxPages: settings.maxPages,
|
|
227
|
+
maxBytes: settings.maxBytes,
|
|
228
|
+
timeoutMs: settings.timeoutMs,
|
|
229
|
+
rateLimitMs: settings.rateLimitMs,
|
|
230
|
+
userAgent: settings.userAgent,
|
|
231
|
+
allowPrivate: settings.allowPrivate,
|
|
232
|
+
signalProvided: Boolean(settings.signal),
|
|
233
|
+
},
|
|
234
|
+
robots: {
|
|
235
|
+
url: robotsUrl,
|
|
236
|
+
status: robotsStatus,
|
|
237
|
+
found: robotsFound,
|
|
238
|
+
blocksEverything: robotsFound ? blocksEverything(robots) : false,
|
|
239
|
+
aiCrawlers: robotsFound ? aiCrawlerPolicy(robots, new URL(startUrl).pathname) : [],
|
|
240
|
+
googlebot: robotsFound ? googlebotAccess(robots) : { allowed: true, imageAllowed: true },
|
|
241
|
+
crawlDelayMs: robotsFound ? crawlDelayMs(robots, settings.userAgent) : 0,
|
|
242
|
+
sitemapDeclarations: robots.sitemaps.slice(0, 10),
|
|
243
|
+
unreachable: robotsUnreachable,
|
|
244
|
+
text: robotsText,
|
|
245
|
+
},
|
|
246
|
+
sitemap: {
|
|
247
|
+
url: null,
|
|
248
|
+
status: 0,
|
|
249
|
+
found: false,
|
|
250
|
+
valid: false,
|
|
251
|
+
declaredInRobots: false,
|
|
252
|
+
urlCount: 0,
|
|
253
|
+
urls: [],
|
|
254
|
+
childSitemaps: 0,
|
|
255
|
+
foreignDeclarations: 0,
|
|
256
|
+
},
|
|
257
|
+
llms: {
|
|
258
|
+
url: new URL('/llms.txt', origin).href,
|
|
259
|
+
status: 0,
|
|
260
|
+
found: false,
|
|
261
|
+
valid: false,
|
|
262
|
+
hasTitle: false,
|
|
263
|
+
sectionCount: 0,
|
|
264
|
+
linkCount: 0,
|
|
265
|
+
text: '',
|
|
266
|
+
},
|
|
267
|
+
blockedByRobots: !startAllowed,
|
|
268
|
+
blockedReason: startAllowed ? null : robotsUnreachable ? 'robots-unreachable' : 'robots-disallow',
|
|
269
|
+
pages: [],
|
|
270
|
+
errors,
|
|
271
|
+
stats: { requested: 0, bytes: 0, pages: 0 },
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
if (!startAllowed) {
|
|
275
|
+
artifact.stats.requested = requested.count;
|
|
276
|
+
return artifact;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const robotsAllows = (url) => !settings.respectRobots || isAllowed(robots, url, settings.userAgent);
|
|
280
|
+
const applyCrawlDelay = () => {
|
|
281
|
+
if (!transport.settings || !Number.isFinite(transport.settings.rateLimitMs)) return;
|
|
282
|
+
// Honoured up to 5 s; a site cannot make an audit hang for minutes.
|
|
283
|
+
transport.settings.rateLimitMs = Math.max(
|
|
284
|
+
transport.settings.rateLimitMs,
|
|
285
|
+
Math.min(crawlDelay, 5000),
|
|
286
|
+
);
|
|
287
|
+
};
|
|
288
|
+
applyCrawlDelay();
|
|
289
|
+
const recordError = (url, code, message) => {
|
|
290
|
+
errors.push({ url, code, message });
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
const snapshotRobots = (extra = {}) => {
|
|
294
|
+
artifact.robots = {
|
|
295
|
+
url: robotsUrl,
|
|
296
|
+
status: robotsStatus,
|
|
297
|
+
found: robotsFound,
|
|
298
|
+
blocksEverything: robotsFound ? blocksEverything(robots) : false,
|
|
299
|
+
aiCrawlers: robotsFound ? aiCrawlerPolicy(robots, new URL(startUrl).pathname) : [],
|
|
300
|
+
googlebot: robotsFound ? googlebotAccess(robots) : { allowed: true, imageAllowed: true },
|
|
301
|
+
crawlDelayMs: robotsFound ? crawlDelayMs(robots, settings.userAgent) : 0,
|
|
302
|
+
sitemapDeclarations: robots.sitemaps.slice(0, 10),
|
|
303
|
+
unreachable: settings.respectRobots && (robotsStatus === 0 || robotsStatus >= 500),
|
|
304
|
+
text: robotsText,
|
|
305
|
+
...extra,
|
|
306
|
+
};
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Gate one URL against robots.txt. Moving to another origin (http -> https,
|
|
311
|
+
* apex -> www) reloads that origin's robots before anything is fetched from
|
|
312
|
+
* it; a 5xx/unreachable robots.txt denies the hop.
|
|
313
|
+
*/
|
|
314
|
+
async function allowByRobots(candidateUrl) {
|
|
315
|
+
if (!settings.respectRobots) return true;
|
|
316
|
+
const candidateOrigin = new URL(candidateUrl).origin;
|
|
317
|
+
if (candidateOrigin !== origin) {
|
|
318
|
+
const reloaded = await loadRobots(candidateOrigin);
|
|
319
|
+
origin = candidateOrigin;
|
|
320
|
+
robots = reloaded.parsed;
|
|
321
|
+
robotsUrl = reloaded.url;
|
|
322
|
+
robotsFound = reloaded.found;
|
|
323
|
+
robotsStatus = reloaded.status;
|
|
324
|
+
robotsText = reloaded.text;
|
|
325
|
+
crawlDelay = Math.max(settings.rateLimitMs, crawlDelayMs(robots, settings.userAgent));
|
|
326
|
+
applyCrawlDelay();
|
|
327
|
+
artifact.origin = origin;
|
|
328
|
+
snapshotRobots({ originChangedTo: origin });
|
|
329
|
+
if (reloaded.status === 0 || reloaded.status >= 500) return false;
|
|
330
|
+
}
|
|
331
|
+
if (robotsStatus === 0 || robotsStatus >= 500) return false;
|
|
332
|
+
return isAllowed(robots, candidateUrl, settings.userAgent);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Fetch a page while applying robots.txt to every redirect hop, and refusing
|
|
337
|
+
* cross-site redirects. Returns the final response plus the hop history.
|
|
338
|
+
*/
|
|
339
|
+
async function fetchPage(url, overrides = {}) {
|
|
340
|
+
let current = url;
|
|
341
|
+
const redirects = [];
|
|
342
|
+
for (let hop = 0; hop <= settings.maxRedirects; hop += 1) {
|
|
343
|
+
if (!(await allowByRobots(current))) {
|
|
344
|
+
recordError(current, 'FETCH_BLOCKED_ROBOTS', 'robots.txt disallows this redirect target');
|
|
345
|
+
throw new FetchError('FETCH_BLOCKED_ROBOTS', `robots.txt disallows ${current}`, { url: current });
|
|
346
|
+
}
|
|
347
|
+
const response = await request(current, { ...overrides, followRedirects: false });
|
|
348
|
+
if (!response.location) return { response, redirects };
|
|
349
|
+
const nextUrl = response.location;
|
|
350
|
+
const fromOrigin = new URL(current).origin;
|
|
351
|
+
const toOrigin = new URL(nextUrl).origin;
|
|
352
|
+
if (fromOrigin !== toOrigin && !isSameSiteRedirect(fromOrigin, toOrigin)) {
|
|
353
|
+
recordError(current, 'FETCH_CROSS_SITE_REDIRECT', `Refusing redirect to ${toOrigin}`);
|
|
354
|
+
throw new FetchError('FETCH_CROSS_SITE_REDIRECT', `Refusing cross-site redirect to ${nextUrl}`, { url: current });
|
|
355
|
+
}
|
|
356
|
+
redirects.push({ from: current, to: nextUrl, status: response.status });
|
|
357
|
+
current = nextUrl;
|
|
358
|
+
}
|
|
359
|
+
recordError(current, 'FETCH_TOO_MANY_REDIRECTS', `More than ${settings.maxRedirects} redirects`);
|
|
360
|
+
throw new FetchError('FETCH_TOO_MANY_REDIRECTS', 'Redirect loop', { url: url });
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// Sitemap: prefer a same-origin declaration, then /sitemap.xml.
|
|
364
|
+
const sitemapCandidates = [];
|
|
365
|
+
for (const declared of robots.sitemaps) {
|
|
366
|
+
try {
|
|
367
|
+
const parsed = new URL(declared, origin);
|
|
368
|
+
if (parsed.origin === origin) sitemapCandidates.push(parsed.href);
|
|
369
|
+
else artifact.sitemap.foreignDeclarations += 1;
|
|
370
|
+
} catch {
|
|
371
|
+
// Ignore malformed declarations.
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
artifact.sitemap.declaredInRobots = sitemapCandidates.length > 0;
|
|
375
|
+
sitemapCandidates.push(new URL('/sitemap.xml', origin).href);
|
|
376
|
+
|
|
377
|
+
const sitemapUrls = [];
|
|
378
|
+
let sitemapDeclaredUrl = null;
|
|
379
|
+
for (const candidate of sitemapCandidates.slice(0, 3)) {
|
|
380
|
+
if (!robotsAllows(candidate)) continue;
|
|
381
|
+
let response;
|
|
382
|
+
try {
|
|
383
|
+
response = await request(candidate, { maxBytes: settings.sitemapMaxBytes });
|
|
384
|
+
} catch {
|
|
385
|
+
continue;
|
|
386
|
+
}
|
|
387
|
+
if (response.status !== 200 || !/<(urlset|sitemapindex)/i.test(response.body)) continue;
|
|
388
|
+
sitemapDeclaredUrl = candidate;
|
|
389
|
+
artifact.sitemap.status = response.status;
|
|
390
|
+
artifact.sitemap.found = true;
|
|
391
|
+
artifact.sitemap.contentType = response.contentType;
|
|
392
|
+
const isIndex = /<sitemapindex/i.test(response.body);
|
|
393
|
+
artifact.sitemap.isIndex = isIndex;
|
|
394
|
+
let locs = parseLocUrls(response.body);
|
|
395
|
+
|
|
396
|
+
if (isIndex) {
|
|
397
|
+
const children = locs
|
|
398
|
+
.map((loc) => {
|
|
399
|
+
try {
|
|
400
|
+
return new URL(loc, origin).href;
|
|
401
|
+
} catch {
|
|
402
|
+
return null;
|
|
403
|
+
}
|
|
404
|
+
})
|
|
405
|
+
.filter((loc) => loc && new URL(loc).origin === origin)
|
|
406
|
+
.slice(0, 2);
|
|
407
|
+
artifact.sitemap.childSitemaps = children.length;
|
|
408
|
+
const collected = [];
|
|
409
|
+
for (const child of children) {
|
|
410
|
+
if (!robotsAllows(child)) continue;
|
|
411
|
+
try {
|
|
412
|
+
const childResponse = await request(child, { maxBytes: settings.sitemapMaxBytes });
|
|
413
|
+
if (childResponse.status === 200) collected.push(...parseLocUrls(childResponse.body));
|
|
414
|
+
} catch {
|
|
415
|
+
// A broken child sitemap should not abort the scan.
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
locs = collected;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
for (const loc of locs) {
|
|
422
|
+
try {
|
|
423
|
+
if (new URL(loc).origin === origin) sitemapUrls.push(canonicalize(loc));
|
|
424
|
+
} catch {
|
|
425
|
+
// Ignore malformed <loc> values.
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
break;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
artifact.sitemap.url = sitemapDeclaredUrl;
|
|
432
|
+
artifact.sitemap.valid = sitemapUrls.length > 0;
|
|
433
|
+
artifact.sitemap.urlCount = sitemapUrls.length;
|
|
434
|
+
const uniqueSitemapUrls = [...new Set(sitemapUrls)];
|
|
435
|
+
artifact.sitemap.urls = uniqueSitemapUrls.slice(0, SITEMAP_URL_LIMIT);
|
|
436
|
+
artifact.sitemap.urlsTruncated = sitemapUrls.length >= SITEMAP_URL_LIMIT
|
|
437
|
+
|| uniqueSitemapUrls.length > artifact.sitemap.urls.length;
|
|
438
|
+
|
|
439
|
+
// llms.txt: the machine-facing manifest for LLM agents. It is a normal
|
|
440
|
+
// resource, so robots.txt applies to it like to every other URL.
|
|
441
|
+
const llmsUrl = new URL('/llms.txt', origin).href;
|
|
442
|
+
if (!robotsAllows(llmsUrl)) {
|
|
443
|
+
artifact.llms = { ...artifact.llms, blockedByRobots: true };
|
|
444
|
+
} else {
|
|
445
|
+
try {
|
|
446
|
+
const response = await request(llmsUrl, { maxBytes: settings.llmsMaxBytes });
|
|
447
|
+
if (response.status === 200 && response.body.trim().length > 0 && !/html/i.test(response.contentType ?? '')) {
|
|
448
|
+
const parsed = parseLlms(response.body);
|
|
449
|
+
artifact.llms = {
|
|
450
|
+
url: llmsUrl,
|
|
451
|
+
status: response.status,
|
|
452
|
+
found: true,
|
|
453
|
+
...parsed,
|
|
454
|
+
};
|
|
455
|
+
} else {
|
|
456
|
+
artifact.llms.status = response.status;
|
|
457
|
+
}
|
|
458
|
+
} catch {
|
|
459
|
+
// Missing llms.txt is a finding, not a scan failure.
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// Crawl from the entry page, breadth-first, respecting robots for each fetch.
|
|
464
|
+
const queue = [{ url: startUrl, depth: 0 }];
|
|
465
|
+
const seen = new Set([startUrl]);
|
|
466
|
+
const pages = [];
|
|
467
|
+
|
|
468
|
+
while (queue.length > 0 && pages.length < settings.maxPages) {
|
|
469
|
+
if (settings.signal?.aborted) {
|
|
470
|
+
throw new FetchError('FETCH_ABORTED', 'Scan aborted', { url: startUrl });
|
|
471
|
+
}
|
|
472
|
+
const next = queue.shift();
|
|
473
|
+
if (!robotsAllows(next.url)) continue;
|
|
474
|
+
|
|
475
|
+
let pageResult;
|
|
476
|
+
try {
|
|
477
|
+
pageResult = await fetchPage(next.url, { maxBytes: settings.maxBytes });
|
|
478
|
+
} catch {
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
const { response } = pageResult;
|
|
482
|
+
const redirects = pageResult.redirects;
|
|
483
|
+
|
|
484
|
+
const finalUrl = canonicalize(response.url) ?? next.url;
|
|
485
|
+
const finalOrigin = new URL(finalUrl).origin;
|
|
486
|
+
|
|
487
|
+
if (pages.some((existing) => existing.url === finalUrl)) continue;
|
|
488
|
+
seen.add(finalUrl);
|
|
489
|
+
|
|
490
|
+
const contentType = response.contentType ?? '';
|
|
491
|
+
const isHtmlPage = looksLikeHtml(contentType, response.body);
|
|
492
|
+
const page = {
|
|
493
|
+
requestedUrl: next.url,
|
|
494
|
+
url: finalUrl,
|
|
495
|
+
path: new URL(finalUrl).pathname,
|
|
496
|
+
depth: next.depth,
|
|
497
|
+
status: response.status,
|
|
498
|
+
ok: response.status >= 200 && response.status < 300,
|
|
499
|
+
contentType,
|
|
500
|
+
bytes: response.bytes,
|
|
501
|
+
truncated: response.truncated,
|
|
502
|
+
redirects,
|
|
503
|
+
headers: pickHeaders(response.headers),
|
|
504
|
+
facts: null,
|
|
505
|
+
};
|
|
506
|
+
|
|
507
|
+
if (page.ok && isHtmlPage) {
|
|
508
|
+
let facts = null;
|
|
509
|
+
try {
|
|
510
|
+
facts = analyzeHtml(response.body, finalUrl);
|
|
511
|
+
if (facts.text.length > PAGE_TEXT_LIMIT) {
|
|
512
|
+
facts.text = `${facts.text.slice(0, PAGE_TEXT_LIMIT)}…`;
|
|
513
|
+
facts.textTruncated = true;
|
|
514
|
+
}
|
|
515
|
+
page.facts = facts;
|
|
516
|
+
} catch (error) {
|
|
517
|
+
page.factsError = `${error?.name ?? 'Error'}: ${error?.message ?? error}`.slice(0, 200);
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
if (facts && pages.length + 1 < settings.maxPages) {
|
|
521
|
+
const queueLimit = Math.max(50, settings.maxPages * 20);
|
|
522
|
+
for (const link of facts.internalLinks) {
|
|
523
|
+
if (queue.length >= queueLimit) break;
|
|
524
|
+
const target = canonicalize(link.href);
|
|
525
|
+
if (!target || seen.has(target)) continue;
|
|
526
|
+
const parsed = new URL(target);
|
|
527
|
+
if (parsed.origin !== origin && parsed.origin !== finalOrigin) continue;
|
|
528
|
+
if (HTML_ASSET.test(parsed.pathname)) continue;
|
|
529
|
+
seen.add(target);
|
|
530
|
+
queue.push({ url: target, depth: next.depth + 1 });
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
pages.push(page);
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// Fill leftover slots from the sitemap, in document order, still obeying robots.
|
|
539
|
+
if (pages.length < settings.maxPages && sitemapUrls.length > 0) {
|
|
540
|
+
for (const candidate of sitemapUrls) {
|
|
541
|
+
if (settings.signal?.aborted) {
|
|
542
|
+
throw new FetchError('FETCH_ABORTED', 'Scan aborted', { url: startUrl });
|
|
543
|
+
}
|
|
544
|
+
if (pages.length >= settings.maxPages) break;
|
|
545
|
+
const target = canonicalize(candidate);
|
|
546
|
+
if (!target || seen.has(target)) continue;
|
|
547
|
+
const parsed = new URL(target);
|
|
548
|
+
if (parsed.origin !== origin) continue;
|
|
549
|
+
if (HTML_ASSET.test(parsed.pathname)) continue;
|
|
550
|
+
seen.add(target);
|
|
551
|
+
if (!robotsAllows(target)) continue;
|
|
552
|
+
let pageResult;
|
|
553
|
+
try {
|
|
554
|
+
pageResult = await fetchPage(target, { maxBytes: settings.maxBytes });
|
|
555
|
+
} catch {
|
|
556
|
+
continue;
|
|
557
|
+
}
|
|
558
|
+
const { response } = pageResult;
|
|
559
|
+
const finalUrl = canonicalize(response.url) ?? target;
|
|
560
|
+
if (pages.some((existing) => existing.url === finalUrl)) continue;
|
|
561
|
+
const isHtmlPage = looksLikeHtml(response.contentType, response.body);
|
|
562
|
+
const page = {
|
|
563
|
+
requestedUrl: target,
|
|
564
|
+
url: finalUrl,
|
|
565
|
+
path: new URL(finalUrl).pathname,
|
|
566
|
+
depth: 1,
|
|
567
|
+
status: response.status,
|
|
568
|
+
ok: response.status >= 200 && response.status < 300,
|
|
569
|
+
contentType: response.contentType ?? '',
|
|
570
|
+
bytes: response.bytes,
|
|
571
|
+
truncated: response.truncated,
|
|
572
|
+
redirects: pageResult.redirects,
|
|
573
|
+
headers: pickHeaders(response.headers),
|
|
574
|
+
facts: null,
|
|
575
|
+
};
|
|
576
|
+
if (page.ok && isHtmlPage) {
|
|
577
|
+
try {
|
|
578
|
+
const facts = analyzeHtml(response.body, finalUrl);
|
|
579
|
+
if (facts.text.length > PAGE_TEXT_LIMIT) {
|
|
580
|
+
facts.text = `${facts.text.slice(0, PAGE_TEXT_LIMIT)}…`;
|
|
581
|
+
facts.textTruncated = true;
|
|
582
|
+
}
|
|
583
|
+
page.facts = facts;
|
|
584
|
+
} catch (error) {
|
|
585
|
+
page.factsError = `${error?.name ?? 'Error'}: ${error?.message ?? error}`.slice(0, 200);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
pages.push(page);
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
artifact.pages = pages;
|
|
593
|
+
artifact.errors = errors;
|
|
594
|
+
artifact.stats = {
|
|
595
|
+
requested: requested.count,
|
|
596
|
+
bytes: pages.reduce((sum, page) => sum + page.bytes, 0),
|
|
597
|
+
pages: pages.length,
|
|
598
|
+
};
|
|
599
|
+
artifact.fetchedOrigins = [...new Set(pages.map((page) => new URL(page.url).origin))];
|
|
600
|
+
|
|
601
|
+
return artifact;
|
|
602
|
+
}
|