GeminiBot commited on
Commit ·
783fb1f
1
Parent(s): a521d64
Update diagnostic logs and stabilize fetch
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950514 unmodified lines5657585960616263646566import { gotScraping } from 'got-scraping';import { JSDOM } from "jsdom";import { createHash } from "node:crypto";export class DuckAI {private async solveChallenge(vqdHash: string, ua: string): Promise<string> {const jsScript = Buffer.from(vqdHash, 'base64').toString('utf-8');const dom = new JSDOM(`<!DOCTYPE html><html><body></body></html>`, { runScripts: 'dangerously' });dom.window.top.__DDG_BE_VERSION__ = 1;dom.window.top.__DDG_FE_CHAT_HASH__ = 1;const result = await dom.window.eval(jsScript) as any;result.client_hashes[0] = ua;result.client_hashes = result.client_hashes.map((t: string) => {const hash = createHash('sha256');hash.update(t);return hash.digest('base64');});return btoa(JSON.stringify(result));}async chat(request: any): Promise<string> {try {// gotScraping автоматически подберет идеальные заголовки и TLS отпечаток// под каждый запрос, имитируя случайный современный браузер.// 1. Получаем токенconst statusRes = await gotScraping.get("https://duckduckgo.com/duckchat/v1/status?q=1", {headers: { "x-vqd-accept": "1" }});const ua = statusRes.request.options.headers['user-agent'] as string;const hashHeader = statusRes.headers["x-vqd-hash-1"] as string;const solvedVqd = await this.solveChallenge(hashHeader, ua);// 2. Делаем запрос в чатconst chatRes = await gotScraping.post("https://duckduckgo.com/duckchat/v1/chat", {headers: {"x-vqd-hash-1": solvedVqd,"content-type": "application/json","accept": "text/event-stream"},json: request,retry: { limit: 2 } // Авто-повтор при сбоях});const text = chatRes.body;let llmResponse = "";const lines = text.split("\n");for (const line of lines) {4 unmodified lines} catch (e) {}}}return llmResponse.trim() || "⚠️ Пустой ответ от ИИ.";} catch (error) {console.error("Scraping Error:", error);return "⚠️ Ошибка маскировки. Попробуйте еще раз.";}}}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465664 unmodified lines7172737475767778798081import { JSDOM } from "jsdom";import { createHash } from "node:crypto";import UserAgent from "user-agents";export class DuckAI {private async solveChallenge(vqdHash: string, ua: string): Promise<string> {try {const jsScript = Buffer.from(vqdHash, 'base64').toString('utf-8');const dom = new JSDOM(`<!DOCTYPE html><html><body></body></html>`, { runScripts: 'dangerously' });dom.window.top.__DDG_BE_VERSION__ = 1;dom.window.top.__DDG_FE_CHAT_HASH__ = 1;const result = await dom.window.eval(jsScript) as any;result.client_hashes[0] = ua;result.client_hashes = result.client_hashes.map((t: string) => {const hash = createHash('sha256');hash.update(t);return hash.digest('base64');});return btoa(JSON.stringify(result));} catch (e: any) {throw new Error("Challenge Solver Error: " + e.message);}}async chat(request: any): Promise<string> {const ua = new UserAgent({ deviceCategory: 'desktop' }).toString();const 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}`;}}}
src/duckai.ts+50-35