| 1 | // Navegación: fetch directo si el sitio lo permite (CORS); si no, cae al |
| 2 | // proxy del servidor (/proxy?url=…) que sirve server/serve.py o el nginx |
| 3 | // de producción. |
| 4 | // |
| 5 | // Cada herramienta recibe la señal de parada del turno ({ signal }, ver |
| 6 | // tools/index.js): con ■, la descarga en curso se corta en vez de seguir por |
| 7 | // detrás hasta el final. |
| 8 | import { require as requirePerm } from '../permissions.js'; |
| 9 | import { t } from '../i18n.js'; |
| 10 | |
| 11 | const MAX = 8000; // caracteres devueltos al agente |
| 12 | const PROXY_MB = 2; // el tope del proxy: MAX_PROXY_BYTES de server/serve.py |
| 13 | |
| 14 | function toText(html) { |
| 15 | const doc = new DOMParser().parseFromString(html, 'text/html'); |
| 16 | doc.querySelectorAll('script,style,noscript,svg,iframe').forEach(n => n.remove()); |
| 17 | const text = (doc.body?.innerText || doc.body?.textContent || '') |
| 18 | .replace(/\n{3,}/g, '\n\n').trim(); |
| 19 | return text || html.slice(0, MAX); |
| 20 | } |
| 21 | |
| 22 | const parado = (e, signal) => signal?.aborted || e?.name === 'AbortError'; |
| 23 | const hostDe = url => { try { return new URL(url).host; } catch { return url; } }; |
| 24 | const motivo = async r => { try { return (await r.text()).replace(/\s+/g, ' ').trim().slice(0, 300); } catch { return ''; } }; |
| 25 | |
| 26 | // Lee una URL: directa si el sitio permite CORS y, si no, por el proxy del |
| 27 | // servidor. Cuando las dos fallan, el error dice POR QUÉ. En especial si el |
| 28 | // proxy no existe en este servidor (404): antes salía «HTTP 404» a secas, que |
| 29 | // se lee como «esa página no existe», y la búsqueda lo convertía en «Sin |
| 30 | // resultados», como si internet no tuviera nada que decir. Así estuvo |
| 31 | // producción semanas sin que nadie lo notara. |
| 32 | // |
| 33 | // Y sin decir más de lo que se sabe. Si el sitio contestó al fetch directo (con |
| 34 | // CORS el navegador deja ver su estado), lo que importa es lo que dijo: su 404 |
| 35 | // es que la página no existe, haya proxy o no. Si el fetch directo falló sin |
| 36 | // respuesta, desde el navegador no se distingue un sitio sin CORS de uno que no |
| 37 | // existe o no resuelve: se dicen las dos cosas y no se afirma que la página |
| 38 | // exista. (Lo mismo que la copia de Elffuss Code.) |
| 39 | // |
| 40 | // El proxy endurecido dice en cabeceras qué ha pasado, y eso es lo que llega al |
| 41 | // agente (antes, un destino prohibido y el 403 de la propia web eran los dos |
| 42 | // «HTTP 403», y un fallo TLS o de DNS, «HTTP 502»): |
| 43 | // · X-Proxy-Error: <código> → el proxy no la trajo (puerto o destino |
| 44 | // prohibido, TLS, DNS, plazo, límites…), y el cuerpo es el motivo; |
| 45 | // · X-Proxy-Upstream-Status → el estado es de la web, que el proxy pasa tal |
| 46 | // cual: su 404 es que la página no existe, NO que falte el proxy; |
| 47 | // · X-Proxy-Truncated: 1 → el proxy cortó la página en su tope. |
| 48 | // Sin ninguna de las dos primeras no ha contestado el proxy: un 404/405/501 es |
| 49 | // un servidor sin la ruta /proxy (o el proxy viejo), y lo demás (el 429 del |
| 50 | // límite de nginx, un 502/504 con el backend caído), un fallo sin más detalle. |
| 51 | async function proxyGet(url, { signal } = {}) { |
| 52 | let directo, estado = 0; |
| 53 | try { |
| 54 | const r = await fetch(url, { signal }); |
| 55 | if (r.ok) return { text: await r.text(), status: r.status, truncated: false }; |
| 56 | estado = r.status; directo = new Error('HTTP ' + r.status); |
| 57 | } catch (e) { |
| 58 | if (parado(e, signal)) throw e; // ■: no se prueba el proxy |
| 59 | directo = e; |
| 60 | } |
| 61 | if (estado === 404 || estado === 410) throw new Error(t('webGone', { url, status: estado })); |
| 62 | let r; |
| 63 | try { r = await fetch('/proxy?url=' + encodeURIComponent(url), { signal }); } |
| 64 | catch (e) { |
| 65 | if (parado(e, signal)) throw e; |
| 66 | throw new Error(t('webBoth', { host: hostDe(url), direct: directo?.message || t('webNoAnswer'), proxy: e?.message || t('webNoAnswer') })); |
| 67 | } |
| 68 | const codigo = r.headers.get('X-Proxy-Error'); |
| 69 | const deLaWeb = Number(r.headers.get('X-Proxy-Upstream-Status')) || 0; |
| 70 | if (r.ok) return { text: await r.text(), status: deLaWeb || r.status, truncated: r.headers.get('X-Proxy-Truncated') === '1' }; |
| 71 | if (codigo) { |
| 72 | throw new Error(t('webProxyRefused', { host: hostDe(url), status: r.status, code: codigo, why: (await motivo(r)) || codigo })); |
| 73 | } |
| 74 | if (deLaWeb) { |
| 75 | if (deLaWeb === 404 || deLaWeb === 410) throw new Error(t('webGone', { url, status: deLaWeb })); |
| 76 | throw new Error(t('webSiteStatus', { host: hostDe(url), status: deLaWeb })); |
| 77 | } |
| 78 | if (r.status === 404 || r.status === 405 || r.status === 501) { |
| 79 | const e = new Error(estado |
| 80 | ? t('webNoProxyStatus', { host: hostDe(url), status: estado, proxy: r.status }) |
| 81 | : t('webNoProxy', { host: hostDe(url), proxy: r.status })); |
| 82 | e.sinProxy = true; |
| 83 | throw e; |
| 84 | } |
| 85 | throw new Error(t('webBoth', { host: hostDe(url), direct: directo?.message || t('webNoAnswer'), proxy: 'HTTP ' + r.status })); |
| 86 | } |
| 87 | |
| 88 | export async function fetchUrl({ url } = {}, { signal } = {}) { |
| 89 | if (!/^https?:\/\//.test(url || '')) throw new Error(t('webBadUrl')); |
| 90 | await requirePerm('web', url); |
| 91 | const { text: html, truncated } = await proxyGet(url, { signal }); |
| 92 | const text = toText(html); |
| 93 | const out = `[${url}]\n` + (text.length > MAX ? text.slice(0, MAX) + '\n' + t('cutMark') : text); |
| 94 | return truncated ? out + '\n' + t('webProxyCut', { mb: PROXY_MB }) : out; |
| 95 | } |
| 96 | |
| 97 | // Búsqueda web REAL. Parseo TOLERANTE (independiente de clases): DuckDuckGo |
| 98 | // envuelve cada resultado en un enlace con ?uddg=<url real>. Buscamos esos. |
| 99 | // Si ningún buscador contesta se dice por qué, en vez de «Sin resultados» (que |
| 100 | // solo vale cuando el buscador SÍ contestó y no encontró nada). Y la página de |
| 101 | // verificación anti-bot de DuckDuckGo no es una lista vacía: es un bloqueo. |
| 102 | // Llega con un 202 (el proxy endurecido pasa el estado de la web; el viejo lo |
| 103 | // cambiaba por 200, y por eso también se mira el texto). |
| 104 | const BLOQUEO_DDG = /anomaly|unusual traffic|are you a human|bots use duckduckgo/i; |
| 105 | export async function search({ query } = {}, { signal } = {}) { |
| 106 | if (!query) throw new Error(t('webNoQuery')); |
| 107 | await requirePerm('web', t('pdWebSearch', { q: query })); |
| 108 | let html = '', ultimoError = null, bloqueado = false; |
| 109 | for (const ep of ['https://html.duckduckgo.com/html/?q=', 'https://lite.duckduckgo.com/lite/?q=']) { |
| 110 | try { |
| 111 | const { text: h, status } = await proxyGet(ep + encodeURIComponent(query), { signal }); |
| 112 | if (!h.includes('uddg=') && (status === 202 || BLOQUEO_DDG.test(h))) { bloqueado = true; continue; } |
| 113 | html = h; |
| 114 | if (html.includes('uddg=') || html.includes('result')) break; |
| 115 | } catch (e) { |
| 116 | if (parado(e, signal)) throw e; |
| 117 | ultimoError = e; |
| 118 | } |
| 119 | } |
| 120 | if (!html) { |
| 121 | if (bloqueado) throw new Error(t('webSearchBlocked', { q: query })); |
| 122 | throw ultimoError || new Error(t('webSearchFailed', { q: query })); |
| 123 | } |
| 124 | const doc = new DOMParser().parseFromString(html, 'text/html'); |
| 125 | const seen = new Set(), out = []; |
| 126 | for (const a of doc.querySelectorAll('a[href*="uddg="]')) { |
| 127 | const m = a.getAttribute('href').match(/uddg=([^&]+)/); |
| 128 | if (!m) continue; |
| 129 | const href = decodeURIComponent(m[1]); |
| 130 | const title = a.textContent.trim(); |
| 131 | if (!title || title.length < 3 || seen.has(href)) continue; |
| 132 | seen.add(href); |
| 133 | // fragmento: el texto del contenedor del resultado, sin el título |
| 134 | const block = a.closest('tr, div, article') || a.parentElement; |
| 135 | const snip = (block?.textContent || '').replace(title, '').replace(/\s+/g, ' ').trim().slice(0, 160); |
| 136 | out.push(`• ${title}\n ${href}${snip ? '\n ' + snip : ''}`); |
| 137 | if (out.length >= 8) break; |
| 138 | } |
| 139 | return out.length ? t('webResults', { q: query }) + '\n\n' + out.join('\n\n') : t('webNoResults', { q: query }); |
| 140 | } |
| 141 | |
| 142 | // Búsqueda de IMÁGENES (Openverse, CC) → URLs para montar una galería. |
| 143 | export async function images({ query } = {}, { signal } = {}) { |
| 144 | if (!query) throw new Error(t('webNoQuery')); |
| 145 | await requirePerm('web', t('pdWebImages', { q: query })); |
| 146 | const { text: raw } = await proxyGet('https://api.openverse.org/v1/images/?q=' + encodeURIComponent(query) + '&page_size=12', { signal }); |
| 147 | let data; |
| 148 | try { data = JSON.parse(raw); } catch { throw new Error(t('webImagesBad')); } |
| 149 | const imgs = (data.results || []).map(r => ({ url: r.url, thumb: r.thumbnail || r.url, title: (r.title || '').slice(0, 60), by: r.creator || '' })) |
| 150 | .filter(i => i.url); |
| 151 | if (!imgs.length) return t('webNoImages', { q: query }); |
| 152 | return JSON.stringify({ query, images: imgs }); |
| 153 | } |