forked from eooce/Cloudflare-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrojan.js
More file actions
630 lines (608 loc) · 31.3 KB
/
trojan.js
File metadata and controls
630 lines (608 loc) · 31.3 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
// 需要开启环境变量,将544——546行前的//号去掉
import { connect } from 'cloudflare:sockets';
let subPath = 'link'; // 节点订阅路径,不修改将使用/sub/${UUID}作为订阅路径
let proxyIP = '13.230.34.30'; // proxyIP
let yourUUID = '5dc15e15-f285-4a9d-959b-0e4fbdd77b63'; // UUID
let cfip = [ 'mfa.gov.ua#SG','saas.sin.fan#HK','store.ubi.com#JP','cf.130519.xyz#KR','cf.008500.xyz#HK','cf.090227.xyz#SG','cf.877774.xyz#HK','cdns.doon.eu.org#JP','sub.danfeng.eu.org#TW','cf.zhetengsha.eu.org#HK'];
function closeSocketQuietly(socket) {
try { if (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CLOSING) { socket.close(); }
} catch (error) {}
}
function base64ToArray(b64Str) {
if (!b64Str) return { error: null };
try {
const binaryString = atob(b64Str.replace(/-/g, '+').replace(/_/g, '/'));
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return { earlyData: bytes.buffer, error: null };
} catch (error) {
return { error };
}
}
function parsePryAddress(serverStr) {
if (!serverStr) return null;
serverStr = serverStr.trim();
if (serverStr.startsWith('socks://') || serverStr.startsWith('socks5://')) {
const urlStr = serverStr.replace(/^socks:\/\//, 'socks5://');
try {
const url = new URL(urlStr);
return {
type: 'socks5',
host: url.hostname,
port: parseInt(url.port) || 1080,
username: url.username ? decodeURIComponent(url.username) : '',
password: url.password ? decodeURIComponent(url.password) : ''
};
} catch (e) {
return null;
}
}
if (serverStr.startsWith('http://') || serverStr.startsWith('https://')) {
try {
const url = new URL(serverStr);
return {
type: 'http',
host: url.hostname,
port: parseInt(url.port) || (serverStr.startsWith('https://') ? 443 : 80),
username: url.username ? decodeURIComponent(url.username) : '',
password: url.password ? decodeURIComponent(url.password) : ''
};
} catch (e) {
return null;
}
}
if (serverStr.startsWith('[')) {
const closeBracket = serverStr.indexOf(']');
if (closeBracket > 0) {
const host = serverStr.substring(1, closeBracket);
const rest = serverStr.substring(closeBracket + 1);
if (rest.startsWith(':')) {
const port = parseInt(rest.substring(1), 10);
if (!isNaN(port) && port > 0 && port <= 65535) {
return { type: 'direct', host, port };
}
}
return { type: 'direct', host, port: 443 };
}
}
const lastColonIndex = serverStr.lastIndexOf(':');
if (lastColonIndex > 0) {
const host = serverStr.substring(0, lastColonIndex);
const portStr = serverStr.substring(lastColonIndex + 1);
const port = parseInt(portStr, 10);
if (!isNaN(port) && port > 0 && port <= 65535) {
return { type: 'direct', host, port };
}
}
return { type: 'direct', host: serverStr, port: 443 };
}
function isSpeedTestSite(hostname) {
const speedTestDomains = ['speedtest.net','fast.com','speedtest.cn','speed.cloudflare.com', 'ovo.speedtestcustom.com'];
if (speedTestDomains.includes(hostname)) { return true; }
for (const domain of speedTestDomains) {
if (hostname.endsWith('.' + domain) || hostname === domain) {
return true;
}
}
return false;
}
async function sha224(text) {
const encoder = new TextEncoder();
const data = encoder.encode(text);
const K = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];
let H = [0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4];
const msgLen = data.length;
const bitLen = msgLen * 8;
const paddedLen = Math.ceil((msgLen + 9) / 64) * 64;
const padded = new Uint8Array(paddedLen);
padded.set(data);
padded[msgLen] = 0x80;
const view = new DataView(padded.buffer);
view.setUint32(paddedLen - 4, bitLen, false);
for (let chunk = 0; chunk < paddedLen; chunk += 64) {
const W = new Uint32Array(64);
for (let i = 0; i < 16; i++) {
W[i] = view.getUint32(chunk + i * 4, false);
}
for (let i = 16; i < 64; i++) {
const s0 = rightRotate(W[i - 15], 7) ^ rightRotate(W[i - 15], 18) ^ (W[i - 15] >>> 3);
const s1 = rightRotate(W[i - 2], 17) ^ rightRotate(W[i - 2], 19) ^ (W[i - 2] >>> 10);
W[i] = (W[i - 16] + s0 + W[i - 7] + s1) >>> 0;
}
let [a, b, c, d, e, f, g, h] = H;
for (let i = 0; i < 64; i++) {
const S1 = rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25);
const ch = (e & f) ^ (~e & g);
const temp1 = (h + S1 + ch + K[i] + W[i]) >>> 0;
const S0 = rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22);
const maj = (a & b) ^ (a & c) ^ (b & c);
const temp2 = (S0 + maj) >>> 0;
h = g;
g = f;
f = e;
e = (d + temp1) >>> 0;
d = c;
c = b;
b = a;
a = (temp1 + temp2) >>> 0;
}
H[0] = (H[0] + a) >>> 0;
H[1] = (H[1] + b) >>> 0;
H[2] = (H[2] + c) >>> 0;
H[3] = (H[3] + d) >>> 0;
H[4] = (H[4] + e) >>> 0;
H[5] = (H[5] + f) >>> 0;
H[6] = (H[6] + g) >>> 0;
H[7] = (H[7] + h) >>> 0;
}
const result = [];
for (let i = 0; i < 7; i++) {
result.push(
((H[i] >>> 24) & 0xff).toString(16).padStart(2, '0'),
((H[i] >>> 16) & 0xff).toString(16).padStart(2, '0'),
((H[i] >>> 8) & 0xff).toString(16).padStart(2, '0'),
(H[i] & 0xff).toString(16).padStart(2, '0')
);
}
return result.join('');
}
function rightRotate(value, amount) {
return (value >>> amount) | (value << (32 - amount));
}
async function handleTroRequest(request, customProxyIP) {
const wssPair = new WebSocketPair();
const [clientSock, serverSock] = Object.values(wssPair);
serverSock.accept();
let remoteConnWrapper = { socket: null };
let isDnsQuery = false;
const earlyData = request.headers.get('sec-websocket-protocol') || '';
const readable = makeReadableStr(serverSock, earlyData);
readable.pipeTo(new WritableStream({
async write(chunk) {
if (isDnsQuery) return await forwardataudp(chunk, serverSock, null);
if (remoteConnWrapper.socket) {
const writer = remoteConnWrapper.socket.writable.getWriter();
await writer.write(chunk);
writer.releaseLock();
return;
}
const trojanResult = await parsetroHeader(chunk, yourUUID);
if (!trojanResult.hasError) {
const { addressType, port, hostname, rawClientData } = trojanResult;
if (isSpeedTestSite(hostname)) {
throw new Error('Speedtest site is blocked');
}
await forwardataTCP(hostname, port, rawClientData, serverSock, null, remoteConnWrapper, customProxyIP);
return;
}
throw new Error('Invalid protocol');
},
})).catch((err) => {
// console.error('Readable pipe error:', err);
});
return new Response(null, { status: 101, webSocket: clientSock });
}
async function parsetroHeader(buffer, passwordPlainText) {
const sha224Password = await sha224(passwordPlainText);
if (buffer.byteLength < 56) {
return { hasError: true, message: "invalid data" };
}
let crLfIndex = 56;
if (new Uint8Array(buffer.slice(56, 57))[0] !== 0x0d || new Uint8Array(buffer.slice(57, 58))[0] !== 0x0a) {
return { hasError: true, message: "invalid header format" };
}
const password = new TextDecoder().decode(buffer.slice(0, crLfIndex));
if (password !== sha224Password) {
return { hasError: true, message: "invalid password" };
}
const socks5DataBuffer = buffer.slice(crLfIndex + 2);
if (socks5DataBuffer.byteLength < 6) {
return { hasError: true, message: "invalid S5 request data" };
}
const view = new DataView(socks5DataBuffer);
const cmd = view.getUint8(0);
if (cmd !== 1) {
return { hasError: true, message: "unsupported command, only TCP is allowed" };
}
const atype = view.getUint8(1);
let addressLength = 0;
let addressIndex = 2;
let address = "";
switch (atype) {
case 1: // IPv4
addressLength = 4;
address = new Uint8Array(socks5DataBuffer.slice(addressIndex, addressIndex + addressLength)).join(".");
break;
case 3: // Domain
addressLength = new Uint8Array(socks5DataBuffer.slice(addressIndex, addressIndex + 1))[0];
addressIndex += 1;
address = new TextDecoder().decode(socks5DataBuffer.slice(addressIndex, addressIndex + addressLength));
break;
case 4: // IPv6
addressLength = 16;
const dataView = new DataView(socks5DataBuffer.slice(addressIndex, addressIndex + addressLength));
const ipv6 = [];
for (let i = 0; i < 8; i++) {
ipv6.push(dataView.getUint16(i * 2).toString(16));
}
address = ipv6.join(":");
break;
default:
return { hasError: true, message: `invalid addressType is ${atype}` };
}
if (!address) {
return { hasError: true, message: `address is empty, addressType is ${atype}` };
}
const portIndex = addressIndex + addressLength;
const portBuffer = socks5DataBuffer.slice(portIndex, portIndex + 2);
const portRemote = new DataView(portBuffer).getUint16(0);
return {
hasError: false,
addressType: atype,
port: portRemote,
hostname: address,
rawClientData: socks5DataBuffer.slice(portIndex + 4)
};
}
async function connect2Socks5(proxyConfig, targetHost, targetPort, initialData) {
const { host, port, username, password } = proxyConfig;
const socket = connect({ hostname: host, port: port });
const writer = socket.writable.getWriter();
const reader = socket.readable.getReader();
try {
const authMethods = username && password ?
new Uint8Array([0x05, 0x02, 0x00, 0x02]) :
new Uint8Array([0x05, 0x01, 0x00]);
await writer.write(authMethods);
const methodResponse = await reader.read();
if (methodResponse.done || methodResponse.value.byteLength < 2) {
throw new Error('S5 method selection failed');
}
const selectedMethod = new Uint8Array(methodResponse.value)[1];
if (selectedMethod === 0x02) {
if (!username || !password) {
throw new Error('S5 requires authentication');
}
const userBytes = new TextEncoder().encode(username);
const passBytes = new TextEncoder().encode(password);
const authPacket = new Uint8Array(3 + userBytes.length + passBytes.length);
authPacket[0] = 0x01;
authPacket[1] = userBytes.length;
authPacket.set(userBytes, 2);
authPacket[2 + userBytes.length] = passBytes.length;
authPacket.set(passBytes, 3 + userBytes.length);
await writer.write(authPacket);
const authResponse = await reader.read();
if (authResponse.done || new Uint8Array(authResponse.value)[1] !== 0x00) {
throw new Error('S5 authentication failed');
}
} else if (selectedMethod !== 0x00) {
throw new Error(`S5 unsupported auth method: ${selectedMethod}`);
}
const hostBytes = new TextEncoder().encode(targetHost);
const connectPacket = new Uint8Array(7 + hostBytes.length);
connectPacket[0] = 0x05;
connectPacket[1] = 0x01;
connectPacket[2] = 0x00;
connectPacket[3] = 0x03;
connectPacket[4] = hostBytes.length;
connectPacket.set(hostBytes, 5);
new DataView(connectPacket.buffer).setUint16(5 + hostBytes.length, targetPort, false);
await writer.write(connectPacket);
const connectResponse = await reader.read();
if (connectResponse.done || new Uint8Array(connectResponse.value)[1] !== 0x00) {
throw new Error('S5 connection failed');
}
await writer.write(initialData);
writer.releaseLock();
reader.releaseLock();
return socket;
} catch (error) {
writer.releaseLock();
reader.releaseLock();
throw error;
}
}
async function connect2Http(proxyConfig, targetHost, targetPort, initialData) {
const { host, port, username, password } = proxyConfig;
const socket = connect({ hostname: host, port: port });
const writer = socket.writable.getWriter();
const reader = socket.readable.getReader();
try {
let connectRequest = `CONNECT ${targetHost}:${targetPort} HTTP/1.1\r\n`;
connectRequest += `Host: ${targetHost}:${targetPort}\r\n`;
if (username && password) {
const auth = btoa(`${username}:${password}`);
connectRequest += `Proxy-Authorization: Basic ${auth}\r\n`;
}
connectRequest += `User-Agent: Mozilla/5.0\r\n`;
connectRequest += `Connection: keep-alive\r\n`;
connectRequest += '\r\n';
await writer.write(new TextEncoder().encode(connectRequest));
let responseBuffer = new Uint8Array(0);
let headerEndIndex = -1;
let bytesRead = 0;
const maxHeaderSize = 8192;
while (headerEndIndex === -1 && bytesRead < maxHeaderSize) {
const { done, value } = await reader.read();
if (done) {
throw new Error('Connection closed before receiving HTTP response');
}
const newBuffer = new Uint8Array(responseBuffer.length + value.length);
newBuffer.set(responseBuffer);
newBuffer.set(value, responseBuffer.length);
responseBuffer = newBuffer;
bytesRead = responseBuffer.length;
for (let i = 0; i < responseBuffer.length - 3; i++) {
if (responseBuffer[i] === 0x0d && responseBuffer[i + 1] === 0x0a &&
responseBuffer[i + 2] === 0x0d && responseBuffer[i + 3] === 0x0a) {
headerEndIndex = i + 4;
break;
}
}
}
if (headerEndIndex === -1) {
throw new Error('Invalid HTTP response');
}
const headerText = new TextDecoder().decode(responseBuffer.slice(0, headerEndIndex));
const statusLine = headerText.split('\r\n')[0];
const statusMatch = statusLine.match(/HTTP\/\d\.\d\s+(\d+)/);
if (!statusMatch) {
throw new Error(`Invalid response: ${statusLine}`);
}
const statusCode = parseInt(statusMatch[1]);
if (statusCode < 200 || statusCode >= 300) {
throw new Error(`Connection failed: ${statusLine}`);
}
await writer.write(initialData);
writer.releaseLock();
reader.releaseLock();
return socket;
} catch (error) {
try {
writer.releaseLock();
} catch (e) {}
try {
reader.releaseLock();
} catch (e) {}
try {
socket.close();
} catch (e) {}
throw error;
}
}
async function forwardataTCP(host, portNum, rawData, ws, respHeader, remoteConnWrapper, customProxyIP) {
async function connectDirect(address, port, data) {
const remoteSock = connect({ hostname: address, port: port });
const writer = remoteSock.writable.getWriter();
await writer.write(data);
writer.releaseLock();
return remoteSock;
}
let proxyConfig = null;
let shouldUseProxy = false;
if (customProxyIP) {
proxyConfig = parsePryAddress(customProxyIP);
if (proxyConfig && (proxyConfig.type === 'socks5' || proxyConfig.type === 'http' || proxyConfig.type === 'https')) {
shouldUseProxy = true;
} else if (!proxyConfig) {
proxyConfig = parsePryAddress(proxyIP) || { type: 'direct', host: proxyIP, port: 443 };
}
} else {
proxyConfig = parsePryAddress(proxyIP) || { type: 'direct', host: proxyIP, port: 443 };
if (proxyConfig.type === 'socks5' || proxyConfig.type === 'http' || proxyConfig.type === 'https') {
shouldUseProxy = true;
}
}
async function connecttoPry() {
let newSocket;
if (proxyConfig.type === 'socks5') {
newSocket = await connect2Socks5(proxyConfig, host, portNum, rawData);
} else if (proxyConfig.type === 'http' || proxyConfig.type === 'https') {
newSocket = await connect2Http(proxyConfig, host, portNum, rawData);
} else {
newSocket = await connectDirect(proxyConfig.host, proxyConfig.port, rawData);
}
remoteConnWrapper.socket = newSocket;
newSocket.closed.catch(() => {}).finally(() => closeSocketQuietly(ws));
connectStreams(newSocket, ws, respHeader, null);
}
if (shouldUseProxy) {
try {
await connecttoPry();
} catch (err) {
throw err;
}
} else {
try {
const initialSocket = await connectDirect(host, portNum, rawData);
remoteConnWrapper.socket = initialSocket;
connectStreams(initialSocket, ws, respHeader, connecttoPry);
} catch (err) {
await connecttoPry();
}
}
}
function makeReadableStr(socket, earlyDataHeader) {
let cancelled = false;
return new ReadableStream({
start(controller) {
socket.addEventListener('message', (event) => {
if (!cancelled) controller.enqueue(event.data);
});
socket.addEventListener('close', () => {
if (!cancelled) {
closeSocketQuietly(socket);
controller.close();
}
});
socket.addEventListener('error', (err) => controller.error(err));
const { earlyData, error } = base64ToArray(earlyDataHeader);
if (error) controller.error(error);
else if (earlyData) controller.enqueue(earlyData);
},
cancel() {
cancelled = true;
closeSocketQuietly(socket);
}
});
}
async function connectStreams(remoteSocket, webSocket, headerData, retryFunc) {
let header = headerData, hasData = false;
await remoteSocket.readable.pipeTo(
new WritableStream({
async write(chunk, controller) {
hasData = true;
if (webSocket.readyState !== WebSocket.OPEN) controller.error('ws.readyState is not open');
if (header) {
const response = new Uint8Array(header.length + chunk.byteLength);
response.set(header, 0);
response.set(chunk, header.length);
webSocket.send(response.buffer);
header = null;
} else {
webSocket.send(chunk);
}
},
abort() {},
})
).catch((err) => {
closeSocketQuietly(webSocket);
});
if (!hasData && retryFunc) {
await retryFunc();
}
}
async function forwardataudp(udpChunk, webSocket, respHeader) {
try {
const tcpSocket = connect({ hostname: '8.8.4.4', port: 53 });
let vlessHeader = respHeader;
const writer = tcpSocket.writable.getWriter();
await writer.write(udpChunk);
writer.releaseLock();
await tcpSocket.readable.pipeTo(new WritableStream({
async write(chunk) {
if (webSocket.readyState === WebSocket.OPEN) {
if (vlessHeader) {
const response = new Uint8Array(vlessHeader.length + chunk.byteLength);
response.set(vlessHeader, 0);
response.set(chunk, vlessHeader.length);
webSocket.send(response.buffer);
vlessHeader = null;
} else {
webSocket.send(chunk);
}
}
},
}));
} catch (error) {
// console.error('UDP forward error:', error);
}
}
function HomePage(request) {
const url = new URL(request.url);
const typelink = 'c'+ 'l'+ 'a'+ 's'+ 'h';
const surlink = 's' + 'u' + 'r' + 'g' + 'e';
const currentDomain = url.hostname;
const baseUrl = `https://${currentDomain}`;
const vUrl = `${baseUrl}/sub/${subPath}`;
const surLink = `https://sub.ssss.xx.kg/${surlink}?config=${vUrl}`;
const claLink = `https://sub.ssss.xx.kg/${typelink}?config=${vUrl}`;
const html = `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Trojan 订阅中心</title><style>body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;margin:0;padding:20px;background:linear-gradient(135deg,#7dd3ca 0%,#a17ec4 100%);color:#333}.container{height:1080px;max-width:800px;margin:0 auto}.header{margin-bottom:30px}.header h1{text-align:center;color:#007fff;border-bottom:2px solid #3498db;padding-bottom:10px}.section{margin-bottom:0px}.section h2{color:#b33ce7;margin-bottom:5px;font-size:1.1em}.link-box{background:#f0fffa;border:1px solid #ddd;border-radius:8px;padding:15px;margin-bottom:15px;display:flex;justify-content:space-between;align-items:flex-start}.lintext{flex:1;word-break:break-all;font-family:monospace;color:#2980b9;margin:10px;}.clesh-config{flex:1;word-break:break-all;font-family:monospace;color:#2980b9;margin:10px;white-space:pre-wrap;background:#f8f9fa;padding:10px;border-radius:4px;border:1px solid #e9ecef}.button-group{display:flex;gap:10px;flex-shrink:0}.copy-btn{background:#27aea2;color:white;border:none;padding:8px 15px;border-radius:4px;cursor:pointer;transition:all 0.3s ease}.copy-btn:hover{background:#219652}.copy-btn.copied{background:#0e981d}.qrcode-btn{background:#e67e22;color:white;border:none;padding:8px 15px;border-radius:4px;cursor:pointer}.qrcode-btn:hover{background:#d35400}.footer{text-align:center;color:#7f8c8d;border-top:1px solid #e1d9fb;}.footer a{color:#c311ffs;text-decoration:none;margin:0 15px}.footer a:hover{text-decoration:underline}#qrModal{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:1000}.modal-content{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);background:white;padding:20px;border-radius:8px;text-align:center;max-width:90%}.modal-content h3{margin-bottom:15px;color:#2c3e50}.modal-content img{max-width:300px;height:auto;margin:10px 0}.close-btn{background:#e74c3c;color:white;border:none;padding:8px 15px;border-radius:4px;cursor:pointer;margin-top:15px}.close-btn:hover{background:#c0392b}@media (max-width:600px){.link-box{flex-direction:column}.button-group{margin-top:10px;align-self:flex-end}}</style></head><body><div class="container"><div class="header"><h1>Trojan 订阅中心</h1></div><div class="section"><h2>v2rayN(g)/Nekobox/小火箭/kraing/stersiand 订阅链接</h2><div class="link-box"><div class="lintext">${vUrl}</div><div class="button-group"><button class="copy-btn" onclick="copyToClipboard(this,'${vUrl}')">复制</button><button class="qrcode-btn" onclick="showQRCode('${vUrl}','V2rayN(g)/nekobox/小火箭/karing/stersiand 订阅链接')">二维码</button></div></div></div><div class="section"><h2>${surlink}订阅链接</h2><div class="link-box"><div class="lintext">${surLink}</div><div class="button-group"><button class="copy-btn" onclick="copyToClipboard(this,'${surLink}')">复制</button><button class="qrcode-btn" onclick="showQRCode('${surLink}','${surlink} 订阅链接')">二维码</button></div></div></div><div class="section"><h2>${typelink}系列订阅链接</h2><div class="link-box"><div class="lintext">${claLink}</div><div class="button-group"><button class="copy-btn" onclick="copyToClipboard(this,'${claLink}')">复制</button><button class="qrcode-btn" onclick="showQRCode('${claLink}','${typelink}系列 订阅链接')">二维码</button></div></div></div><div class="footer"><p><a href="https://github.com/eooce/CF-workers-and-snip-VLESS" target="_blank">GitHub</a> | <a href="https://check-proxyip.ssss.nyc.mn" target="_blank">Proxyip检测</a> | <a href="https://t.me/+vtZ8GLzjksA4OTVl" target="_blank">TG交流群</a></p></div></div><div id="qrModal"><div class="modal-content"><h3 id="modalTitle">二维码</h3><img id="qrImage" src="" alt="QR Code"><p id="qrText" style="word-break:break-all;margin:10px 0"></p><button class="close-btn" onclick="closeQRModal()">关闭</button></div></div><script>function copyToClipboard(button,text){const originalText=button.textContent;const decodedText=text.replace(/\\\\n/g,'\\n').replace(/"/g,'"');navigator.clipboard.writeText(decodedText).then(()=>{button.textContent='已复制';button.classList.add('copied');setTimeout(()=>{button.textContent=originalText;button.classList.remove('copied')},2000)}).catch(()=>{const e=document.createElement('textarea');e.value=decodedText;document.body.appendChild(e);e.select();document.execCommand('copy');document.body.removeChild(e);button.textContent='已复制';button.classList.add('copied');setTimeout(()=>{button.textContent=originalText;button.classList.remove('copied')},2000)})}function showQRCode(text,title){document.getElementById('modalTitle').textContent=title;document.getElementById('qrText').textContent=text;const e='https://tool.oschina.net/action/qrcode/generate?data='+encodeURIComponent(text)+'&output=image%2Fpng&error=L&type=0&margin=4&size=4';fetch(e).then(t=>t.blob()).then(t=>{const n=URL.createObjectURL(t);document.getElementById('qrImage').src=n}).catch(()=>{document.getElementById('qrImage').src=e});document.getElementById('qrModal').style.display='block'}function closeQRModal(){document.getElementById('qrModal').style.display='none'}</script></body></html>`;
return new Response(html, {
status: 200,
headers: {
'Content-Type': 'text/html;charset=utf-8',
'Cache-Control': 'no-cache, no-store, must-revalidate',
},
});
}
export default {
async fetch(request, env) {
try {
// 需要开启环境变量,将以下3行前的//号去掉
// if (env.PROXYIP || env.proxyip || env.proxyIP) { const servers = (env.PROXYIP || env.proxyip || env.proxyIP).split(',').map(s => s.trim()); proxyIP = servers[0]; }
// subPath = env.SUB_PATH || env.subpath || subPath;
// yourUUID = env.UUID || env.uuid || yourUUID;
if (subPath === 'link' || subPath === '') { subPath = yourUUID; }
const troHeader = 't' + 'r' + 'o' + 'j' + 'a' + 'n';
const servers = proxyIP.split(',').map(s => s.trim());
proxyIP = servers[0];
const url = new URL(request.url);
const pathname = url.pathname;
let pathProxyIP = null;
if (pathname.startsWith('/proxyip=')) {
try { pathProxyIP = decodeURIComponent(pathname.substring(9)).trim();
} catch (e) {
// ignore error
}
if (pathProxyIP && !request.headers.get('Upgrade')) {
proxyIP = pathProxyIP;
return new Response(`set proxyIP to: ${proxyIP}\n\n`, {
headers: {
'Content-Type': 'text/plain; charset=utf-8',
'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
},
});
}
}
if (request.headers.get('Upgrade') === 'websocket') {
let wsPathProxyIP = null;
if (pathname.startsWith('/proxyip=')) {
try {
wsPathProxyIP = decodeURIComponent(pathname.substring(9)).trim();
} catch (e) {
// ignore error
}
}
const customProxyIP = wsPathProxyIP || url.searchParams.get('proxyip') || request.headers.get('proxyip');
return await handleTroRequest(request, customProxyIP);
} else if (request.method === 'GET') {
if (url.pathname === '/') {
const url = request.headers.get('Host');
const baseUrl = `https://${url}`;
return new Response(`Hello ${troHeader}!\n\n请访问: ${baseUrl}/你的UUID 进入订阅中心`);
}
if (url.pathname === `/${yourUUID.toLowerCase()}`) { return HomePage(request);}
if (url.pathname.toLowerCase().includes(`/${subPath.toLowerCase()}`)) {
const currentDomain = url.hostname;
const troLinks = cfip.map(cdnItem => {
let host, port = 443, nodeName = '';
if (cdnItem.includes('#')) {
const parts = cdnItem.split('#');
cdnItem = parts[0];
nodeName = parts[1];
}
if (cdnItem.startsWith('[') && cdnItem.includes(']:')) {
const ipv6End = cdnItem.indexOf(']:');
host = cdnItem.substring(0, ipv6End + 1);
const portStr = cdnItem.substring(ipv6End + 2);
port = parseInt(portStr) || 443;
} else if (cdnItem.includes(':')) {
const parts = cdnItem.split(':');
host = parts[0];
port = parseInt(parts[1]) || 443;
} else {
host = cdnItem;
}
const troNodeName = nodeName ? `${nodeName}-${troHeader}` : `Workers-${troHeader}`;
return `${troHeader}://${yourUUID}@${host}:${port}?security=tls&sni=${currentDomain}&fp=firefox&allowInsecure=0&type=ws&host=${currentDomain}&path=%2F%3Fed%3D2560#${troNodeName}`;
});
const linksText = troLinks.join('\n');
const base64Content = btoa(unescape(encodeURIComponent(linksText)));
return new Response(base64Content, {
headers: {
'Content-Type': 'text/plain; charset=utf-8',
'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
},
});
}
}
return new Response('Not Found', { status: 404 });
} catch (err) {
return new Response('Internal Server Error', { status: 500 });
}
},
};