-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathworker.js
More file actions
7647 lines (7046 loc) · 266 KB
/
Copy pathworker.js
File metadata and controls
7647 lines (7046 loc) · 266 KB
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const isDeno = typeof Deno !== 'undefined';
const isCf =
!isDeno &&
typeof navigator !== 'undefined' &&
navigator.userAgent === 'Cloudflare-Workers';
const isNode =
!isDeno && !isCf && typeof process !== 'undefined' && process.versions?.node;
// 获取环境变量
const SERVER_TYPE = isDeno ? 'DENO' : isCf ? 'CF' : 'NODE';
function getEnv(key, env = {}) {
if (isDeno) {
return Deno.env.get(key) || '';
} else if (typeof process !== 'undefined' && process.env) {
// Node.js 环境
return process.env[key] || '';
} else {
// Cloudflare Workers环境,从传入的 env 对象获取
return env[key] || '';
}
}
// ⚠️注意: 仅当您有密码共享需求时才需要配置 SECRET_PASSWORD 和 API_KEYS 这两个环境变量! 否则您无需配置, 默认会使用WebUI填写的API Key进行请求
// 这里是您和您的朋友共享的密码, 优先使用环境变量, 双竖线后可以直接硬编码(例如 'yijiaren.308' 免得去管理面板配置环境变量了, 但极不推荐这么做!)
const SECRET_PASSWORD_DEFAULT = `yijiaren.${~~(Math.random() * 1000)}`;
// 这里是您的API密钥清单, 多个时使用逗号分隔, 会轮询(随机)使用, 同样也是优先使用环境变量, 其次使用代码中硬写的值, 注意不要在公开代码仓库中提交密钥的明文信息, 谨防泄露!!
const API_KEYS_DEFAULT = 'sk-xxxxx,sk-yyyyy';
const MODEL_IDS_DEFAULT = 'gpt-5-pro,gpt-5,gpt-5-mini';
const API_BASE_DEFAULT = 'https://api.openai.com';
const DEMO_PASSWORD_DEFAULT = '';
const DEMO_MAX_TIMES_PER_HOUR_DEFAULT = 15;
const TITLE_DEFAULT = 'OpenAI Chat';
// KV 存储适配器 - 兼容 Cloudflare Workers 和 Deno Deploy
let kvStore = null;
/**
* 初始化 KV 存储
* @param {Object} env - 环境变量对象(Cloudflare Workers 会传入)
*/
async function initKV(env = {}) {
if (isDeno) {
// Deno Deploy: 使用 Deno KV
try {
kvStore = await Deno.openKv();
} catch (error) {
console.error('Failed to open Deno KV:', error);
kvStore = null;
}
} else if (env.KV) {
// Cloudflare Workers: 使用绑定的 KV namespace
kvStore = env.KV;
} else {
// 没有 KV 存储,使用内存模拟(不推荐用于生产环境)
console.warn('KV storage not available, using in-memory fallback');
kvStore = null;
}
return kvStore;
}
/**
* 从 KV 存储获取值
* @param {string} key - 键名
* @returns {Promise<any>} - 返回解析后的 JSON 对象,如果不存在返回 null
*/
async function getKV(key) {
if (!kvStore) {
return null;
}
try {
if (isDeno) {
// Deno KV
const result = await kvStore.get([key]);
return result.value;
} else {
// Cloudflare Workers KV
const value = await kvStore.get(key, { type: 'json' });
return value;
}
} catch (error) {
console.error('KV get error:', error);
return null;
}
}
/**
* 向 KV 存储设置值
* @param {string} key - 键名
* @param {any} value - 要存储的值(会被序列化为 JSON)
* @param {number} ttl - 过期时间(秒),可选
* @returns {Promise<boolean>} - 成功返回 true
*/
async function setKV(key, value, ttl = null) {
if (!kvStore) {
return false;
}
try {
if (isDeno) {
// Deno KV
const options = ttl ? { expireIn: ttl * 1000 } : {};
await kvStore.set([key], value, options);
return true;
} else {
// Cloudflare Workers KV
const options = ttl ? { expirationTtl: ttl } : {};
await kvStore.put(key, JSON.stringify(value), options);
return true;
}
} catch (error) {
console.error('KV set error:', error);
return false;
}
}
// 临时演示密码记忆(仅作为 KV 不可用时的后备方案)
const demoMemory = {
hour: 0,
times: 0,
maxTimes: DEMO_MAX_TIMES_PER_HOUR_DEFAULT
};
// API Key 轮询索引
let apiKeyIndex = 0;
// 通用的请求处理函数
async function handleRequest(request, env = {}) {
// 初始化 KV 存储
await initKV(env);
// 从环境变量获取配置
const SECRET_PASSWORD =
getEnv('SECRET_PASSWORD', env) || SECRET_PASSWORD_DEFAULT;
const API_KEYS = getEnv('API_KEYS', env) || API_KEYS_DEFAULT;
const API_KEY_LIST = (API_KEYS || '')
.split(',')
.map(i => i.trim())
.filter(i => i);
const MODEL_IDS = getEnv('MODEL_IDS', env) || MODEL_IDS_DEFAULT;
const API_BASE = (getEnv('API_BASE', env) || API_BASE_DEFAULT).replace(
/\/$/,
''
);
const DEMO_PASSWORD = getEnv('DEMO_PASSWORD', env) || DEMO_PASSWORD_DEFAULT;
const DEMO_MAX_TIMES =
parseInt(getEnv('DEMO_MAX_TIMES_PER_HOUR', env)) ||
DEMO_MAX_TIMES_PER_HOUR_DEFAULT;
const TAVILY_KEYS = getEnv('TAVILY_KEYS', env) || '';
const TAVILY_KEY_LIST = (TAVILY_KEYS || '')
.split(',')
.map(i => i.trim())
.filter(i => i);
const TITLE = getEnv('TITLE', env) || TITLE_DEFAULT;
const TTS_API_BASE = (getEnv('TTS_API_BASE', env) || '').replace(/\/$/, '');
const TTS_API_KEY = getEnv('TTS_API_KEY', env) || '';
const ttsEnabled = !!(TTS_API_BASE && TTS_API_KEY);
let CHAT_TYPE = 'bot';
if (/openai/i.test(TITLE)) {
CHAT_TYPE = 'openai';
} else if (/gemini/i.test(TITLE)) {
CHAT_TYPE = 'gemini';
} else if (/claude/i.test(TITLE)) {
CHAT_TYPE = 'claude';
} else if (/qwen/i.test(TITLE)) {
CHAT_TYPE = 'qwen';
} else if (/deepseek/i.test(TITLE)) {
CHAT_TYPE = 'deepseek';
} else if (/glm|zhipu/i.test(TITLE)) {
CHAT_TYPE = 'glm';
} else if (/minimax/i.test(TITLE)) {
CHAT_TYPE = 'minimax';
} else if (/kimi|moonshot/i.test(TITLE)) {
CHAT_TYPE = 'kimi';
} else if (/router/i.test(TITLE)) {
CHAT_TYPE = 'router';
} else if (/nvidia/i.test(TITLE)) {
CHAT_TYPE = 'nvidia';
}
/**
* 检查并更新 demo 密码的调用次数
* @param {number} increment - 要增加的次数,默认为 1
* @returns {Promise<{allowed: boolean, message: string, data: object}>}
*/
async function checkAndUpdateDemoCounter(increment = 1) {
const hour = Math.floor(Date.now() / 3600000);
const kvKey = 'demo_counter';
// 尝试从 KV 获取计数器数据
let demoData = await getKV(kvKey);
if (!demoData || demoData.hour !== hour) {
// KV 中没有数据或者已经过了一个小时,重置计数器
demoData = {
hour: hour,
times: 0,
maxTimes: DEMO_MAX_TIMES
};
}
// 检查是否超过最大调用次数
if (demoData.times >= demoData.maxTimes) {
return {
allowed: false,
message: `Exceeded maximum API calls (${demoData.maxTimes}) for this hour. Please try again next hour.`,
data: demoData
};
}
// 增加计数
demoData.times += increment;
// 保存到 KV(不设置过期时间,下次检查时会自动重置)
await setKV(kvKey, demoData);
// 如果 KV 存储失败,回退到内存记忆(仅当前实例有效)
if (!kvStore) {
if (demoMemory.hour === hour) {
if (demoMemory.times >= DEMO_MAX_TIMES) {
return {
allowed: false,
message: `Exceeded maximum API calls (${DEMO_MAX_TIMES}) for this hour`,
data: { hour, times: demoMemory.times, maxTimes: DEMO_MAX_TIMES }
};
}
} else {
demoMemory.hour = hour;
demoMemory.times = 0;
}
demoMemory.times += increment;
}
return {
allowed: true,
message: 'OK',
data: demoData
};
}
/**
* 验证并处理 API Key
* @param {string} apiKey - 原始 API Key
* @param {number} demoIncrement - Demo 密码的计数增量,默认为 1
* @returns {Promise<{valid: boolean, apiKey: string, error?: Response}>}
*/
async function validateAndProcessApiKey(apiKey, demoIncrement = 1) {
if (!apiKey) {
return {
valid: false,
apiKey: '',
error: createErrorResponse(
'Missing API key. Provide via ?key= parameter or Authorization header',
401
)
};
}
// 检查是否是共享密码
if (apiKey === SECRET_PASSWORD) {
return {
valid: true,
apiKey: getNextApiKey(API_KEY_LIST)
};
}
// 检查是否是临时演示密码
if (apiKey === DEMO_PASSWORD && DEMO_PASSWORD) {
const result = await checkAndUpdateDemoCounter(demoIncrement);
if (!result.allowed) {
return {
valid: false,
apiKey: '',
error: createErrorResponse(result.message, 429)
};
}
return {
valid: true,
apiKey: getNextApiKey(API_KEY_LIST)
};
}
// 不是两类密码的情况下,如果传入的apiKey长度少于10位,认为是无效的密码(因为一般情况下各类系统的API Key不会短于这个长度)
if (apiKey.length <= 10) {
return {
valid: false,
apiKey: '',
error: createErrorResponse('Wrong password.', 401)
};
}
// 其他情况,使用原始 API Key
return {
valid: true,
apiKey: apiKey
};
}
const url = new URL(request.url);
const apiPath = url.pathname;
const apiMethod = request.method.toUpperCase();
// 处理HTML页面请求
if (apiPath === '/' || apiPath === '/index.html') {
const htmlContent = getHtmlContent(
MODEL_IDS,
TAVILY_KEYS,
TITLE,
ttsEnabled
);
return new Response(htmlContent, {
headers: {
'Content-Type': 'text/html;charset=UTF-8',
'Cache-Control': 'public, max-age=14400' // 缓存4小时
}
});
}
if (apiPath === '/favicon.svg') {
const svgContent = getSvgContent(CHAT_TYPE);
return new Response(svgContent, {
headers: {
'Content-Type': 'image/svg+xml',
'Cache-Control': 'public, max-age=43200' // 缓存12小时
}
});
}
if (apiPath === '/manifest.json' || apiPath === '/site.webmanifest') {
const manifestContent = getManifestContent(TITLE);
return new Response(manifestContent, {
headers: {
'Content-Type': 'application/json;charset=UTF-8',
'Cache-Control': 'public, max-age=43200' // 缓存12小时
}
});
}
// 直接返回客户端的原本的请求信息(用于调试)
if (apiPath === '/whoami') {
return new Response(
JSON.stringify({
serverType: SERVER_TYPE,
serverInfo: isDeno
? {
target: Deno.build.target,
os: Deno.build.os,
arch: Deno.build.arch,
vendor: Deno.build.vendor
}
: request.cf || 'unknown',
url: request.url,
headers: Object.fromEntries(request.headers.entries()),
method: request.method,
bodyUsed: request.bodyUsed
}),
{
headers: { 'Content-Type': 'application/json' }
}
);
}
// 调用tavily搜索API
if (apiPath === '/search' && apiMethod === 'POST') {
let apiKey =
url.searchParams.get('key') || request.headers.get('Authorization') || '';
apiKey = apiKey.replace('Bearer ', '').trim();
// 从body中获取query参数
const query = (await request.json()).query || '';
if (!query) {
return createErrorResponse('Missing query parameter', 400);
}
const keyValidation = await validateAndProcessApiKey(apiKey, 0.1);
if (!keyValidation.valid) {
return keyValidation.error;
}
const modelPrompt = getTavilyPrompt(query);
const model = getLiteModelId(MODEL_IDS);
let modelUrl = `${API_BASE}/v1/chat/completions`;
modelUrl = replaceApiUrl(modelUrl);
const modelPayload = {
model,
messages: [
{
role: 'user',
content: modelPrompt.trim()
}
],
stream: false
};
let modelResponse;
try {
modelResponse = await doWithTimeout(
fetch(modelUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + keyValidation.apiKey
},
body: JSON.stringify(modelPayload)
}),
30000 // 30秒超时
);
} catch (error) {
console.error('Search tavily failed:', error);
return new Response(JSON.stringify([]), {
status: 200,
headers: {
'Content-Type': 'application/json'
}
});
}
// 接下来从modelResponse中提取content
const modelJsonData = await modelResponse.json();
const content = modelJsonData.choices?.[0]?.message?.content || '';
// 从中找到反引号`的位置, 提取反引号里包裹的内容
// 从结果中找到花括号内容, 提取为JSON
const jsonMatch = content.replace(/\n/g, '').match(/({.*})/);
let searchJson = jsonMatch ? jsonMatch[1].trim() : content;
try {
searchJson = JSON.parse(searchJson);
} catch (e) {
searchJson = null;
}
if (!searchJson || searchJson.num_results === 0) {
return new Response(JSON.stringify([]), {
status: 200,
headers: {
'Content-Type': 'application/json'
}
});
}
// 并发请求所有搜索关键词
const searchPromises = searchJson.search_queries.map(
async searchKeyword => {
const tavilyUrl = 'https://api.tavily.com/search';
const tavilyKey = getRandomApiKey(TAVILY_KEY_LIST);
const payload = {
query: searchKeyword,
max_results: searchJson.num_results,
include_answer: 'basic',
auto_parameters: true,
exclude_domains: [
// 此处排除:带有明显zz色彩/偏见的网站,确保搜索结果不混入其内容
// 不可解释
'ntdtv.com',
'ntd.tv',
'aboluowang.com',
'epochtimes.com',
'epochtimes.jp',
'dafahao.com',
'minghui.org',
// 其他强烈偏见性媒体
'secretchina.com',
'kanzhongguo.com',
'soundofhope.org',
'rfa.org',
'bannedbook.org',
'boxun.com',
'peacehall.com',
'creaders.net',
'backchina.com',
// 其他方向的偏见性媒体
'guancha.cn', // 观察者网(强烈民族主义倾向)
'wenxuecity.com', // 文学城(部分内容质量参差)
// 阴谋论和伪科学网站
'awaker.cn',
'tuidang.org',
// === 英文媒体 ===
// 极右翼/阴谋论
'breitbart.com', // Breitbart News(已被维基百科弃用)
'infowars.com', // InfoWars(阴谋论)
'naturalnews.com', // Natural News(伪科学)
'globalresearch.ca', // Global Research(阴谋论,维基百科黑名单)
'zerohedge.com', // Zero Hedge(极端金融偏见)
'thegatewaypu<wbr>ndit.com', // Gateway Pundit(虚假新闻)
'newsmax.com', // Newsmax(强烈保守派偏见)
'oann.com', // One America News(虚假信息)
'dailywire.com', // Daily Wire(强烈保守派)
'theblaze.com', // The Blaze(维基百科认定不可靠)
'redstate.com', // RedState(党派性强)
'thenationalpulse.com', // National Pulse(极右翼)
'thefederalist.com', // The Federalist(强烈保守派)
// 极左翼
'dailykos.com', // Daily Kos(维基百科建议避免)
'alternet.org', // AlterNet(维基百科认定不可靠)
'commondreams.org', // Common Dreams(强烈左翼)
'thecanary.co', // The Canary(维基百科认定不可靠)
'occupy<wbr>democrats.com', // Occupy Democrats(党派性强)
'truthout.org', // Truthout(强烈左翼)
// 小报和低质量新闻
'dailymail.co.uk', // Daily Mail(维基百科弃用)
'thesun.co.uk', // The Sun(小报)
'nypost.com', // New York Post(质量参差)
'express.co.uk', // Daily Express(维基百科认定不可靠)
'mirror.co.uk', // Daily Mirror(小报)
'dailystar.co.uk', // Daily Star(小报)
// 讽刺/虚假新闻网站
'theonion.com', // The Onion(讽刺网站)
'clickhole.com', // ClickHole(讽刺)
'babylonbee.com', // Babylon Bee(讽刺)
'newspunch.com', // News Punch/Your News Wire(虚假新闻)
'beforeitsnews.com', // Before It's News(阴谋论)
// 俄罗斯国家媒体
'rt.com', // RT(Russia Today)
'sputniknews.com', // Sputnik News
'tass.com', // TASS(需谨慎)
// 其他问题网站
'wikileaks.org', // WikiLeaks(主要来源,需谨慎)
'mediabiasfactcheck.com', // Media Bias Fact Check(维基百科不建议引用)
'allsides.com' // AllSides(维基百科认为不可靠)
]
};
try {
const response = await fetch(tavilyUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + tavilyKey
},
body: JSON.stringify(payload)
});
if (!response.ok) {
console.error(
`Tavily API request failed for "${searchKeyword}":`,
response.status
);
return null;
}
return await response.json();
} catch (error) {
console.error(
`Error fetching Tavily results for "${searchKeyword}":`,
error
);
return null;
}
}
);
// 等待所有请求完成
const searchResults = await Promise.all(searchPromises);
// 过滤掉失败的请求,合并结果
const validResults = searchResults.filter(result => result !== null);
return new Response(JSON.stringify(validResults), {
status: 200,
headers: {
'Content-Type': 'application/json'
}
});
}
// 总结会话
if (apiPath === '/summarize' && apiMethod === 'POST') {
let apiKey =
url.searchParams.get('key') || request.headers.get('Authorization') || '';
apiKey = apiKey.replace('Bearer ', '').trim();
// 从body中获取question和answer参数
const { question, answer } = await request.json();
if (!question || !answer) {
return createErrorResponse('Missing question or answer parameter', 400);
}
const keyValidation = await validateAndProcessApiKey(apiKey, 0.1);
if (!keyValidation.valid) {
return keyValidation.error;
}
// 截取question和answer,避免过长
const truncatedQuestion =
question.length <= 300
? question
: question.slice(0, 150) + '......' + question.slice(-150);
const truncatedAnswer =
answer.length <= 300
? answer
: answer.slice(0, 150) + '......' + answer.slice(-150);
// 构建总结提示词
const summaryPrompt = `请为以下对话生成一个简短的标题(不超过20个字):
问题:
\`\`\`
${truncatedQuestion}
\`\`\`
回答:
\`\`\`
${truncatedAnswer}
\`\`\`
要求:
1. 标题要简洁明了,能概括对话的核心内容
2. 不要使用引号或其他标点符号包裹
3. 直接输出标题文本即可`;
const messages = [
{
role: 'user',
content: summaryPrompt
}
];
// 选择合适的精简模型
const summaryModel = getLiteModelId(MODEL_IDS);
let modelUrl = `${API_BASE}/v1/chat/completions`;
modelUrl = replaceApiUrl(modelUrl);
const modelPayload = {
model: summaryModel,
messages: messages,
max_tokens: 500,
stream: false
};
try {
const modelResponse = await fetch(modelUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + keyValidation.apiKey
},
body: JSON.stringify(modelPayload)
});
if (!modelResponse.ok) {
throw new Error('Model API request failed');
}
const modelJsonData = await modelResponse.json();
const summary = modelJsonData.choices?.[0]?.message?.content || '';
return new Response(
JSON.stringify({
success: true,
summary: summary.trim()
}),
{
status: 200,
headers: {
'Content-Type': 'application/json'
}
}
);
} catch (error) {
console.error('Generate summary failed:', error);
return createErrorResponse('Failed to generate summary', 500);
}
}
// 处理 WebDAV 代理的 OPTIONS 预检请求(必须放在 WebDAV 代理逻辑之前)
if (apiMethod === 'OPTIONS' && apiPath.startsWith('/webdav')) {
return new Response(null, {
status: 204,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods':
'GET, PUT, POST, DELETE, PROPFIND, MKCOL, OPTIONS',
'Access-Control-Allow-Headers':
'Content-Type, Authorization, Depth, X-WebDAV-URL, X-WebDAV-Auth',
'Access-Control-Max-Age': '86400'
}
});
}
// WebDAV 代理接口 - 解决跨域问题
if (apiPath === '/webdav' || apiPath.startsWith('/webdav/')) {
// 从请求头获取 WebDAV 配置
const webdavUrl = request.headers.get('X-WebDAV-URL');
const webdavAuth = request.headers.get('X-WebDAV-Auth');
if (!webdavUrl) {
return createErrorResponse('Missing X-WebDAV-URL header', 400);
}
// 构建目标 URL
// 如果路径是 /webdav/xxx,则将 /xxx 附加到 webdavUrl
let targetUrl = webdavUrl;
if (apiPath.startsWith('/webdav/')) {
const subPath = apiPath.substring(7); // 移除 '/webdav'
targetUrl = webdavUrl.replace(/\/$/, '') + subPath;
}
// 构建转发请求的 headers
const forwardHeaders = new Headers();
// 添加标准 User-Agent,避免某些服务器拒绝空或异常的 UA
forwardHeaders.set('User-Agent', 'WebDAV-Client/1.0');
if (webdavAuth) {
forwardHeaders.set('Authorization', webdavAuth);
}
// 复制某些必要的请求头
const contentType = request.headers.get('Content-Type');
if (contentType) {
forwardHeaders.set('Content-Type', contentType);
}
// PROPFIND 需要 Depth 头
const depth = request.headers.get('Depth');
if (depth) {
forwardHeaders.set('Depth', depth);
}
// 获取请求体
let requestBody = null;
if (!['GET', 'HEAD', 'OPTIONS'].includes(apiMethod)) {
// 使用 arrayBuffer 而不是 text,保持二进制数据完整性
requestBody = await request.arrayBuffer();
// 对于有内容的请求,设置 Content-Length
if (requestBody && requestBody.byteLength > 0) {
forwardHeaders.set('Content-Length', requestBody.byteLength.toString());
}
}
try {
// 调试日志
console.log('[WebDAV Proxy] Method:', apiMethod);
console.log('[WebDAV Proxy] Target URL:', targetUrl);
console.log(
'[WebDAV Proxy] Headers:',
Object.fromEntries(forwardHeaders.entries())
);
// 转发请求到 WebDAV 服务器
// 使用 redirect: 'manual' 避免 HTTP 重定向时 PUT 变成 GET 的问题
const webdavResponse = await fetch(targetUrl, {
method: apiMethod,
headers: forwardHeaders,
body: requestBody,
redirect: 'manual'
});
// 如果是重定向响应,记录日志
if ([301, 302, 303, 307, 308].includes(webdavResponse.status)) {
const location = webdavResponse.headers.get('Location');
console.log('[WebDAV Proxy] Redirect detected! Location:', location);
// 返回错误提示用户使用 HTTPS
return createErrorResponse(
'WebDAV 服务器返回重定向,请检查是否需要使用 HTTPS URL。重定向目标: ' +
location,
502
);
}
// 调试日志
console.log('[WebDAV Proxy] Response Status:', webdavResponse.status);
// 构建响应头,添加 CORS 头
const responseHeaders = new Headers(webdavResponse.headers);
responseHeaders.set('Access-Control-Allow-Origin', '*');
responseHeaders.set(
'Access-Control-Allow-Methods',
'GET, PUT, POST, DELETE, PROPFIND, MKCOL, OPTIONS'
);
responseHeaders.set(
'Access-Control-Allow-Headers',
'Content-Type, Authorization, Depth, X-WebDAV-URL, X-WebDAV-Auth'
);
// 移除 WWW-Authenticate 头,避免浏览器弹出原生认证框
responseHeaders.delete('WWW-Authenticate');
// 对于二进制内容(gzip),确保 Content-Type 正确且禁用自动压缩
const contentType = responseHeaders.get('Content-Type');
if (
contentType &&
(contentType.includes('gzip') || contentType.includes('octet-stream'))
) {
// 明确告知 Cloudflare 不要对二进制数据进行额外处理
responseHeaders.set('Cache-Control', 'no-transform');
// 确保 Content-Encoding 不被误设置
responseHeaders.delete('Content-Encoding');
}
return new Response(webdavResponse.body, {
status: webdavResponse.status,
statusText: webdavResponse.statusText,
headers: responseHeaders
});
} catch (error) {
console.error('WebDAV proxy error:', error);
return createErrorResponse('WebDAV proxy error: ' + error.message, 502);
}
}
// TTS 语音合成代理接口
if (apiPath === '/speech' && apiMethod === 'POST') {
let apiKey =
url.searchParams.get('key') || request.headers.get('Authorization') || '';
apiKey = apiKey.replace('Bearer ', '').trim();
const keyValidation = await validateAndProcessApiKey(apiKey, 0.1);
if (!keyValidation.valid) return keyValidation.error;
if (!TTS_API_BASE || !TTS_API_KEY) {
return createErrorResponse('TTS service not configured', 503);
}
let ttsBody;
try {
ttsBody = await request.json();
} catch (e) {
return createErrorResponse('Invalid JSON body', 400);
}
const { input, voice = 'alloy', speed = 1.0, pitch = 1.0 } = ttsBody;
if (!input) {
return createErrorResponse('Missing input parameter', 400);
}
try {
const ttsResponse = await fetch(`${TTS_API_BASE}/v1/audio/speech`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${TTS_API_KEY}`
},
body: JSON.stringify({
model: 'tts-1',
input,
voice,
response_format: 'mp3',
speed,
pitch,
cleaning_options: {
remove_markdown: true,
remove_emoji: true,
remove_urls: true,
remove_line_breaks: true
}
})
});
if (!ttsResponse.ok) {
const errText = await ttsResponse.text();
return createErrorResponse(`TTS error: ${errText}`, ttsResponse.status);
}
const audioBuffer = await ttsResponse.arrayBuffer();
return new Response(audioBuffer, {
status: 200,
headers: {
'Content-Type': 'audio/mpeg',
'Cache-Control': 'no-cache',
'Access-Control-Allow-Origin': '*'
}
});
} catch (error) {
console.error('TTS proxy error:', error);
return createErrorResponse('TTS proxy failed: ' + error.message, 502);
}
}
if (!apiPath.startsWith('/v1')) {
return createErrorResponse(
apiPath + ' Invalid API path. Must start with /v1',
400
);
}
// 2. 获取和验证API密钥
let apiKey =
url.searchParams.get('key') || request.headers.get('Authorization') || '';
apiKey = apiKey.replace('Bearer ', '').trim();
let urlSearch = url.searchParams.toString();
const originalApiKey = apiKey;
const keyValidation = await validateAndProcessApiKey(apiKey);
if (!keyValidation.valid) {
return keyValidation.error;
}
apiKey = keyValidation.apiKey;
// 替换 URL 中的密码为实际 API Key
if (originalApiKey === SECRET_PASSWORD) {
urlSearch = urlSearch.replace(`key=${SECRET_PASSWORD}`, `key=${apiKey}`);
} else if (originalApiKey === DEMO_PASSWORD) {
urlSearch = urlSearch.replace(`key=${DEMO_PASSWORD}`, `key=${apiKey}`);
}
// 3. 构建请求
let fullPath = `${API_BASE}${apiPath}`;
fullPath = replaceApiUrl(fullPath);
const targetUrl = `${fullPath}?${urlSearch}`;
const proxyRequest = buildProxyRequest(request, apiKey);
// 4. 发起请求并处理响应
try {
const response = await fetch(targetUrl, proxyRequest);
// 直接透传响应 - 无缓冲流式处理
return new Response(response.body, {
status: response.status,
headers: response.headers
});
} catch (error) {
console.error('Proxy request failed:', error);
return createErrorResponse('Proxy request failed', 502);
}
}
// Cloudflare Workers 导出
export default {
async fetch(request, env) {
return handleRequest(request, env);
}
};
// // Deno Deploy 支持
// if (isDeno) {
// Deno.serve(handleRequest);
// }
/**
* 构建代理请求配置
*/
function buildProxyRequest(originalRequest, apiKey) {
const headers = new Headers();
// 复制必要的请求头
const headersToForward = [
'content-type',
'accept',
'accept-encoding',
'user-agent'
];
headersToForward.forEach(headerName => {
const value = originalRequest.headers.get(headerName);
if (value) {
headers.set(headerName, value);
}
});
// 设置API密钥
headers.set('Authorization', `Bearer ${apiKey}`);
return {
method: originalRequest.method,
headers: headers,
body: originalRequest.body,
redirect: 'follow',
...(isNode ? { duplex: 'half' } : {})
};
}
/**
* 创建错误响应
*/
function createErrorResponse(message, status) {
return new Response(
JSON.stringify({
error: message,
timestamp: new Date().toISOString()
}),
{
status: status,
headers: { 'Content-Type': 'application/json' }
}
);
}
/**
* 为 Promise 添加超时控制
* @param {Promise} promise - 需要执行的 Promise
* @param {number} timeout - 超时时间(毫秒)
* @returns {Promise} 返回一个带超时控制的 Promise
*/
function doWithTimeout(promise, timeout) {
return Promise.race([
promise,
new Promise((_, reject) =>
setTimeout(() => reject(new Error(`请求超时(${timeout}ms)`)), timeout)
)
]);
}
/**