Spaces:
Paused
Paused
Update index.js
Browse files
index.js
CHANGED
|
@@ -2,16 +2,20 @@ import fetch from 'node-fetch';
|
|
| 2 |
import express from 'express';
|
| 3 |
import cors from 'cors';
|
| 4 |
import dotenv from 'dotenv';
|
|
|
|
| 5 |
|
| 6 |
dotenv.config();
|
| 7 |
|
| 8 |
-
const Tokens =[];
|
| 9 |
let tokenManager;
|
|
|
|
| 10 |
let currentIndex = 0;
|
| 11 |
const CONFIG = {
|
| 12 |
API: {
|
| 13 |
BASE_URL: "https://partyrock.aws",
|
| 14 |
-
API_KEY: process.env.API_KEY || "sk-123456"
|
|
|
|
|
|
|
| 15 |
},
|
| 16 |
RETRY: {
|
| 17 |
MAX_ATTEMPTS: 1,
|
|
@@ -49,33 +53,127 @@ const CONFIG = {
|
|
| 49 |
"Cookie": "",
|
| 50 |
"accept-language": "zh-CN,zh;q=0.9",
|
| 51 |
"priority": "u=1, i"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
}
|
| 53 |
};
|
| 54 |
-
|
| 55 |
class TokenManager {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
async updateCacheTokens() {
|
| 57 |
CONFIG.DEFAULT_HEADERS["anti-csrftoken-a2z"] = Tokens[currentIndex]["anti_csrftoken_a2z"];
|
| 58 |
CONFIG.DEFAULT_HEADERS.Cookie = `idToken=${Tokens[currentIndex]["idToken"]}; pr_refresh_token=${Tokens[currentIndex]["pr_refresh_token"]};aws-waf-token=${Tokens[currentIndex]["aws_waf_token"]}`;
|
| 59 |
CONFIG.DEFAULT_HEADERS.referer = Tokens[currentIndex]["refreshUrl"];
|
| 60 |
}
|
| 61 |
|
| 62 |
-
async updateTokens(response) {
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
}
|
| 67 |
-
|
| 68 |
const cookies = response.headers.get('set-cookie');
|
| 69 |
-
if (cookies) {
|
|
|
|
|
|
|
| 70 |
const idTokenMatch = cookies.match(/idToken=([^;]+)/);
|
| 71 |
if (idTokenMatch && idTokenMatch[1]) {
|
| 72 |
Tokens[currentIndex]["idToken"] = idTokenMatch[1];
|
| 73 |
}
|
|
|
|
|
|
|
| 74 |
}
|
| 75 |
currentIndex = (currentIndex + 1) % Tokens.length;
|
| 76 |
}
|
| 77 |
}
|
|
|
|
|
|
|
| 78 |
class Utils {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
static async extractTokens(cookieString) {
|
| 80 |
const tokens = {};
|
| 81 |
const cookiePairs = cookieString.split(';').map(pair => pair.trim());
|
|
@@ -116,30 +214,55 @@ class Utils {
|
|
| 116 |
}
|
| 117 |
async function initializeService() {
|
| 118 |
console.log('服务初始化中...');
|
| 119 |
-
|
|
|
|
|
|
|
| 120 |
let index = 0;
|
| 121 |
while (true) {
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
if (
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
}
|
| 139 |
index++;
|
| 140 |
}
|
| 141 |
-
|
| 142 |
-
tokenManager = new TokenManager();
|
| 143 |
}
|
| 144 |
|
| 145 |
await initializeService();
|
|
@@ -285,6 +408,10 @@ class ResponseHandler {
|
|
| 285 |
if (trimmedLine && trimmedLine.startsWith('data: ')) {
|
| 286 |
const data = trimmedLine.substring(6);
|
| 287 |
if (!data) continue;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 288 |
try {
|
| 289 |
const json = JSON.parse(data);
|
| 290 |
if (json?.text) {
|
|
@@ -366,6 +493,7 @@ app.get('/hf/v1/models', (req, res) => {
|
|
| 366 |
});
|
| 367 |
|
| 368 |
app.post('/hf/v1/chat/completions', async (req, res) => {
|
|
|
|
| 369 |
try {
|
| 370 |
const authToken = req.headers.authorization?.replace('Bearer ', '');
|
| 371 |
if (authToken !== CONFIG.API.API_KEY) {
|
|
@@ -389,16 +517,20 @@ app.post('/hf/v1/chat/completions', async (req, res) => {
|
|
| 389 |
},
|
| 390 |
body: JSON.stringify(requestPayload)
|
| 391 |
});
|
| 392 |
-
await tokenManager.updateTokens(response);
|
| 393 |
if (response.status == 200) {
|
| 394 |
console.log("请求成功");
|
| 395 |
break; // 如果请求成功,跳出重试循环
|
| 396 |
}
|
| 397 |
if (response.status != 200) {
|
| 398 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
}
|
| 400 |
retryCount++;
|
| 401 |
if (retryCount >= CONFIG.RETRY.MAX_ATTEMPTS) {
|
|
|
|
| 402 |
throw new Error(`上游服务请求失败! status: ${response.status}`);
|
| 403 |
}
|
| 404 |
// 等待一段时间后重试
|
|
@@ -418,9 +550,10 @@ app.post('/hf/v1/chat/completions', async (req, res) => {
|
|
| 418 |
} else {
|
| 419 |
await ResponseHandler.handleNormalResponse(response, req.body.model, res);
|
| 420 |
}
|
| 421 |
-
|
|
|
|
| 422 |
} catch (error) {
|
| 423 |
-
res.status(
|
| 424 |
error: {
|
| 425 |
message: error.message,
|
| 426 |
type: 'server_error',
|
|
|
|
| 2 |
import express from 'express';
|
| 3 |
import cors from 'cors';
|
| 4 |
import dotenv from 'dotenv';
|
| 5 |
+
import puppeteer from 'puppeteer';
|
| 6 |
|
| 7 |
dotenv.config();
|
| 8 |
|
| 9 |
+
const Tokens = [];
|
| 10 |
let tokenManager;
|
| 11 |
+
let redisClient;
|
| 12 |
let currentIndex = 0;
|
| 13 |
const CONFIG = {
|
| 14 |
API: {
|
| 15 |
BASE_URL: "https://partyrock.aws",
|
| 16 |
+
API_KEY: process.env.API_KEY || "sk-123456",//自定义你自己的认证密钥,记得修改
|
| 17 |
+
RedisUrl: process.env.RedisUrl,
|
| 18 |
+
RedisToken: process.env.RedisToken
|
| 19 |
},
|
| 20 |
RETRY: {
|
| 21 |
MAX_ATTEMPTS: 1,
|
|
|
|
| 53 |
"Cookie": "",
|
| 54 |
"accept-language": "zh-CN,zh;q=0.9",
|
| 55 |
"priority": "u=1, i"
|
| 56 |
+
},
|
| 57 |
+
CHROME_PATH: process.env.CHROME_PATH || "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"
|
| 58 |
+
};
|
| 59 |
+
var RedisClient = class {
|
| 60 |
+
constructor() {
|
| 61 |
+
this.url = CONFIG.API.RedisUrl;
|
| 62 |
+
this.token = CONFIG.API.RedisToken;
|
| 63 |
+
console.log(this.url, this.token);
|
| 64 |
+
}
|
| 65 |
+
async get(key) {
|
| 66 |
+
const response = await fetch(`${this.url}/get/${key}`, {
|
| 67 |
+
headers: {
|
| 68 |
+
Authorization: `Bearer ${this.token}`
|
| 69 |
+
}
|
| 70 |
+
});
|
| 71 |
+
if (!response.ok) {
|
| 72 |
+
console.log("redis获取内容失败", response.status);
|
| 73 |
+
}
|
| 74 |
+
const data = await response.json();
|
| 75 |
+
return data.result;
|
| 76 |
+
}
|
| 77 |
+
async set(key, value) {
|
| 78 |
+
const url = `${this.url}/set/${key}`;
|
| 79 |
+
const response = await fetch(url, {
|
| 80 |
+
method: "POST",
|
| 81 |
+
headers: {
|
| 82 |
+
Authorization: `Bearer ${this.token}`
|
| 83 |
+
},
|
| 84 |
+
body: `${value}`
|
| 85 |
+
});
|
| 86 |
+
if (!response.ok) {
|
| 87 |
+
console.log("redis设置内容失败", response.status);
|
| 88 |
+
}
|
| 89 |
}
|
| 90 |
};
|
|
|
|
| 91 |
class TokenManager {
|
| 92 |
+
async updateRedisTokens() {
|
| 93 |
+
await redisClient.set(`tokens_${currentIndex}`, JSON.stringify(Tokens[currentIndex]));
|
| 94 |
+
}
|
| 95 |
+
async getRedisTokens() {
|
| 96 |
+
var checkRedis = JSON.parse(await redisClient.get(`tokens_${currentIndex}`));
|
| 97 |
+
return checkRedis;
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
async updateCacheTokens() {
|
| 101 |
CONFIG.DEFAULT_HEADERS["anti-csrftoken-a2z"] = Tokens[currentIndex]["anti_csrftoken_a2z"];
|
| 102 |
CONFIG.DEFAULT_HEADERS.Cookie = `idToken=${Tokens[currentIndex]["idToken"]}; pr_refresh_token=${Tokens[currentIndex]["pr_refresh_token"]};aws-waf-token=${Tokens[currentIndex]["aws_waf_token"]}`;
|
| 103 |
CONFIG.DEFAULT_HEADERS.referer = Tokens[currentIndex]["refreshUrl"];
|
| 104 |
}
|
| 105 |
|
| 106 |
+
async updateTokens(response, isWaf = false) {
|
| 107 |
+
if (isWaf) {
|
| 108 |
+
console.log("更新waf");
|
| 109 |
+
if (await Utils.extractWaf()) {
|
| 110 |
+
Tokens[currentIndex]["aws_waf_token"] = await Utils.extractWaf();
|
| 111 |
+
return;
|
| 112 |
+
} else {
|
| 113 |
+
console.log("提取aws-waf-token失败");
|
| 114 |
+
currentIndex = (currentIndex + 1) % Tokens.length;
|
| 115 |
+
}
|
| 116 |
}
|
| 117 |
+
const newCsrfToken = response.headers.get('anti-csrftoken-a2z');
|
| 118 |
const cookies = response.headers.get('set-cookie');
|
| 119 |
+
if (newCsrfToken && cookies) {
|
| 120 |
+
console.log("更新缓存");
|
| 121 |
+
Tokens[currentIndex]["anti_csrftoken_a2z"] = newCsrfToken;
|
| 122 |
const idTokenMatch = cookies.match(/idToken=([^;]+)/);
|
| 123 |
if (idTokenMatch && idTokenMatch[1]) {
|
| 124 |
Tokens[currentIndex]["idToken"] = idTokenMatch[1];
|
| 125 |
}
|
| 126 |
+
await this.updateRedisTokens();//最后更新redis数据库缓存
|
| 127 |
+
console.log("更新缓存完毕");
|
| 128 |
}
|
| 129 |
currentIndex = (currentIndex + 1) % Tokens.length;
|
| 130 |
}
|
| 131 |
}
|
| 132 |
+
|
| 133 |
+
|
| 134 |
class Utils {
|
| 135 |
+
static async extractWaf() {
|
| 136 |
+
const browser = await puppeteer.launch({
|
| 137 |
+
headless: true,
|
| 138 |
+
args: [
|
| 139 |
+
'--no-sandbox',
|
| 140 |
+
'--disable-setuid-sandbox',
|
| 141 |
+
'--disable-dev-shm-usage',
|
| 142 |
+
'--disable-gpu'
|
| 143 |
+
],
|
| 144 |
+
executablePath: CONFIG.CHROME_PATH
|
| 145 |
+
});
|
| 146 |
+
try {
|
| 147 |
+
const page = await browser.newPage();
|
| 148 |
+
await page.setExtraHTTPHeaders({
|
| 149 |
+
cookie: `pr_refresh_token=${Tokens[currentIndex]["pr_refresh_token"]};aws-waf-token=${Tokens[currentIndex]["aws_waf_token"]};idToken=${Tokens[currentIndex]["idToken"]}`
|
| 150 |
+
});
|
| 151 |
+
|
| 152 |
+
await page.goto(Tokens[currentIndex]["refreshUrl"], { waitUntil: 'networkidle0' });
|
| 153 |
+
|
| 154 |
+
// 直接从页面 cookies 中提取 aws-waf-token
|
| 155 |
+
const awsWafToken = (await page.cookies()).find(
|
| 156 |
+
cookie => cookie.name.toLowerCase() === 'aws-waf-token'
|
| 157 |
+
)?.value;
|
| 158 |
+
|
| 159 |
+
if (awsWafToken) {
|
| 160 |
+
Tokens[currentIndex]["aws_waf_token"] = awsWafToken;
|
| 161 |
+
console.log("成功提取 aws-waf-token");
|
| 162 |
+
await browser.close();
|
| 163 |
+
return awsWafToken;
|
| 164 |
+
} else {
|
| 165 |
+
console.log("提取aws-waf-token失败");
|
| 166 |
+
await browser.close();
|
| 167 |
+
return null;
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
} catch (error) {
|
| 171 |
+
console.error('获取 aws-waf-token 出错:', error);
|
| 172 |
+
await browser.close();
|
| 173 |
+
return null;
|
| 174 |
+
}
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
static async extractTokens(cookieString) {
|
| 178 |
const tokens = {};
|
| 179 |
const cookiePairs = cookieString.split(';').map(pair => pair.trim());
|
|
|
|
| 214 |
}
|
| 215 |
async function initializeService() {
|
| 216 |
console.log('服务初始化中...');
|
| 217 |
+
tokenManager = new TokenManager();
|
| 218 |
+
redisClient = new RedisClient();
|
| 219 |
+
|
| 220 |
let index = 0;
|
| 221 |
while (true) {
|
| 222 |
+
console.log(index, '开始检测是否有缓存');
|
| 223 |
+
// 使用 JSON.parse 确保正确解析
|
| 224 |
+
var checkRedis = await redisClient.get(`tokens_${index}`);
|
| 225 |
+
if (checkRedis) {
|
| 226 |
+
// 尝试解析 JSON 字符串
|
| 227 |
+
try {
|
| 228 |
+
const parsedRedis = typeof checkRedis === 'string'
|
| 229 |
+
? JSON.parse(checkRedis)
|
| 230 |
+
: checkRedis;
|
| 231 |
+
Tokens.push({
|
| 232 |
+
refreshUrl: parsedRedis.refreshUrl,
|
| 233 |
+
anti_csrftoken_a2z: parsedRedis.anti_csrftoken_a2z,
|
| 234 |
+
pr_refresh_token: parsedRedis.pr_refresh_token,
|
| 235 |
+
aws_waf_token: parsedRedis.aws_waf_token,
|
| 236 |
+
idToken: parsedRedis.idToken
|
| 237 |
+
});
|
| 238 |
+
console.log(`成功添加第 ${index} 组 Token`);
|
| 239 |
+
} catch (error) {
|
| 240 |
+
console.error(`解析第 ${index} 组 Token 时出错:`, error);
|
| 241 |
+
}
|
| 242 |
+
} else {
|
| 243 |
+
console.log(index, '没有缓存,开始提取环境变量');
|
| 244 |
+
const refreshUrl = process.env[`AUTH_TOKENS_${index}_REFRESH_URL`];
|
| 245 |
+
const anti_csrftoken_a2z = process.env[`AUTH_TOKENS_${index}_ANTI_CSRF_TOKEN`];
|
| 246 |
+
const cookie = process.env[`AUTH_TOKENS_${index}_COOKIE`];
|
| 247 |
+
|
| 248 |
+
if (!refreshUrl && !anti_csrftoken_a2z && !cookie) {
|
| 249 |
+
break;
|
| 250 |
+
}
|
| 251 |
+
const cookies = await Utils.extractTokens(cookie);
|
| 252 |
+
|
| 253 |
+
if (refreshUrl && anti_csrftoken_a2z && cookie) {
|
| 254 |
+
Tokens.push({
|
| 255 |
+
refreshUrl,
|
| 256 |
+
anti_csrftoken_a2z,
|
| 257 |
+
pr_refresh_token: cookies["pr_refresh_token"],
|
| 258 |
+
aws_waf_token: cookies["aws-waf-token"],
|
| 259 |
+
idToken: cookies["idToken"]
|
| 260 |
+
});
|
| 261 |
+
}
|
| 262 |
}
|
| 263 |
index++;
|
| 264 |
}
|
| 265 |
+
console.log('服务初始化完毕');
|
|
|
|
| 266 |
}
|
| 267 |
|
| 268 |
await initializeService();
|
|
|
|
| 408 |
if (trimmedLine && trimmedLine.startsWith('data: ')) {
|
| 409 |
const data = trimmedLine.substring(6);
|
| 410 |
if (!data) continue;
|
| 411 |
+
if (data == "[DONE]") {
|
| 412 |
+
res.write('data: [DONE]\n\n');
|
| 413 |
+
return res.end();
|
| 414 |
+
}
|
| 415 |
try {
|
| 416 |
const json = JSON.parse(data);
|
| 417 |
if (json?.text) {
|
|
|
|
| 493 |
});
|
| 494 |
|
| 495 |
app.post('/hf/v1/chat/completions', async (req, res) => {
|
| 496 |
+
var reqStatus = 500;
|
| 497 |
try {
|
| 498 |
const authToken = req.headers.authorization?.replace('Bearer ', '');
|
| 499 |
if (authToken !== CONFIG.API.API_KEY) {
|
|
|
|
| 517 |
},
|
| 518 |
body: JSON.stringify(requestPayload)
|
| 519 |
});
|
|
|
|
| 520 |
if (response.status == 200) {
|
| 521 |
console.log("请求成功");
|
| 522 |
break; // 如果请求成功,跳出重试循环
|
| 523 |
}
|
| 524 |
if (response.status != 200) {
|
| 525 |
+
reqStatus = response.status;
|
| 526 |
+
if (response.status == 202) {
|
| 527 |
+
console.log("请求失败,已达到速率,重新获取waf然后更新token库");
|
| 528 |
+
await tokenManager.updateTokens(response, true);
|
| 529 |
+
}
|
| 530 |
}
|
| 531 |
retryCount++;
|
| 532 |
if (retryCount >= CONFIG.RETRY.MAX_ATTEMPTS) {
|
| 533 |
+
reqStatus = response.status;
|
| 534 |
throw new Error(`上游服务请求失败! status: ${response.status}`);
|
| 535 |
}
|
| 536 |
// 等待一段时间后重试
|
|
|
|
| 550 |
} else {
|
| 551 |
await ResponseHandler.handleNormalResponse(response, req.body.model, res);
|
| 552 |
}
|
| 553 |
+
//请求完毕后再尝试更新redis数据库缓存,避免阻塞
|
| 554 |
+
await tokenManager.updateTokens(response);
|
| 555 |
} catch (error) {
|
| 556 |
+
res.status(reqStatus).json({
|
| 557 |
error: {
|
| 558 |
message: error.message,
|
| 559 |
type: 'server_error',
|