Spaces:
Sleeping
Sleeping
Update stealth-proxy/index.js
Browse files6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697010 unmodified lines8182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119216 unmodified lines2092102112122132142152 unmodified lines2182192202212222231 unmodified line22522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735815 unmodified lines3743753763773783793803813824 unmodified lines38738838939039139239339439527 unmodified lines4234244254264274284294304314324334344354364374384394404411 unmodified line4434444454464474484491 unmodified line4514524534544554564574584594604614624634644654664674684694704714724734746 unmodified lines* 原理:* 1. 启动时用 stealth 浏览器访问 cursor.com,通过 JS Challenge 获取 _vcrcs cookie* 2. 在同一浏览器上下文内通过 page.evaluate(fetch) 代理 API 请求* 3. 定时完整重建浏览器上下文,避免只刷新 challengePage 导致 workerPage 状态失配* 4. 支持 SSE 流式响应透传*/const express = require('express');const crypto = require('crypto');const fs = require('fs');const PORT = parseInt(process.env.PORT || '3011', 10);const CHALLENGE_URL = process.env.CHALLENGE_URL || 'https://cursor.com/cn/docs';const REFRESH_INTERVAL = parseInt(process.env.REFRESH_INTERVAL || '3000000', 10); // 50 分钟const CHALLENGE_WAIT = parseInt(process.env.CHALLENGE_WAIT || '55000', 10); // challenge 最长等待时间const MAX_INIT_RETRIES = parseInt(process.env.MAX_INIT_RETRIES || '5', 10);const RESTART_POSTPONE_MS = parseInt(process.env.RESTART_POSTPONE_MS || '60000', 10); // 有活跃请求时延后 60 秒let browser = null;let context = null;let challengePage = null;let workerPage = null;let refreshTimer = null;let ready = false;let expectedBrowserClose = false;let isShuttingDown = false;let restartPromise = null;let scheduledRestartPending = false;let startTime = Date.now();let challengeCount = 0;let requestCount = 0;const pendingRequests = new Map();function sleep(ms) {return new Promise((resolve) => setTimeout(resolve, ms));}function getActiveRequestCount() {return pendingRequests.size;}function getCookiePreview(value) {if (!value) return null;return `${value.substring(0, 40)}...`;}async function getVcrcsCookie() {if (!context) return null;const cookies = await context.cookies().catch(() => []);return cookies.find((c) => c.name === '_vcrcs') || null;}// 自动检测系统 Chrome 路径(优先使用,指纹更真实)function findSystemChrome() {const paths = ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome','/usr/bin/google-chrome','/usr/bin/google-chrome-stable','/usr/bin/chromium','/usr/bin/chromium-browser','C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe','C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',];10 unmodified linesreturn chromium;}function attachBrowserHandlers(currentBrowser) {currentBrowser.on('disconnected', () => {if (expectedBrowserClose || isShuttingDown) {return;}console.error('[Stealth] Browser disconnected unexpectedly! Restarting...');ready = false;setTimeout(() => {restartBrowser('browser disconnected').catch((err) => {console.error('[Stealth] Restart after disconnect failed:', err.message);});}, 3000);});}async function waitForCookie(maxWait) {const timeout = maxWait || CHALLENGE_WAIT;const start = Date.now();while (Date.now() - start < timeout) {const vcrcs = await getVcrcsCookie();if (vcrcs) {console.log('[Stealth] _vcrcs obtained:', getCookiePreview(vcrcs.value));return vcrcs;}await sleep(2000);}console.error('[Stealth] Failed to obtain _vcrcs within timeout');return null;}// 模拟人类行为:鼠标移动、点击、滚动,帮助通过 Vercel bot 检测async function simulateHumanBehavior(page) {try {await sleep(500 + Math.random() * 1000);const points = Array.from({ length: 5 }, () => ({x: 100 + Math.random() * 600,y: 100 + Math.random() * 400,}));for (const p of points) {await page.mouse.move(p.x, p.y, { steps: 5 + Math.floor(Math.random() * 10) });await sleep(100 + Math.random() * 300);}await page.mouse.wheel(0, 100 + Math.random() * 200);await sleep(300 + Math.random() * 500);await page.mouse.wheel(0, -(50 + Math.random() * 100));await page.mouse.click(300 + Math.random() * 400, 300 + Math.random() * 200);await sleep(200 + Math.random() * 500);console.log('[Stealth] Human behavior simulation done');} catch (e) {console.log('[Stealth] Human simulation skipped:', e.message);}}async function createWorkerPage() {workerPage = await context.newPage();await workerPage.goto(CHALLENGE_URL, {waitUntil: 'domcontentloaded',timeout: 60000,});await workerPage.exposeFunction('__proxyCallback', (requestId, type, data) => {const pending = pendingRequests.get(requestId);if (!pending) return;switch (type) {case 'headers': {const { status, contentType } = JSON.parse(data);const headers = {'Cache-Control': 'no-cache',Connection: 'keep-alive',};if (contentType) headers['Content-Type'] = contentType;pending.res.writeHead(status, headers);break;}case 'chunk':pending.res.write(data);break;case 'end':pending.res.end();pending.resolve();break;case 'error':if (!pending.res.headersSent) {pending.res.writeHead(502, {'Content-Type': 'application/json',});}pending.res.end(JSON.stringify({ error: { message: data } }));pending.resolve();break;default:break;}});}async function initBrowser() {ready = false;const chromium = await loadStealth();const chromePath = findSystemChrome();16 unmodified linesconsole.log('[Stealth] Launching browser...');browser = await chromium.launch(launchOptions);attachBrowserHandlers(browser);context = await browser.newContext({userAgent:2 unmodified linesviewport: { width: 1920, height: 1080 },});challengePage = await context.newPage();console.log(`[Stealth] Passing Vercel challenge: ${CHALLENGE_URL}`);await challengePage.goto(CHALLENGE_URL, {1 unmodified linetimeout: 60000,});await simulateHumanBehavior(challengePage);let vcrcs = await waitForCookie();if (!vcrcs) {console.log('[Stealth] First attempt failed, retrying challenge...');await challengePage.reload({ waitUntil: 'domcontentloaded', timeout: 60000 });await simulateHumanBehavior(challengePage);vcrcs = await waitForCookie();if (!vcrcs) {throw new Error('Failed to obtain _vcrcs cookie after retry');}}challengeCount += 1;await createWorkerPage();ready = true;console.log('[Stealth] Ready! Accepting proxy requests.');}async function closeBrowserSilently() {if (!browser) return;try {expectedBrowserClose = true;await browser.close().catch(() => {});} finally {expectedBrowserClose = false;}}async function restartBrowser(reason = 'manual') {if (restartPromise) {console.log(`[Stealth] Restart already in progress, joining existing restart (${reason})...`);return restartPromise;}restartPromise = (async () => {console.log(`[Stealth] Restarting browser (${reason})...`);ready = false;await closeBrowserSilently();browser = null;context = null;challengePage = null;workerPage = null;await initBrowser();})();try {await restartPromise;} finally {restartPromise = null;}}async function scheduleFullRestart(reason) {if (isShuttingDown) {return;}if (restartPromise) {console.log(`[Stealth] Skip scheduled restart (${reason}): restart already in progress.`);return restartPromise;}const active = getActiveRequestCount();if (active > 0) {if (!scheduledRestartPending) {scheduledRestartPending = true;console.log(`[Stealth] Postponing scheduled restart (${reason}) because ${active} request(s) are active. Will retry in ${Math.floor(RESTART_POSTPONE_MS / 1000)}s.`,);setTimeout(() => {scheduleFullRestart('postponed scheduled restart').catch((err) => {console.error('[Stealth] Postponed scheduled restart failed:', err.message);});}, RESTART_POSTPONE_MS);} else {console.log(`[Stealth] Scheduled restart (${reason}) already postponed.`);}return;}scheduledRestartPending = false;await restartBrowser(reason);console.log('[Stealth] Scheduled full browser restart completed.');}const app = express();app.use(express.json({ limit: '10mb' }));app.get('/health', async (_req, res) => {const vcrcs = await getVcrcsCookie();res.json({status: ready ? 'ok' : restartPromise ? 'restarting' : 'initializing',uptime: Math.floor((Date.now() - startTime) / 1000),challengeCount,requestCount,activeRequests: getActiveRequestCount(),cookie: getCookiePreview(vcrcs && vcrcs.value),});});app.post('/proxy/chat', async (req, res) => {if (!ready || restartPromise || !workerPage) {res.status(503).json({error: { message: 'Stealth proxy is restarting, please retry shortly' },});return;}const requestId = crypto.randomUUID();requestCount += 1;req.on('close', () => {const pending = pendingRequests.get(requestId);if (pending && !pending.res.writableEnded) {try {pending.res.end();} catch (_) {}pending.resolve();}pendingRequests.delete(requestId);});const promise = new Promise((resolve) => {pendingRequests.set(requestId, { res, resolve });});workerPage.evaluate(async ({ body, requestId }) => {15 unmodified linesif (!r.body) {const text = await r.text();if (text) {await window.__proxyCallback(requestId, 'chunk', text);}await window.__proxyCallback(requestId, 'end', '');return;}4 unmodified linesconst { done, value } = await reader.read();if (done) break;const chunk = decoder.decode(value, { stream: true });if (chunk) {await window.__proxyCallback(requestId, 'chunk', chunk);}}await window.__proxyCallback(requestId, 'end', '');} catch (e) {27 unmodified linespendingRequests.delete(requestId);});(async () => {for (let attempt = 1; attempt <= MAX_INIT_RETRIES; attempt += 1) {try {console.log(`[Stealth] Initialization attempt ${attempt}/${MAX_INIT_RETRIES}...`);await initBrowser();break;} catch (e) {console.error(`[Stealth] Attempt ${attempt} failed:`, e.message);await closeBrowserSilently();browser = null;context = null;challengePage = null;workerPage = null;if (attempt >= MAX_INIT_RETRIES) {console.error(`[Stealth] All ${MAX_INIT_RETRIES} attempts failed, exiting.`);1 unmodified line}const delay = attempt * 5;console.log(`[Stealth] Retrying in ${delay}s...`);await sleep(delay * 1000);}}1 unmodified lineconsole.log(`[Stealth] Proxy listening on port ${PORT}`);});refreshTimer = setInterval(() => {scheduleFullRestart('scheduled refresh').catch((err) => {console.error('[Stealth] Scheduled full restart failed:', err.message);});}, REFRESH_INTERVAL);})();const shutdown = async () => {console.log('[Stealth] Shutting down...');isShuttingDown = true;ready = false;if (refreshTimer) {clearInterval(refreshTimer);refreshTimer = null;}await closeBrowserSilently();process.exit(0);};process.on('SIGTERM', shutdown);process.on('SIGINT', shutdown);6 unmodified lines789101112131415161718192021222324252627282930313233343536373839404142434445464710 unmodified lines5859606162636416 unmodified lines8182838485862 unmodified lines899091929394951 unmodified line97989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030115 unmodified lines3173183193203213223233243253263273284 unmodified lines33333433533633733833934034134234334427 unmodified lines3723733743753763773783793803813823833843853863873883893903913923931 unmodified line3953963973983994004011 unmodified line4034044054064074084094104114124134144154164174184194204214224234244254266 unmodified lines* 原理:* 1. 启动时用 stealth 浏览器访问 cursor.com,通过 JS Challenge 获取 _vcrcs cookie* 2. 在同一浏览器上下文内通过 page.evaluate(fetch) 代理 API 请求* 3. 定时刷新 challenge(_vcrcs 有效期 3600s,每 50 分钟刷新)* 4. 支持 SSE 流式响应透传*/const express = require('express');const crypto = require('crypto');const PORT = parseInt(process.env.PORT || '3011');const CHALLENGE_URL = process.env.CHALLENGE_URL || 'https://cursor.com/cn/docs';const REFRESH_INTERVAL = parseInt(process.env.REFRESH_INTERVAL || '3000000'); // 50 分钟const CHALLENGE_WAIT = parseInt(process.env.CHALLENGE_WAIT || '55000'); // challenge 最长等待时间let browser, context, challengePage, workerPage;let ready = false;let startTime = Date.now();let challengeCount = 0;let requestCount = 0;const pendingRequests = new Map();// ==================== 浏览器管理 ====================const fs = require('fs');// 自动检测系统 Chrome 路径(优先使用,指纹更真实)function findSystemChrome() {const paths = [// macOS'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',// Linux'/usr/bin/google-chrome','/usr/bin/google-chrome-stable','/usr/bin/chromium','/usr/bin/chromium-browser',// Windows'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe','C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',];10 unmodified linesreturn chromium;}async function initBrowser() {const chromium = await loadStealth();const chromePath = findSystemChrome();16 unmodified linesconsole.log('[Stealth] Launching browser...');browser = await chromium.launch(launchOptions);context = await browser.newContext({userAgent:2 unmodified linesviewport: { width: 1920, height: 1080 },});// ---- Challenge 页面:获取 _vcrcs ----challengePage = await context.newPage();console.log(`[Stealth] Passing Vercel challenge: ${CHALLENGE_URL}`);await challengePage.goto(CHALLENGE_URL, {1 unmodified linetimeout: 60000,});// 模拟人类行为,帮助通过 bot 检测await simulateHumanBehavior(challengePage);// 等待 cookie(challenge JS 会异步设置 _vcrcs)const ok = await waitForCookie();if (!ok) {// 重试:刷新页面 + 再次模拟行为console.log('[Stealth] First attempt failed, retrying challenge...');await challengePage.reload({ waitUntil: 'domcontentloaded', timeout: 60000 });await simulateHumanBehavior(challengePage);const retryOk = await waitForCookie();if (!retryOk) {throw new Error('Failed to obtain _vcrcs cookie after retry');}}challengeCount++;// ---- Worker 页面:代理 API 请求 ----// cookie 已在 challenge 页面获取,worker 页面只需加载到 domcontentloaded 即可workerPage = await context.newPage();await workerPage.goto(CHALLENGE_URL, {waitUntil: 'domcontentloaded',timeout: 60000,});// 注册流式回调(Node.js 侧接收浏览器内 fetch 的数据块)await workerPage.exposeFunction('__proxyCallback',(requestId, type, data) => {const pending = pendingRequests.get(requestId);if (!pending) return;switch (type) {case 'headers': {const { status, contentType } = JSON.parse(data);const headers = {'Cache-Control': 'no-cache',Connection: 'keep-alive',};if (contentType) headers['Content-Type'] = contentType;pending.res.writeHead(status, headers);break;}case 'chunk':pending.res.write(data);break;case 'end':pending.res.end();pending.resolve();break;case 'error':if (!pending.res.headersSent) {pending.res.writeHead(502, {'Content-Type': 'application/json',});}pending.res.end(JSON.stringify({ error: { message: data } }),);pending.resolve();break;}},);ready = true;console.log('[Stealth] Ready! Accepting proxy requests.');}async function waitForCookie(maxWait) {maxWait = maxWait || CHALLENGE_WAIT;const start = Date.now();while (Date.now() - start < maxWait) {const cookies = await context.cookies();const vcrcs = cookies.find((c) => c.name === '_vcrcs');if (vcrcs) {console.log('[Stealth] _vcrcs obtained:',vcrcs.value.substring(0, 40) + '...',);return true;}await new Promise((r) => setTimeout(r, 2000));}console.error('[Stealth] Failed to obtain _vcrcs within timeout');return false;}// 模拟人类行为:鼠标移动、点击、滚动,帮助通过 Vercel bot 检测async function simulateHumanBehavior(page) {try {// 随机延迟await new Promise(r => setTimeout(r, 500 + Math.random() * 1000));// 模拟鼠标移动轨迹(多个随机点)const points = Array.from({ length: 5 }, () => ({x: 100 + Math.random() * 600,y: 100 + Math.random() * 400,}));for (const p of points) {await page.mouse.move(p.x, p.y, { steps: 5 + Math.floor(Math.random() * 10) });await new Promise(r => setTimeout(r, 100 + Math.random() * 300));}// 模拟滚动await page.mouse.wheel(0, 100 + Math.random() * 200);await new Promise(r => setTimeout(r, 300 + Math.random() * 500));await page.mouse.wheel(0, -(50 + Math.random() * 100));// 模拟点击页面空白区域await page.mouse.click(300 + Math.random() * 400, 300 + Math.random() * 200);await new Promise(r => setTimeout(r, 200 + Math.random() * 500));console.log('[Stealth] Human behavior simulation done');} catch (e) {// 模拟行为失败不影响主流程console.log('[Stealth] Human simulation skipped:', e.message);}}async function refreshChallenge() {console.log('[Stealth] Refreshing challenge...');try {await challengePage.goto(CHALLENGE_URL, {waitUntil: 'networkidle',timeout: 30000,});const ok = await waitForCookie();if (ok) {challengeCount++;console.log(`[Stealth] Challenge refreshed (total: ${challengeCount})`,);} else {console.error('[Stealth] Challenge refresh failed - cookie not obtained');}} catch (e) {console.error('[Stealth] Challenge refresh error:', e.message);}}async function restartBrowser() {console.log('[Stealth] Restarting browser...');ready = false;try {if (browser) await browser.close().catch(() => {});} catch (_) {}browser = null;context = null;challengePage = null;workerPage = null;await initBrowser();}// ==================== HTTP 服务 ====================const app = express();app.use(express.json({ limit: '10mb' }));// 健康检查app.get('/health', async (_req, res) => {let cookie = null;if (context) {const cookies = await context.cookies().catch(() => []);const vcrcs = cookies.find((c) => c.name === '_vcrcs');if (vcrcs) cookie = vcrcs.value.substring(0, 40) + '...';}res.json({status: ready ? 'ok' : 'initializing',uptime: Math.floor((Date.now() - startTime) / 1000),challengeCount,requestCount,cookie,});});// 代理请求app.post('/proxy/chat', async (req, res) => {if (!ready) {res.status(503).json({error: { message: 'Stealth proxy not ready, please wait' },});return;}const requestId = crypto.randomUUID();requestCount++;// 客户端断开时清理let aborted = false;req.on('close', () => {aborted = true;});const promise = new Promise((resolve) => {pendingRequests.set(requestId, { res, resolve });});// 在浏览器上下文内发起 fetch 并流式回传workerPage.evaluate(async ({ body, requestId }) => {15 unmodified linesif (!r.body) {const text = await r.text();if (text)await window.__proxyCallback(requestId,'chunk',text,);await window.__proxyCallback(requestId, 'end', '');return;}4 unmodified linesconst { done, value } = await reader.read();if (done) break;const chunk = decoder.decode(value, { stream: true });if (chunk)await window.__proxyCallback(requestId,'chunk',chunk,);}await window.__proxyCallback(requestId, 'end', '');} catch (e) {27 unmodified linespendingRequests.delete(requestId);});// ==================== 启动 ====================const MAX_INIT_RETRIES = parseInt(process.env.MAX_INIT_RETRIES || '5');(async () => {// 自动重试启动:网络不稳定时多试几次for (let attempt = 1; attempt <= MAX_INIT_RETRIES; attempt++) {try {console.log(`[Stealth] Initialization attempt ${attempt}/${MAX_INIT_RETRIES}...`);await initBrowser();break; // 成功,跳出重试循环} catch (e) {console.error(`[Stealth] Attempt ${attempt} failed:`, e.message);// 清理失败的浏览器实例if (browser) await browser.close().catch(() => {});browser = null; context = null; challengePage = null; workerPage = null;if (attempt >= MAX_INIT_RETRIES) {console.error(`[Stealth] All ${MAX_INIT_RETRIES} attempts failed, exiting.`);1 unmodified line}const delay = attempt * 5;console.log(`[Stealth] Retrying in ${delay}s...`);await new Promise(r => setTimeout(r, delay * 1000));}}1 unmodified lineconsole.log(`[Stealth] Proxy listening on port ${PORT}`);});// 定时刷新 challengesetInterval(refreshChallenge, REFRESH_INTERVAL);// 浏览器崩溃恢复browser.on('disconnected', () => {console.error('[Stealth] Browser disconnected! Restarting...');ready = false;setTimeout(restartBrowser, 3000);});})();// 优雅退出const shutdown = async () => {console.log('[Stealth] Shutting down...');ready = false;if (browser) await browser.close().catch(() => {});process.exit(0);};process.on('SIGTERM', shutdown);process.on('SIGINT', shutdown);
stealth-proxy/index.js+189-237