File size: 21,454 Bytes
b65bb2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d388885
04b10b6
b65bb2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64415d9
b65bb2a
 
 
 
fb3eefa
 
 
 
 
 
 
 
 
 
d388885
fb3eefa
 
 
64415d9
fb3eefa
 
64415d9
fb3eefa
d388885
dcc5257
64415d9
 
b65bb2a
 
 
 
 
 
 
 
 
 
 
64415d9
b65bb2a
 
 
fb3eefa
dcc5257
b65bb2a
 
 
d388885
b65bb2a
 
 
 
 
 
 
 
 
 
 
 
 
 
d388885
 
643ea85
 
d388885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
643ea85
 
 
 
 
 
 
 
d388885
 
 
 
 
 
 
b65bb2a
fb3eefa
b65bb2a
 
fb3eefa
 
 
 
 
 
b65bb2a
 
d388885
b65bb2a
 
 
 
 
fb3eefa
d388885
fb3eefa
d388885
 
 
 
 
 
 
 
 
 
 
643ea85
d388885
 
 
 
 
 
 
 
 
fb3eefa
b65bb2a
 
 
 
d388885
fb3eefa
 
 
 
 
 
b65bb2a
fb3eefa
 
b65bb2a
643ea85
 
 
 
 
 
d388885
 
b65bb2a
d388885
b65bb2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64415d9
b65bb2a
 
 
64415d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b65bb2a
64415d9
b65bb2a
 
 
64415d9
 
 
 
 
 
 
 
 
 
b65bb2a
64415d9
 
 
b65bb2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
import fetch from 'node-fetch';
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import puppeteer from 'puppeteer-extra'
import StealthPlugin from 'puppeteer-extra-plugin-stealth'
import UserAgent from 'user-agents';

dotenv.config();

const Tokens = [];
let tokenManager;
let redisClient;
let currentIndex = 0;
let sessionId = null;
const CONFIG = {
  API: {
    BASE_URL: process.env.DENO_URL || "https://partyrock.aws/stream/getCompletion",//如果需要多号循环,需要设置你自己的denourl
    API_KEY: process.env.API_KEY || "sk-123456",//自定义你自己的认证密钥,记得修改
    RedisUrl: process.env.RedisUrl,
    RedisToken: process.env.RedisToken,
    CAPSOLVER_KEY: process.env.CAPSOLVER_KEY // 完全从环境变量读取
  },
  SERVER: {
    PORT: process.env.PORT || 3000,
    BODY_LIMIT: '5mb'
  },
  MODELS: {
    'claude-3-5-haiku-20241022': 'bedrock-anthropic.claude-3-5-haiku',
    'claude-3-5-sonnet-20241022': 'bedrock-anthropic.claude-3-5-sonnet-v2-0',
    'nova-lite-v1-0': 'bedrock-amazon.nova-lite-v1-0',
    'nova-pro-v1-0': 'bedrock-amazon.nova-pro-v1-0',
    'llama3-1-7b': 'bedrock-meta.llama3-1-8b-instruct-v1',
    'llama3-1-70b': 'bedrock-meta.llama3-1-70b-instruct-v1',
    'mistral-small': 'bedrock-mistral.mistral-small-2402-v1-0',
    'mistral-large': 'bedrock-mistral.mistral-large-2407-v1-0'
  },
  DEFAULT_HEADERS: {
    "request-id": "",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
    "Cache-Control": "no-cache, no-store",
    "pragma": "no-cache",
    "Accept": "text/event-stream",
    "Accept-Encoding": "gzip, deflate, br, zstd",
    "Content-Type": "application/json",
    "anti-csrftoken-a2z": "",
    "origin": "https://partyrock.aws",
    "sec-fetch-site": "same-origin",
    "sec-fetch-mode": "cors",
    "sec-fetch-dest": "empty",
    "referer": "",
    "Cookie": "",
    "accept-language": "zh-CN,zh;q=0.9",
    "priority": "u=1, i"
  },
  CHROME_PATH: process.env.CHROME_PATH || "/usr/bin/chromium"
};
var RedisClient = class {
  constructor() {
    this.url = CONFIG.API.RedisUrl;
    this.token = CONFIG.API.RedisToken;
  }
  async get(key) {
    const response = await fetch(`${this.url}/get/${key}`, {
      headers: {
        Authorization: `Bearer ${this.token}`
      }
    });
    if (!response.ok) {
      console.log("redis获取内容失败", response.status);
    }
    const data = await response.json();
    return data.result;
  }
  async set(key, value) {
    const url = `${this.url}/set/${key}`;
    const response = await fetch(url, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${this.token}`
      },
      body: `${value}`
    });
    if (!response.ok) {
      console.log("redis设置内容失败", response.status);
    }
  }
};
class TokenManager {
  async updateRedisTokens() {
    await redisClient.set(`tokens_${currentIndex}`, JSON.stringify(Tokens[currentIndex]));
  }
  async getRedisTokens() {
    var checkRedis = JSON.parse(await redisClient.get(`tokens_${currentIndex}`));
    return checkRedis;
  }

  async updateCacheTokens() {
    sessionId = Utils.uuidv4();
    CONFIG.DEFAULT_HEADERS["anti-csrftoken-a2z"] = Tokens[currentIndex].anti_csrftoken_a2z;
    CONFIG.DEFAULT_HEADERS.Cookie = `idToken=${Tokens[currentIndex].idToken}; pr_refresh_token=${Tokens[currentIndex].pr_refresh_token};aws-waf-token=${Tokens[currentIndex].aws_waf_token};cwr_s=${Tokens[currentIndex].cwr_s};cwr_u=${sessionId}`;
    CONFIG.DEFAULT_HEADERS.referer = Tokens[currentIndex].refreshUrl;
    CONFIG.DEFAULT_HEADERS["request-id"] = `request-id-${Utils.uuidv4()}`;
    CONFIG.DEFAULT_HEADERS["User-Agent"] = await Utils.getRandomUserAgent();
  }

  async updateTokens(response, isWaf = false) {
    if (isWaf) {
      let wafToken = await Utils.extractWaf();
      console.log("原aws-waf-token:", Tokens[currentIndex].aws_waf_token);
      
      // 如果新 token 与旧 token 相同,等待后重试一次
      if (wafToken === Tokens[currentIndex].aws_waf_token) {
        console.log("⚠️ 更新后的aws-waf-token与现有token一致,等待后重试一次");
        await new Promise(resolve => setTimeout(resolve, 1000));
        wafToken = await Utils.extractWaf();
      }
      
      if (wafToken) {
        console.log("新获取的aws-waf-token:", wafToken);
        if (wafToken !== Tokens[currentIndex].aws_waf_token) {
          console.log("✅ 成功更新aws-waf-token | 新token长度:", wafToken.length);
          Tokens[currentIndex].aws_waf_token = wafToken;
        } else {
          console.log("⚠️ 重试后aws-waf-token依旧与现有token一致");
        }
        // 更新内存缓存和Redis持久化
        await this.updateCacheTokens();
        await this.updateRedisTokens();
      } else {
        console.log("❌ 提取aws-waf-token失败");
      }
    } else {
      const newCsrfToken = response.headers.get('anti-csrftoken-a2z');
      const cookies = response.headers.get('set-cookie');
      if (newCsrfToken && cookies) {
        console.log("更新缓存");
        Tokens[currentIndex].anti_csrftoken_a2z = newCsrfToken;
        const idTokenMatch = cookies.match(/idToken=([^;]+)/);
        if (idTokenMatch && idTokenMatch[1]) {
          Tokens[currentIndex].idToken = idTokenMatch[1];
        }
        await this.updateRedisTokens();
        console.log("更新缓存完毕");
      }
    }
    // 单账号场景下轮换仍然无副作用
    currentIndex = (currentIndex + 1) % Tokens.length;
  }
}


class Utils {
  static async getRandomUserAgent() {
    try {
      let type = ["Win32", "MacIntel", "Linux x86_64"]
      const userAgent = new UserAgent({ platform: type[Math.floor(Math.random() * type.length)] });
      return userAgent.random().toString();
    } catch (error) {
      let type = [
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Safari/605.1.15"
      ]
      return type[Math.floor(Math.random() * type.length)]
    }
  }
  static async solveAwsWaf(images, questionType = 'aws:grid') {
    try {
      console.log(`开始Capsolver验证 (类型: ${questionType}), 图片数量: ${images.length}`);
      
      const response = await fetch('https://api.capsolver.com/createTask', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          clientKey: CONFIG.API.CAPSOLVER_KEY,
          task: {
            type: 'AwsWafClassification',
            websiteURL: Tokens[currentIndex].refreshUrl,
            images: images,
            question: questionType
          }
        })
      });

      const data = await response.json();
      if (data.errorId === 0) {
        if (data.status === 'ready') {
          console.log(`✅ Capsolver验证成功 | 任务ID: ${data.taskId} | 使用图片: ${images.length}张`);
          return data.solution;
        }
        console.log(`⏳ Capsolver处理中 | 任务ID: ${data.taskId} | 状态: ${data.status}`);
      } else {
        console.error(`❌ Capsolver错误 | 代码: ${data.errorCode} | 描述: ${data.errorDescription}`);
      }
      return null;
    } catch (error) {
      console.error('Capsolver请求失败:', error);
      return null;
    }
  }
  static async extractWaf() {
    puppeteer.use(StealthPlugin());
    const browser = await puppeteer.launch({
      headless: true,
      args: [
        '--no-sandbox',
        '--disable-setuid-sandbox',
        '--disable-dev-shm-usage',
        '--disable-gpu'
      ],
      executablePath: CONFIG.CHROME_PATH
    });

    try {
      const page = await browser.newPage();
      await page.setExtraHTTPHeaders({
        cookie: `pr_refresh_token=${Tokens[currentIndex].pr_refresh_token};idToken=${Tokens[currentIndex].idToken};aws-waf-token=${Tokens[currentIndex].aws_waf_token};cwr_s=${Tokens[currentIndex].cwr_s};cwr_u=${Utils.uuidv4()}`
      });
      await page.setUserAgent(CONFIG.DEFAULT_HEADERS["User-Agent"]);

      // 监听验证挑战事件,自动截屏并解决挑战
      page.on('response', async (response) => {
        if (response.url().includes('aws-waf-challenge')) {
          const screenshots = [];
          const challengeElements = await page.$$('.aws-waf-challenge');
          for (const element of challengeElements) {
            const screenshot = await element.screenshot({ encoding: 'base64' });
            screenshots.push(`data:image/png;base64,${screenshot}`);
          }

          const solution = await this.solveAwsWaf(screenshots, 'aws:grid');
          if (solution?.objects) {
            console.log(`🎯 验证答案位置: ${solution.objects.join(', ')}`);
            await page.evaluate((objects) => {
              document.querySelectorAll('.grid-item').forEach((el, index) => {
                if (objects.includes(index)) el.click();
              });
            }, solution.objects);
          }
        }
      });

      // 进入验证页
      await page.goto(Tokens[currentIndex].refreshUrl, {
        waitUntil: 'networkidle2',
        timeout: 30000
      });

      // 延长等待时间让挑战完成(根据实际情况可调整)
      await page.waitForTimeout(5000);

      // 再次等待,确保所有动态变动已结束
      const cookies = await page.cookies();
      const awsWafCookie = cookies.find(
        cookie => cookie.name.toLowerCase() === 'aws-waf-token'
      );
      const awsWafToken = awsWafCookie ? awsWafCookie.value : null;

      if (awsWafToken) {
        console.log(`🔑 成功获取aws-waf-token | 长度: ${awsWafToken.length}字符`);
      } else {
        console.error('❌ 获取aws-waf-token失败');
      }

      await browser.close();
      return awsWafToken;
    } catch (error) {
      console.error('获取aws-waf-token出错:', error);
      await browser.close();
      return null;
    }
  }

  static async extractTokens(cookieString) {
    const tokens = {};
    const cookiePairs = cookieString.split(';').map(pair => pair.trim());

    cookiePairs.forEach(pair => {
      const splitIndex = pair.indexOf('=');
      const key = pair.slice(0, splitIndex).trim();
      const value = pair.slice(splitIndex + 1).trim();

      tokens[key] = value;
    });

    return tokens;
  }
  // 获取数组中的随机元素
  static getRandomElement(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
  }

  // 生成UUID
  static uuidv4() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      const r = (Math.random() * 16) | 0;
      const v = c === 'x' ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    });
  }

  // 生成随机十六进制字符串
  static generateRandomHexString(length) {
    let result = '';
    const characters = '0123456789ABCDEF';
    for (let i = 0; i < length; i++) {
      result += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return result;
  }
}
async function initializeService() {
  console.log('服务初始化中...');
  tokenManager = new TokenManager();
  redisClient = new RedisClient();
  let index = 0;
  while (true) {
    console.log(index, '开始检测是否有缓存');
    // 使用 JSON.parse 确保正确解析
    var checkRedis = await redisClient.get(`tokens_${index}`);
    if (checkRedis) {
      // 尝试解析 JSON 字符串
      try {
        const parsedRedis = typeof checkRedis === 'string'
          ? JSON.parse(checkRedis)
          : checkRedis;
        Tokens.push({
          refreshUrl: parsedRedis.refreshUrl,
          anti_csrftoken_a2z: parsedRedis.anti_csrftoken_a2z,
          pr_refresh_token: parsedRedis.pr_refresh_token,
          aws_waf_token: parsedRedis.aws_waf_token,
          idToken: parsedRedis.idToken,
          cwr_s: parsedRedis.cwr_s
        });
        console.log(`成功添加第 ${index} 组 Token`);
      } catch (error) {
        console.error(`解析第 ${index} 组 Token 时出错:`, error);
      }
    } else {
      console.log(index, '没有缓存,开始提取环境变量');
      const refreshUrl = process.env[`AUTH_TOKENS_${index}_REFRESH_URL`];
      const anti_csrftoken_a2z = process.env[`AUTH_TOKENS_${index}_ANTI_CSRF_TOKEN`];
      const cookie = process.env[`AUTH_TOKENS_${index}_COOKIE`];

      if (!refreshUrl && !anti_csrftoken_a2z && !cookie) {
        break;
      }
      const cookies = await Utils.extractTokens(cookie);

      if (refreshUrl && anti_csrftoken_a2z && cookie) {
        Tokens.push({
          refreshUrl,
          anti_csrftoken_a2z,
          pr_refresh_token: cookies["pr_refresh_token"],
          aws_waf_token: cookies["aws-waf-token"],
          idToken: cookies["idToken"],
          cwr_s: cookies["cwr_s"]
        });
      }
    }
    index++;
  }
  console.log('服务初始化完毕');
}

await initializeService();

class ApiClient {
  constructor(modelId) {
    if (!CONFIG.MODELS[modelId]) {
      throw new Error(`不支持的模型: ${modelId}`);
    }
    this.modelId = CONFIG.MODELS[modelId];
  }

  processMessageContent(content) {
    if (typeof content === 'string') return content;

    if (Array.isArray(content)) {
      return content
        .map(item => item.text)
        .join('\n');
    }

    if (typeof content === 'object') return content.text || null;
    return null;
  }

  //合并相同role的消息
  async transformMessages(request) {
    const mergedMessages = await request.messages.reduce(async (accPromise, current) => {
      const acc = await accPromise;
      const lastMessage = acc[acc.length - 1];
      if (lastMessage && lastMessage.role == "system") {
        lastMessage.role = "user"
      }
      if (current && current.role == "system") {
        current.role = "user"
      }
      const currentContent = this.processMessageContent(current.content);

      if (currentContent === null) return acc;

      if (lastMessage && current && (lastMessage.role == current.role)) {
        const lastContent = this.processMessageContent(lastMessage.content);
        if (lastContent !== null) {
          lastMessage.content = [
            {
              "text": `${lastContent}\r\n${currentContent}`
            }
          ];
          return acc;
        }
      }
      current.content = [
        {
          "text": currentContent
        }
      ]
      acc.push(current);
      return acc;
    }, Promise.resolve([]));
    // 处理请求参数
    let topP = request.top_p || 0.5;
    let temperature = request.temperature || 0.95;
    if (topP >= 1) {
      topP = 1;
    }
    if (temperature >= 1) {
      temperature = 1;
    }
    const extractPartyRockId = url => url.match(/https:\/\/partyrock\.aws\/u\/[^/]+\/([^/]+)/)?.[1];
    console.log("当前请求的是", CONFIG.DEFAULT_HEADERS.referer);

    const requestPayload = {
      "messages": mergedMessages,
      "modelName": this.modelId,
      "context": {
        "type": "chat-widget",
        "appId": extractPartyRockId(CONFIG.DEFAULT_HEADERS.referer)
      },
      "options": {
        "temperature": temperature,
        "topP": topP
      },
      "apiVersion": 3
    }
    return requestPayload;
  }
}
class MessageProcessor {
  static createChatResponse(message, model, isStream = false) {
    const baseResponse = {
      id: `chatcmpl-${Utils.uuidv4()}`,
      created: Math.floor(Date.now() / 1000),
      model: model
    };

    if (isStream) {
      return {
        ...baseResponse,
        object: 'chat.completion.chunk',
        choices: [{
          index: 0,
          delta: { content: message }
        }]
      };
    }

    return {
      ...baseResponse,
      object: 'chat.completion',
      choices: [{
        index: 0,
        message: {
          role: 'assistant',
          content: message
        },
        finish_reason: 'stop'
      }],
      usage: null
    };
  }
}
class ResponseHandler {
  static async handleStreamResponse(response, model, res) {
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');

    try {
      const stream = response.body;
      let buffer = '';
      let decoder = new TextDecoder('utf-8');
      stream.on('data', (chunk) => {
        buffer += decoder.decode(chunk, { stream: true });
        const lines = buffer.split('\n');
        buffer = lines.pop() || '';

        for (const line of lines) {
          if (!line.trim()) continue;
          if (line.startsWith('data: ')) {
            const data = line.substring(6);
            if (!data) continue;
            if (data == "[DONE]") {
              res.write('data: [DONE]\n\n');
              return res.end();
            }
            try {
              const json = JSON.parse(data);
              if (json?.text) {
                var content = json.text;
                const responseData = MessageProcessor.createChatResponse(content, model, true);
                res.write(`data: ${JSON.stringify(responseData)}\n\n`);
              }
            } catch (error) {
              console.error('JSON解析错误:', error);
            }
          }
        }
      });
      stream.on('end', () => {
        res.write('data: [DONE]\n\n');
        res.end();
      });
      stream.on('error', (error) => {
        console.error('流处理错误:', error);
        res.write('data: [DONE]\n\n');
        res.end();
      });

    } catch (error) {
      console.error('处理响应错误:', error);
      res.write('data: [DONE]\n\n');
      res.end();
    }
  }

  static async handleNormalResponse(response, model, res) {
    const text = await response.text();
    const lines = text.split("\n");
    let fullResponse = '';

    for (let line of lines) {
      line = line.trim();
      if (line) {
        if (line.startsWith('data: ')) {
          let data = line.substring(6);
          if (data === '[DONE]') break;
          try {
            let json = JSON.parse(data)
            if (json?.text) {
              fullResponse += json.text;
            }
          } catch (error) {
            console.log("json解析错误");
            continue
          }
        }
      }
    }
    const responseData = MessageProcessor.createChatResponse(fullResponse, model);
    res.json(responseData);
  }
}
// Express 应用设置
const app = express();
app.use(express.json({ limit: CONFIG.SERVER.BODY_LIMIT }));
app.use(express.urlencoded({ extended: true, limit: CONFIG.SERVER.BODY_LIMIT }));

app.use(cors({
  origin: '*',
  methods: ['GET', 'POST', 'OPTIONS'],
  allowedHeaders: ['*']
}));
// 路由处理
app.get('/hf/v1/models', (req, res) => {
  res.json({
    object: "list",
    data: Object.keys(CONFIG.MODELS).map((model, index) => ({
      id: model,
      object: "model",
      created: Math.floor(Date.now() / 1000),
      owned_by: "partyrock",
    }))
  });
});

app.post('/hf/v1/chat/completions', async (req, res) => {
  var reqStatus = 500;
  try {
    const authToken = req.headers.authorization?.replace('Bearer ', '');
    if (authToken !== CONFIG.API.API_KEY) {
      return res.status(401).json({ error: "Unauthorized" });
    }
    // 每次请求前确保请求头更新为最新的token信息
    await tokenManager.updateCacheTokens();
    const apiClient = new ApiClient(req.body.model);
    const requestPayload = await apiClient.transformMessages(req.body);

    console.log("开始请求");
    let response = await fetch(`${CONFIG.API.BASE_URL}`, {
      method: "POST",
      headers: { ...CONFIG.DEFAULT_HEADERS },
      body: JSON.stringify(requestPayload)
    });
    reqStatus = response.status;

    // 当出现请求受限或人机验证时,先更新token,再重试一次
    if ([202, 405].includes(reqStatus)) {
      console.log("请求受限或人机验证,正在更新token并重试请求");
      await tokenManager.updateTokens(response, true);
      // 延时1秒,等待新token生效
      await new Promise(resolve => setTimeout(resolve, 1000));
      response = await fetch(`${CONFIG.API.BASE_URL}`, {
        method: "POST",
        headers: { ...CONFIG.DEFAULT_HEADERS },
        body: JSON.stringify(requestPayload)
      });
      reqStatus = response.status;
    }

    if (reqStatus === 200) {
      console.log("请求成功");
      // 异步更新token(注意此处可不用 await 以保证响应速度)
      tokenManager.updateTokens(response);
      if (req.body.stream) {
        await ResponseHandler.handleStreamResponse(response, req.body.model, res);
      } else {
        await ResponseHandler.handleNormalResponse(response, req.body.model, res);
      }
      return;
    } else {
      throw new Error(`请求失败! status: ${response.statusText}`);
    }
  } catch (error) {
    res.status(parseInt(reqStatus)).json({
      error: {
        message: error.message,
        type: 'server_error',
        param: null,
        code: error.code || null
      }
    });
  }
});


app.use((req, res) => {
  res.status(404).send("API服务运行正常,,请使用正确请求路径");
});

// 启动服务器
app.listen(CONFIG.SERVER.PORT, () => {
  console.log(`服务器运行在端口 ${CONFIG.SERVER.PORT} `);
});