| 1 | // web.fetch y web.search frente al proxy endurecido (server/serve.py): lo que |
| 2 | // el proxy dice en sus cabeceras llega al agente, y la página anti-bot de |
| 3 | // DuckDuckGo (un 202) es un bloqueo, no «Sin resultados». |
| 4 | // |
| 5 | // Sin red: arranca su propio serve.py en un puerto libre y corta todo lo que |
| 6 | // no sea ese servidor. Lo que se le pide de verdad a /proxy son destinos que |
| 7 | // rechaza ANTES de conectar a nada; el resto de respuestas del proxy se |
| 8 | // simulan con las mismas cabeceras que pone serve.py (tests/test_proxy.py |
| 9 | // comprueba que las pone). |
| 10 | // |
| 11 | // cd tests && node web-proxy.mjs |
| 12 | import { chromium } from 'playwright'; |
| 13 | import { spawn } from 'node:child_process'; |
| 14 | import net from 'node:net'; |
| 15 | import { fileURLToPath } from 'node:url'; |
| 16 | |
| 17 | const SERVE = fileURLToPath(new URL('../server/serve.py', import.meta.url)); |
| 18 | let fails = 0; |
| 19 | const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + String(e).slice(0, 240) : '')); if (!c) fails++; }; |
| 20 | |
| 21 | const libre = () => new Promise((res, rej) => { |
| 22 | const s = net.createServer().once('error', rej).listen(0, '127.0.0.1', () => { const { port } = s.address(); s.close(() => res(port)); }); |
| 23 | }); |
| 24 | const port = await libre(); |
| 25 | const BASE = `http://127.0.0.1:${port}`; |
| 26 | const server = spawn('python3', [SERVE, String(port)], { |
| 27 | env: { ...process.env, PYTHONDONTWRITEBYTECODE: '1', ELFFUSS_BIND: '127.0.0.1' }, stdio: ['ignore', 'ignore', 'ignore'], |
| 28 | }); |
| 29 | const parar = () => { try { server.kill(); } catch { /* */ } }; |
| 30 | process.on('exit', parar); |
| 31 | for (let i = 0; ; i++) { |
| 32 | try { if ((await fetch(BASE + '/robots.txt')).ok) break; } catch { /* aún arrancando */ } |
| 33 | if (i > 100) { console.log('❌ serve.py no arrancó'); process.exit(1); } |
| 34 | await new Promise(r => setTimeout(r, 100)); |
| 35 | } |
| 36 | |
| 37 | const DDG_OK = '<html><body><table><tr><td><a href="/l/?uddg=https%3A%2F%2Fejemplo.org%2Fhistoria-del-reloj&rut=x">Historia del reloj</a> Un repaso a la historia del reloj.</td></tr></table></body></html>'; |
| 38 | // La página que DuckDuckGo le da a un servidor que le parece un bot (con un 202). |
| 39 | const DDG_ANTIBOT = '<html><body><div class="anomaly-modal__title">Unfortunately, bots use DuckDuckGo too.</div><form id="challenge-form" action="//duckduckgo.com/anomaly.js"></form></body></html>'; |
| 40 | const DDG_202_SIN_TEXTO = '<html><body><p>Procesando…</p></body></html>'; |
| 41 | |
| 42 | // Cómo contesta el «proxy» según la url pedida: null = que conteste el serve.py de verdad. |
| 43 | const P = (status, headers, body = '') => ({ status, headers, body }); |
| 44 | let ddg = 'ok'; |
| 45 | function respuestaProxy(pedida) { |
| 46 | if (pedida.startsWith('http://127.0.0.1:1/')) return null; // de verdad: forbidden-port |
| 47 | if (pedida.startsWith('https://caducado.ejemplo/')) |
| 48 | return P(502, { 'X-Proxy-Error': 'tls' }, 'fallo TLS con la web (SSLCertVerificationError)\n'); |
| 49 | if (pedida.startsWith('https://sin-pagina.ejemplo/')) return P(404, { 'X-Proxy-Upstream-Status': '404' }, 'Not Found'); |
| 50 | if (pedida.startsWith('https://prohibe.ejemplo/')) return P(403, { 'X-Proxy-Upstream-Status': '403' }, 'Forbidden'); |
| 51 | if (pedida.startsWith('https://enorme.ejemplo/')) |
| 52 | return P(200, { 'X-Proxy-Upstream-Status': '200', 'X-Proxy-Truncated': '1' }, '<p>principio de una página enorme</p>'); |
| 53 | if (pedida.startsWith('https://normal.ejemplo/')) |
| 54 | return P(200, { 'X-Proxy-Upstream-Status': '200', 'X-Proxy-Truncated': '0' }, '<p>una página normal</p>'); |
| 55 | if (pedida.startsWith('https://sin-ruta.ejemplo/')) return P(404, {}, '<html><body>404 Not Found</body></html>'); // nginx sin /proxy |
| 56 | if (/duckduckgo\.com\//.test(pedida)) { |
| 57 | if (ddg === 'antibot') return P(202, { 'X-Proxy-Upstream-Status': '202' }, DDG_ANTIBOT); |
| 58 | if (ddg === '202') return P(202, { 'X-Proxy-Upstream-Status': '202' }, DDG_202_SIN_TEXTO); |
| 59 | if (ddg === 'antibot-proxy-viejo') return P(200, {}, DDG_ANTIBOT); // el proxy viejo lo daba como 200 |
| 60 | if (ddg === 'limite') return P(429, { 'X-Proxy-Error': 'rate-limited', 'Retry-After': '60' }, 'demasiadas peticiones al proxy, espera un poco\n'); |
| 61 | if (ddg === 'ocupado') return P(503, { 'X-Proxy-Error': 'busy', 'Retry-After': '5' }, 'proxy ocupado, prueba en unos segundos\n'); |
| 62 | return P(200, { 'X-Proxy-Upstream-Status': '200' }, DDG_OK); |
| 63 | } |
| 64 | return P(502, { 'X-Proxy-Error': 'upstream' }, 'no previsto en la prueba\n'); |
| 65 | } |
| 66 | |
| 67 | const b = await chromium.launch(); |
| 68 | async function pagina(locale) { |
| 69 | const ctx = await b.newContext({ locale }); |
| 70 | await ctx.addInitScript(() => { try { localStorage.setItem('elffuss.grants', JSON.stringify(['web'])); } catch { /* */ } }); |
| 71 | await ctx.route('**/*', async route => { |
| 72 | const u = new URL(route.request().url()); |
| 73 | if (u.origin !== BASE) return route.abort('failed'); // ni internet ni el fetch directo: sin CORS |
| 74 | if (u.pathname !== '/proxy') return route.continue(); |
| 75 | const r = respuestaProxy(u.searchParams.get('url') || ''); |
| 76 | if (!r) return route.continue(); |
| 77 | return route.fulfill({ status: r.status, headers: { 'Content-Type': 'text/html; charset=utf-8', ...r.headers }, body: r.body }); |
| 78 | }); |
| 79 | const p = await ctx.newPage(); |
| 80 | const errores = []; |
| 81 | p.on('pageerror', e => errores.push(e.message)); |
| 82 | await p.goto(BASE + '/robots.txt'); |
| 83 | return { ctx, p, errores }; |
| 84 | } |
| 85 | const llamar = (p, fn, args) => p.evaluate(async ({ fn, args }) => { |
| 86 | const web = await import('/js/tools/web.js'); |
| 87 | try { return { ok: true, res: await web[fn](args) }; } catch (e) { return { ok: false, err: String(e?.message || e) }; } |
| 88 | }, { fn, args }); |
| 89 | |
| 90 | const { ctx, p, errores } = await pagina('es-ES'); |
| 91 | |
| 92 | // ---- lo que dice el proxy llega al agente (antes: «HTTP 403» o «HTTP 502» a secas) |
| 93 | const f1 = await llamar(p, 'fetchUrl', { url: 'http://127.0.0.1:1/' }); |
| 94 | ok('un puerto prohibido lo dice el proxy de verdad: forbidden-port y el motivo', |
| 95 | !f1.ok && /forbidden-port/.test(f1.err) && /solo se permiten los puertos 80 y 443/.test(f1.err) && /proxy del servidor no la trajo/.test(f1.err), f1.err); |
| 96 | const f2 = await llamar(p, 'fetchUrl', { url: 'https://caducado.ejemplo/' }); |
| 97 | ok('un fallo TLS es un fallo TLS, no «HTTP 502»', !f2.ok && /\btls\b/.test(f2.err) && /fallo TLS con la web/.test(f2.err), f2.err); |
| 98 | const f3 = await llamar(p, 'fetchUrl', { url: 'https://sin-pagina.ejemplo/x' }); |
| 99 | ok('el 404 de la web a través del proxy es «esa página no existe», no «falta el proxy»', |
| 100 | !f3.ok && /no existe/.test(f3.err) && !/proxy de respaldo/.test(f3.err), f3.err); |
| 101 | const f4 = await llamar(p, 'fetchUrl', { url: 'https://prohibe.ejemplo/x' }); |
| 102 | ok('el 403 de la propia web se distingue de un destino que rechaza el proxy', |
| 103 | !f4.ok && /la web respondió HTTP 403/.test(f4.err) && !/forbidden/.test(f4.err), f4.err); |
| 104 | const f5 = await llamar(p, 'fetchUrl', { url: 'https://sin-ruta.ejemplo/x' }); |
| 105 | ok('sin la ruta /proxy (un 404 sin cabeceras del proxy) sigue diciendo que falta el proxy de respaldo', |
| 106 | !f5.ok && /proxy de respaldo/.test(f5.err), f5.err); |
| 107 | |
| 108 | // ---- el recorte del proxy no es silencioso |
| 109 | const g1 = await llamar(p, 'fetchUrl', { url: 'https://enorme.ejemplo/' }); |
| 110 | ok('una página que el proxy cortó lo dice al final', g1.ok && /principio de una página enorme/.test(g1.res) && /cortó la página en 2 MB/.test(g1.res), g1.ok ? g1.res : g1.err); |
| 111 | const g2 = await llamar(p, 'fetchUrl', { url: 'https://normal.ejemplo/' }); |
| 112 | ok('…y una entera no lleva el aviso', g2.ok && /una página normal/.test(g2.res) && !/cortó/.test(g2.res), g2.ok ? g2.res : g2.err); |
| 113 | |
| 114 | // ---- web.search: el bloqueo anti-bot y los errores no son «Sin resultados» |
| 115 | for (const [modo, nombre] of [['antibot', 'la página anti-bot (202, anomaly-modal)'], |
| 116 | ['202', 'un 202 sin enlaces aunque no traiga el texto de siempre'], |
| 117 | ['antibot-proxy-viejo', 'la página anti-bot que el proxy viejo daba como 200']]) { |
| 118 | ddg = modo; |
| 119 | const s = await llamar(p, 'search', { query: 'historia del reloj' }); |
| 120 | ok(`${nombre} es un bloqueo del buscador`, !s.ok && /bloqueó la consulta/.test(s.err) && !/Sin resultados/.test(s.err), s.ok ? s.res : s.err); |
| 121 | } |
| 122 | for (const [modo, codigo] of [['limite', 'rate-limited'], ['ocupado', 'busy']]) { |
| 123 | ddg = modo; |
| 124 | const s = await llamar(p, 'search', { query: 'historia del reloj' }); |
| 125 | ok(`si el proxy no contesta (${codigo}) la búsqueda falla diciendo por qué`, |
| 126 | !s.ok && new RegExp(codigo).test(s.err) && !/Sin resultados/.test(s.err), s.ok ? s.res : s.err); |
| 127 | } |
| 128 | ddg = 'ok'; |
| 129 | const s3 = await llamar(p, 'search', { query: 'historia del reloj' }); |
| 130 | ok('con el buscador contestando salen los resultados con su enlace', |
| 131 | s3.ok && /Resultados para «historia del reloj»/.test(s3.res) && /https:\/\/ejemplo\.org\/historia-del-reloj/.test(s3.res), s3.ok ? s3.res : s3.err); |
| 132 | ok('sin errores de página', errores.length === 0, errores.join(' | ')); |
| 133 | await ctx.close(); |
| 134 | |
| 135 | { |
| 136 | const { ctx: c2, p: q } = await pagina('en-US'); |
| 137 | const r = await llamar(q, 'fetchUrl', { url: 'http://127.0.0.1:1/' }); |
| 138 | ok('in English the proxy refusal reads in English', !r.ok && /the server’s proxy did not fetch it/.test(r.err) && /forbidden-port/.test(r.err), r.err); |
| 139 | await c2.close(); |
| 140 | } |
| 141 | |
| 142 | await b.close(); |
| 143 | parar(); |
| 144 | console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ WEB: el agente recibe lo que dice el proxy, y un bloqueo no es «Sin resultados»'); |
| 145 | process.exit(fails ? 1 : 0); |