Elffuss BraidHub

utopia-ia/elffuss-code public

main · 8.5 KiBRawPermalink
1// web.fetch y web.search dicen POR QUÉ no pueden, en vez de callarlo.
2//
3// En producción el servidor no tiene ruta /proxy (nginx contesta 404): los
4// sitios sin CORS no se pueden leer y DuckDuckGo tampoco. Antes web.fetch daba
5// «HTTP 404» a secas (se lee como «esa página no existe») y web.search tragaba
6// los dos fallos y contestaba «Sin resultados», como si no hubiera nada. Ahora:
7// 1. sin proxy (404): las dos lo dicen, con la causa;
8// 2. el proxy falla (502): se dice que falló el proxy;
9// 3. DuckDuckGo pide su verificación anti-bot: es un bloqueo, no una lista vacía;
10// 4. con resultados, los da (y «Sin resultados» solo cuando el buscador
11// contestó y no encontró nada);
12// 5. un sitio con CORS se lee directo, sin pasar por el proxy;
13// 6-8. y sin decir más de lo que se sabe: el 404 del propio sitio es que la
14// página no existe; un fetch fallido sin respuesta no distingue «sin CORS»
15// de «no se pudo conectar», y no se afirma que la página exista.
16// Todo con page.route: ninguna petición sale a internet.
17//
18// BASE=http://localhost:8799 node tests/web-honest.mjs
19import { chromium } from 'playwright';
20const BASE = process.env.BASE || 'http://localhost:8799';
21let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + String(e).replace(/\n/g, ' ').slice(0, 150) : '')); if (!c) fails++; };
22
23const RESULTADOS = `<html><body><table>
24<tr><td><a href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fdeveloper.mozilla.org%2Fes%2Fdocs%2FArray%2Fmap&rut=x">Array.prototype.map() - JavaScript | MDN</a></td></tr>
25<tr><td>El método map() crea un nuevo array con los resultados.</td></tr>
26</table></body></html>`;
27const VACIO = '<html><body><table><tr><td>No results.</td></tr></table></body></html>';
28const ANTIBOT = '<html><body><div class="anomaly-modal__title">Unfortunately, bots use DuckDuckGo too.</div></body></html>';
29
30const b = await chromium.launch();
31async function escenario(proxy, { directoCORS = false, sitio = null } = {}) {
32 const ctx = await b.newContext();
33 const p = await ctx.newPage();
34 const alProxy = [];
35 // Los sitios de fuera: sin CORS (el fetch directo falla), salvo que se diga.
36 // `sitio` contesta en su lugar (un 404 propio, un dominio que no resuelve…).
37 await p.route(/^https:\/\/(example\.com|html\.duckduckgo\.com|lite\.duckduckgo\.com|cors-site\.example|no-such-host\.invalid)\//, r => sitio
38 ? sitio(r)
39 : directoCORS
40 ? r.fulfill({ status: 200, contentType: 'text/html', headers: { 'access-control-allow-origin': '*' }, body: '<html><body><p>Example Domain directo</p></body></html>' })
41 : r.abort('failed'));
42 await p.route('**/proxy?url=*', r => { alProxy.push(decodeURIComponent(r.request().url().split('url=')[1] || '')); return proxy(r); });
43 await p.goto(BASE + '/manifest.json');
44 const llama = (que, args) => p.evaluate(async ({ que, args }) => {
45 const web = await import('/js/tools/web.js');
46 try { return { ok: true, out: await (que === 'search' ? web.search(args) : web.fetchUrl(args)) }; }
47 catch (e) { return { ok: false, out: String(e.message || e) }; }
48 }, { que, args });
49 return { ctx, alProxy, llama };
50}
51
52// 1 · sin proxy en el servidor (lo de producción hoy)
53{
54 const { ctx, llama } = await escenario(r => r.fulfill({ status: 404, contentType: 'text/html', body: '<h1>404 Not Found</h1>' }));
55 const f = await llama('fetch', { url: 'https://example.com' });
56 ok('1 · web.fetch sin proxy: falla diciendo que el servidor no tiene el proxy', !f.ok && /no tiene el proxy de respaldo/.test(f.out) && /404/.test(f.out), f.out);
57 // Desde el navegador un fetch fallido no distingue «sin CORS» de «no existe»:
58 // se dicen las dos posibilidades y no se afirma que la página exista.
59 ok(' …sin afirmar que la página exista: CORS o sin conexión, no se distingue',
60 /CORS/.test(f.out) && /no se pudiera conectar/.test(f.out) && /no dice nada de si la página existe/.test(f.out) && !/No es que la página no exista/.test(f.out), f.out);
61 const s = await llama('search', { query: 'mdn array map' });
62 ok('1 · web.search sin proxy: falla con la causa, NO «Sin resultados»', !s.ok && /no tiene el proxy de respaldo/.test(s.out) && !/Sin resultados/.test(s.out), s.out);
63 await ctx.close();
64}
65// 2 · el proxy existe pero falla
66{
67 const { ctx, llama } = await escenario(r => r.fulfill({ status: 502, contentType: 'text/plain', body: 'proxy: timed out' }));
68 const f = await llama('fetch', { url: 'https://example.com' });
69 ok('2 · el proxy falla: se dice que falló el proxy (HTTP 502)', !f.ok && /proxy del servidor \(HTTP 502\)/.test(f.out), f.out);
70 await ctx.close();
71}
72// 3 · DuckDuckGo pide la verificación anti-bot
73{
74 const { ctx, llama } = await escenario(r => r.fulfill({ status: 202, contentType: 'text/html', body: ANTIBOT }));
75 const s = await llama('search', { query: 'mdn array map' });
76 ok('3 · la verificación anti-bot es un bloqueo, no «Sin resultados»', !s.ok && /bloqueó la consulta/.test(s.out) && !/Sin resultados/.test(s.out), s.out);
77 await ctx.close();
78}
79// 4 · con resultados, y vacío de verdad
80{
81 const { ctx, llama } = await escenario(r => r.fulfill({ status: 200, contentType: 'text/html', body: RESULTADOS }));
82 const s = await llama('search', { query: 'mdn array map' });
83 ok('4 · con resultados: los da, con su URL', s.ok && /Resultados para «mdn array map»/.test(s.out) && /developer\.mozilla\.org/.test(s.out), s.out);
84 await ctx.close();
85 const v = await escenario(r => r.fulfill({ status: 200, contentType: 'text/html', body: VACIO }));
86 const sv = await v.llama('search', { query: 'xyzzy-nada' });
87 ok('4 · y «Sin resultados» cuando el buscador contestó y no encontró nada', sv.ok && /Sin resultados para «xyzzy-nada»/.test(sv.out), sv.out);
88 await v.ctx.close();
89}
90// 5 · un sitio con CORS se lee directo
91{
92 const { ctx, alProxy, llama } = await escenario(r => r.fulfill({ status: 404, body: '' }), { directoCORS: true });
93 const f = await llama('fetch', { url: 'https://example.com' });
94 ok('5 · con CORS se lee directo y el proxy ni se toca', f.ok && /Example Domain directo/.test(f.out) && alProxy.length === 0, `${f.out} · proxy ${alProxy.length}`);
95 await ctx.close();
96}
97// 6 · el sitio contesta él mismo un 404 (con CORS se ve): la página NO existe, y
98// eso es lo que se dice. Antes, con /proxy en 404, decía «CORS» y «no es que la
99// página no exista».
100{
101 const sinProxy = r => r.fulfill({ status: 404, contentType: 'text/html', body: '<h1>404 Not Found</h1>' });
102 const { ctx, alProxy, llama } = await escenario(sinProxy, {
103 sitio: r => r.fulfill({ status: 404, contentType: 'text/html', headers: { 'access-control-allow-origin': '*' }, body: 'Not Found' }),
104 });
105 const f = await llama('fetch', { url: 'https://cors-site.example/no-such-page' });
106 ok('6 · el 404 del propio sitio: dice que esa página no existe, sin hablar de CORS', !f.ok && /respondió HTTP 404/.test(f.out) && /no existe/.test(f.out) && !/CORS/.test(f.out) && !/No es que/.test(f.out), f.out);
107 ok(' …y ni pregunta al proxy (la respuesta del sitio ya es la que es)', alProxy.length === 0, `proxy ${alProxy.length}`);
108 await ctx.close();
109}
110// 7 · un dominio que no resuelve, sin proxy: no se le llama «CORS» a secas ni se
111// dice que la página exista.
112{
113 const { ctx, llama } = await escenario(r => r.fulfill({ status: 404, contentType: 'text/html', body: '<h1>404 Not Found</h1>' }), {
114 sitio: r => r.abort('namenotresolved'),
115 });
116 const f = await llama('fetch', { url: 'https://no-such-host.invalid/' });
117 ok('7 · un dominio que no resuelve: CORS o sin conexión, sin afirmar que la página exista', !f.ok && /no se pudiera conectar/.test(f.out) && !/No es que la página no exista/.test(f.out), f.out);
118 await ctx.close();
119}
120// 8 · el sitio contesta otro error (403) y no hay proxy: se dice su estado.
121{
122 const { ctx, alProxy, llama } = await escenario(r => r.fulfill({ status: 404, contentType: 'text/html', body: '<h1>404 Not Found</h1>' }), {
123 sitio: r => r.fulfill({ status: 403, contentType: 'text/html', headers: { 'access-control-allow-origin': '*' }, body: 'Forbidden' }),
124 });
125 const f = await llama('fetch', { url: 'https://cors-site.example/privada' });
126 ok('8 · otro error del sitio (403): se dice su estado y que no hay proxy para intentarlo de otra forma', !f.ok && /respondió HTTP 403/.test(f.out) && /no tiene el proxy de respaldo/.test(f.out) && !/CORS/.test(f.out), `${f.out} · proxy ${alProxy.length}`);
127 await ctx.close();
128}
129
130console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ WEB: si no puede leer o buscar, dice por qué');
131await b.close();
132process.exit(fails ? 1 : 0);