Update index.js
Browse files6 unmodified lines78910111213144 unmodified lines1920212223243 unmodified lines28293031323334353637383940414243444546474853 unmodified lines1021031041051061071083 unmodified lines1121131141151161172 unmodified lines12012112212312412512612712812913037 unmodified lines16816917017117217317416 unmodified lines19119219319419519619712 unmodified lines2102112122132142152168 unmodified lines2252262272282292302312322332342351 unmodified line2372382392402412422432442452462472483 unmodified lines25225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330411 unmodified lines31631731831932032132232332447 unmodified lines3723733743753763773785 unmodified lines38438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741866 unmodified lines48548648748848949049164 unmodified lines5565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925 unmodified lines5985996006016026036046052 unmodified lines60860961061161261361461561661761861962062162220 unmodified lines64364464564664764864913 unmodified lines6636646656666676686696706716726736746756762 unmodified lines6796806816826836846856866876886896906916926936946956962 unmodified lines6997007017027037047057067077087097107117127137141 unmodified line71671771871972072172272372472572672772813 unmodified lines7427437447457467477481 unmodified line7507517527537547554 unmodified lines7607617627637647657667676 unmodified lines7747757767777787797801 unmodified line78278378478578678778878979079179279379479579679779879980080180280312 unmodified lines81681781881982082182212 unmodified lines83583683783883984084110 unmodified lines85285385485585685785836 unmodified lines8958968978988999009019029039049059066 unmodified linesimport StealthPlugin from 'puppeteer-extra-plugin-stealth'import { v4 as uuidv4 } from 'uuid';import Logger from './logger.js';import fs from 'fs';import path from 'path';dotenv.config();4 unmodified lines'grok-2-imageGen': 'grok-latest','grok-2-search': 'grok-latest',"grok-3": "grok-3","grok-3-imageGen": "grok-3","grok-3-deepsearch": "grok-3","grok-3-reasoning": "grok-3"3 unmodified linesAPI_KEY: process.env.API_KEY || "sk-123456",SIGNATURE_COOKIE: null,TEMP_COOKIE: null,PICGO_KEY: process.env.PICGO_KEY || null //想要生图的话需要填入这个PICGO图床的key},SERVER: {PORT: process.env.PORT || 3000,BODY_LIMIT: '5mb'},RETRY: {MAX_ATTEMPTS: 2,//重试次数DELAY_BASE: 1000 // 基础延迟时间(毫秒)},IS_THINKING: false,IS_IMG_GEN: false,IS_IMG_GEN2: false,SSO_INDEX: 0,//sso的索引ISSHOW_SEARCH_RESULTS: process.env.ISSHOW_SEARCH_RESULTS === 'true',//是否显示搜索结果,默认关闭CHROME_PATH: process.env.CHROME_PATH || "/usr/bin/chromium"//chrome路径};puppeteer.use(StealthPlugin())53 unmodified lines}getTokenByIndex(index, model) {if (!this.modelRateLimit[model]) return;if(this.activeTokens.length === 0){return null;}3 unmodified lines}recordModelRequest(token, model) {if (!this.modelRateLimit[model]) return;const tokenFrequency = this.tokenModelFrequency.get(token);if (tokenFrequency && tokenFrequency[model] !== undefined) {2 unmodified linesthis.checkAndRemoveTokenIfLimitReached(token);}setModelLimit(index, model) {if (!this.modelRateLimit[model]) return;const tokenFrequency = this.tokenModelFrequency.get(this.activeTokens[index]);tokenFrequency[model] = 9999;}isTokenModelLimitReached(index, model) {if (!this.modelRateLimit[model]) return;const token = this.activeTokens[index];const tokenFrequency = this.tokenModelFrequency.get(token);37 unmodified linesif (now - expiredTime >= 2 * 60 * 60 * 1000) {this.tokenModelUsage.set(token, {"grok-3": 0,"grok-3-imageGen": 0,"grok-3-deepsearch": 0,"grok-3-reasoning": 0});16 unmodified linesclass Utils {static async extractGrokHeaders() {console.log("开始提取头信息");try {// 启动浏览器const browser = await puppeteer.launch({12 unmodified linesawait page.evaluate(() => {return new Promise(resolve => setTimeout(resolve, 5000))})console.log('等待5秒完成')// 获取所有 Cookiesconst cookies = await page.cookies();const targetHeaders = ['x-anonuserid', 'x-challenge', 'x-signature'];8 unmodified lines// 关闭浏览器await browser.close();// 打印并返回提取的头信息console.log('提取的头信息:', JSON.stringify(extractedHeaders, null, 2));return extractedHeaders;} catch (error) {console.error('获取头信息出错:', error);return null;}}1 unmodified lineif (CONFIG.API.TEMP_COOKIE) {return CONFIG.API.TEMP_COOKIE;}console.log("刷新认证信息");let retryCount = 0;while (!CONFIG.API.TEMP_COOKIE || retryCount < CONFIG.RETRY.MAX_ATTEMPTS) {let headers = await Utils.extractGrokHeaders();if (headers) {console.log("获取认证信息成功");CONFIG.API.TEMP_COOKIE = { cookie: `x-anonuserid=${headers["x-anonuserid"]}; x-challenge=${headers["x-challenge"]}; x-signature=${headers["x-signature"]}` };return;}3 unmodified lines}}}static async handleError(error, res) {// 如果是500错误且提供了原始请求函数,尝试重新获取签名并重试if (String(error).includes("status: 500")) {try {await Utils.get_signature();if (CONFIG.API.SIGNATURE_COOKIE) {return res.status(500).json({error: {message: `${error.message}已重新刷新认证信息,请重新对话`,type: 'server_error',param: null,code: retryError.code || null}});} else {return res.status(500).json({error: {message: "认证信息获取失败",type: 'server_error',param: null,code: null}});}} catch (error) {console.error('重试失败:', error);return res.status(500).json({error: {message: `${error.message},认证信息获取失败`,type: 'server_error',param: null,code: error.code || null}});}}// 其他错误直接返回res.status(500).json({error: {message: error.message,type: 'server_error',param: null,code: error.code || null}});}static async organizeSearchResults(searchResults) {// 确保传入的是有效的搜索结果对象if (!searchResults || !searchResults.results) {11 unmodified lines});return formattedResults.join('\n\n');}static createAuthHeaders(model) {return {'cookie': `${tokenManager.getTokenByIndex(CONFIG.SSO_INDEX, model)}`};}}47 unmodified linescontent: imageBuffer}};console.log("发送图片请求");// 发送请求const response = await fetch(url, {method: 'POST',5 unmodified lines});if (!response.ok) {console.error(`上传图片失败,状态码:${response.status},原因:${response.error}`);return '';}const result = await response.json();console.log('上传图片成功:', result);return result.fileMetadataId;} catch (error) {console.error('上传图片失败:', error);return '';}}async prepareChatRequest(request) {if ((request.model === 'grok-2-imageGen' || request.model === 'grok-3-imageGen') && !CONFIG.API.PICGO_KEY) {throw new Error(`该模型需要配置PICGO图床密钥!`);}const todoMessages = request.messages;const fileAttachments = [];let messages = '';let lastRole = null;let lastContent = '';const search = request.model === 'grok-2-search';// 移除<think>标签及其内容const removeThinkTags = (text) => {return text.replace(/<think>[\s\S]*?<\/think>/g, '').trim();};const processImageUrl = async (content) => {66 unmodified linesreturn {modelName: this.modelId,message: messages.trim(),fileAttachments: fileAttachments.slice(0, 4), // 最多保留4张图片imageAttachments: [],disableSearch: false,enableImageGeneration: true,64 unmodified lines}return result;}var token = linejosn?.tokenif (!token) return result;//非生图模型的处理switch (model) {case 'grok-2':result.token = token;return result;case 'grok-2-search':if (linejosn?.webSearchResults && CONFIG.ISSHOW_SEARCH_RESULTS) {result.token = `\r\n<think>${await Utils.organizeSearchResults(linejosn.webSearchResults)}</think>\r\n`;} else {result.token = token;}return result;case 'grok-3':result.token = token;return result;case 'grok-3-deepsearch':if (linejosn.messageTag === "final") {result.token = token;}return result;case 'grok-3-reasoning':if (linejosn?.isThinking && !CONFIG.IS_THINKING) {result.token = "<think>" + token;CONFIG.IS_THINKING = true;} else if (CONFIG.IS_THINKING && !linejosn.isThinking) {result.token = "</think>" + token;CONFIG.IS_THINKING = false;} else {result.token = token;}return result;}5 unmodified lineslet buffer = '';let fullResponse = '';const dataPromises = [];return new Promise((resolve, reject) => {stream.on('data', async (chunk) => {buffer += chunk.toString();const lines = buffer.split('\n');2 unmodified linesfor (const line of lines) {if (!line.trim()) continue;const trimmedLine = line.trim();fs.appendFileSync(path.resolve(process.cwd(), 'response4.txt'), trimmedLine + '\n');if (trimmedLine.startsWith('data: ')) {const data = trimmedLine.substring(6);try {if (!data.trim()) continue;if(data === "[DONE]")continue;const linejosn = JSON.parse(data);if (linejosn?.error) {reject(new Error(linejosn));return;}if (linejosn?.doImgGen || linejosn?.imageAttachmentInfo) {20 unmodified lines})();dataPromises.push(processPromise);} catch (error) {console.log(error);continue;}}13 unmodified lines}CONFIG.IS_IMG_GEN = false;CONFIG.IS_IMG_GEN2 = false;resolve();} catch (error) {reject(error);}});stream.on('error', (error) => {Logger.error(error, 'Server');reject(error);});});} catch (error) {2 unmodified linesCONFIG.IS_IMG_GEN2 = false;throw error;}}async function handleImageResponse(imageUrl) {//对服务器发送图片请求const MAX_RETRIES = 3;let retryCount = 0;let imageBase64Response;while (retryCount < MAX_RETRIES) {try {//发送图片请求获取图片imageBase64Response = await fetch(`https://assets.grok.com/${imageUrl}`, {method: 'GET',headers: {2 unmodified lines}});if (imageBase64Response.ok) {break; // 如果请求成功,跳出重试循环}retryCount++;if (retryCount === MAX_RETRIES) {throw new Error(`上游服务请求失败! status: ${imageBase64Response.status}`);}// 等待一段时间后重试(可以使用指数退避)await new Promise(resolve => setTimeout(resolve, CONFIG.API.RETRY_TIME * retryCount));} catch (error) {1 unmodified lineif (retryCount === MAX_RETRIES) {throw error;}// 等待一段时间后重试await new Promise(resolve => setTimeout(resolve, CONFIG.API.RETRY_TIME * retryCount));}}const arrayBuffer = await imageBase64Response.arrayBuffer();const imageBuffer = Buffer.from(arrayBuffer);const formData = new FormData();formData.append('source', imageBuffer, {13 unmodified linesif (!responseURL.ok) {return "生图失败,请查看图床密钥是否设置正确"} else {console.log("生图成功");const result = await responseURL.json();return ``}1 unmodified lineconst tokenManager = new AuthTokenManager();await initialization();// 中间件配置const app = express();app.use(Logger.requestLogger);4 unmodified linesmethods: ['GET', 'POST', 'OPTIONS'],allowedHeaders: ['Content-Type', 'Authorization']}));// API路由app.get('/hf/v1/models', (req, res) => {res.json({object: "list",data: Object.keys(CONFIG.MODELS).map((model, index) => ({6 unmodified lines});app.post('/hf/v1/chat/completions', async (req, res) => {try {const authToken = req.headers.authorization?.replace('Bearer ', '');if (authToken !== CONFIG.API.API_KEY) {1 unmodified line}let isTempCookie = req.body.model.includes("grok-2");let retryCount = 0;while (retryCount < CONFIG.RETRY.MAX_ATTEMPTS) {retryCount++;const grokClient = new GrokApiClient(req.body.model);const requestPayload = await grokClient.prepareChatRequest(req.body);console.log(JSON.stringify(requestPayload,null,2));if (!CONFIG.API.TEMP_COOKIE) {await Utils.get_signature();}//获取验证cookieif (isTempCookie) {CONFIG.API.SIGNATURE_COOKIE = CONFIG.API.TEMP_COOKIE;Logger.info(`已切换为临时令牌`, 'Server');} else {CONFIG.API.SIGNATURE_COOKIE = Utils.createAuthHeaders(req.body.model);}Logger.info(`当前令牌索引: ${CONFIG.SSO_INDEX}`, 'Server');const newMessageReq = await fetch(`${CONFIG.API.BASE_URL}/api/rpc`, {12 unmodified linesconst responseText = await newMessageReq.json();const conversationId = responseText.conversationId;//发送对话const response = await fetch(`${CONFIG.API.BASE_URL}/api/conversations/${conversationId}/responses`, {method: 'POST',headers: {12 unmodified linesLogger.info(`当前剩余可用令牌数: ${tokenManager.getTokenCount()}`, 'Server');try {await handleResponse(response, req.body.model, res, req.body.stream);return; // 成功后直接返回} catch (error) {if(isTempCookie){await Utils.get_signature();10 unmodified lines}}} else {// 处理429错误if (response.status === 429) {if (isTempCookie) {await Utils.get_signature();36 unmodified lines});// 404处理app.use((req, res) => {res.status(200).send('api运行正常');});// 启动服务器app.listen(CONFIG.SERVER.PORT, () => {console.log(`服务器已启动,监听端口: ${CONFIG.SERVER.PORT}`);});6 unmodified lines7891011124 unmodified lines171819202122233 unmodified lines27282930313233343536373839404142434445464753 unmodified lines1011021031041051063 unmodified lines1101111121131141151161171181192 unmodified lines12212312412512612712812913013113213313413513613713837 unmodified lines17617717817918018116 unmodified lines19819920020120220320412 unmodified lines2172182192202212228 unmodified lines2312322332342352362372382392402411 unmodified line2432442452462472482492502512522532543 unmodified lines25825926026126226311 unmodified lines27527627727827928028128228347 unmodified lines3313323333343353363375 unmodified lines34334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738866 unmodified lines45545645745845946046164 unmodified lines5265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645 unmodified lines5705715725735745755765772 unmodified lines58058158258358458558658758858959059159259359459520 unmodified lines61661761861962062113 unmodified lines6356366376386396406416426436446456466476482 unmodified lines6516526536546556566576586596606616626636646652 unmodified lines6686696706716726736746756766776781 unmodified line68068168268368468568668768868969069169269369469569669769869913 unmodified lines7137147157167177187191 unmodified line7217227237247257267274 unmodified lines7327337347357367377387396 unmodified lines7467477487497507517521 unmodified line75475575675775875976076176276376476576676776876977077177277312 unmodified lines78678778878979079179212 unmodified lines80580680780880981081110 unmodified lines82282382482582682736 unmodified lines8648658668678688698708718728738746 unmodified linesimport StealthPlugin from 'puppeteer-extra-plugin-stealth'import { v4 as uuidv4 } from 'uuid';import Logger from './logger.js';dotenv.config();4 unmodified lines'grok-2-imageGen': 'grok-latest','grok-2-search': 'grok-latest',"grok-3": "grok-3","grok-3-search": "grok-3","grok-3-imageGen": "grok-3","grok-3-deepsearch": "grok-3","grok-3-reasoning": "grok-3"3 unmodified linesAPI_KEY: process.env.API_KEY || "sk-123456",SIGNATURE_COOKIE: null,TEMP_COOKIE: null,PICGO_KEY: process.env.PICGO_KEY || null //想要流式生图的话需要填入这个PICGO图床的key},SERVER: {PORT: process.env.PORT || 3000,BODY_LIMIT: '5mb'},RETRY: {MAX_ATTEMPTS: 2//重试次数},SHOW_THINKING:process.env.SHOW_THINKING === 'true',IS_THINKING: false,IS_IMG_GEN: false,IS_IMG_GEN2: false,SSO_INDEX: 0,//sso的索引ISSHOW_SEARCH_RESULTS: process.env.ISSHOW_SEARCH_RESULTS === 'true',//是否显示搜索结果CHROME_PATH: process.env.CHROME_PATH || "/usr/bin/chromium"//chrome路径};puppeteer.use(StealthPlugin())53 unmodified lines}getTokenByIndex(index, model) {if(this.activeTokens.length === 0){return null;}3 unmodified lines}recordModelRequest(token, model) {if(model === 'grok-3-search' || model === 'grok-3-imageGen'){model = 'grok-3';}if (!this.modelRateLimit[model]) return;const tokenFrequency = this.tokenModelFrequency.get(token);if (tokenFrequency && tokenFrequency[model] !== undefined) {2 unmodified linesthis.checkAndRemoveTokenIfLimitReached(token);}setModelLimit(index, model) {if(model === 'grok-3-search' || model === 'grok-3-imageGen'){model = 'grok-3';}if (!this.modelRateLimit[model]) return;const tokenFrequency = this.tokenModelFrequency.get(this.activeTokens[index]);tokenFrequency[model] = 9999;}isTokenModelLimitReached(index, model) {if(model === 'grok-3-search' || model === 'grok-3-imageGen'){model = 'grok-3';}if (!this.modelRateLimit[model]) return;const token = this.activeTokens[index];const tokenFrequency = this.tokenModelFrequency.get(token);37 unmodified linesif (now - expiredTime >= 2 * 60 * 60 * 1000) {this.tokenModelUsage.set(token, {"grok-3": 0,"grok-3-deepsearch": 0,"grok-3-reasoning": 0});16 unmodified linesclass Utils {static async extractGrokHeaders() {Logger.info("开始提取头信息", 'Server');try {// 启动浏览器const browser = await puppeteer.launch({12 unmodified linesawait page.evaluate(() => {return new Promise(resolve => setTimeout(resolve, 5000))})// 获取所有 Cookiesconst cookies = await page.cookies();const targetHeaders = ['x-anonuserid', 'x-challenge', 'x-signature'];8 unmodified lines// 关闭浏览器await browser.close();// 打印并返回提取的头信息Logger.info('提取的头信息:', JSON.stringify(extractedHeaders, null, 2), 'Server');return extractedHeaders;} catch (error) {Logger.error('获取头信息出错:', error, 'Server');return null;}}1 unmodified lineif (CONFIG.API.TEMP_COOKIE) {return CONFIG.API.TEMP_COOKIE;}Logger.info("刷新认证信息", 'Server');let retryCount = 0;while (!CONFIG.API.TEMP_COOKIE || retryCount < CONFIG.RETRY.MAX_ATTEMPTS) {let headers = await Utils.extractGrokHeaders();if (headers) {Logger.info("获取认证信息成功", 'Server');CONFIG.API.TEMP_COOKIE = { cookie: `x-anonuserid=${headers["x-anonuserid"]}; x-challenge=${headers["x-challenge"]}; x-signature=${headers["x-signature"]}` };return;}3 unmodified lines}}}static async organizeSearchResults(searchResults) {// 确保传入的是有效的搜索结果对象if (!searchResults || !searchResults.results) {11 unmodified lines});return formattedResults.join('\n\n');}static async createAuthHeaders(model) {return {'cookie': `${await tokenManager.getTokenByIndex(CONFIG.SSO_INDEX, model)}`};}}47 unmodified linescontent: imageBuffer}};Logger.info("发送图片请求", 'Server');// 发送请求const response = await fetch(url, {method: 'POST',5 unmodified lines});if (!response.ok) {Logger.error(`上传图片失败,状态码:${response.status},原因:${response.error}`, 'Server');return '';}const result = await response.json();Logger.info('上传图片成功:', result, 'Server');return result.fileMetadataId;} catch (error) {Logger.error(error, 'Server');return '';}}async prepareChatRequest(request) {if ((request.model === 'grok-2-imageGen' || request.model === 'grok-3-imageGen') && !CONFIG.API.PICGO_KEY && request.stream) {throw new Error(`该模型流式输出需要配置PICGO图床密钥!`);}// 处理画图模型的消息限制let todoMessages = request.messages;if (request.model === 'grok-2-imageGen' || request.model === 'grok-3-imageGen') {const lastMessage = todoMessages[todoMessages.length - 1];if (lastMessage.role !== 'user') {throw new Error('画图模型的最后一条消息必须是用户消息!');}todoMessages = [lastMessage];}const fileAttachments = [];let messages = '';let lastRole = null;let lastContent = '';const search = request.model === 'grok-2-search' || request.model === 'grok-3-search';// 移除<think>标签及其内容和base64图片const removeThinkTags = (text) => {text = text.replace(/<think>[\s\S]*?<\/think>/g, '').trim();text = text.replace(/!\[image\]\(data:.*?base64,.*?\)/g, '[图片]');return text;};const processImageUrl = async (content) => {66 unmodified linesreturn {modelName: this.modelId,message: messages.trim(),fileAttachments: fileAttachments.slice(0, 4),imageAttachments: [],disableSearch: false,enableImageGeneration: true,64 unmodified lines}return result;}//非生图模型的处理switch (model) {case 'grok-2':result.token = linejosn?.token;return result;case 'grok-2-search':case 'grok-3-search':if (linejosn?.webSearchResults && CONFIG.ISSHOW_SEARCH_RESULTS) {result.token = `\r\n<think>${await Utils.organizeSearchResults(linejosn.webSearchResults)}</think>\r\n`;} else {result.token = linejosn?.token;}return result;case 'grok-3':result.token = linejosn?.token;return result;case 'grok-3-deepsearch':if (linejosn.messageTag === "final") {result.token = linejosn?.token;}return result;case 'grok-3-reasoning':if(linejosn?.isThinking && !CONFIG.SHOW_THINKING)return result;if (linejosn?.isThinking && !CONFIG.IS_THINKING) {result.token = "<think>" + linejosn?.token;CONFIG.IS_THINKING = true;} else if (CONFIG.IS_THINKING && !linejosn.isThinking) {result.token = "</think>" + linejosn?.token;CONFIG.IS_THINKING = false;} else {result.token = linejosn?.token;}return result;}5 unmodified lineslet buffer = '';let fullResponse = '';const dataPromises = [];return new Promise((resolve, reject) => {stream.on('data', async (chunk) => {buffer += chunk.toString();const lines = buffer.split('\n');2 unmodified linesfor (const line of lines) {if (!line.trim()) continue;const trimmedLine = line.trim();if (trimmedLine.startsWith('data: ')) {const data = trimmedLine.substring(6);try {if (!data.trim()) continue;if(data === "[DONE]") continue;const linejosn = JSON.parse(data);if (linejosn?.error) {Logger.error(JSON.stringify(linejosn,null,2), 'Server');stream.destroy();reject(new Error("RateLimitError"));return;}if (linejosn?.doImgGen || linejosn?.imageAttachmentInfo) {20 unmodified lines})();dataPromises.push(processPromise);} catch (error) {continue;}}13 unmodified lines}CONFIG.IS_IMG_GEN = false;CONFIG.IS_IMG_GEN2 = false;resolve();} catch (error) {reject(error);}});stream.on('error', (error) => {reject(error);});});} catch (error) {2 unmodified linesCONFIG.IS_IMG_GEN2 = false;throw error;}}async function handleImageResponse(imageUrl) {const MAX_RETRIES = 2;let retryCount = 0;let imageBase64Response;while (retryCount < MAX_RETRIES) {try {imageBase64Response = await fetch(`https://assets.grok.com/${imageUrl}`, {method: 'GET',headers: {2 unmodified lines}});if (imageBase64Response.ok) break;retryCount++;if (retryCount === MAX_RETRIES) {throw new Error(`上游服务请求失败! status: ${imageBase64Response.status}`);}await new Promise(resolve => setTimeout(resolve, CONFIG.API.RETRY_TIME * retryCount));} catch (error) {1 unmodified lineif (retryCount === MAX_RETRIES) {throw error;}await new Promise(resolve => setTimeout(resolve, CONFIG.API.RETRY_TIME * retryCount));}}const arrayBuffer = await imageBase64Response.arrayBuffer();const imageBuffer = Buffer.from(arrayBuffer);if(!CONFIG.API.PICGO_KEY){const base64Image = imageBuffer.toString('base64');const imageContentType = imageBase64Response.headers.get('content-type');return ``}const formData = new FormData();formData.append('source', imageBuffer, {13 unmodified linesif (!responseURL.ok) {return "生图失败,请查看图床密钥是否设置正确"} else {Logger.info("生图成功", 'Server');const result = await responseURL.json();return ``}1 unmodified lineconst tokenManager = new AuthTokenManager();await initialization();// 中间件配置const app = express();app.use(Logger.requestLogger);4 unmodified linesmethods: ['GET', 'POST', 'OPTIONS'],allowedHeaders: ['Content-Type', 'Authorization']}));app.get('/v1/models', (req, res) => {res.json({object: "list",data: Object.keys(CONFIG.MODELS).map((model, index) => ({6 unmodified lines});app.post('/v1/chat/completions', async (req, res) => {try {const authToken = req.headers.authorization?.replace('Bearer ', '');if (authToken !== CONFIG.API.API_KEY) {1 unmodified line}let isTempCookie = req.body.model.includes("grok-2");let retryCount = 0;const grokClient = new GrokApiClient(req.body.model);const requestPayload = await grokClient.prepareChatRequest(req.body);while (retryCount < CONFIG.RETRY.MAX_ATTEMPTS) {retryCount++;if (!CONFIG.API.TEMP_COOKIE) {await Utils.get_signature();}if (isTempCookie) {CONFIG.API.SIGNATURE_COOKIE = CONFIG.API.TEMP_COOKIE;Logger.info(`已切换为临时令牌`, 'Server');} else {CONFIG.API.SIGNATURE_COOKIE = await Utils.createAuthHeaders(req.body.model);}Logger.info(`当前令牌索引: ${CONFIG.SSO_INDEX}`, 'Server');const newMessageReq = await fetch(`${CONFIG.API.BASE_URL}/api/rpc`, {12 unmodified linesconst responseText = await newMessageReq.json();const conversationId = responseText.conversationId;const response = await fetch(`${CONFIG.API.BASE_URL}/api/conversations/${conversationId}/responses`, {method: 'POST',headers: {12 unmodified linesLogger.info(`当前剩余可用令牌数: ${tokenManager.getTokenCount()}`, 'Server');try {await handleResponse(response, req.body.model, res, req.body.stream);return;} catch (error) {if(isTempCookie){await Utils.get_signature();10 unmodified lines}}} else {if (response.status === 429) {if (isTempCookie) {await Utils.get_signature();36 unmodified lines});app.use((req, res) => {res.status(200).send('api运行正常');});app.listen(CONFIG.SERVER.PORT, () => {Logger.info(`服务器已启动,监听端口: ${CONFIG.SERVER.PORT}`, 'Server');});
index.js+88-120