-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy path_worker.js
More file actions
3908 lines (3504 loc) · 122 KB
/
Copy path_worker.js
File metadata and controls
3908 lines (3504 loc) · 122 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
// =================================================================================
// _worker.js V2.0 FINAL - Correct Structure
// 备注:增加了节点管理和导入功能
// =================================================================================
import { connect } from "cloudflare:sockets";
// =================================================================================
// 用户配置区域 - 可直接修改
// =================================================================================
// ProxyIP 配置 - 用户可以修改为自己的 ProxyIP 地址
const DEFAULT_PROXY_IP = "129.159.84.71";
// 如果需要多个 ProxyIP,用逗号分隔,例如:
// const DEFAULT_PROXY_IP = '129.159.84.71,your.second.proxy.ip';
// =================================================================================
// =================================================================================
// 辅助函数和常量 - 必须在 export default 之前定义
// =================================================================================
// =================================================================================
// VLESS 代理核心功能 - 从参考项目复制
// =================================================================================
const WS_READY_STATE_OPEN = 1;
const WS_READY_STATE_CLOSING = 2;
// VLESS WebSocket 处理函数 - 基于 BPB 真实实现
async function handleVlessWebSocket(request, env) {
const webSocketPair = new WebSocketPair();
const [client, webSocket] = Object.values(webSocketPair);
webSocket.accept();
// BPB 风格的全局变量初始化 - 完全照搬 BPB 的 init.js
const url = new URL(request.url);
globalThis.pathName = url.pathname;
globalThis.hostName = request.headers.get("Host");
globalThis.urlOrigin = url.origin;
// BPB 的 ProxyIP 初始化逻辑 - 使用顶部配置的 ProxyIP
globalThis.proxyIPs = DEFAULT_PROXY_IP;
console.log(
`BPB 风格初始化完成: pathName=${globalThis.pathName}, proxyIPs=${globalThis.proxyIPs}`
);
let address = "";
let portWithRandomLog = "";
const log = (info, event) => {
console.log(`[${address}:${portWithRandomLog}] ${info}`, event || "");
};
const earlyDataHeader = request.headers.get("sec-websocket-protocol") || "";
const readableWebSocketStream = makeReadableWebSocketStream(
webSocket,
earlyDataHeader,
log
);
let remoteSocketWapper = { value: null };
let udpStreamWrite = null;
let isDns = false;
// ws --> remote
readableWebSocketStream
.pipeTo(
new WritableStream({
async write(chunk, controller) {
if (isDns && udpStreamWrite) {
return udpStreamWrite(chunk);
}
if (remoteSocketWapper.value) {
const writer = remoteSocketWapper.value.writable.getWriter();
await writer.write(chunk);
writer.releaseLock();
return;
}
const {
hasError,
message,
portRemote = 443,
addressRemote = "",
rawDataIndex,
vlessVersion = new Uint8Array([0, 0]),
isUDP,
} = await processVlessHeader(chunk, env);
address = addressRemote;
portWithRandomLog = `${portRemote}--${Math.random()} ${
isUDP ? "udp " : "tcp "
} `;
if (hasError) {
throw new Error(message);
return;
}
// if UDP but port not DNS port, close it
if (isUDP) {
if (portRemote === 53) {
isDns = true;
} else {
throw new Error("UDP proxy only enable for DNS which is port 53");
return;
}
}
const vlessResponseHeader = new Uint8Array([vlessVersion[0], 0]);
const rawClientData = chunk.slice(rawDataIndex);
if (isDns) {
const { write } = await handleUDPOutBound(
webSocket,
vlessResponseHeader,
log
);
udpStreamWrite = write;
udpStreamWrite(rawClientData);
return;
}
// 使用 BPB 风格的连接处理(包含 ProxyIP 重试机制)
log(`使用 BPB 风格连接处理: ${addressRemote}:${portRemote}`);
handleTCPOutBound(
remoteSocketWapper,
addressRemote,
portRemote,
rawClientData,
webSocket,
vlessResponseHeader,
log
);
},
close() {
log(`readableWebSocketStream is close`);
},
abort(reason) {
log(`readableWebSocketStream is abort`, JSON.stringify(reason));
},
})
)
.catch((err) => {
log("readableWebSocketStream pipeTo error", err);
});
return new Response(null, {
status: 101,
webSocket: client,
});
}
// 创建 WebSocket 可读流
function makeReadableWebSocketStream(webSocketServer, earlyDataHeader, log) {
let readableStreamCancel = false;
const stream = new ReadableStream({
start(controller) {
webSocketServer.addEventListener("message", (event) => {
if (readableStreamCancel) {
return;
}
const message = event.data;
controller.enqueue(message);
});
webSocketServer.addEventListener("close", () => {
safeCloseWebSocket(webSocketServer);
if (readableStreamCancel) {
return;
}
controller.close();
});
webSocketServer.addEventListener("error", (err) => {
log("webSocketServer has error");
controller.error(err);
});
// for ws 0rtt
const { earlyData, error } = base64ToArrayBuffer(earlyDataHeader);
if (error) {
controller.error(error);
} else if (earlyData) {
controller.enqueue(earlyData);
}
},
pull(controller) {
// if ws can stop read if stream is full, we can implement backpressure
},
cancel(reason) {
if (readableStreamCancel) {
return;
}
log(`ReadableStream was canceled, due to ${reason}`);
readableStreamCancel = true;
safeCloseWebSocket(webSocketServer);
},
});
return stream;
}
// VLESS 头部处理函数
async function processVlessHeader(vlessBuffer, env) {
if (vlessBuffer.byteLength < 24) {
return {
hasError: true,
message: "invalid data",
};
}
const version = new Uint8Array(vlessBuffer.slice(0, 1));
let isValidUser = false;
let isUDP = false;
const slicedBuffer = new Uint8Array(vlessBuffer.slice(1, 17));
const slicedBufferString = stringify(slicedBuffer);
// 验证用户UUID - 从数据库中查找
try {
const user = await env.DB.prepare(
"SELECT id FROM users WHERE user_uuid = ?"
)
.bind(slicedBufferString)
.first();
isValidUser = !!user;
} catch (e) {
console.error("UUID验证失败:", e);
isValidUser = false;
}
if (!isValidUser) {
return {
hasError: true,
message: "invalid user",
};
}
const optLength = new Uint8Array(vlessBuffer.slice(17, 18))[0];
const command = new Uint8Array(
vlessBuffer.slice(18 + optLength, 18 + optLength + 1)
)[0];
// 0x01 TCP, 0x02 UDP, 0x03 MUX
if (command === 1) {
} else if (command === 2) {
isUDP = true;
} else {
return {
hasError: true,
message: `command ${command} is not support, command 01-tcp,02-udp,03-mux`,
};
}
const portIndex = 18 + optLength + 1;
const portBuffer = vlessBuffer.slice(portIndex, portIndex + 2);
const portRemote = new DataView(portBuffer).getUint16(0);
let addressIndex = portIndex + 2;
const addressBuffer = new Uint8Array(
vlessBuffer.slice(addressIndex, addressIndex + 1)
);
const addressType = addressBuffer[0];
let addressLength = 0;
let addressValueIndex = addressIndex + 1;
let addressValue = "";
switch (addressType) {
case 1:
addressLength = 4;
addressValue = new Uint8Array(
vlessBuffer.slice(addressValueIndex, addressValueIndex + addressLength)
).join(".");
break;
case 2:
addressLength = new Uint8Array(
vlessBuffer.slice(addressValueIndex, addressValueIndex + 1)
)[0];
addressValueIndex += 1;
addressValue = new TextDecoder().decode(
vlessBuffer.slice(addressValueIndex, addressValueIndex + addressLength)
);
break;
case 3:
addressLength = 16;
const dataView = new DataView(
vlessBuffer.slice(addressValueIndex, addressValueIndex + addressLength)
);
const ipv6 = [];
for (let i = 0; i < 8; i++) {
ipv6.push(dataView.getUint16(i * 2).toString(16));
}
addressValue = ipv6.join(":");
break;
default:
return {
hasError: true,
message: `invild addressType is ${addressType}`,
};
}
if (!addressValue) {
return {
hasError: true,
message: `addressValue is empty, addressType is ${addressType}`,
};
}
return {
hasError: false,
addressRemote: addressValue,
addressType,
portRemote,
rawDataIndex: addressValueIndex + addressLength,
vlessVersion: version,
isUDP,
};
}
// 辅助函数
function base64ToArrayBuffer(base64Str) {
if (!base64Str) {
return { error: null };
}
try {
base64Str = base64Str.replace(/-/g, "+").replace(/_/g, "/");
const decode = atob(base64Str);
const arryBuffer = Uint8Array.from(decode, (c) => c.charCodeAt(0));
return { earlyData: arryBuffer.buffer, error: null };
} catch (error) {
return { error };
}
}
function safeCloseWebSocket(socket) {
try {
if (
socket.readyState === WS_READY_STATE_OPEN ||
socket.readyState === WS_READY_STATE_CLOSING
) {
socket.close();
}
} catch (error) {
console.error("safeCloseWebSocket error", error);
}
}
const byteToHex = [];
for (let i = 0; i < 256; ++i) {
byteToHex.push((i + 256).toString(16).slice(1));
}
function unsafeStringify(arr, offset = 0) {
return (
byteToHex[arr[offset + 0]] +
byteToHex[arr[offset + 1]] +
byteToHex[arr[offset + 2]] +
byteToHex[arr[offset + 3]] +
"-" +
byteToHex[arr[offset + 4]] +
byteToHex[arr[offset + 5]] +
"-" +
byteToHex[arr[offset + 6]] +
byteToHex[arr[offset + 7]] +
"-" +
byteToHex[arr[offset + 8]] +
byteToHex[arr[offset + 9]] +
"-" +
byteToHex[arr[offset + 10]] +
byteToHex[arr[offset + 11]] +
byteToHex[arr[offset + 12]] +
byteToHex[arr[offset + 13]] +
byteToHex[arr[offset + 14]] +
byteToHex[arr[offset + 15]]
).toLowerCase();
}
function stringify(arr, offset = 0) {
const uuid = unsafeStringify(arr, offset);
return uuid;
}
// BPB 风格:不需要复杂的 ProxyIP 检测逻辑
// BPB 的实现更简单:直连失败时自动使用 ProxyIP 重试
// BPB 风格的 TCP 出站处理函数 - 完全基于真实 BPB 源码
async function handleTCPOutBound(
remoteSocket,
addressRemote,
portRemote,
rawClientData,
webSocket,
vlessResponseHeader,
log
) {
async function connectAndWrite(address, port) {
// BPB 的 IPv4 地址处理逻辑 - 完全照搬 BPB 源码
if (
/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(
address
)
) {
address = `${atob("d3d3Lg==")}${address}${atob("LnNzbGlwLmlv")}`;
}
const tcpSocket = connect({
hostname: address,
port: port,
});
remoteSocket.value = tcpSocket;
log(`connected to ${address}:${port}`);
const writer = tcpSocket.writable.getWriter();
await writer.write(rawClientData); // first write, normal is tls client hello
writer.releaseLock();
return tcpSocket;
}
// BPB 的 ProxyIP 重试逻辑 - 完全照搬 BPB 源码
async function retry() {
let proxyIP, proxyIpPort;
const encodedPanelProxyIPs = globalThis.pathName.split("/")[2] || "";
const decodedProxyIPs = encodedPanelProxyIPs
? atob(encodedPanelProxyIPs)
: globalThis.proxyIPs;
const proxyIpList = decodedProxyIPs.split(",").map((ip) => ip.trim());
const selectedProxyIP =
proxyIpList[Math.floor(Math.random() * proxyIpList.length)];
if (selectedProxyIP.includes("]:")) {
const match = selectedProxyIP.match(/^(\[.*?\]):(\d+)$/);
proxyIP = match[1];
proxyIpPort = match[2];
} else {
[proxyIP, proxyIpPort] = selectedProxyIP.split(":");
}
const tcpSocket = await connectAndWrite(
proxyIP || addressRemote,
+proxyIpPort || portRemote
);
// no matter retry success or not, close websocket
tcpSocket.closed
.catch((error) => {
console.log("retry tcpSocket closed error", error);
})
.finally(() => {
safeCloseWebSocket(webSocket);
});
remoteSocketToWS(tcpSocket, webSocket, vlessResponseHeader, null, log);
}
const tcpSocket = await connectAndWrite(addressRemote, portRemote);
// when remoteSocket is ready, pass to websocket
// remote--> ws
remoteSocketToWS(tcpSocket, webSocket, vlessResponseHeader, retry, log);
}
// 检查是否为 IPv4 地址
function isIPv4(address) {
const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/;
return ipv4Regex.test(address);
}
// 远程 Socket 到 WebSocket 的数据转发
async function remoteSocketToWS(
remoteSocket,
webSocket,
vlessResponseHeader,
retry,
log
) {
let remoteChunkCount = 0;
let chunks = [];
let vlessHeader = vlessResponseHeader;
let hasIncomingData = false;
await remoteSocket.readable
.pipeTo(
new WritableStream({
start() {},
async write(chunk, controller) {
hasIncomingData = true;
if (webSocket.readyState !== WS_READY_STATE_OPEN) {
controller.error("webSocket.readyState is not open, maybe close");
}
if (vlessHeader) {
webSocket.send(await new Blob([vlessHeader, chunk]).arrayBuffer());
vlessHeader = null;
} else {
webSocket.send(chunk);
}
},
close() {
log(
`remoteConnection!.readable is close with hasIncomingData is ${hasIncomingData}`
);
},
abort(reason) {
console.error(`remoteConnection!.readable abort`, reason);
},
})
)
.catch((error) => {
console.error(`remoteSocketToWS has exception `, error.stack || error);
safeCloseWebSocket(webSocket);
});
if (hasIncomingData === false && retry) {
log(`retry`);
retry();
}
}
// UDP 出站处理函数
async function handleUDPOutBound(webSocket, vlessResponseHeader, log) {
let isVlessHeaderSent = false;
const transformStream = new TransformStream({
start(controller) {},
transform(chunk, controller) {
for (let index = 0; index < chunk.byteLength; ) {
const lengthBuffer = chunk.slice(index, index + 2);
const udpPakcetLength = new DataView(lengthBuffer).getUint16(0);
const udpData = new Uint8Array(
chunk.slice(index + 2, index + 2 + udpPakcetLength)
);
index = index + 2 + udpPakcetLength;
controller.enqueue(udpData);
}
},
flush(controller) {},
});
transformStream.readable
.pipeTo(
new WritableStream({
async write(chunk) {
const resp = await fetch("https://1.1.1.1/dns-query", {
method: "POST",
headers: {
"content-type": "application/dns-message",
},
body: chunk,
});
const dnsQueryResult = await resp.arrayBuffer();
const udpSize = dnsQueryResult.byteLength;
const udpSizeBuffer = new Uint8Array([
(udpSize >> 8) & 0xff,
udpSize & 0xff,
]);
if (webSocket.readyState === WS_READY_STATE_OPEN) {
log(`doh success and dns message length is ${udpSize}`);
if (isVlessHeaderSent) {
webSocket.send(
await new Blob([udpSizeBuffer, dnsQueryResult]).arrayBuffer()
);
} else {
webSocket.send(
await new Blob([
vlessResponseHeader,
udpSizeBuffer,
dnsQueryResult,
]).arrayBuffer()
);
isVlessHeaderSent = true;
}
}
},
})
)
.catch((error) => {
log("dns udp has error" + error);
});
const writer = transformStream.writable.getWriter();
return {
write(chunk) {
writer.write(chunk);
},
};
}
// =================================================================================
// 源节点生成器功能 - NAT64 和 ProxyIP
// =================================================================================
/**
* 生成一个参数完全符合 cf-vless 脚本反检测逻辑的 NAT64 VLESS 节点。
* 该函数采用直连模式,Address、SNI 和 Host 均使用实际的 Pages 域名。
* @param {string} uuid 用户的 UUID.
* @param {string} actualPagesDomain 用户实际部署的 Pages 域名 (e.g., "fq88-2wy.pages.dev").
* @returns {string} 一个完整的、可用的 VLESS 链接.
*/
function generateSimpleNAT64Node(uuid, actualPagesDomain) {
const port = 443; // 使用 443 或其他受支持的 HTTPS 端口
const nodeName = actualPagesDomain; // 使用域名作为节点名,简洁明了
// 关键:严格遵循可用节点的参数,特别是 fp="randomized" 和 path="...ed=2560"
return `vless://${uuid}@${actualPagesDomain}:${port}?encryption=none&security=tls&sni=${actualPagesDomain}&fp=randomized&type=ws&host=${actualPagesDomain}&path=%2F%3Fed%3D2560#${nodeName}`;
}
// NAT64 IPv6地址转换函数 - 从简版集成
function convertToNAT64IPv6(ipv4Address) {
const parts = ipv4Address.split(".");
if (parts.length !== 4) {
throw new Error("无效的IPv4地址");
}
const hex = parts.map((part) => {
const num = parseInt(part, 10);
if (num < 0 || num > 255) {
throw new Error("无效的IPv4地址段");
}
return num.toString(16).padStart(2, "0");
});
// 创建一个包含多个优质NAT64前缀的列表,按推荐度排序
const prefixes = [
"64:ff9b::", // 1. Google Public NAT64 (首选)
"2001:67c:2b0::", // 2. TREX.CZ (欧洲优质备选)
"2001:67c:27e4:1064::", // 3. go6lab (欧洲优质备选)
"2602:fc59:b0:64::", // 4. 您原来脚本中的服务 (保留作为备用)
];
const chosenPrefix = prefixes[Math.floor(Math.random() * prefixes.length)];
return `[${chosenPrefix}${hex[0]}${hex[1]}:${hex[2]}${hex[3]}]`;
}
// 获取IPv6代理地址 - 从简版集成
async function getIPv6ProxyAddress(domain) {
try {
const dnsQuery = await fetch(
`https://1.1.1.1/dns-query?name=${domain}&type=A`,
{
headers: {
Accept: "application/dns-json",
},
}
);
const dnsResult = await dnsQuery.json();
if (dnsResult.Answer && dnsResult.Answer.length > 0) {
const aRecord = dnsResult.Answer.find((record) => record.type === 1);
if (aRecord) {
const ipv4Address = aRecord.data;
return convertToNAT64IPv6(ipv4Address);
}
}
throw new Error("无法解析域名的IPv4地址");
} catch (err) {
throw new Error(`DNS解析失败: ${err.message}`);
}
}
// 删除重复的isIPv4函数定义 - 这个函数已经在前面定义过了
// ProxyIP 源节点生成函数 - 基于 BPB 实现,支持用户自定义配置
function generateProxyIPSourceNode(config_data, config_name = null) {
// 兼容前端传递的错误参数名
let proxyIPs = config_data.proxyIPs;
let port = config_data.port;
// 如果前端传递了错误的参数名,进行兼容处理
if (!proxyIPs && config_data.proxyIP) {
proxyIPs = [config_data.proxyIP]; // 将字符串转换为数组
console.log(
`兼容处理:将 proxyIP 转换为 proxyIPs: ${JSON.stringify(proxyIPs)}`
);
}
if (!port && config_data.proxyPort) {
port = config_data.proxyPort;
console.log(`兼容处理:将 proxyPort 转换为 port: ${port}`);
}
const {
uuid,
domain,
proxyIPs: defaultProxyIPs = [DEFAULT_PROXY_IP], // 默认 ProxyIP 地址,用户可自定义
port: defaultPort = 443,
fingerprint = "randomized", // 默认指纹,用户可自定义
alpn = "http/1.1", // 默认 ALPN,用户可自定义
} = config_data;
// 使用兼容处理后的值或默认值
proxyIPs = proxyIPs || defaultProxyIPs;
port = port || defaultPort;
// 参数验证
if (!uuid || !domain) {
throw new Error("UUID 和域名是必需的参数");
}
// UUID 格式验证
const uuidRegex =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
if (!uuidRegex.test(uuid)) {
throw new Error("UUID 格式无效");
}
// 域名格式验证
const domainRegex =
/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
if (!domainRegex.test(domain)) {
throw new Error("域名格式无效");
}
// 端口验证
const portNum = parseInt(port);
if (isNaN(portNum) || portNum < 1 || portNum > 65535) {
throw new Error("端口必须是 1-65535 之间的数字");
}
// ProxyIP 验证
if (!Array.isArray(proxyIPs) || proxyIPs.length === 0) {
throw new Error("ProxyIP 列表不能为空");
}
const ipRegex =
/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
for (const ip of proxyIPs) {
if (!ipRegex.test(ip)) {
throw new Error(`无效的 ProxyIP 地址: ${ip}`);
}
}
// 指纹验证
const validFingerprints = [
"chrome",
"firefox",
"safari",
"randomized",
"android",
"edge",
"360",
"qq",
];
if (!validFingerprints.includes(fingerprint)) {
throw new Error(
`无效的指纹类型: ${fingerprint}。支持的类型: ${validFingerprints.join(
", "
)}`
);
}
// ALPN 验证
const validAlpns = ["http/1.1", "h2", "h3", "h2,http/1.1"];
if (!validAlpns.includes(alpn)) {
throw new Error(
`无效的 ALPN 协议: ${alpn}。支持的协议: ${validAlpns.join(", ")}`
);
}
// BPB 的 getRandomPath 函数 - 完全照搬 BPB 源码
function getRandomPath(length) {
let result = "";
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
// BPB 的 buildConfig 函数逻辑 - 完全照搬 normalConfigs.js
const isTLS =
portNum === 443 ||
portNum === 8443 ||
portNum === 2053 ||
portNum === 2083 ||
portNum === 2087 ||
portNum === 2096;
const security = isTLS ? "tls" : "none";
// BPB 关键:路径生成逻辑
const path = `${getRandomPath(16)}${
proxyIPs.length ? `/${btoa(proxyIPs.join(","))}` : ""
}`;
const fullPath = `/${path}?ed=2560`;
console.log(
`生成自定义 BPB ProxyIP 节点: path=${fullPath}, proxyIPs=${proxyIPs.join(
","
)}, port=${portNum}, fingerprint=${fingerprint}, alpn=${alpn}`
);
// 直接构建标准格式的URL字符串,确保与v2rayN导出格式完全一致
// 参数顺序:encryption -> security -> sni -> alpn -> fp -> type -> host -> path
const params = [];
params.push(`encryption=none`);
params.push(`security=${security}`);
if (isTLS) {
params.push(`sni=${domain}`);
params.push(`alpn=${encodeURIComponent(alpn)}`); // 保持编码一致性
params.push(`fp=${fingerprint}`);
}
params.push(`type=ws`);
params.push(`host=${domain}`);
params.push(`path=${encodeURIComponent(fullPath)}`); // 保持路径编码一致性
// 使用配置名称作为remarks,如果没有则使用默认格式
const remarks = config_name || `BPB-ProxyIP-${domain}`;
const hashPart = encodeURIComponent(remarks);
// 构建完整的标准格式URL
const standardUrl = `vless://${uuid}@${domain}:${portNum}?${params.join(
"&"
)}#${hashPart}`;
console.log(
`生成自定义标准格式ProxyIP节点: ${standardUrl.substring(0, 150)}...`
);
return standardUrl;
}
// 创建用户默认源节点配置 - 简化版本,只生成NAT64节点
async function createDefaultSourceNodes(userId, userUuid, env, hostName) {
try {
// 使用实际的Pages域名,如果没有提供则使用默认值
const actualDomain = hostName || "your-worker.workers.dev";
// 使用新的简化函数生成NAT64源节点
const nat64Node = generateSimpleNAT64Node(userUuid, actualDomain);
// 创建配置对象用于存储
const nat64Config = {
uuid: userUuid,
domain: actualDomain,
};
// 保存到数据库并自动添加到节点池(包含 NAT64 + 可选 ProxyIP)
const statements = [
// 保存源节点配置
env.DB.prepare(
`
INSERT INTO source_node_configs
(user_id, config_name, node_type, config_data, generated_node, is_default, enabled)
VALUES (?, ?, ?, ?, ?, ?, ?)
`
).bind(
userId,
"系统默认NAT64源节点",
"nat64",
JSON.stringify(nat64Config),
nat64Node,
true,
true
),
];
// 同时添加到节点池
const nat64Hash = generateSimpleHash(nat64Node);
if (nat64Hash) {
statements.push(
env.DB.prepare(
`
INSERT OR IGNORE INTO node_pool
(user_id, source_id, node_url, node_hash, status)
VALUES (?, ?, ?, ?, 'active')
`
).bind(userId, null, nat64Node, nat64Hash)
);
}
// 生成 ProxyIP 节点 - 使用新的生成函数,完全基于 BPB 标准
const proxyIPConfig = {
uuid: userUuid,
domain: actualDomain,
proxyIPs: [DEFAULT_PROXY_IP], // BPB 默认 ProxyIP 地址,在文件顶部配置
port: 443,
fingerprint: "randomized", // BPB 默认指纹
alpn: "http/1.1", // BPB 默认 ALPN
};
const proxyIPNode = generateProxyIPSourceNode(proxyIPConfig);
const proxyIPHash = generateSimpleHash(proxyIPNode);
// 保存 ProxyIP 源节点配置到数据库
statements.push(
env.DB.prepare(
`
INSERT INTO source_node_configs
(user_id, config_name, node_type, config_data, generated_node, is_default, enabled)
VALUES (?, ?, ?, ?, ?, ?, ?)
`
).bind(
userId,
"系统默认ProxyIP源节点",
"proxyip",
JSON.stringify(proxyIPConfig),
proxyIPNode,
true,
true
)
);
// 保存 ProxyIP 节点到节点池
if (proxyIPHash) {
statements.push(
env.DB.prepare(
`
INSERT OR IGNORE INTO node_pool
(user_id, source_id, node_url, node_hash, status)
VALUES (?, ?, ?, ?, 'active')
`
).bind(userId, null, proxyIPNode, proxyIPHash)
);
}
await env.DB.batch(statements);
console.log(`为用户 ${userId} 创建了系统默认NAT64源节点配置并添加到节点池`);
console.log(
`为用户 ${userId} 创建了系统默认ProxyIP源节点配置并添加到节点池`
);
console.log(`生成的NAT64节点: ${nat64Node}`);
console.log(`生成的ProxyIP节点: ${proxyIPNode}`);
return true;
} catch (e) {
console.error("创建默认源节点配置失败:", e);
return false;
}
}
// Clash 配置模板
const clashConfigTemplate = `
mixed-port: 7890
allow-lan: true
mode: rule
log-level: info
external-controller: :9090
proxies:
##PROXIES##
proxy-groups:
- name: "🚀 节点选择"
type: select
proxies:
##PROXY_NAMES##
- name: "♻️ 自动选择"
type: url-test
proxies:
##PROXY_NAMES##
url: 'http://www.gstatic.com/generate_204'
interval: 300
rules:
- MATCH,🚀 节点选择
`;
// UTF-8 安全的 Base64 编码/解码函数
function safeBase64Encode(str) {
try {
return btoa(unescape(encodeURIComponent(str)));
} catch (e) {
return null;
}
}
function safeBase64Decode(str) {
try {
return decodeURIComponent(
escape(atob(str.replace(/-/g, "+").replace(/_/g, "/")))
);
} catch (e) {
return null;
}
}
// 密码哈希函数
async function hashPassword(password) {
const data = new TextEncoder().encode(password);
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
return Array.from(new Uint8Array(hashBuffer))
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
// 用户会话验证函数
async function getUserBySession(request, env) {
const cookieHeader = request.headers.get("Cookie");
if (!cookieHeader || !cookieHeader.includes("session_id=")) {
return null;
}
try {
const sessionId = cookieHeader.match(/session_id=([^;]+)/)[1];
const userId = await env.subscription.get(`session:${sessionId}`);
if (!userId) return null;
const user = await env.DB.prepare("SELECT * FROM users WHERE id = ?")