@astratra/web-search 1.1.0 → 1.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.
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Le contrôle de chaque requête qu'une page fait partir du navigateur.
3
+ *
4
+ * - protocole : `https` (et `wss`) ; `http` (et `ws`) seulement avec
5
+ * `allowHttp`, et jamais pour la page elle-même ;
6
+ * - port : ceux de `ports` (443 par défaut ; 80 en plus avec `allowHttp`) ;
7
+ * - pas d'identifiants dans l'adresse ;
8
+ * - nom : refusé sans résolution s'il est interne (`localhost`, `*.internal`…,
9
+ * IP non publique), puis résolu ; si UNE de ses adresses n'est pas publique
10
+ * (mêmes plages que `isPublicAddress`), la requête est refusée.
11
+ *
12
+ * Le nom est résolu ici, puis encore par Chromium au moment de se connecter :
13
+ * un DNS qui changerait de réponse entre les deux (DNS rebinding) passerait ce
14
+ * contrôle. Seul le pare-feu système, obligatoire en production, couvre ce cas
15
+ * (et WebRTC) : ce contrôle est la deuxième ligne, pas la seule.
16
+ */
17
+
18
+ const dns = require('dns');
19
+ const net = require('net');
20
+ const { isPublicAddress, isBlockedHostname } = require('../address');
21
+
22
+ const SECURE = new Set(['https:', 'wss:']);
23
+ const PLAIN = new Set(['http:', 'ws:']);
24
+
25
+ function lookupAll(resolve, hostname) {
26
+ return new Promise((resolvePromise, reject) => {
27
+ resolve(hostname, { all: true, family: 0 }, (error, addresses) => {
28
+ if (error) return reject(error);
29
+ const list = (Array.isArray(addresses) ? addresses : [{ address: addresses }]).map((entry) => (typeof entry === 'string' ? entry : entry?.address)).filter(Boolean);
30
+ return resolvePromise(list);
31
+ });
32
+ });
33
+ }
34
+
35
+ /**
36
+ * @param {object} [options]
37
+ * @param {Function} [options.resolve] dns.lookup (remplaçable dans les tests).
38
+ * @param {number[]} [options.ports] Défaut [443] (et 80 avec allowHttp).
39
+ * @param {boolean} [options.allowHttp] Défaut false.
40
+ * @param {number} [options.dnsTtlMs] Défaut 60 s.
41
+ */
42
+ function createRequestGuard(options = {}) {
43
+ const resolve = options.resolve || dns.lookup;
44
+ const allowHttp = options.allowHttp === true;
45
+ const ports = new Set(options.ports || (allowHttp ? [443, 80] : [443]));
46
+ const dnsTtlMs = options.dnsTtlMs ?? 60_000;
47
+ const cache = new Map();
48
+
49
+ async function addressesOf(hostname) {
50
+ const cached = cache.get(hostname);
51
+ if (cached && cached.expires > Date.now()) return cached.job;
52
+ const job = lookupAll(resolve, hostname);
53
+ cache.set(hostname, { job, expires: Date.now() + dnsTtlMs });
54
+ job.catch(() => cache.delete(hostname));
55
+ if (cache.size > 2_000) cache.delete(cache.keys().next().value);
56
+ return job;
57
+ }
58
+
59
+ /**
60
+ * @param {string} value
61
+ * @param {{ document?: boolean }} [context] document : la page elle-même (https seulement).
62
+ * @returns {Promise<{ ok: true, url: URL } | { ok: false, reason: string }>}
63
+ */
64
+ async function check(value, context = {}) {
65
+ let url;
66
+ try {
67
+ url = new URL(String(value));
68
+ } catch (_error) {
69
+ return { ok: false, reason: 'invalid_url' };
70
+ }
71
+ const secure = SECURE.has(url.protocol);
72
+ if (!secure && !(PLAIN.has(url.protocol) && allowHttp && !context.document)) return { ok: false, reason: 'protocol' };
73
+ if (url.username || url.password) return { ok: false, reason: 'credentials' };
74
+ const port = url.port ? Number(url.port) : (secure ? 443 : 80);
75
+ if (!ports.has(port)) return { ok: false, reason: 'port' };
76
+ const hostname = url.hostname.replace(/^\[|\]$/g, '').toLowerCase().replace(/\.$/, '');
77
+ if (isBlockedHostname(hostname)) return { ok: false, reason: 'address' };
78
+ if (net.isIP(hostname)) return { ok: true, url };
79
+ let addresses;
80
+ try {
81
+ addresses = await addressesOf(hostname);
82
+ } catch (_error) {
83
+ return { ok: false, reason: 'dns' };
84
+ }
85
+ if (!addresses.length || addresses.some((address) => !isPublicAddress(address))) return { ok: false, reason: 'address' };
86
+ return { ok: true, url };
87
+ }
88
+
89
+ return { check };
90
+ }
91
+
92
+ module.exports = { createRequestGuard };
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Le contrôle d'isolement, au démarrage du service : depuis le processus du
3
+ * service (même utilisateur que Chromium, donc mêmes règles de pare-feu), on
4
+ * tente de joindre
5
+ * - la boucle locale, sur le port du service lui-même (il écoute : sans
6
+ * pare-feu, la connexion aboutit à coup sûr) ;
7
+ * - une adresse privée de la machine (port 22), ou 10.0.0.1 ;
8
+ * - les métadonnées du nuage, 169.254.169.254:80.
9
+ *
10
+ * Une sonde qui aboutit (connexion, ou refus du port par l'hôte joint) prouve
11
+ * que l'intérieur est joignable : le service refuse de démarrer
12
+ * (`isolation_failed`). Le pare-feu du pack jette ces paquets à la sortie : la
13
+ * connexion échoue (EPERM, ou délai dépassé : sur Linux, une demande TCP jetée
14
+ * en sortie attend son délai).
15
+ */
16
+
17
+ const net = require('net');
18
+ const os = require('os');
19
+
20
+ /** La première adresse IPv4 privée de la machine, s'il y en a une. */
21
+ function privateAddress() {
22
+ for (const entries of Object.values(os.networkInterfaces())) {
23
+ for (const entry of entries || []) {
24
+ if (entry.family !== 'IPv4' && entry.family !== 4) continue;
25
+ if (entry.internal) continue;
26
+ if (/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.)/.test(entry.address)) return entry.address;
27
+ }
28
+ }
29
+ return null;
30
+ }
31
+
32
+ /**
33
+ * Une sonde TCP.
34
+ * @returns {Promise<'reached'|'blocked'|'timeout'|'unreachable'>}
35
+ */
36
+ function probe({ host, port, timeoutMs, connect = net.connect }) {
37
+ return new Promise((resolve) => {
38
+ let settled = false;
39
+ const socket = connect({ host, port });
40
+ const finish = (outcome) => {
41
+ if (settled) return;
42
+ settled = true;
43
+ clearTimeout(timer);
44
+ socket.destroy();
45
+ resolve(outcome);
46
+ };
47
+ const timer = setTimeout(() => finish('timeout'), timeoutMs);
48
+ socket.once('connect', () => finish('reached'));
49
+ socket.once('error', (error) => {
50
+ const code = error?.code;
51
+ /* ECONNREFUSED : l'hôte a répondu (rien n'écoute là) : le paquet est passé. */
52
+ if (code === 'ECONNREFUSED' || code === 'ECONNRESET') return finish('reached');
53
+ if (code === 'EPERM' || code === 'EACCES') return finish('blocked');
54
+ return finish('unreachable');
55
+ });
56
+ });
57
+ }
58
+
59
+ /**
60
+ * @param {object} options
61
+ * @param {number} options.servicePort
62
+ * @param {number} [options.timeoutMs] Défaut 1 500.
63
+ * @param {{ name: string, host: string, port: number }[]} [options.targets] à la place des sondes par défaut.
64
+ * @param {Function} [options.connect] net.connect (tests).
65
+ * @returns {Promise<{ ok: boolean, checkedAt: string, probes: { name: string, host: string, port: number, outcome: string }[] }>}
66
+ */
67
+ async function checkIsolation(options = {}) {
68
+ const timeoutMs = options.timeoutMs ?? 1_500;
69
+ const targets = options.targets || [
70
+ { name: 'loopback', host: '127.0.0.1', port: options.servicePort },
71
+ { name: 'private', host: privateAddress() || '10.0.0.1', port: 22 },
72
+ { name: 'metadata', host: '169.254.169.254', port: 80 }
73
+ ];
74
+ const probes = await Promise.all(targets.map(async (target) => ({
75
+ ...target,
76
+ outcome: await probe({ host: target.host, port: target.port, timeoutMs, connect: options.connect })
77
+ })));
78
+ return { ok: probes.every((entry) => entry.outcome !== 'reached'), checkedAt: new Date().toISOString(), probes };
79
+ }
80
+
81
+ module.exports = { checkIsolation, privateAddress };
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Le script exécuté dans la page, une fois rendue. Il ne clique sur rien, ne
3
+ * tape rien, n'envoie rien : il masque et il lit.
4
+ *
5
+ * 1. Les surcouches fixes (bandeaux de cookies, fenêtres d'abonnement,
6
+ * boîtes modales) sont masquées, et le défilement bloqué est rendu.
7
+ * 2. Le texte caché est retiré : élément invisible (`display`, `visibility`,
8
+ * `opacity` de lui ou d'un parent, `content-visibility`), de taille nulle ou
9
+ * d'un pixel (texte « sr-only »), hors de l'écran, découpé à rien
10
+ * (`clip`, `clip-path`), police de moins d'un pixel, couleur transparente
11
+ * ou identique au fond, `aria-hidden`, `hidden`. Un texte caché est l'arme
12
+ * classique pour glisser un ordre à une IA : il ne doit pas être lu.
13
+ * 3. Le texte visible (`innerText` après masquage), les liens visibles, les
14
+ * descriptions OpenSearch et les formulaires de recherche sont rendus.
15
+ *
16
+ * Doit rester autonome : Playwright le sérialise et l'exécute dans la page.
17
+ */
18
+
19
+ /* global window, document, NodeFilter -- exécuté dans Chromium */
20
+ function readRenderedPage(limits) {
21
+ const MAX_ELEMENTS = limits.maxElements;
22
+ const MAX_TEXT = limits.maxTextChars;
23
+ const view = { width: window.innerWidth || 1280, height: window.innerHeight || 800 };
24
+ const viewArea = view.width * view.height;
25
+ let overlays = 0;
26
+ let hidden = 0;
27
+
28
+ const hide = (element) => {
29
+ element.setAttribute('data-astratra-hidden', '');
30
+ element.style.setProperty('display', 'none', 'important');
31
+ };
32
+
33
+ /* 1. Surcouches fixes : grandes, ou nommées comme un bandeau / une fenêtre. */
34
+ const overlayWords = /(cookie|consent|gdpr|rgpd|cmp|onetrust|didomi|tarteaucitron|axeptio|orejime|klaro|cookiebot|cookieyes|iubenda|complianz|cmplz|osano|trustarc|termly|usercentrics|newsletter|subscribe|abonn|paywall|modal|popup|pop-up|overlay|lightbox|interstitial|dialog)/i;
35
+ const all = Array.from(document.body ? document.body.querySelectorAll('*') : []).slice(0, MAX_ELEMENTS);
36
+ for (const element of all) {
37
+ const style = window.getComputedStyle(element);
38
+ if (style.position !== 'fixed' && style.position !== 'sticky') continue;
39
+ if (style.display === 'none') continue;
40
+ const rect = element.getBoundingClientRect();
41
+ const area = Math.max(0, Math.min(rect.right, view.width) - Math.max(rect.left, 0)) * Math.max(0, Math.min(rect.bottom, view.height) - Math.max(rect.top, 0));
42
+ const named = overlayWords.test(`${element.id} ${typeof element.className === 'string' ? element.className : ''} ${element.getAttribute('role') || ''} ${element.getAttribute('aria-label') || ''}`)
43
+ || element.getAttribute('aria-modal') === 'true';
44
+ const big = area >= viewArea * 0.3;
45
+ if ((style.position === 'fixed' && (big || named)) || (style.position === 'sticky' && named && big)) {
46
+ hide(element);
47
+ overlays += 1;
48
+ }
49
+ }
50
+ /* Bandeaux de consentement qui ne sont pas fixes (en tête de page, boîte <dialog>) : nommés comme tels, et courts. */
51
+ const consentWords = /(cookie|consent|gdpr|rgpd|onetrust|didomi|tarteaucitron|axeptio|orejime|klaro|cookiebot|cookieyes|iubenda|complianz|cmplz|osano|trustarc|termly|usercentrics|sp_message|qc-cmp)/i;
52
+ for (const element of all) {
53
+ if (element.hasAttribute('data-astratra-hidden') || element.closest('[data-astratra-hidden]')) continue;
54
+ const label = `${element.id} ${typeof element.className === 'string' ? element.className : ''} ${element.getAttribute('aria-label') || ''}`;
55
+ if (!consentWords.test(label)) continue;
56
+ if (element.matches('main, article, body, html') || element.querySelector('main, article')) continue;
57
+ if ((element.textContent || '').length > 3000) continue;
58
+ /* Un bandeau propose un choix ; une section qui parle des cookies, non. */
59
+ if (!element.querySelector('button, [role="button"], input[type="button"], input[type="submit"]')) continue;
60
+ hide(element);
61
+ overlays += 1;
62
+ }
63
+ for (const dialog of Array.from(document.querySelectorAll('dialog[open], [role="dialog"][aria-modal="true"], [role="alertdialog"]'))) {
64
+ if (dialog.closest('[data-astratra-hidden]')) continue;
65
+ hide(dialog);
66
+ overlays += 1;
67
+ }
68
+ for (const root of [document.documentElement, document.body]) {
69
+ if (!root) continue;
70
+ root.style.setProperty('overflow', 'visible', 'important');
71
+ root.style.setProperty('position', 'static', 'important');
72
+ }
73
+
74
+ /* 2. Texte caché. */
75
+ const parseColor = (value) => {
76
+ const match = /rgba?\(([^)]+)\)/.exec(value || '');
77
+ if (!match) return null;
78
+ const parts = match[1].split(/[\s,/]+/).filter(Boolean).map(Number);
79
+ return { r: parts[0], g: parts[1], b: parts[2], a: parts.length > 3 ? parts[3] : 1 };
80
+ };
81
+ const backgroundOf = (element) => {
82
+ for (let node = element; node && node.nodeType === 1; node = node.parentElement) {
83
+ const color = parseColor(window.getComputedStyle(node).backgroundColor);
84
+ if (color && color.a > 0.9) return color;
85
+ if (window.getComputedStyle(node).backgroundImage !== 'none') return null;
86
+ }
87
+ return { r: 255, g: 255, b: 255, a: 1 };
88
+ };
89
+ const isHidden = (element) => {
90
+ if (element.closest('[aria-hidden="true"], [hidden], [inert]')) return true;
91
+ if (typeof element.checkVisibility === 'function'
92
+ && !element.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true, contentVisibilityAuto: true })) return true;
93
+ const style = window.getComputedStyle(element);
94
+ if (parseFloat(style.fontSize) < 1) return true;
95
+ const rects = element.getClientRects();
96
+ if (!rects.length) return true;
97
+ let visible = false;
98
+ for (const rect of rects) {
99
+ if (rect.width <= 1 || rect.height <= 1) continue;
100
+ const scrollX = window.scrollX;
101
+ const scrollY = window.scrollY;
102
+ if (rect.right + scrollX <= 0 || rect.bottom + scrollY <= 0) continue;
103
+ if (rect.left + scrollX >= Math.max(document.documentElement.scrollWidth, view.width) + 50) continue;
104
+ visible = true;
105
+ break;
106
+ }
107
+ if (!visible) return true;
108
+ for (let node = element; node && node.nodeType === 1; node = node.parentElement) {
109
+ const nodeStyle = node === element ? style : window.getComputedStyle(node);
110
+ if (nodeStyle.clip && /rect\(\s*0(px)?[\s,]+0(px)?[\s,]+0(px)?[\s,]+0(px)?\s*\)/.test(nodeStyle.clip)) return true;
111
+ if (nodeStyle.clipPath && /inset\(\s*(50%|100%)/.test(nodeStyle.clipPath)) return true;
112
+ if (nodeStyle.clipPath && /circle\(\s*0/.test(nodeStyle.clipPath)) return true;
113
+ if (node !== element && nodeStyle.overflow !== 'visible') {
114
+ const box = node.getBoundingClientRect();
115
+ if (box.width <= 1 || box.height <= 1) return true;
116
+ }
117
+ }
118
+ const color = parseColor(style.color);
119
+ if (color && color.a < 0.1) return true;
120
+ const textFill = parseColor(style.webkitTextFillColor);
121
+ if (textFill && textFill.a < 0.1) return true;
122
+ const background = backgroundOf(element);
123
+ if (color && background && Math.abs(color.r - background.r) + Math.abs(color.g - background.g) + Math.abs(color.b - background.b) < 24) return true;
124
+ return false;
125
+ };
126
+ const withText = new Set();
127
+ const walker = document.createTreeWalker(document.body || document.documentElement, NodeFilter.SHOW_TEXT);
128
+ let steps = 0;
129
+ for (let node = walker.nextNode(); node && steps < MAX_ELEMENTS * 4; node = walker.nextNode()) {
130
+ steps += 1;
131
+ if (!node.nodeValue || !node.nodeValue.trim()) continue;
132
+ const parent = node.parentElement;
133
+ if (!parent || ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE'].includes(parent.tagName)) continue;
134
+ withText.add(parent);
135
+ }
136
+ const toHide = [];
137
+ for (const element of withText) {
138
+ if (element.closest('[data-astratra-hidden]')) continue;
139
+ if (isHidden(element)) toHide.push(element);
140
+ }
141
+ for (const element of toHide) {
142
+ hide(element);
143
+ hidden += 1;
144
+ }
145
+
146
+ /* 3. Ce que la page montre. */
147
+ let text = (document.body ? document.body.innerText : '') || '';
148
+ text = text.replace(/\u00a0/g, ' ').replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim();
149
+ const textTruncated = text.length > MAX_TEXT;
150
+ if (textTruncated) text = text.slice(0, MAX_TEXT);
151
+
152
+ const links = [];
153
+ const seen = new Set();
154
+ for (const anchor of Array.from(document.querySelectorAll('a[href]')).slice(0, MAX_ELEMENTS)) {
155
+ if (anchor.closest('[data-astratra-hidden]')) continue;
156
+ let href;
157
+ try {
158
+ const url = new URL(anchor.href, document.baseURI);
159
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') continue;
160
+ url.hash = '';
161
+ href = url.href;
162
+ } catch (_error) {
163
+ continue;
164
+ }
165
+ if (seen.has(href)) continue;
166
+ const label = (anchor.innerText || anchor.getAttribute('aria-label') || anchor.getAttribute('title') || '').replace(/\s+/g, ' ').trim();
167
+ if (!label) continue;
168
+ if (isHidden(anchor)) continue;
169
+ seen.add(href);
170
+ links.push({ url: href, text: label.slice(0, 120) });
171
+ if (links.length >= limits.maxLinksScanned) break;
172
+ }
173
+
174
+ const openSearch = Array.from(document.querySelectorAll('link[rel~="search"][href]'))
175
+ .filter((link) => String(link.getAttribute('type') || '').toLowerCase().startsWith('application/opensearchdescription+xml'))
176
+ .map((link) => link.href)
177
+ .slice(0, 3);
178
+
179
+ const forms = [];
180
+ for (const form of Array.from(document.querySelectorAll('form')).slice(0, 20)) {
181
+ const fields = [];
182
+ for (const field of Array.from(form.elements).slice(0, 40)) {
183
+ const tag = field.tagName;
184
+ if (tag === 'INPUT') {
185
+ const type = String(field.getAttribute('type') || '').toLowerCase();
186
+ if (['submit', 'button', 'image', 'reset'].includes(type)) continue;
187
+ fields.push({ name: field.name || '', type, value: type === 'hidden' || type === 'checkbox' || type === 'radio' ? field.value : '', checked: Boolean(field.checked) });
188
+ } else if (tag === 'SELECT') {
189
+ fields.push({ name: field.name || '', type: 'select', value: field.value });
190
+ } else if (tag === 'TEXTAREA') {
191
+ fields.push({ name: field.name || '', type: 'textarea', value: '' });
192
+ }
193
+ }
194
+ forms.push({
195
+ action: form.getAttribute('action') ? form.action : '',
196
+ method: String(form.getAttribute('method') || 'get').toLowerCase(),
197
+ searchRole: form.getAttribute('role') === 'search' || Boolean(form.closest('[role="search"], search')),
198
+ fields
199
+ });
200
+ }
201
+
202
+ return {
203
+ title: (document.title || '').replace(/\s+/g, ' ').trim().slice(0, 300),
204
+ lang: document.documentElement.getAttribute('lang') || null,
205
+ text,
206
+ textTruncated,
207
+ links,
208
+ openSearch,
209
+ forms,
210
+ removed: { overlays, hidden }
211
+ };
212
+ }
213
+
214
+ module.exports = { readRenderedPage };
@@ -0,0 +1,167 @@
1
+ /**
2
+ * `robots.txt` (RFC 9309) pour le navigateur intégré.
3
+ *
4
+ * - Le groupe retenu est celui dont une ligne `User-agent` est le jeton de
5
+ * l'agent (`AstratraWebBrowser`, sans tenir compte de la casse) ; sinon le
6
+ * groupe `*` ; sinon tout est permis. Plusieurs groupes du même agent se
7
+ * cumulent.
8
+ * - La règle qui correspond le plus longuement au chemin l'emporte ; à
9
+ * longueur égale, `Allow` l'emporte. `*` vaut n'importe quelle suite de
10
+ * caractères, `$` la fin du chemin. `/robots.txt` est toujours permis.
11
+ * - Lecture : 2xx → les règles ; 4xx (sauf 429) → tout est permis ; 5xx, 429
12
+ * ou panne → tout est interdit (le site est peut-être en difficulté, on ne
13
+ * le parcourt pas à l'aveugle). Au plus 500 Kio lus.
14
+ *
15
+ * Le réseau est injecté (`fetchRobots`) : ce module ne lit rien lui-même.
16
+ */
17
+
18
+ const MAX_BYTES = 500 * 1024;
19
+ const AGENT_TOKEN = 'AstratraWebBrowser';
20
+
21
+ /** Le chemin et la requête d'une adresse, encodés comme dans robots.txt. */
22
+ function pathOf(url) {
23
+ return `${url.pathname || '/'}${url.search || ''}`;
24
+ }
25
+
26
+ /* Les octets non réservés sont décodés, pour comparer « %7E » et « ~ » ; le reste garde son encodage, en majuscules. */
27
+ function normalizePath(path) {
28
+ return String(path).replace(/%([0-9a-fA-F]{2})/g, (whole, hex) => {
29
+ const code = parseInt(hex, 16);
30
+ const char = String.fromCharCode(code);
31
+ return /[A-Za-z0-9\-._~]/.test(char) ? char : `%${hex.toUpperCase()}`;
32
+ }).replace(/[^\x21-\x7e]/g, (char) => encodeURIComponent(char));
33
+ }
34
+
35
+ /**
36
+ * Lit le texte d'un robots.txt.
37
+ * @returns {{ groups: { agents: string[], rules: { allow: boolean, path: string }[] }[] }}
38
+ */
39
+ function parseRobots(text) {
40
+ const groups = [];
41
+ let current = null;
42
+ let lastWasAgent = false;
43
+ for (const rawLine of String(text ?? '').slice(0, MAX_BYTES).split(/\r\n|\r|\n/)) {
44
+ const line = rawLine.replace(/#.*$/, '').trim();
45
+ if (!line) continue;
46
+ const colon = line.indexOf(':');
47
+ if (colon === -1) continue;
48
+ const key = line.slice(0, colon).trim().toLowerCase();
49
+ const value = line.slice(colon + 1).trim();
50
+ if (key === 'user-agent') {
51
+ if (!lastWasAgent || !current) {
52
+ current = { agents: [], rules: [] };
53
+ groups.push(current);
54
+ }
55
+ current.agents.push(value.toLowerCase());
56
+ lastWasAgent = true;
57
+ continue;
58
+ }
59
+ lastWasAgent = false;
60
+ if (!current) continue;
61
+ if (key === 'allow' || key === 'disallow') {
62
+ /* « Disallow: » vide ne dit rien : tout reste permis. */
63
+ if (!value) continue;
64
+ current.rules.push({ allow: key === 'allow', path: normalizePath(value) });
65
+ }
66
+ }
67
+ return { groups };
68
+ }
69
+
70
+ /** Le motif d'une règle en expression régulière (ancrée au début). */
71
+ function patternOf(path) {
72
+ const anchored = path.endsWith('$');
73
+ const body = (anchored ? path.slice(0, -1) : path)
74
+ .split('*')
75
+ .map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&'))
76
+ .join('.*');
77
+ return new RegExp(`^${body}${anchored ? '$' : ''}`);
78
+ }
79
+
80
+ /** Les règles qui s'appliquent à un agent (jeton exact, sinon `*`). */
81
+ function rulesFor(parsed, token = AGENT_TOKEN) {
82
+ const wanted = token.toLowerCase();
83
+ const own = parsed.groups.filter((group) => group.agents.includes(wanted));
84
+ const chosen = own.length ? own : parsed.groups.filter((group) => group.agents.includes('*'));
85
+ return chosen.flatMap((group) => group.rules);
86
+ }
87
+
88
+ /**
89
+ * Vrai si l'agent peut ouvrir cette adresse.
90
+ * @param {object} parsed parseRobots(…), ou { allowAll: true } / { disallowAll: true }.
91
+ * @param {string|URL} target
92
+ */
93
+ function robotsAllows(parsed, target, token = AGENT_TOKEN) {
94
+ if (parsed?.allowAll) return true;
95
+ if (parsed?.disallowAll) return false;
96
+ const url = target instanceof URL ? target : new URL(String(target));
97
+ const path = normalizePath(pathOf(url));
98
+ if (url.pathname === '/robots.txt') return true;
99
+ let best = null;
100
+ for (const rule of rulesFor(parsed, token)) {
101
+ if (!patternOf(rule.path).test(path)) continue;
102
+ const length = rule.path.replace(/\$$/, '').length;
103
+ if (!best || length > best.length || (length === best.length && rule.allow && !best.allow)) best = { length, allow: rule.allow };
104
+ }
105
+ return best ? best.allow : true;
106
+ }
107
+
108
+ /**
109
+ * Un cache de robots.txt par origine.
110
+ * @param {object} options
111
+ * @param {(url: string, ctx: { signal?: AbortSignal }) => Promise<{ status: number, body: string }>} options.fetchRobots
112
+ * lève sur une panne réseau.
113
+ * @param {number} [options.ttlMs] Défaut une heure.
114
+ * @param {number} [options.errorTtlMs] pour un robots.txt illisible. Défaut 10 min.
115
+ * @param {number} [options.maxEntries] Défaut 1 000.
116
+ * @param {string} [options.token]
117
+ * @param {Function} [options.now]
118
+ */
119
+ function createRobotsCache(options = {}) {
120
+ if (typeof options.fetchRobots !== 'function') throw new TypeError('createRobotsCache needs fetchRobots.');
121
+ const ttlMs = options.ttlMs ?? 3_600_000;
122
+ const errorTtlMs = options.errorTtlMs ?? 600_000;
123
+ const maxEntries = options.maxEntries ?? 1_000;
124
+ const token = options.token || AGENT_TOKEN;
125
+ const now = options.now || Date.now;
126
+ const entries = new Map();
127
+ const pending = new Map();
128
+
129
+ async function load(origin, signal) {
130
+ try {
131
+ const answer = await options.fetchRobots(`${origin}/robots.txt`, { signal });
132
+ const status = Number(answer?.status) || 0;
133
+ if (status >= 200 && status < 300) return { rules: parseRobots(String(answer.body ?? '').slice(0, MAX_BYTES)), ttl: ttlMs };
134
+ if (status >= 400 && status < 500 && status !== 429) return { rules: { allowAll: true }, ttl: ttlMs };
135
+ return { rules: { disallowAll: true, unavailable: true }, ttl: errorTtlMs };
136
+ } catch (_error) {
137
+ if (signal?.aborted) throw signal.reason;
138
+ return { rules: { disallowAll: true, unavailable: true }, ttl: errorTtlMs };
139
+ }
140
+ }
141
+
142
+ async function rulesOf(origin, signal) {
143
+ const cached = entries.get(origin);
144
+ if (cached && cached.expires > now()) return cached.rules;
145
+ if (pending.has(origin)) return pending.get(origin);
146
+ const job = load(origin, signal).then(({ rules, ttl }) => {
147
+ if (entries.size >= maxEntries) entries.delete(entries.keys().next().value);
148
+ entries.set(origin, { rules, expires: now() + ttl });
149
+ return rules;
150
+ }).finally(() => pending.delete(origin));
151
+ pending.set(origin, job);
152
+ return job;
153
+ }
154
+
155
+ /**
156
+ * @returns {Promise<{ allowed: boolean, unavailable?: boolean }>}
157
+ */
158
+ async function check(target, { signal } = {}) {
159
+ const url = target instanceof URL ? target : new URL(String(target));
160
+ const rules = await rulesOf(url.origin, signal);
161
+ return { allowed: robotsAllows(rules, url, token), ...(rules.unavailable ? { unavailable: true } : {}) };
162
+ }
163
+
164
+ return { check, clear: () => entries.clear(), size: () => entries.size };
165
+ }
166
+
167
+ module.exports = { parseRobots, robotsAllows, createRobotsCache, ROBOTS_AGENT_TOKEN: AGENT_TOKEN };