GeminiBot commited on
Commit ·
adb9567
1
Parent(s): 387c337
Ultra-deep browser simulation with Canvas mock
Browse filesFiles changed (2)
- package.json+3-2
- src/duckai.ts+43-39
3 unmodified lines4567893 unmodified lines"main": "src/server.ts","dependencies": {"jsdom": "^25.0.1","user-agents": "^1.1.0"}}3 unmodified lines456789103 unmodified lines"main": "src/server.ts","dependencies": {"jsdom": "^25.0.1","user-agents": "^1.1.0","canvas": "^2.11.2"}}
6 unmodified lines789101112131415161718192021222324252627282930313233343536373839404114 unmodified lines5657585960616263646566676869707172737475767778798081828384858687888990919293944 unmodified lines991001011021031041051061071081096 unmodified linestry {const jsScript = Buffer.from(vqdHash, 'base64').toString('utf-8');// Создаем максимально детальную симуляцию браузераconst dom = new JSDOM(`<!DOCTYPE html><html><head></head><body><div id="app"></div></body></html>`, {url: "https://duckduckgo.com/",referrer: "https://duckduckgo.com/",contentType: "text/html",runScripts: "dangerously",resources: "usable"});// Эмулируем Navigator и другие свойстваObject.defineProperty(dom.window, 'navigator', {value: {userAgent: ua,platform: 'Win32',languages: ['en-US', 'en'],deviceMemory: 8,hardwareConcurrency: 8}});// Установка обязательных переменных DDGdom.window.top.__DDG_BE_VERSION__ = 1;dom.window.top.__DDG_FE_CHAT_HASH__ = 1;// Выполняем скриптconst result = await dom.window.eval(jsScript) as any;if (!result || !result.client_hashes) {throw new Error("Challenge script returned invalid result");}result.client_hashes[0] = ua;14 unmodified linesconst headers: any = {"User-Agent": ua,"Accept": "text/event-stream","Accept-Language": "en-US,en;q=0.9","Referer": "https://duckduckgo.com/","Origin": "https://duckduckgo.com","x-vqd-accept": "1"};try {// 1. Получаем статусconst statusRes = await fetch("https://duckduckgo.com/duckchat/v1/status?q=1", { headers });if (!statusRes.ok) throw new Error(`DDG Status Fail: ${statusRes.status}`);const hashHeader = statusRes.headers.get("x-vqd-hash-1");if (!hashHeader) throw new Error("Missing x-vqd-hash-1 header");const solvedVqd = await this.solveChallenge(hashHeader, ua);// 2. Делаем запрос в чатconst chatRes = await fetch("https://duckduckgo.com/duckchat/v1/chat", {method: "POST",headers: {...headers,"x-vqd-hash-1": solvedVqd,"Content-Type": "application/json"},body: JSON.stringify(request)});if (!chatRes.ok) {const errText = await chatRes.text();throw new Error(`DDG Chat Fail: ${chatRes.status} - ${errText.substring(0, 100)}`);}const text = await chatRes.text();let llmResponse = "";const lines = text.split("\n");for (const line of lines) {4 unmodified lines} catch (e) {}}}return llmResponse.trim() || "⚠️ Пустой ответ от DDG.";} catch (error: any) {console.error("Scraping Detail:", error.message);return `⚠️ Ошибка бэкенда: ${error.message}`;}}}6 unmodified lines78910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626314 unmodified lines787980818283848586878889909192939495969798991004 unmodified lines1051061071081091101111121136 unmodified linestry {const jsScript = Buffer.from(vqdHash, 'base64').toString('utf-8');const dom = new JSDOM(`<!DOCTYPE html><html><body></body></html>`, {url: "https://duckduckgo.com/",referrer: "https://duckduckgo.com/",runScripts: "dangerously",resources: "usable"});const window = dom.window as any;// ГЛУБОКАЯ ЭМУЛЯЦИЯObject.defineProperties(window.navigator, {userAgent: { value: ua },platform: { value: 'Win32' },webdriver: { value: false },languages: { value: ['en-US', 'en'] }});window.screen = { width: 1920, height: 1080, availWidth: 1920, availHeight: 1080 };window.chrome = { runtime: {} };// Заглушка для Canvas (часто ищут её)window.HTMLCanvasElement.prototype.getContext = () => ({fillRect: () => {},clearRect: () => {},getImageData: () => ({ data: new Uint8ClampedArray(4) }),putImageData: () => {},createImageData: () => ({ data: new Uint8ClampedArray(4) }),setTransform: () => {},drawImage: () => {},save: () => {},restore: () => {},beginPath: () => {},moveTo: () => {},lineTo: () => {},closePath: () => {},stroke: () => {},translate: () => {},scale: () => {},rotate: () => {},arc: () => {},fill: () => {},measureText: () => ({ width: 0 })});dom.window.top.__DDG_BE_VERSION__ = 1;dom.window.top.__DDG_FE_CHAT_HASH__ = 1;const result = await dom.window.eval(jsScript) as any;if (!result || !result.client_hashes) {throw new Error("Invalid Challenge Response");}result.client_hashes[0] = ua;14 unmodified linesconst headers: any = {"User-Agent": ua,"Accept": "text/event-stream","x-vqd-accept": "1"};try {const statusRes = await fetch("https://duckduckgo.com/duckchat/v1/status?q=1", { headers });const hashHeader = statusRes.headers.get("x-vqd-hash-1");if (!hashHeader) throw new Error("Missing x-vqd-hash-1");const solvedVqd = await this.solveChallenge(hashHeader, ua);const response = await fetch("https://duckduckgo.com/duckchat/v1/chat", {method: "POST",headers: { ...headers, "x-vqd-hash-1": solvedVqd, "Content-Type": "application/json" },body: JSON.stringify(request)});const text = await response.text();let llmResponse = "";const lines = text.split("\n");for (const line of lines) {4 unmodified lines} catch (e) {}}}return llmResponse.trim() || "⚠️ Ошибка потока.";} catch (error: any) {return `⚠️ Ошибка бэкенда: ${error.message}`;}}}
package.json+3-2
src/duckai.ts+43-39