前言

一个月前马斯克开源了自家的大语言模型 grok-1 并顺带着嘲讽了一下 OpenAI,想看看 OpenAI 关于 “Open” 的部分。

这波我肯定是站马斯克了,记得第一次听说 OpenAI 名字的时候,还以为这是一个研究 AI 的开源社区,应为它遵循了 OpenCV, OpenGL 这样的命名模式。

后来 GPT-4 需要一个月 20 刀的时候,也算是认清 OpenAI 的真面目了。

自从大语言模型诞生以来,中国民众想使用 AI 服务是真的难。可谓是双向卡脖子,一方面阿美丽卡的公司不对中国开放服务。另一方面国民无法访问自由的互联网。

最近,ChatGPT-3.5 可以免注册使用了(它总算是 Open 了一小部分😂),也就是说对于我们来说又少了一道使用 ChatCPT 的门槛。

这篇博客介绍了一种访问 chat.openai.com 的方法。

基于 Cloudflare 搭建 Vless 节点

既然 chat.openai.com 已经可以免注册使用了,那么原则上我们就只剩下 GFW 这一个障碍了。但并不是任何一个梯子都可以访问 chat.openai.com 的,比如我的甲骨文云的梯子就不行。

原因在于 OpenAI 屏蔽了许多知名云服务提供商的 IP,也就是专门针对我们这些使用代理的用户设置的障碍。

把代理节点搭建在 Cloudflare 家里,使用 Cloudflare 的 IP 就可以正常访问 chat.openai.com 了。

免费的东西,建议人手一个。

节点搭建

  1. 登录 Cloudflare

    https://www.cloudflare.com/

  2. 按下图操作依次执行

  1. 进入到编辑代码界面后,删除默认内容,然后复制下面的代码并粘贴到 worker.js 代码框中

2024-07-21 更新:

这种白嫖的教程总是很容易失效,往往是白嫖客和官方之间的循环对抗。

在我写这篇文章的时候,下面两个代码都是可用的,但是未来可能会失效。

点击查看代码 1
// <!--GAMFC-->version base on commit 43fad05dcdae3b723c53c226f8181fc5bd47223e, time is 2023-06-22 15:20:05 UTC<!--GAMFC-END-->.
// @ts-ignore
import { connect } from 'cloudflare:sockets';

// How to generate your own UUID:
// [Windows] Press "Win + R", input cmd and run:  Powershell -NoExit -Command "[guid]::NewGuid()"
let userID = '❗❗❗填写这里❗❗❗';

let proxyIP = '';

let sub = '';// 留空则使用内置订阅
let subconverter = 'subapi-loadbalancing.pages.dev';// clash订阅转换后端,目前使用CM的订阅转换功能。自带虚假uuid和host订阅。
let subconfig = "https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online.ini"; //订阅配置文件

// The user name and password do not contain special characters
// Setting the address will ignore proxyIP
// Example:  user:pass@host:port  or  host:port
let socks5Address = 'wgxls:wgxlsslxgw@uk2.1881997.xyz:44753';

if (!isValidUUID(userID)) {
	throw new Error('uuid is not valid');
}

let parsedSocks5Address = {}; 
let enableSocks = true;

// 虚假uuid和hostname,用于发送给配置生成服务
let fakeUserID ;
let fakeHostName ;
let noTLS = 'false'; 
const expire = 4102329600;//2099-12-31
let proxyIPs;
let addresses = [];
let addressesapi = [];
let addressesnotls = [];
let addressesnotlsapi = [];
let addressescsv = [];
let DLS = 8;
let FileName = 'edgetunnel';
let BotToken ='';
let ChatID =''; 
let proxyhosts = [];//本地代理域名池
let proxyhostsURL = 'https://raw.githubusercontent.com/cmliu/CFcdnVmess2sub/main/proxyhosts';//在线代理域名池URL
let RproxyIP = 'false';
export default {
	/**
	 * @param {import("@cloudflare/workers-types").Request} request
	 * @param {{UUID: string, PROXYIP: string}} env
	 * @param {import("@cloudflare/workers-types").ExecutionContext} ctx
	 * @returns {Promise<Response>}
	 */
	async fetch(request, env, ctx) {
		try {
			const UA = request.headers.get('User-Agent') || 'null';
			const userAgent = UA.toLowerCase();
			userID = (env.UUID || userID).toLowerCase();

			const currentDate = new Date();
			currentDate.setHours(0, 0, 0, 0); 
			const timestamp = Math.ceil(currentDate.getTime() / 1000);
			const fakeUserIDMD5 = await MD5MD5(``);
			fakeUserID = fakeUserIDMD5.slice(0, 8) + "-" + fakeUserIDMD5.slice(8, 12) + "-" + fakeUserIDMD5.slice(12, 16) + "-" + fakeUserIDMD5.slice(16, 20) + "-" + fakeUserIDMD5.slice(20);
			fakeHostName = fakeUserIDMD5.slice(6, 9) + "." + fakeUserIDMD5.slice(13, 19);
			//console.log(`\n`); // 打印fakeID

			proxyIP = env.PROXYIP || proxyIP;
			proxyIPs = await ADD(proxyIP);
			proxyIP = proxyIPs[Math.floor(Math.random() * proxyIPs.length)];
			//console.log(proxyIP);
			socks5Address = env.SOCKS5 || socks5Address;
			sub = env.SUB || sub;
			subconverter = env.SUBAPI || subconverter;
			subconfig = env.SUBCONFIG || subconfig;
			if (socks5Address) {
				try {
					parsedSocks5Address = socks5AddressParser(socks5Address);
					RproxyIP = env.RPROXYIP || 'false';
					enableSocks = true;
				} catch (err) {
  					/** @type {Error} */ 
					let e = err;
					console.log(e.toString());
					RproxyIP = env.RPROXYIP || !proxyIP ? 'true' : 'false';
					enableSocks = false;
				}
			} else {
				RproxyIP = env.RPROXYIP || !proxyIP ? 'true' : 'false';
			}
			if (env.ADD) addresses = await ADD(env.ADD);
			if (env.ADDAPI) addressesapi = await ADD(env.ADDAPI);
			if (env.ADDNOTLS) addressesnotls = await ADD(env.ADDNOTLS);
			if (env.ADDNOTLSAPI) addressesnotlsapi = await ADD(env.ADDNOTLSAPI);
			if (env.ADDCSV) addressescsv = await ADD(env.ADDCSV);
			DLS = env.DLS || DLS;
			BotToken = env.TGTOKEN || BotToken;
			ChatID = env.TGID || ChatID; 
			const upgradeHeader = request.headers.get('Upgrade');
			const url = new URL(request.url);
			if (url.searchParams.has('sub') && url.searchParams.get('sub') !== '') sub = url.searchParams.get('sub');
			if (url.searchParams.has('notls')) noTLS = 'true';
			if (!upgradeHeader || upgradeHeader !== 'websocket') {
				// const url = new URL(request.url);
				switch (url.pathname.toLowerCase()) {
				case '/':
					const envKey = env.URL302 ? 'URL302' : (env.URL ? 'URL' : null);
					if (envKey) {
						const URLs = await ADD(env[envKey]);
						const URL = URLs[Math.floor(Math.random() * URLs.length)];
						return envKey === 'URL302' ? Response.redirect(URL, 302) : fetch(new Request(URL, request));
					}
					return new Response(JSON.stringify(request.cf, null, 4), { status: 200 });
				case `/`:
					const fakeConfig = await getVLESSConfig(userID, request.headers.get('Host'), sub, 'CF-Workers-SUB', RproxyIP, url);
					return new Response(``, { status: 200 });
				case '/config': {
					await sendMessage(`#获取订阅 `, request.headers.get('CF-Connecting-IP'), `UA: </tg-spoiler>\n域名: ${url.hostname}\n<tg-spoiler>入口: ${url.pathname + url.search}</tg-spoiler>`);
					if ((!sub || sub == '') && (addresses.length + addressesapi.length + addressesnotls.length + addressesnotlsapi.length + addressescsv.length) == 0){
						if (request.headers.get('Host').includes(".workers.dev")) {
							sub = 'workervless2sub-f1q.pages.dev'; 
							subconfig = 'https://raw.githubusercontent.com/cmliu/ACL4SSR/main/Clash/config/ACL4SSR_Online.ini';
						} else {
							sub = 'vless-4ca.pages.dev';
							subconfig = "https://raw.githubusercontent.com/cmliu/ACL4SSR/main/Clash/config/ACL4SSR_Online_Full_MultiMode.ini";
						}
					} 
					const vlessConfig = await getVLESSConfig(userID, request.headers.get('Host'), sub, UA, RproxyIP, url);
					const now = Date.now();
					//const timestamp = Math.floor(now / 1000);
					const today = new Date(now);
					today.setHours(0, 0, 0, 0);
					const UD = Math.floor(((now - today.getTime())/86400000) * 24 * 1099511627776 / 2);
					let pagesSum = UD;
					let workersSum = UD;
					let total = 24 * 1099511627776 ;
					if (env.CFEMAIL && env.CFKEY){
						const email = env.CFEMAIL;
						const key = env.CFKEY;
						const accountIndex = env.CFID || 0;
						const accountId = await getAccountId(email, key);
						if (accountId){
							const now = new Date()
							now.setUTCHours(0, 0, 0, 0)
							const startDate = now.toISOString()
							const endDate = new Date().toISOString();
							const Sum = await getSum(accountId, accountIndex, email, key, startDate, endDate);
							pagesSum = Sum[0];
							workersSum = Sum[1];
							total = 102400 ;
						}
					}
					//console.log(`pagesSum: \nworkersSum: \ntotal: `);
					if (userAgent && userAgent.includes('mozilla')){
						return new Response(``, {
							status: 200,
							headers: {
								"Content-Type": "text/plain;charset=utf-8",
								"Profile-Update-Interval": "6",
								"Subscription-Userinfo": `upload=; download=; total=; expire=`,
							}
						});
					} else {
						return new Response(``, {
							status: 200,
							headers: {
								"Content-Disposition": `attachment; filename=; filename*=utf-8''${encodeURIComponent(FileName)}`,
								"Content-Type": "text/plain;charset=utf-8",
								"Profile-Update-Interval": "6",
								"Subscription-Userinfo": `upload=; download=; total=; expire=`,
							}
						});
					}
				}
				default:
					return new Response('Not found', { status: 404 });
				}
			} else {
				proxyIP = url.searchParams.get('proxyip') || proxyIP;
				if (new RegExp('/proxyip=', 'i').test(url.pathname)) proxyIP = url.pathname.toLowerCase().split('/proxyip=')[1];
				else if (new RegExp('/proxyip.', 'i').test(url.pathname)) proxyIP = `proxyip.${url.pathname.toLowerCase().split("/proxyip.")[1]}`;
				
				socks5Address = url.searchParams.get('socks5') || socks5Address;
				if (new RegExp('/socks5=', 'i').test(url.pathname)) socks5Address = url.pathname.split('5=')[1];
				else if (new RegExp('/socks://', 'i').test(url.pathname) || new RegExp('/socks5://', 'i').test(url.pathname)) {
					socks5Address = url.pathname.split('://')[1].split('#')[0];
					if (socks5Address.includes('@')){
						let userPassword = socks5Address.split('@')[0];
						const base64Regex = /^(?:[A-Z0-9+/]{4})*(?:[A-Z0-9+/]{2}==|[A-Z0-9+/]{3}=)?$/i;
						if (base64Regex.test(userPassword) && !userPassword.includes(':')) userPassword = atob(userPassword);
						socks5Address = `@${socks5Address.split('@')[1]}`;
					}
				}
				if (socks5Address) {
					try {
						parsedSocks5Address = socks5AddressParser(socks5Address);
						enableSocks = true;
					} catch (err) {
						/** @type {Error} */ 
						let e = err;
						console.log(e.toString());
						enableSocks = false;
					}
				} else {
					enableSocks = false;
				}
				return await vlessOverWSHandler(request);
			}
		} catch (err) {
			/** @type {Error} */ let e = err;
			return new Response(e.toString());
		}
	},
};

/**
 * 处理 VLESS over WebSocket 的请求
 * @param {import("@cloudflare/workers-types").Request} request
 */
async function vlessOverWSHandler(request) {

	/** @type {import("@cloudflare/workers-types").WebSocket[]} */
	// @ts-ignore
	const webSocketPair = new WebSocketPair();
	const [client, webSocket] = Object.values(webSocketPair);

	// 接受 WebSocket 连接
	webSocket.accept();

	let address = '';
	let portWithRandomLog = '';
	// 日志函数,用于记录连接信息
	const log = (/** @type {string} */ info, /** @type {string | undefined} */ event) => {
		console.log(`[:] `, event || '');
	};
	// 获取早期数据头部,可能包含了一些初始化数据
	const earlyDataHeader = request.headers.get('sec-websocket-protocol') || '';

	// 创建一个可读的 WebSocket 流,用于接收客户端数据
	const readableWebSocketStream = makeReadableWebSocketStream(webSocket, earlyDataHeader, log);

	/** @type {{ value: import("@cloudflare/workers-types").Socket | null}}*/
	// 用于存储远程 Socket 的包装器
	let remoteSocketWapper = {
		value: null,
	};
	// 标记是否为 DNS 查询
	let isDns = false;

	// WebSocket 数据流向远程服务器的管道
	readableWebSocketStream.pipeTo(new WritableStream({
		async write(chunk, controller) {
			if (isDns) {
				// 如果是 DNS 查询,调用 DNS 处理函数
				return await handleDNSQuery(chunk, webSocket, null, log);
			}
			if (remoteSocketWapper.value) {
				// 如果已有远程 Socket,直接写入数据
				const writer = remoteSocketWapper.value.writable.getWriter()
				await writer.write(chunk);
				writer.releaseLock();
				return;
			}

			// 处理 VLESS 协议头部
			const {
				hasError,
				message,
				addressType,
				portRemote = 443,
				addressRemote = '',
				rawDataIndex,
				vlessVersion = new Uint8Array([0, 0]),
				isUDP,
			} = processVlessHeader(chunk, userID);
			// 设置地址和端口信息,用于日志
			address = addressRemote;
			portWithRandomLog = `--${Math.random()} ${isUDP ? 'udp ' : 'tcp '} `;
			if (hasError) {
				// 如果有错误,抛出异常
				throw new Error(message);
				return;
			}
			// 如果是 UDP 且端口不是 DNS 端口(53),则关闭连接
			if (isUDP) {
				if (portRemote === 53) {
					isDns = true;
				} else {
					throw new Error('UDP 代理仅对 DNS(53 端口)启用');
					return;
				}
			}
			// 构建 VLESS 响应头部
			const vlessResponseHeader = new Uint8Array([vlessVersion[0], 0]);
			// 获取实际的客户端数据
			const rawClientData = chunk.slice(rawDataIndex);

			if (isDns) {
				// 如果是 DNS 查询,调用 DNS 处理函数
				return handleDNSQuery(rawClientData, webSocket, vlessResponseHeader, log);
			}
			// 处理 TCP 出站连接
			log(`处理 TCP 出站连接 :`);
			handleTCPOutBound(remoteSocketWapper, addressType, addressRemote, portRemote, rawClientData, webSocket, vlessResponseHeader, log);
		},
		close() {
			log(`readableWebSocketStream 已关闭`);
		},
		abort(reason) {
			log(`readableWebSocketStream 已中止`, JSON.stringify(reason));
		},
	})).catch((err) => {
		log('readableWebSocketStream 管道错误', err);
	});

	// 返回一个 WebSocket 升级的响应
	return new Response(null, {
		status: 101,
		// @ts-ignore
		webSocket: client,
	});
}

/**
 * 处理出站 TCP 连接。
 *
 * @param {any} remoteSocket 远程 Socket 的包装器,用于存储实际的 Socket 对象
 * @param {number} addressType 要连接的远程地址类型(如 IP 类型:IPv4 或 IPv6)
 * @param {string} addressRemote 要连接的远程地址
 * @param {number} portRemote 要连接的远程端口
 * @param {Uint8Array} rawClientData 要写入的原始客户端数据
 * @param {import("@cloudflare/workers-types").WebSocket} webSocket 用于传递远程 Socket 的 WebSocket
 * @param {Uint8Array} vlessResponseHeader VLESS 响应头部
 * @param {function} log 日志记录函数
 * @returns {Promise<void>} 异步操作的 Promise
 */
async function handleTCPOutBound(remoteSocket, addressType, addressRemote, portRemote, rawClientData, webSocket, vlessResponseHeader, log,) {
	/**
	 * 连接远程服务器并写入数据
	 * @param {string} address 要连接的地址
	 * @param {number} port 要连接的端口
	 * @param {boolean} socks 是否使用 SOCKS5 代理连接
	 * @returns {Promise<import("@cloudflare/workers-types").Socket>} 连接后的 TCP Socket
	 */
	async function connectAndWrite(address, port, socks = false) {
		/** @type {import("@cloudflare/workers-types").Socket} */
		log(`connected to :`);
		//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==')}${atob('LmlwLjA5MDIyNy54eXo=')}`;
		// 如果指定使用 SOCKS5 代理,则通过 SOCKS5 协议连接;否则直接连接
		const tcpSocket = socks ? await socks5Connect(addressType, address, port, log)
			: connect({
				hostname: address,
				port: port,
			});
		remoteSocket.value = tcpSocket;
		//log(`connected to :`);
		const writer = tcpSocket.writable.getWriter();
		// 首次写入,通常是 TLS 客户端 Hello 消息
		await writer.write(rawClientData);
		writer.releaseLock();
		return tcpSocket;
	}

	/**
	 * 重试函数:当 Cloudflare 的 TCP Socket 没有传入数据时,我们尝试重定向 IP
	 * 这可能是因为某些网络问题导致的连接失败
	 */
	async function retry() {
		if (enableSocks) {
			// 如果启用了 SOCKS5,通过 SOCKS5 代理重试连接
			tcpSocket = await connectAndWrite(addressRemote, portRemote, true);
		} else {
			// 否则,尝试使用预设的代理 IP(如果有)或原始地址重试连接
			if (!proxyIP || proxyIP == '') proxyIP = atob('cHJveHlpcC5meHhrLmRlZHluLmlv');
			tcpSocket = await connectAndWrite(proxyIP || addressRemote, portRemote);
		}
		// 无论重试是否成功,都要关闭 WebSocket(可能是为了重新建立连接)
		tcpSocket.closed.catch(error => {
			console.log('retry tcpSocket closed error', error);
		}).finally(() => {
			safeCloseWebSocket(webSocket);
		})
		// 建立从远程 Socket 到 WebSocket 的数据流
		remoteSocketToWS(tcpSocket, webSocket, vlessResponseHeader, null, log);
	}

	// 首次尝试连接远程服务器
	let tcpSocket = await connectAndWrite(addressRemote, portRemote);

	// 当远程 Socket 就绪时,将其传递给 WebSocket
	// 建立从远程服务器到 WebSocket 的数据流,用于将远程服务器的响应发送回客户端
	// 如果连接失败或无数据,retry 函数将被调用进行重试
	remoteSocketToWS(tcpSocket, webSocket, vlessResponseHeader, retry, log);
}

/**
 * 将 WebSocket 转换为可读流(ReadableStream)
 * @param {import("@cloudflare/workers-types").WebSocket} webSocketServer 服务器端的 WebSocket 对象
 * @param {string} earlyDataHeader WebSocket 0-RTT(零往返时间)的早期数据头部
 * @param {(info: string)=> void} log 日志记录函数,用于记录 WebSocket 0-RTT 相关信息
 * @returns {ReadableStream} 由 WebSocket 消息组成的可读流
 */
function makeReadableWebSocketStream(webSocketServer, earlyDataHeader, log) {
	// 标记可读流是否已被取消
	let readableStreamCancel = false;

	// 创建一个新的可读流
	const stream = new ReadableStream({
		// 当流开始时的初始化函数
		start(controller) {
			// 监听 WebSocket 的消息事件
			webSocketServer.addEventListener('message', (event) => {
				// 如果流已被取消,不再处理新消息
				if (readableStreamCancel) {
					return;
				}
				const message = event.data;
				// 将消息加入流的队列中
				controller.enqueue(message);
			});

			// 监听 WebSocket 的关闭事件
			// 注意:这个事件意味着客户端关闭了客户端 -> 服务器的流
			// 但是,服务器 -> 客户端的流仍然打开,直到在服务器端调用 close()
			// WebSocket 协议要求在每个方向上都要发送单独的关闭消息,以完全关闭 Socket
			webSocketServer.addEventListener('close', () => {
				// 客户端发送了关闭信号,需要关闭服务器端
				safeCloseWebSocket(webSocketServer);
				// 如果流未被取消,则关闭控制器
				if (readableStreamCancel) {
					return;
				}
				controller.close();
			});

			// 监听 WebSocket 的错误事件
			webSocketServer.addEventListener('error', (err) => {
				log('WebSocket 服务器发生错误');
				// 将错误传递给控制器
				controller.error(err);
			});

			// 处理 WebSocket 0-RTT(零往返时间)的早期数据
			// 0-RTT 允许在完全建立连接之前发送数据,提高了效率
			const { earlyData, error } = base64ToArrayBuffer(earlyDataHeader);
			if (error) {
				// 如果解码早期数据时出错,将错误传递给控制器
				controller.error(error);
			} else if (earlyData) {
				// 如果有早期数据,将其加入流的队列中
				controller.enqueue(earlyData);
			}
		},

		// 当使用者从流中拉取数据时调用
		pull(controller) {
			// 这里可以实现反压机制
			// 如果 WebSocket 可以在流满时停止读取,我们就可以实现反压
			// 参考:https://streams.spec.whatwg.org/#example-rs-push-backpressure
		},

		// 当流被取消时调用
		cancel(reason) {
			// 流被取消的几种情况:
			// 1. 当管道的 WritableStream 有错误时,这个取消函数会被调用,所以在这里处理 WebSocket 服务器的关闭
			// 2. 如果 ReadableStream 被取消,所有 controller.close/enqueue 都需要跳过
			// 3. 但是经过测试,即使 ReadableStream 被取消,controller.error 仍然有效
			if (readableStreamCancel) {
				return;
			}
			log(`可读流被取消,原因是 `);
			readableStreamCancel = true;
			// 安全地关闭 WebSocket
			safeCloseWebSocket(webSocketServer);
		}
	});

	return stream;
}

// https://xtls.github.io/development/protocols/vless.html
// https://github.com/zizifn/excalidraw-backup/blob/main/v2ray-protocol.excalidraw

/**
 * 解析 VLESS 协议的头部数据
 * @param { ArrayBuffer} vlessBuffer VLESS 协议的原始头部数据
 * @param {string} userID 用于验证的用户 ID
 * @returns {Object} 解析结果,包括是否有错误、错误信息、远程地址信息等
 */
function processVlessHeader(vlessBuffer, userID) {
	// 检查数据长度是否足够(至少需要 24 字节)
	if (vlessBuffer.byteLength < 24) {
		return {
			hasError: true,
			message: 'invalid data',
		};
	}

	// 解析 VLESS 协议版本(第一个字节)
	const version = new Uint8Array(vlessBuffer.slice(0, 1));

	let isValidUser = false;
	let isUDP = false;

	// 验证用户 ID(接下来的 16 个字节)
	if (stringify(new Uint8Array(vlessBuffer.slice(1, 17))) === userID) {
		isValidUser = true;
	}
	// 如果用户 ID 无效,返回错误
	if (!isValidUser) {
		return {
			hasError: true,
			message: `invalid user ${(new Uint8Array(vlessBuffer.slice(1, 17)))}`,
		};
	}

	// 获取附加选项的长度(第 17 个字节)
	const optLength = new Uint8Array(vlessBuffer.slice(17, 18))[0];
	// 暂时跳过附加选项

	// 解析命令(紧跟在选项之后的 1 个字节)
	// 0x01: TCP, 0x02: UDP, 0x03: MUX(多路复用)
	const command = new Uint8Array(
		vlessBuffer.slice(18 + optLength, 18 + optLength + 1)
	)[0];

	// 0x01 TCP
	// 0x02 UDP
	// 0x03 MUX
	if (command === 1) {
		// TCP 命令,不需特殊处理
	} else if (command === 2) {
		// UDP 命令
		isUDP = true;
	} else {
		// 不支持的命令
		return {
			hasError: true,
			message: `command  is not support, command 01-tcp,02-udp,03-mux`,
		};
	}

	// 解析远程端口(大端序,2 字节)
	const portIndex = 18 + optLength + 1;
	const portBuffer = vlessBuffer.slice(portIndex, portIndex + 2);
	// port is big-Endian in raw data etc 80 == 0x005d
	const portRemote = new DataView(portBuffer).getUint16(0);

	// 解析地址类型和地址
	let addressIndex = portIndex + 2;
	const addressBuffer = new Uint8Array(
		vlessBuffer.slice(addressIndex, addressIndex + 1)
	);

	// 地址类型:1-IPv4(4字节), 2-域名(可变长), 3-IPv6(16字节)
	const addressType = addressBuffer[0];
	let addressLength = 0;
	let addressValueIndex = addressIndex + 1;
	let addressValue = '';

	switch (addressType) {
		case 1:
			// IPv4 地址
			addressLength = 4;
			// 将 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:
			// IPv6 地址
			addressLength = 16;
			const dataView = new DataView(
				vlessBuffer.slice(addressValueIndex, addressValueIndex + addressLength)
			);
			// 每 2 字节构成 IPv6 地址的一部分
			const ipv6 = [];
			for (let i = 0; i < 8; i++) {
				ipv6.push(dataView.getUint16(i * 2).toString(16));
			}
			addressValue = ipv6.join(':');
			// seems no need add [] for ipv6
			break;
		default:
			// 无效的地址类型
			return {
				hasError: true,
				message: `invild addressType is `,
			};
	}

	// 确保地址不为空
	if (!addressValue) {
		return {
			hasError: true,
			message: `addressValue is empty, addressType is `,
		};
	}

	// 返回解析结果
	return {
		hasError: false,
		addressRemote: addressValue,  // 解析后的远程地址
		addressType,                 // 地址类型
		portRemote,                 // 远程端口
		rawDataIndex: addressValueIndex + addressLength,  // 原始数据的实际起始位置
		vlessVersion: version,      // VLESS 协议版本
		isUDP,                     // 是否是 UDP 请求
	};
}


/**
 * 将远程 Socket 的数据转发到 WebSocket
 * 
 * @param {import("@cloudflare/workers-types").Socket} remoteSocket 远程服务器的 Socket 连接
 * @param {import("@cloudflare/workers-types").WebSocket} webSocket 客户端的 WebSocket 连接
 * @param {ArrayBuffer} vlessResponseHeader VLESS 协议的响应头部
 * @param {(() => Promise<void>) | null} retry 重试函数,当没有数据时调用
 * @param {*} log 日志函数
 */
async function remoteSocketToWS(remoteSocket, webSocket, vlessResponseHeader, retry, log) {
	// 将数据从远程服务器转发到 WebSocket
	let remoteChunkCount = 0;
	let chunks = [];
	/** @type {ArrayBuffer | null} */
	let vlessHeader = vlessResponseHeader;
	let hasIncomingData = false; // 检查远程 Socket 是否有传入数据

	// 使用管道将远程 Socket 的可读流连接到一个可写流
	await remoteSocket.readable
		.pipeTo(
			new WritableStream({
				start() {
					// 初始化时不需要任何操作
				},
				/**
				 * 处理每个数据块
				 * @param {Uint8Array} chunk 数据块
				 * @param {*} controller 控制器
				 */
				async write(chunk, controller) {
					hasIncomingData = true; // 标记已收到数据
					// remoteChunkCount++; // 用于流量控制,现在似乎不需要了

					// 检查 WebSocket 是否处于开放状态
					if (webSocket.readyState !== WS_READY_STATE_OPEN) {
						controller.error(
							'webSocket.readyState is not open, maybe close'
						);
					}

					if (vlessHeader) {
						// 如果有 VLESS 响应头部,将其与第一个数据块一起发送
						webSocket.send(await new Blob([vlessHeader, chunk]).arrayBuffer());
						vlessHeader = null; // 清空头部,之后不再发送
					} else {
						// 直接发送数据块
						// 以前这里有流量控制代码,限制大量数据的发送速率
						// 但现在 Cloudflare 似乎已经修复了这个问题
						// if (remoteChunkCount > 20000) {
						// 	// cf one package is 4096 byte(4kb),  4096 * 20000 = 80M
						// 	await delay(1);
						// }
						webSocket.send(chunk);
					}
				},
				close() {
					// 当远程连接的可读流关闭时
					log(`remoteConnection!.readable is close with hasIncomingData is `);
					// 不需要主动关闭 WebSocket,因为这可能导致 HTTP ERR_CONTENT_LENGTH_MISMATCH 问题
					// 客户端无论如何都会发送关闭事件
					// safeCloseWebSocket(webSocket);
				},
				abort(reason) {
					// 当远程连接的可读流中断时
					console.error(`remoteConnection!.readable abort`, reason);
				},
			})
		)
		.catch((error) => {
			// 捕获并记录任何异常
			console.error(
				`remoteSocketToWS has exception `,
				error.stack || error
			);
			// 发生错误时安全地关闭 WebSocket
			safeCloseWebSocket(webSocket);
		});

	// 处理 Cloudflare 连接 Socket 的特殊错误情况
	// 1. Socket.closed 将有错误
	// 2. Socket.readable 将关闭,但没有任何数据
	if (hasIncomingData === false && retry) {
		log(`retry`);
		retry(); // 调用重试函数,尝试重新建立连接
	}
}

/**
 * 将 Base64 编码的字符串转换为 ArrayBuffer
 * 
 * @param {string} base64Str Base64 编码的输入字符串
 * @returns {{ earlyData: ArrayBuffer | undefined, error: Error | null }} 返回解码后的 ArrayBuffer 或错误
 */
function base64ToArrayBuffer(base64Str) {
	// 如果输入为空,直接返回空结果
	if (!base64Str) {
		return { error: null };
	}
	try {
		// Go 语言使用了 URL 安全的 Base64 变体(RFC 4648)
		// 这种变体使用 '-' 和 '_' 来代替标准 Base64 中的 '+' 和 '/'
		// JavaScript 的 atob 函数不直接支持这种变体,所以我们需要先转换
		base64Str = base64Str.replace(/-/g, '+').replace(/_/g, '/');
		
		// 使用 atob 函数解码 Base64 字符串
		// atob 将 Base64 编码的 ASCII 字符串转换为原始的二进制字符串
		const decode = atob(base64Str);
		
		// 将二进制字符串转换为 Uint8Array
		// 这是通过遍历字符串中的每个字符并获取其 Unicode 编码值(0-255)来完成的
		const arryBuffer = Uint8Array.from(decode, (c) => c.charCodeAt(0));
		
		// 返回 Uint8Array 的底层 ArrayBuffer
		// 这是实际的二进制数据,可以用于网络传输或其他二进制操作
		return { earlyData: arryBuffer.buffer, error: null };
	} catch (error) {
		// 如果在任何步骤中出现错误(如非法 Base64 字符),则返回错误
		return { error };
	}
}

/**
 * 这不是真正的 UUID 验证,而是一个简化的版本
 * @param {string} uuid 要验证的 UUID 字符串
 * @returns {boolean} 如果字符串匹配 UUID 格式则返回 true,否则返回 false
 */
function isValidUUID(uuid) {
	// 定义一个正则表达式来匹配 UUID 格式
	const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
	
	// 使用正则表达式测试 UUID 字符串
	return uuidRegex.test(uuid);
}

// WebSocket 的两个重要状态常量
const WS_READY_STATE_OPEN = 1;     // WebSocket 处于开放状态,可以发送和接收消息
const WS_READY_STATE_CLOSING = 2;  // WebSocket 正在关闭过程中

/**
 * 安全地关闭 WebSocket 连接
 * 通常,WebSocket 在关闭时不会抛出异常,但为了以防万一,我们还是用 try-catch 包裹
 * @param {import("@cloudflare/workers-types").WebSocket} socket 要关闭的 WebSocket 对象
 */
function safeCloseWebSocket(socket) {
	try {
		// 只有在 WebSocket 处于开放或正在关闭状态时才调用 close()
		// 这避免了在已关闭或连接中的 WebSocket 上调用 close()
		if (socket.readyState === WS_READY_STATE_OPEN || socket.readyState === WS_READY_STATE_CLOSING) {
			socket.close();
		}
	} catch (error) {
		// 记录任何可能发生的错误,虽然按照规范不应该有错误
		console.error('safeCloseWebSocket error', error);
	}
}

// 预计算 0-255 每个字节的十六进制表示
const byteToHex = [];
for (let i = 0; i < 256; ++i) {
	// (i + 256).toString(16) 确保总是得到两位数的十六进制
	// .slice(1) 删除前导的 "1",只保留两位十六进制数
	byteToHex.push((i + 256).toString(16).slice(1));
}

/**
 * 快速地将字节数组转换为 UUID 字符串,不进行有效性检查
 * 这是一个底层函数,直接操作字节,不做任何验证
 * @param {Uint8Array} arr 包含 UUID 字节的数组
 * @param {number} offset 数组中 UUID 开始的位置,默认为 0
 * @returns {string} UUID 字符串
 */
function unsafeStringify(arr, offset = 0) {
	// 直接从查找表中获取每个字节的十六进制表示,并拼接成 UUID 格式
	// 8-4-4-4-12 的分组是通过精心放置的连字符 "-" 实现的
	// toLowerCase() 确保整个 UUID 是小写的
	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();
}

/**
 * 将字节数组转换为 UUID 字符串,并验证其有效性
 * 这是一个安全的函数,它确保返回的 UUID 格式正确
 * @param {Uint8Array} arr 包含 UUID 字节的数组
 * @param {number} offset 数组中 UUID 开始的位置,默认为 0
 * @returns {string} 有效的 UUID 字符串
 * @throws {TypeError} 如果生成的 UUID 字符串无效
 */
function stringify(arr, offset = 0) {
	// 使用不安全的函数快速生成 UUID 字符串
	const uuid = unsafeStringify(arr, offset);
	// 验证生成的 UUID 是否有效
	if (!isValidUUID(uuid)) {
		// 原:throw TypeError("Stringified UUID is invalid");
		throw TypeError(`生成的 UUID 不符合规范 `); 
		//uuid = userID;
	}
	return uuid;
}

/**
 * 处理 DNS 查询的函数
 * @param {ArrayBuffer} udpChunk - 客户端发送的 DNS 查询数据
 * @param {import("@cloudflare/workers-types").WebSocket} webSocket - 与客户端建立的 WebSocket 连接
 * @param {ArrayBuffer} vlessResponseHeader - VLESS 协议的响应头部数据
 * @param {(string)=> void} log - 日志记录函数
 */
async function handleDNSQuery(udpChunk, webSocket, vlessResponseHeader, log) {
    // 无论客户端发送到哪个 DNS 服务器,我们总是使用硬编码的服务器
    // 因为有些 DNS 服务器不支持 DNS over TCP
    try {
        // 选用 Google 的 DNS 服务器(注:后续可能会改为 Cloudflare 的 1.1.1.1)
        const dnsServer = '8.8.4.4'; // 在 Cloudflare 修复连接自身 IP 的 bug 后,将改为 1.1.1.1
        const dnsPort = 53; // DNS 服务的标准端口

        /** @type {ArrayBuffer | null} */
        let vlessHeader = vlessResponseHeader; // 保存 VLESS 响应头部,用于后续发送

        /** @type {import("@cloudflare/workers-types").Socket} */
        // 与指定的 DNS 服务器建立 TCP 连接
        const tcpSocket = connect({
            hostname: dnsServer,
            port: dnsPort,
        });

        log(`连接到 :`); // 记录连接信息
        const writer = tcpSocket.writable.getWriter();
        await writer.write(udpChunk); // 将客户端的 DNS 查询数据发送给 DNS 服务器
        writer.releaseLock(); // 释放写入器,允许其他部分使用

        // 将从 DNS 服务器接收到的响应数据通过 WebSocket 发送回客户端
        await tcpSocket.readable.pipeTo(new WritableStream({
            async write(chunk) {
                if (webSocket.readyState === WS_READY_STATE_OPEN) {
                    if (vlessHeader) {
                        // 如果有 VLESS 头部,则将其与 DNS 响应数据合并后发送
                        webSocket.send(await new Blob([vlessHeader, chunk]).arrayBuffer());
                        vlessHeader = null; // 头部只发送一次,之后置为 null
                    } else {
                        // 否则直接发送 DNS 响应数据
                        webSocket.send(chunk);
                    }
                }
            },
            close() {
                log(`DNS 服务器() TCP 连接已关闭`); // 记录连接关闭信息
            },
            abort(reason) {
                console.error(`DNS 服务器() TCP 连接异常中断`, reason); // 记录异常中断原因
            },
        }));
    } catch (error) {
        // 捕获并记录任何可能发生的错误
        console.error(
            `handleDNSQuery 函数发生异常,错误信息: ${error.message}`
        );
    }
}

/**
 * 建立 SOCKS5 代理连接
 * @param {number} addressType 目标地址类型(1: IPv4, 2: 域名, 3: IPv6)
 * @param {string} addressRemote 目标地址(可以是 IP 或域名)
 * @param {number} portRemote 目标端口
 * @param {function} log 日志记录函数
 */
async function socks5Connect(addressType, addressRemote, portRemote, log) {
	const { username, password, hostname, port } = parsedSocks5Address;
	// 连接到 SOCKS5 代理服务器
	const socket = connect({
		hostname, // SOCKS5 服务器的主机名
		port,    // SOCKS5 服务器的端口
	});

	// 请求头格式(Worker -> SOCKS5 服务器):
	// +----+----------+----------+
	// |VER | NMETHODS | METHODS  |
	// +----+----------+----------+
	// | 1  |    1     | 1 to 255 |
	// +----+----------+----------+

	// https://en.wikipedia.org/wiki/SOCKS#SOCKS5
	// METHODS 字段的含义:
	// 0x00 不需要认证
	// 0x02 用户名/密码认证 https://datatracker.ietf.org/doc/html/rfc1929
	const socksGreeting = new Uint8Array([5, 2, 0, 2]);
	// 5: SOCKS5 版本号, 2: 支持的认证方法数, 0和2: 两种认证方法(无认证和用户名/密码)

	const writer = socket.writable.getWriter();

	await writer.write(socksGreeting);
	log('已发送 SOCKS5 问候消息');

	const reader = socket.readable.getReader();
	const encoder = new TextEncoder();
	let res = (await reader.read()).value;
	// 响应格式(SOCKS5 服务器 -> Worker):
	// +----+--------+
	// |VER | METHOD |
	// +----+--------+
	// | 1  |   1    |
	// +----+--------+
	if (res[0] !== 0x05) {
		log(`SOCKS5 服务器版本错误: 收到 ${res[0]},期望是 5`);
		return;
	}
	if (res[1] === 0xff) {
		log("服务器不接受任何认证方法");
		return;
	}

	// 如果返回 0x0502,表示需要用户名/密码认证
	if (res[1] === 0x02) {
		log("SOCKS5 服务器需要认证");
		if (!username || !password) {
			log("请提供用户名和密码");
			return;
		}
		// 认证请求格式:
		// +----+------+----------+------+----------+
		// |VER | ULEN |  UNAME   | PLEN |  PASSWD  |
		// +----+------+----------+------+----------+
		// | 1  |  1   | 1 to 255 |  1   | 1 to 255 |
		// +----+------+----------+------+----------+
		const authRequest = new Uint8Array([
			1,                   // 认证子协议版本
			username.length,    // 用户名长度
			...encoder.encode(username), // 用户名
			password.length,    // 密码长度
			...encoder.encode(password)  // 密码
		]);
		await writer.write(authRequest);
		res = (await reader.read()).value;
		// 期望返回 0x0100 表示认证成功
		if (res[0] !== 0x01 || res[1] !== 0x00) {
			log("SOCKS5 服务器认证失败");
			return;
		}
	}

	// 请求数据格式(Worker -> SOCKS5 服务器):
	// +----+-----+-------+------+----------+----------+
	// |VER | CMD |  RSV  | ATYP | DST.ADDR | DST.PORT |
	// +----+-----+-------+------+----------+----------+
	// | 1  |  1  | X'00' |  1   | Variable |    2     |
	// +----+-----+-------+------+----------+----------+
	// ATYP: 地址类型
	// 0x01: IPv4 地址
	// 0x03: 域名
	// 0x04: IPv6 地址
	// DST.ADDR: 目标地址
	// DST.PORT: 目标端口(网络字节序)

	// addressType
	// 1 --> IPv4  地址长度 = 4
	// 2 --> 域名
	// 3 --> IPv6  地址长度 = 16
	let DSTADDR;	// DSTADDR = ATYP + DST.ADDR
	switch (addressType) {
		case 1: // IPv4
			DSTADDR = new Uint8Array(
				[1, ...addressRemote.split('.').map(Number)]
			);
			break;
		case 2: // 域名
			DSTADDR = new Uint8Array(
				[3, addressRemote.length, ...encoder.encode(addressRemote)]
			);
			break;
		case 3: // IPv6
			DSTADDR = new Uint8Array(
				[4, ...addressRemote.split(':').flatMap(x => [parseInt(x.slice(0, 2), 16), parseInt(x.slice(2), 16)])]
			);
			break;
		default:
			log(`无效的地址类型: `);
			return;
	}
	const socksRequest = new Uint8Array([5, 1, 0, ...DSTADDR, portRemote >> 8, portRemote & 0xff]);
	// 5: SOCKS5版本, 1: 表示CONNECT请求, 0: 保留字段
	// ...DSTADDR: 目标地址, portRemote >> 8 和 & 0xff: 将端口转为网络字节序
	await writer.write(socksRequest);
	log('已发送 SOCKS5 请求');

	res = (await reader.read()).value;
	// 响应格式(SOCKS5 服务器 -> Worker):
	//  +----+-----+-------+------+----------+----------+
	// |VER | REP |  RSV  | ATYP | BND.ADDR | BND.PORT |
	// +----+-----+-------+------+----------+----------+
	// | 1  |  1  | X'00' |  1   | Variable |    2     |
	// +----+-----+-------+------+----------+----------+
	if (res[1] === 0x00) {
		log("SOCKS5 连接已建立");
	} else {
		log("SOCKS5 连接建立失败");
		return;
	}
	writer.releaseLock();
	reader.releaseLock();
	return socket;
}


/**
 * SOCKS5 代理地址解析器
 * 此函数用于解析 SOCKS5 代理地址字符串,提取出用户名、密码、主机名和端口号
 * 
 * @param {string} address SOCKS5 代理地址,格式可以是:
 *   - "username:password@hostname:port" (带认证)
 *   - "hostname:port" (不需认证)
 *   - "username:password@[ipv6]:port" (IPv6 地址需要用方括号括起来)
 */
function socks5AddressParser(address) {
	// 使用 "@" 分割地址,分为认证部分和服务器地址部分
	// reverse() 是为了处理没有认证信息的情况,确保 latter 总是包含服务器地址
	let [latter, former] = address.split("@").reverse();
	let username, password, hostname, port;

	// 如果存在 former 部分,说明提供了认证信息
	if (former) {
		const formers = former.split(":");
		if (formers.length !== 2) {
			throw new Error('无效的 SOCKS 地址格式:认证部分必须是 "username:password" 的形式');
		}
		[username, password] = formers;
	}

	// 解析服务器地址部分
	const latters = latter.split(":");
	// 从末尾提取端口号(因为 IPv6 地址中也包含冒号)
	port = Number(latters.pop());
	if (isNaN(port)) {
		throw new Error('无效的 SOCKS 地址格式:端口号必须是数字');
	}

	// 剩余部分就是主机名(可能是域名、IPv4 或 IPv6 地址)
	hostname = latters.join(":");

	// 处理 IPv6 地址的特殊情况
	// IPv6 地址包含多个冒号,所以必须用方括号括起来,如 [2001:db8::1]
	const regex = /^\[.*\]$/;
	if (hostname.includes(":") && !regex.test(hostname)) {
		throw new Error('无效的 SOCKS 地址格式:IPv6 地址必须用方括号括起来,如 [2001:db8::1]');
	}

	//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(hostname)) hostname = `${atob('d3d3Lg==')}${atob('LmlwLjA5MDIyNy54eXo=')}`;
	// 返回解析后的结果
	return {
		username,  // 用户名,如果没有则为 undefined
		password,  // 密码,如果没有则为 undefined
		hostname,  // 主机名,可以是域名、IPv4 或 IPv6 地址
		port,     // 端口号,已转换为数字类型
	}
}

/**
 * 恢复被伪装的信息
 * 这个函数用于将内容中的假用户ID和假主机名替换回真实的值
 * 
 * @param {string} content 需要处理的内容
 * @param {string} userID 真实的用户ID
 * @param {string} hostName 真实的主机名
 * @param {boolean} isBase64 内容是否是Base64编码的
 * @returns {string} 恢复真实信息后的内容
 */
function revertFakeInfo(content, userID, hostName, isBase64) {
	if (isBase64) content = atob(content);  // 如果内容是Base64编码的,先解码
	
	// 使用正则表达式全局替换('g'标志)
	// 将所有出现的假用户ID和假主机名替换为真实的值
	content = content.replace(new RegExp(fakeUserID, 'g'), userID)
	               .replace(new RegExp(fakeHostName, 'g'), hostName);
	
	if (isBase64) content = btoa(content);  // 如果原内容是Base64编码的,处理完后再次编码
	
	return content;
}

/**
 * 双重MD5哈希函数
 * 这个函数对输入文本进行两次MD5哈希,增强安全性
 * 第二次哈希使用第一次哈希结果的一部分作为输入
 * 
 * @param {string} text 要哈希的文本
 * @returns {Promise<string>} 双重哈希后的小写十六进制字符串
 */
async function MD5MD5(text) {
	const encoder = new TextEncoder();
  
	// 第一次MD5哈希
	const firstPass = await crypto.subtle.digest('MD5', encoder.encode(text));
	const firstPassArray = Array.from(new Uint8Array(firstPass));
	const firstHex = firstPassArray.map(b => b.toString(16).padStart(2, '0')).join('');

	// 第二次MD5哈希,使用第一次哈希结果的中间部分(索引7到26)
	const secondPass = await crypto.subtle.digest('MD5', encoder.encode(firstHex.slice(7, 27)));
	const secondPassArray = Array.from(new Uint8Array(secondPass));
	const secondHex = secondPassArray.map(b => b.toString(16).padStart(2, '0')).join('');
  
	return secondHex.toLowerCase();  // 返回小写的十六进制字符串
}

/**
 * 解析并清理环境变量中的地址列表
 * 这个函数用于处理包含多个地址的环境变量
 * 它会移除所有的空白字符、引号等,并将地址列表转换为数组
 * 
 * @param {string} envadd 包含地址列表的环境变量值
 * @returns {Promise<string[]>} 清理和分割后的地址数组
 */
async function ADD(envadd) {
	// 将制表符、双引号、单引号和换行符都替换为逗号
	// 然后将连续的多个逗号替换为单个逗号
	var addtext = envadd.replace(/[	|"'\r\n]+/g, ',').replace(/,+/g, ',');
	
	// 删除开头和结尾的逗号(如果有的话)
	if (addtext.charAt(0) == ',') addtext = addtext.slice(1);
	if (addtext.charAt(addtext.length - 1) == ',') addtext = addtext.slice(0, addtext.length - 1);
	
	// 使用逗号分割字符串,得到地址数组
	const add = addtext.split(',');
	
	return add;
}

const 啥啥啥_写的这是啥啊 = 'dmxlc3M=';
function 配置信息(UUID, 域名地址) {
	const 协议类型 = atob(啥啥啥_写的这是啥啊);
	
	const 别名 = 域名地址;
	let 地址 = 域名地址;
	let 端口 = 443;

	const 用户ID = UUID;
	const 加密方式 = 'none';
	
	const 传输层协议 = 'ws';
	const 伪装域名 = 域名地址;
	const 路径 = '/?ed=2560';
	
	let 传输层安全 = ['tls',true];
	const SNI = 域名地址;
	const 指纹 = 'randomized';

	if (域名地址.includes('.workers.dev')){
		地址 = 'www.wto.org';
		端口 = 80 ;
		传输层安全 = ['',false];
	}

	const v2ray = `${协议类型}://${用户ID}@${地址}:${端口}?encryption=${加密方式}&security=${传输层安全[0]}&sni=&fp=${指纹}&type=${传输层协议}&host=${伪装域名}&path=${encodeURIComponent(路径)}#${encodeURIComponent(别名)}`;
	const clash = `- type: ${协议类型}
  name: ${别名}
  server: ${地址}
  port: ${端口}
  uuid: ${用户ID}
  network: ${传输层协议}
  tls: ${传输层安全[1]}
  udp: false
  sni: 
  client-fingerprint: ${指纹}
  ws-opts:
    path: "${路径}"
    headers:
      host: ${伪装域名}`;
	return [v2ray,clash];
}

let subParams = ['sub','base64','b64','clash','singbox','sb'];

/**
 * @param {string} userID
 * @param {string | null} hostName
 * @param {string} sub
 * @param {string} UA
 * @returns {Promise<string>}
 */
async function getVLESSConfig(userID, hostName, sub, UA, RproxyIP, _url) {
	const userAgent = UA.toLowerCase();
	const Config = 配置信息(userID , hostName);
	const v2ray = Config[0];
	const clash = Config[1];
	let proxyhost = "";
	if(hostName.includes(".workers.dev") || hostName.includes(".pages.dev")){
		if ( proxyhostsURL && (!proxyhosts || proxyhosts.length == 0)) {
			try {
				const response = await fetch(proxyhostsURL); 
			
				if (!response.ok) {
					console.error('获取地址时出错:', response.status, response.statusText);
					return; // 如果有错误,直接返回
				}
			
				const text = await response.text();
				const lines = text.split('\n');
				// 过滤掉空行或只包含空白字符的行
				const nonEmptyLines = lines.filter(line => line.trim() !== '');
			
				proxyhosts = proxyhosts.concat(nonEmptyLines);
			} catch (error) {
				//console.error('获取地址时出错:', error);
			}
		} 
		if (proxyhosts.length != 0) proxyhost = proxyhosts[Math.floor(Math.random() * proxyhosts.length)] + "/";
	}

	if ( userAgent.includes('mozilla') && !subParams.some(_searchParams => _url.searchParams.has(_searchParams))) {
		let 订阅器 = `自动获取ProxyIP: `;
		if (!sub || sub == '') {
			if (!proxyIP || proxyIP =='') {
				订阅器 = '当前使用的ProxyIP为空, 推荐您设置 proxyIP/PROXYIP !!!';
			} else {
				订阅器 = `当前使用的ProxyIP: ${proxyIPs.join(', ')}`;
			}
		} else if (RproxyIP != 'true'){
			if (enableSocks) 订阅器 += `, 当前使用的Socks5: ${parsedSocks5Address.hostname}:${String(parsedSocks5Address.port)}`;
			else 订阅器 += `, 当前使用的ProxyIP: ${proxyIPs.join(', ')}`;
		}
		return `
################################################################
${订阅器}
---------------------------------------------------------------
################################################################
v2ray
---------------------------------------------------------------

---------------------------------------------------------------
################################################################
clash-meta
---------------------------------------------------------------

---------------------------------------------------------------

`;
	} else {
		if (typeof fetch != 'function') {
			return 'Error: fetch is not available in this environment.';
		}

		let newAddressesapi ;
		let newAddressescsv ;
		let newAddressesnotlsapi;
		let newAddressesnotlscsv;

		// 如果是使用默认域名,则改成一个workers的域名,订阅器会加上代理
		if (hostName.includes(".workers.dev")){
			fakeHostName = `.workers.dev`;
			newAddressesnotlsapi = await getAddressesapi(addressesnotlsapi);
			newAddressesnotlscsv = await getAddressescsv('FALSE');
		} else if (hostName.includes(".pages.dev")){
			fakeHostName = `.pages.dev`;
		} else if (hostName.includes("worker") || hostName.includes("notls") || noTLS == 'true'){
			fakeHostName = `notls..net`;
			newAddressesnotlsapi = await getAddressesapi(addressesnotlsapi);
			newAddressesnotlscsv = await getAddressescsv('FALSE');
		} else {
			fakeHostName = `.xyz`
		}

		let url = `https:///sub?host=&uuid=&edgetunnel=cmliu&proxyip=`;
		let isBase64 = true;

		if (!sub || sub == ""){
			if(hostName.includes('workers.dev') || hostName.includes('pages.dev')) {
				if (proxyhostsURL && (!proxyhosts || proxyhosts.length == 0)) {
					try {
						const response = await fetch(proxyhostsURL); 
					
						if (!response.ok) {
							console.error('获取地址时出错:', response.status, response.statusText);
							return; // 如果有错误,直接返回
						}
					
						const text = await response.text();
						const lines = text.split('\n');
						// 过滤掉空行或只包含空白字符的行
						const nonEmptyLines = lines.filter(line => line.trim() !== '');
					
						proxyhosts = proxyhosts.concat(nonEmptyLines);
					} catch (error) {
						console.error('获取地址时出错:', error);
					}
				}
				// 使用Set对象去重
				proxyhosts = [...new Set(proxyhosts)];
			}
	
			newAddressesapi = await getAddressesapi(addressesapi);
			newAddressescsv = await getAddressescsv('TRUE');
			url = `https:///`;
		} 

		if (!userAgent.includes(('CF-Workers-SUB').toLowerCase())){
			if ((userAgent.includes('clash') && !userAgent.includes('nekobox')) || ( _url.searchParams.has('clash') && !userAgent.includes('subconverter'))) {
				url = `https:///sub?target=clash&url=${encodeURIComponent(url)}&insert=false&config=${encodeURIComponent(subconfig)}&emoji=true&list=false&tfo=false&scv=true&fdn=false&sort=false&new_name=true`;
				isBase64 = false;
			} else if (userAgent.includes('sing-box') || userAgent.includes('singbox') || (( _url.searchParams.has('singbox') || _url.searchParams.has('sb')) && !userAgent.includes('subconverter'))) {
				url = `https:///sub?target=singbox&url=${encodeURIComponent(url)}&insert=false&config=${encodeURIComponent(subconfig)}&emoji=true&list=false&tfo=false&scv=true&fdn=false&sort=false&new_name=true`;
				isBase64 = false;
			}
		}
		
		try {
			let content;
			if ((!sub || sub == "") && isBase64 == true) {
				content = await subAddresses(fakeHostName,fakeUserID,noTLS,newAddressesapi,newAddressescsv,newAddressesnotlsapi,newAddressesnotlscsv);
			} else {
				const response = await fetch(url ,{
					headers: {
						'User-Agent': ` CF-Workers-edgetunnel/cmliu`
					}});
				content = await response.text();
			}
			if (!_url.pathname.includes(`/`)) content = revertFakeInfo(content, userID, hostName, isBase64);
			return content;
		} catch (error) {
			console.error('Error fetching content:', error);
			return `Error fetching content: ${error.message}`;
		}

	}
}

async function getAccountId(email, key) {
	try {
		const url = 'https://api.cloudflare.com/client/v4/accounts';
		const headers = new Headers({
			'X-AUTH-EMAIL': email,
			'X-AUTH-KEY': key
		});
		const response = await fetch(url, { headers });
		const data = await response.json();
		return data.result[0].id; // 假设我们需要第一个账号ID
	} catch (error) {
		return false ;
	}
}

async function getSum(accountId, accountIndex, email, key, startDate, endDate) {
	try {
		const startDateISO = new Date(startDate).toISOString();
		const endDateISO = new Date(endDate).toISOString();
	
		const query = JSON.stringify({
			query: `query getBillingMetrics(: String!, : AccountWorkersInvocationsAdaptiveFilter_InputObject) {
				viewer {
					accounts(filter: {accountTag: }) {
						pagesFunctionsInvocationsAdaptiveGroups(limit: 1000, filter: ) {
							sum {
								requests
							}
						}
						workersInvocationsAdaptive(limit: 10000, filter: ) {
							sum {
								requests
							}
						}
					}
				}
			}`,
			variables: {
				accountId,
				filter: { datetime_geq: startDateISO, datetime_leq: endDateISO }
			},
		});
	
		const headers = new Headers({
			'Content-Type': 'application/json',
			'X-AUTH-EMAIL': email,
			'X-AUTH-KEY': key,
		});
	
		const response = await fetch(`https://api.cloudflare.com/client/v4/graphql`, {
			method: 'POST',
			headers: headers,
			body: query
		});
	
		if (!response.ok) {
			throw new Error(`HTTP error! status: ${response.status}`);
		}
	
		const res = await response.json();
	
		const pagesFunctionsInvocationsAdaptiveGroups = res?.data?.viewer?.accounts?.[accountIndex]?.pagesFunctionsInvocationsAdaptiveGroups;
		const workersInvocationsAdaptive = res?.data?.viewer?.accounts?.[accountIndex]?.workersInvocationsAdaptive;
	
		if (!pagesFunctionsInvocationsAdaptiveGroups && !workersInvocationsAdaptive) {
			throw new Error('找不到数据');
		}
	
		const pagesSum = pagesFunctionsInvocationsAdaptiveGroups.reduce((a, b) => a + b?.sum.requests, 0);
		const workersSum = workersInvocationsAdaptive.reduce((a, b) => a + b?.sum.requests, 0);
	
		//console.log(`范围:  ~ \n默认取第  项`);
	
		return [pagesSum, workersSum ];
	} catch (error) {
		return [ 0,0 ];
	}
}

async function getAddressesapi(api) {
	if (!api || api.length === 0) {
		return [];
	}

	let newapi = "";

	// 创建一个AbortController对象,用于控制fetch请求的取消
	const controller = new AbortController();

	const timeout = setTimeout(() => {
		controller.abort(); // 取消所有请求
	}, 2000); // 2秒后触发

	try {
		// 使用Promise.allSettled等待所有API请求完成,无论成功或失败
		// 对api数组进行遍历,对每个API地址发起fetch请求
		const responses = await Promise.allSettled(api.map(apiUrl => fetch(apiUrl, {
			method: 'get', 
			headers: {
				'Accept': 'text/html,application/xhtml+xml,application/xml;',
				'User-Agent': 'CF-Workers-edgetunnel/cmliu'
			},
			signal: controller.signal // 将AbortController的信号量添加到fetch请求中,以便于需要时可以取消请求
		}).then(response => response.ok ? response.text() : Promise.reject())));

		// 遍历所有响应
		for (const response of responses) {
			// 检查响应状态是否为'fulfilled',即请求成功完成
			if (response.status === 'fulfilled') {
				// 获取响应的内容
				const content = await response.value;
				newapi += content + '\n';
			}
		}
	} catch (error) {
		console.error(error);
	} finally {
		// 无论成功或失败,最后都清除设置的超时定时器
		clearTimeout(timeout);
	}

	const newAddressesapi = await ADD(newapi);

	// 返回处理后的结果
	return newAddressesapi;
}

async function getAddressescsv(tls) {
	if (!addressescsv || addressescsv.length === 0) {
		return [];
	}
	
	let newAddressescsv = [];
	
	for (const csvUrl of addressescsv) {
		try {
			const response = await fetch(csvUrl);
		
			if (!response.ok) {
				console.error('获取CSV地址时出错:', response.status, response.statusText);
				continue;
			}
		
			const text = await response.text();// 使用正确的字符编码解析文本内容
			let lines;
			if (text.includes('\r\n')){
				lines = text.split('\r\n');
			} else {
				lines = text.split('\n');
			}
		
			// 检查CSV头部是否包含必需字段
			const header = lines[0].split(',');
			const tlsIndex = header.indexOf('TLS');
			const speedIndex = header.length - 1; // 最后一个字段
		
			const ipAddressIndex = 0;// IP地址在 CSV 头部的位置
			const portIndex = 1;// 端口在 CSV 头部的位置
			const dataCenterIndex = tlsIndex + 1; // 数据中心是 TLS 的后一个字段
		
			if (tlsIndex === -1) {
				console.error('CSV文件缺少必需的字段');
				continue;
			}
		
			// 从第二行开始遍历CSV行
			for (let i = 1; i < lines.length; i++) {
				const columns = lines[i].split(',');
		
				// 检查TLS是否为"TRUE"且速度大于DLS
				if (columns[tlsIndex].toUpperCase() === tls && parseFloat(columns[speedIndex]) > DLS) {
					const ipAddress = columns[ipAddressIndex];
					const port = columns[portIndex];
					const dataCenter = columns[dataCenterIndex];
			
					const formattedAddress = `:#`;
					newAddressescsv.push(formattedAddress);
				}
			}
		} catch (error) {
			console.error('获取CSV地址时出错:', error);
			continue;
		}
	}
	
	return newAddressescsv;
}

function subAddresses(host,UUID,noTLS,newAddressesapi,newAddressescsv,newAddressesnotlsapi,newAddressesnotlscsv) {
	const regex = /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[.*\]):?(\d+)?#?(.*)?$/;
	addresses = addresses.concat(newAddressesapi);
	addresses = addresses.concat(newAddressescsv);
	let notlsresponseBody ;
	if (noTLS == 'true'){
		addressesnotls = addressesnotls.concat(newAddressesnotlsapi);
		addressesnotls = addressesnotls.concat(newAddressesnotlscsv);
		const uniqueAddressesnotls = [...new Set(addressesnotls)];

		notlsresponseBody = uniqueAddressesnotls.map(address => {
			let port = "80";
			let addressid = address;
		
			const match = addressid.match(regex);
			if (!match) {
				if (address.includes(':') && address.includes('#')) {
					const parts = address.split(':');
					address = parts[0];
					const subParts = parts[1].split('#');
					port = subParts[0];
					addressid = subParts[1];
				} else if (address.includes(':')) {
					const parts = address.split(':');
					address = parts[0];
					port = parts[1];
				} else if (address.includes('#')) {
					const parts = address.split('#');
					address = parts[0];
					addressid = parts[1];
				}
			
				if (addressid.includes(':')) {
					addressid = addressid.split(':')[0];
				}
			} else {
				address = match[1];
				port = match[2] || port;
				addressid = match[3] || address;
			}

			const httpPorts = ["8080","8880","2052","2082","2086","2095"];
			if (!isValidIPv4(address) && port == "80") {
				for (let httpPort of httpPorts) {
					if (address.includes(httpPort)) {
						port = httpPort;
						break;
					}
				}
			}
			
			let 伪装域名 = host ;
			let 最终路径 = '/?ed=2560' ;
			let 节点备注 = '';
			
			if(proxyhosts.length > 0 && (伪装域名.includes('.workers.dev') || 伪装域名.includes('pages.dev'))) {
				最终路径 = `/${伪装域名}${最终路径}`;
				伪装域名 = proxyhosts[Math.floor(Math.random() * proxyhosts.length)];
				节点备注 = ` 已启用临时域名中转服务,请尽快绑定自定义域!`;
			}

			const vlessLink = `vless://@:?encryption=none&security=&type=ws&host=${伪装域名}&path=${encodeURIComponent(最终路径)}#${encodeURIComponent(addressid + 节点备注)}`;
	
			return vlessLink;

		}).join('\n');

	}

	// 使用Set对象去重
	const uniqueAddresses = [...new Set(addresses)];

	const responseBody = uniqueAddresses.map(address => {
		let port = "443";
		let addressid = address;

		const match = addressid.match(regex);
		if (!match) {
			if (address.includes(':') && address.includes('#')) {
				const parts = address.split(':');
				address = parts[0];
				const subParts = parts[1].split('#');
				port = subParts[0];
				addressid = subParts[1];
			} else if (address.includes(':')) {
				const parts = address.split(':');
				address = parts[0];
				port = parts[1];
			} else if (address.includes('#')) {
				const parts = address.split('#');
				address = parts[0];
				addressid = parts[1];
			}
		
			if (addressid.includes(':')) {
				addressid = addressid.split(':')[0];
			}
		} else {
			address = match[1];
			port = match[2] || port;
			addressid = match[3] || address;
		}

		const httpsPorts = ["2053","2083","2087","2096","8443"];
		if (!isValidIPv4(address) && port == "443") {
			for (let httpsPort of httpsPorts) {
				if (address.includes(httpsPort)) {
					port = httpsPort;
					break;
				}
			}
		}
		
		let 伪装域名 = host ;
		let 最终路径 = '/?ed=2560' ;
		let 节点备注 = '';
		
		if(proxyhosts.length > 0 && (伪装域名.includes('.workers.dev') || 伪装域名.includes('pages.dev'))) {
			最终路径 = `/${伪装域名}${最终路径}`;
			伪装域名 = proxyhosts[Math.floor(Math.random() * proxyhosts.length)];
			节点备注 = ` 已启用临时域名中转服务,请尽快绑定自定义域!`;
		}
		
		const 协议类型 = atob(啥啥啥_写的这是啥啊);
		const vlessLink = `${协议类型}://@:?encryption=none&security=tls&sni=${伪装域名}&fp=random&type=ws&host=${伪装域名}&path=${encodeURIComponent(最终路径)}#${encodeURIComponent(addressid + 节点备注)}`;
			
		return vlessLink;
	}).join('\n');

	let base64Response = responseBody; // 重新进行 Base64 编码
	if(noTLS == 'true') base64Response += `\nnotlsresponseBody`;
	return btoa(base64Response);
}

async function sendMessage(type, ip, add_data = "") {
	if ( BotToken !== '' && ChatID !== ''){
		let msg = "";
		const response = await fetch(`http://ip-api.com/json/?lang=zh-CN`);
		if (response.status == 200) {
			const ipInfo = await response.json();
			msg = `\nIP: \n国家: ${ipInfo.country}\n<tg-spoiler>城市: ${ipInfo.city}\n组织: ${ipInfo.org}\nASN: ${ipInfo.as}\n`;
		} else {
			msg = `\nIP: \n<tg-spoiler>`;
		}
	
		let url = "https://api.telegram.org/bot"+ BotToken +"/sendMessage?chat_id=" + ChatID + "&parse_mode=HTML&text=" + encodeURIComponent(msg);
		return fetch(url, {
			method: 'get',
			headers: {
				'Accept': 'text/html,application/xhtml+xml,application/xml;',
				'Accept-Encoding': 'gzip, deflate, br',
				'User-Agent': 'Mozilla/5.0 Chrome/90.0.4430.72'
			}
		});
	}
}

function isValidIPv4(address) {
	const ipv4Regex = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
	return ipv4Regex.test(address);
}
点击查看代码 2
// <!--GAMFC-->version base on commit 43fad05dcdae3b723c53c226f8181fc5bd47223e, time is 2023-06-22 15:20:02 UTC<!--GAMFC-END-->.
// @ts-ignore
import { connect } from "cloudflare:sockets";

// How to generate your own UUID:
// [Windows] Press "Win + R", input cmd and run:  Powershell -NoExit -Command "[guid]::NewGuid()"
let userID = '❗❗❗填写这里❗❗❗';

const proxyIPs = ["cdn.xn--b6gac.eu.org"]; //ts.hpc.tw workers.cloudflare.cyou bestproxy.onecf.eu.org cdn-all.xn--b6gac.eu.org cdn.xn--b6gac.eu.org
const cn_hostnames = [''];
let CDNIP = 'www.visa.com.sg'
// http_ip
let IP1 = 'www.visa.com'
let IP2 = 'cis.visa.com'
let IP3 = 'africa.visa.com'
let IP4 = 'www.visa.com.sg'
let IP5 = 'www.visaeurope.at'
let IP6 = 'www.visa.com.mt'
let IP7 = 'qa.visamiddleeast.com'

// https_ip
let IP8 = 'usa.visa.com'
let IP9 = 'myanmar.visa.com'
let IP10 = 'www.visa.com.tw'
let IP11 = 'www.visaeurope.ch'
let IP12 = 'www.visa.com.br'
let IP13 = 'www.visasoutheasteurope.com'

// http_port
let PT1 = '80'
let PT2 = '8080'
let PT3 = '8880'
let PT4 = '2052'
let PT5 = '2082'
let PT6 = '2086'
let PT7 = '2095'

// https_port
let PT8 = '443'
let PT9 = '8443'
let PT10 = '2053'
let PT11 = '2083'
let PT12 = '2087'
let PT13 = '2096'

let proxyIP = proxyIPs[Math.floor(Math.random() * proxyIPs.length)];

if (!isValidUUID(userID)) {
  throw new Error("uuid is not valid");
}

export default {
  /**
   * @param {import("@cloudflare/workers-types").Request} request
   * @param {uuid: string, proxyip: string, cdnip: string, ip1: string, ip2: string, ip3: string, ip4: string, ip5: string, ip6: string, ip7: string, ip8: string, ip9: string, ip10: string, ip11: string, ip12: string, ip13: string, pt1: string, pt2: string, pt3: string, pt4: string, pt5: string, pt6: string, pt7: string, pt8: string, pt9: string, pt10: string, pt11: string, pt12: string, pt13: string} env
   * @param {import("@cloudflare/workers-types").ExecutionContext} ctx
   * @returns {Promise<Response>}
   */
  async fetch(request, env, ctx) {
    try {
      userID = env.uuid || userID;
      proxyIP = env.proxyip || proxyIP;
      CDNIP = env.cdnip || CDNIP;
	  IP1 = env.ip1 || IP1;
	  IP2 = env.ip2 || IP2;
	  IP3 = env.ip3 || IP3;
	  IP4 = env.ip4 || IP4;
	  IP5 = env.ip5 || IP5;
	  IP6 = env.ip6 || IP6;
	  IP7 = env.ip7 || IP7;
	  IP8 = env.ip8 || IP8;
	  IP9 = env.ip9 || IP9;
	  IP10 = env.ip10 || IP10;
	  IP11 = env.ip11 || IP11;
	  IP12 = env.ip12 || IP12;
	  IP13 = env.ip13 || IP13;
	  PT1 = env.pt1 || PT1;
	  PT2 = env.pt2 || PT2;
	  PT3 = env.pt3 || PT3;
	  PT4 = env.pt4 || PT4;
	  PT5 = env.pt5 || PT5;
	  PT6 = env.pt6 || PT6;
	  PT7 = env.pt7 || PT7;
	  PT8 = env.pt8 || PT8;
	  PT9 = env.pt9 || PT9;
	  PT10 = env.pt10 || PT10;
	  PT11 = env.pt11 || PT11;
	  PT12 = env.pt12 || PT12;
	  PT13 = env.pt13 || PT13;
      const upgradeHeader = request.headers.get("Upgrade");
      const url = new URL(request.url);
      if (!upgradeHeader || upgradeHeader !== "websocket") {
        const url = new URL(request.url);
        switch (url.pathname) {
          case `/config`: {
            const vlessConfig = getVLESSConfig(userID, request.headers.get("Host"));
            return new Response(``, {
              status: 200,
              headers: {
                "Content-Type": "text/html;charset=utf-8",
              },
            });
          }
		  case `/config/ty`: {
			const tyConfig = gettyConfig(userID, request.headers.get('Host'));
			return new Response(``, {
				status: 200,
				headers: {
					"Content-Type": "text/plain;charset=utf-8",
				}
			});
		}
		case `/config/cl`: {
			const clConfig = getclConfig(userID, request.headers.get('Host'));
			return new Response(``, {
				status: 200,
				headers: {
					"Content-Type": "text/plain;charset=utf-8",
				}
			});
		}
		case `/config/sb`: {
			const sbConfig = getsbConfig(userID, request.headers.get('Host'));
			return new Response(``, {
				status: 200,
				headers: {
					"Content-Type": "application/json;charset=utf-8",
				}
			});
		}
		case `/config/pty`: {
			const ptyConfig = getptyConfig(userID, request.headers.get('Host'));
			return new Response(``, {
				status: 200,
				headers: {
					"Content-Type": "text/plain;charset=utf-8",
				}
			});
		}
		case `/config/pcl`: {
			const pclConfig = getpclConfig(userID, request.headers.get('Host'));
			return new Response(``, {
				status: 200,
				headers: {
					"Content-Type": "text/plain;charset=utf-8",
				}
			});
		}
		case `/config/psb`: {
			const psbConfig = getpsbConfig(userID, request.headers.get('Host'));
			return new Response(``, {
				status: 200,
				headers: {
					"Content-Type": "application/json;charset=utf-8",
				}
			});
		}
          default:
            // return new Response('Not found', { status: 404 });
            // For any other path, reverse proxy to 'ramdom website' and return the original response, caching it in the process
            if (cn_hostnames.includes('')) {
            return new Response(JSON.stringify(request.cf, null, 4), {
              status: 200,
              headers: {
                "Content-Type": "application/json;charset=utf-8",
              },
            });
            }
            const randomHostname = cn_hostnames[Math.floor(Math.random() * cn_hostnames.length)];
            const newHeaders = new Headers(request.headers);
            newHeaders.set("cf-connecting-ip", "1.2.3.4");
            newHeaders.set("x-forwarded-for", "1.2.3.4");
            newHeaders.set("x-real-ip", "1.2.3.4");
            newHeaders.set("referer", "https://www.google.com/search?q=edtunnel");
            // Use fetch to proxy the request to 15 different domains
            const proxyUrl = "https://" + randomHostname + url.pathname + url.search;
            let modifiedRequest = new Request(proxyUrl, {
              method: request.method,
              headers: newHeaders,
              body: request.body,
              redirect: "manual",
            });
            const proxyResponse = await fetch(modifiedRequest, { redirect: "manual" });
            // Check for 302 or 301 redirect status and return an error response
            if ([301, 302].includes(proxyResponse.status)) {
              return new Response(`Redirects to  are not allowed.`, {
                status: 403,
                statusText: "Forbidden",
              });
            }
            // Return the response from the proxy server
            return proxyResponse;
        }
      } else {
			if(url.pathname.includes('/pyip='))
			{
				const tmp_ip=url.pathname.split("=")[1];
				if(isValidIP(tmp_ip))
				{
					proxyIP=tmp_ip;
				}
				
			}
        return await vlessOverWSHandler(request);
		}
    } catch (err) {
      /** @type {Error} */ let e = err;
      return new Response(e.toString());
    }
  },
};

function isValidIP(ip) {
    var reg = /^[\s\S]*$/;
    return reg.test(ip);
}

/**
 *
 * @param {import("@cloudflare/workers-types").Request} request
 */
async function vlessOverWSHandler(request) {
  /** @type {import("@cloudflare/workers-types").WebSocket[]} */
  // @ts-ignore
  const webSocketPair = new WebSocketPair();
  const [client, webSocket] = Object.values(webSocketPair);

  webSocket.accept();

  let address = "";
  let portWithRandomLog = "";
  const log = (/** @type {string} */ info, /** @type {string | undefined} */ event) => {
    console.log(`[:] `, event || "");
  };
  const earlyDataHeader = request.headers.get("sec-websocket-protocol") || "";

  const readableWebSocketStream = makeReadableWebSocketStream(webSocket, earlyDataHeader, log);

  /** @type {{ value: import("@cloudflare/workers-types").Socket | null}}*/
  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, userID);
          address = addressRemote;
          portWithRandomLog = `--${Math.random()} ${isUDP ? "udp " : "tcp "} `;
          if (hasError) {
            // controller.error(message);
            throw new Error(message); // cf seems has bug, controller.error will not end stream
            // webSocket.close(1000, message);
            return;
          }
          // if UDP but port not DNS port, close it
          if (isUDP) {
            if (portRemote === 53) {
              isDns = true;
            } else {
              // controller.error('UDP proxy only enable for DNS which is port 53');
              throw new Error("UDP proxy only enable for DNS which is port 53"); // cf seems has bug, controller.error will not end stream
              return;
            }
          }
          // ["version", "附加信息长度 N"]
          const vlessResponseHeader = new Uint8Array([vlessVersion[0], 0]);
          const rawClientData = chunk.slice(rawDataIndex);

          // TODO: support udp here when cf runtime has udp support
          if (isDns) {
            const { write } = await handleUDPOutBound(webSocket, vlessResponseHeader, log);
            udpStreamWrite = write;
            udpStreamWrite(rawClientData);
            return;
          }
          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,
    // @ts-ignore
    webSocket: client,
  });
}

/**
 * Checks if a given UUID is present in the API response.
 * @param {string} targetUuid The UUID to search for.
 * @returns {Promise<boolean>} A Promise that resolves to true if the UUID is present in the API response, false otherwise.
 */
async function checkUuidInApiResponse(targetUuid) {
  // Check if any of the environment variables are empty

  try {
    const apiResponse = await getApiResponse();
    if (!apiResponse) {
      return false;
    }
    const isUuidInResponse = apiResponse.users.some((user) => user.uuid === targetUuid);
    return isUuidInResponse;
  } catch (error) {
    console.error("Error:", error);
    return false;
  }
}

/**
 * Handles outbound TCP connections.
 *
 * @param {any} remoteSocket
 * @param {string} addressRemote The remote address to connect to.
 * @param {number} portRemote The remote port to connect to.
 * @param {Uint8Array} rawClientData The raw client data to write.
 * @param {import("@cloudflare/workers-types").WebSocket} webSocket The WebSocket to pass the remote socket to.
 * @param {Uint8Array} vlessResponseHeader The VLESS response header.
 * @param {function} log The logging function.
 * @returns {Promise<void>} The remote socket.
 */
async function handleTCPOutBound(
  remoteSocket,
  addressRemote,
  portRemote,
  rawClientData,
  webSocket,
  vlessResponseHeader,
  log
) {
  async function connectAndWrite(address, port) {
    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==')}${atob('LnNzbGlwLmlv')}`;
    /** @type {import("@cloudflare/workers-types").Socket} */
    const tcpSocket = connect({
      hostname: address,
      port: port,
    });
    remoteSocket.value = tcpSocket;
    log(`connected to :`);
    const writer = tcpSocket.writable.getWriter();
    await writer.write(rawClientData); // first write, nomal is tls client hello
    writer.releaseLock();
    return tcpSocket;
  }

  // if the cf connect tcp socket have no incoming data, we retry to redirect ip
  async function retry() {
    const tcpSocket = await connectAndWrite(proxyIP || addressRemote, 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);
}

/**
 *
 * @param {import("@cloudflare/workers-types").WebSocket} webSocketServer
 * @param {string} earlyDataHeader for ws 0rtt
 * @param {(info: string)=> void} log for ws 0rtt
 */
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);
      });

      // The event means that the client closed the client -> server stream.
      // However, the server -> client stream is still open until you call close() on the server side.
      // The WebSocket protocol says that a separate close message must be sent in each direction to fully close the socket.
      webSocketServer.addEventListener("close", () => {
        // client send close, need close server
        // if stream is cancel, skip controller.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
      // https://streams.spec.whatwg.org/#example-rs-push-backpressure
    },
    cancel(reason) {
      // 1. pipe WritableStream has error, this cancel will called, so ws handle server close into here
      // 2. if readableStream is cancel, all controller.close/enqueue need skip,
      // 3. but from testing controller.error still work even if readableStream is cancel
      if (readableStreamCancel) {
        return;
      }
      log(`ReadableStream was canceled, due to `);
      readableStreamCancel = true;
      safeCloseWebSocket(webSocketServer);
    },
  });

  return stream;
}

// https://xtls.github.io/development/protocols/vless.html
// https://github.com/zizifn/excalidraw-backup/blob/main/v2ray-protocol.excalidraw

/**
 *
 * @param { ArrayBuffer} vlessBuffer
 * @param {string} userID
 * @returns
 */
async function processVlessHeader(vlessBuffer, userID) {
  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);

  const uuids = userID.includes(",") ? userID.split(",") : [userID];

  const checkUuidInApi = await checkUuidInApiResponse(slicedBufferString);
  isValidUser = uuids.some((userUuid) => checkUuidInApi || slicedBufferString === userUuid.trim());

  console.log(`checkUuidInApi: ${await checkUuidInApiResponse(slicedBufferString)}, userID: `);

  if (!isValidUser) {
    return {
      hasError: true,
      message: "invalid user",
    };
  }

  const optLength = new Uint8Array(vlessBuffer.slice(17, 18))[0];
  //skip opt for now

  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  is not support, command 01-tcp,02-udp,03-mux`,
    };
  }
  const portIndex = 18 + optLength + 1;
  const portBuffer = vlessBuffer.slice(portIndex, portIndex + 2);
  // port is big-Endian in raw data etc 80 == 0x005d
  const portRemote = new DataView(portBuffer).getUint16(0);

  let addressIndex = portIndex + 2;
  const addressBuffer = new Uint8Array(vlessBuffer.slice(addressIndex, addressIndex + 1));

  // 1--> ipv4  addressLength =4
  // 2--> domain name addressLength=addressBuffer[1]
  // 3--> ipv6  addressLength =16
  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));
      // 2001:0db8:85a3:0000:0000:8a2e:0370:7334
      const ipv6 = [];
      for (let i = 0; i < 8; i++) {
        ipv6.push(dataView.getUint16(i * 2).toString(16));
      }
      addressValue = ipv6.join(":");
      // seems no need add [] for ipv6
      break;
    default:
      return {
        hasError: true,
        message: `invild  addressType is `,
      };
  }
  if (!addressValue) {
    return {
      hasError: true,
      message: `addressValue is empty, addressType is `,
    };
  }

  return {
    hasError: false,
    addressRemote: addressValue,
    addressType,
    portRemote,
    rawDataIndex: addressValueIndex + addressLength,
    vlessVersion: version,
    isUDP,
  };
}

/**
 *
 * @param {import("@cloudflare/workers-types").Socket} remoteSocket
 * @param {import("@cloudflare/workers-types").WebSocket} webSocket
 * @param {ArrayBuffer} vlessResponseHeader
 * @param {(() => Promise<void>) | null} retry
 * @param {*} log
 */
async function remoteSocketToWS(remoteSocket, webSocket, vlessResponseHeader, retry, log) {
  // remote--> ws
  let remoteChunkCount = 0;
  let chunks = [];
  /** @type {ArrayBuffer | null} */
  let vlessHeader = vlessResponseHeader;
  let hasIncomingData = false; // check if remoteSocket has incoming data
  await remoteSocket.readable
    .pipeTo(
      new WritableStream({
        start() {},
        /**
         *
         * @param {Uint8Array} chunk
         * @param {*} controller
         */
        async write(chunk, controller) {
          hasIncomingData = true;
          // remoteChunkCount++;
          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 {
            // seems no need rate limit this, CF seems fix this??..
            // if (remoteChunkCount > 20000) {
            // 	// cf one package is 4096 byte(4kb),  4096 * 20000 = 80M
            // 	await delay(1);
            // }
            webSocket.send(chunk);
          }
        },
        close() {
          log(`remoteConnection!.readable is close with hasIncomingData is `);
          // safeCloseWebSocket(webSocket); // no need server close websocket frist for some case will casue HTTP ERR_CONTENT_LENGTH_MISMATCH issue, client will send close event anyway.
        },
        abort(reason) {
          console.error(`remoteConnection!.readable abort`, reason);
        },
      })
    )
    .catch((error) => {
      console.error(`remoteSocketToWS has exception `, error.stack || error);
      safeCloseWebSocket(webSocket);
    });

  // seems is cf connect socket have error,
  // 1. Socket.closed will have error
  // 2. Socket.readable will be close without any data coming
  if (hasIncomingData === false && retry) {
    log(`retry`);
    retry();
  }
}

/**
 *
 * @param {string} base64Str
 * @returns
 */
function base64ToArrayBuffer(base64Str) {
  if (!base64Str) {
    return { error: null };
  }
  try {
    // go use modified Base64 for URL rfc4648 which js atob not support
    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 };
  }
}

/**
 * This is not real UUID validation
 * @param {string} uuid
 */
function isValidUUID(uuid) {
  const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
  return uuidRegex.test(uuid);
}

const WS_READY_STATE_OPEN = 1;
const WS_READY_STATE_CLOSING = 2;
/**
 * Normally, WebSocket will not has exceptions when close.
 * @param {import("@cloudflare/workers-types").WebSocket} socket
 */
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);
  if (!isValidUUID(uuid)) {
    throw TypeError("Stringified UUID is invalid");
  }
  return uuid;
}
 
/**
 *
 * @param {import("@cloudflare/workers-types").WebSocket} webSocket
 * @param {ArrayBuffer} vlessResponseHeader
 * @param {(string)=> void} log
 */
async function handleUDPOutBound(webSocket, vlessResponseHeader, log) {
  let isVlessHeaderSent = false;
  const transformStream = new TransformStream({
    start(controller) {},
    transform(chunk, controller) {
      // udp message 2 byte is the the length of udp data
      // TODO: this should have bug, beacsue maybe udp chunk can be in two websocket message
      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) {},
  });

  // only handle dns udp for now
  transformStream.readable
    .pipeTo(
      new WritableStream({
        async write(chunk) {
          const resp = await fetch(
            dohURL, // dns server url
            {
              method: "POST",
              headers: {
                "content-type": "application/dns-message",
              },
              body: chunk,
            }
          );
          const dnsQueryResult = await resp.arrayBuffer();
          const udpSize = dnsQueryResult.byteLength;
          // console.log([...new Uint8Array(dnsQueryResult)].map((x) => x.toString(16)));
          const udpSizeBuffer = new Uint8Array([(udpSize >> 8) & 0xff, udpSize & 0xff]);
          if (webSocket.readyState === WS_READY_STATE_OPEN) {
            log(`doh success and dns message length is `);
            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 {
    /**
     *
     * @param {Uint8Array} chunk
     */
    write(chunk) {
      writer.write(chunk);
    },
  };
}

/**
 *
 * @param {string} userID
 * @param {string | null} hostName
 * @returns {string}
 */
function getVLESSConfig(userID, hostName) {
  const wvlessws = `vless://\u0040:8880?encryption=none&security=none&type=ws&host=&path=%2F%3Fed%3D2560#`;
  const pvlesswstls = `vless://\u0040:8443?encryption=none&security=tls&type=ws&host=&sni=&fp=random&path=%2F%3Fed%3D2560#`;
  const note = `ProxyIP全局运行中:`;
  const ty = `https:////ty`
  const cl = `https:////cl`
  const sb = `https:////sb`
  const pty = `https:////pty`
  const pcl = `https:////pcl`
  const psb = `https:////psb`
  const noteshow = note.replace(/\n/g, '<br>');
  const displayHtml = `
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
<style>
.limited-width {
    max-width: 200px;
    overflow: auto;
    word-wrap: break-word;
}
</style>
</head>
<script>
function copyToClipboard(text) {
  const input = document.createElement('textarea');
  input.style.position = 'fixed';
  input.style.opacity = 0;
  input.value = text;
  document.body.appendChild(input);
  input.select();
  document.execCommand('Copy');
  document.body.removeChild(input);
  alert('已复制到剪贴板');
}
</script>
`;
if (hostName.includes("workers.dev")) {
return `
<br>
<br>

<body>
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h1>Cloudflare-workers/pages-vless代理脚本</h1>
	    <hr>
            <p></p>
            <hr>
	    <hr>
	    <hr>
            <br>
            <br>
            <h3>1:CF-workers-vless+ws节点</h3>
			<table class="table">
				<thead>
					<tr>
						<th>节点特色:</th>
						<th>单节点链接如下:</th>
					</tr>
				</thead>
				<tbody>
					<tr>
						<td class="limited-width">关闭了TLS加密,无视域名阻断</td>
						<td class="limited-width"></td>
						<td><button class="btn btn-primary" onclick="copyToClipboard('')">点击复制链接</button></td>
					</tr>
				</tbody>
			</table>
            <h5>客户端参数如下:</h5>
            <ul>
                <li>客户端地址(address):自定义的域名 或者 优选域名 或者 优选IP 或者 反代IP</li>
                <li>端口(port):7个http端口可任意选择(80、8080、8880、2052、2082、2086、2095),或反代IP对应端口</li>
                <li>用户ID(uuid):</li>
                <li>传输协议(network):ws 或者 websocket</li>
                <li>伪装域名(host):</li>
                <li>路径(path):/?ed=2560</li>
		<li>传输安全(TLS):关闭</li>
            </ul>
            <hr>
			<hr>
			<hr>
            <br>
            <br>
            <h3>2:CF-workers-vless+ws+tls节点</h3>
			<table class="table">
				<thead>
					<tr>
						<th>节点特色:</th>
						<th>单节点链接如下:</th>
					</tr>
				</thead>
				<tbody>
					<tr>
						<td class="limited-width">启用了TLS加密,<br>如果客户端支持分片(Fragment)功能,建议开启,防止域名阻断</td>
						<td class="limited-width"></td>	
						<td><button class="btn btn-primary" onclick="copyToClipboard('')">点击复制链接</button></td>
					</tr>
				</tbody>
			</table>
            <h5>客户端参数如下:</h5>
            <ul>
                <li>客户端地址(address):自定义的域名 或者 优选域名 或者 优选IP 或者 反代IP</li>
                <li>端口(port):6个https端口可任意选择(443、8443、2053、2083、2087、2096),或反代IP对应端口</li>
                <li>用户ID(uuid):</li>
                <li>传输协议(network):ws 或者 websocket</li>
                <li>伪装域名(host):</li>
                <li>路径(path):/?ed=2560</li>
                <li>传输安全(TLS):开启</li>
                <li>跳过证书验证(allowlnsecure):false</li>
			</ul>
			<hr>
			<hr>
			<hr>
			<br>	
			<br>
			<h3>3:通用、Clash-meta、Sing-box订阅链接如下:</h3>
			<hr>
			<p>注意:<br>1、默认每个订阅链接包含TLS+非TLS共13个端口节点<br>2、当前workers域名作为订阅链接,需通过代理进行订阅更新<br>3、需要开启分片功能使TLS节点可用,否则仅非TLS节点可用</p>
			<hr>
			<table class="table">
					<thead>
						<tr>
							<th>通用订阅链接:</th>
						</tr>
					</thead>
					<tbody>
						<tr>
							<td class="limited-width"></td>	
							<td><button class="btn btn-primary" onclick="copyToClipboard('')">点击复制链接</button></td>
						</tr>
					</tbody>
				</table>	

				<table class="table">
						<thead>
							<tr>
								<th>Clash-meta订阅链接:</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td class="limited-width"></td>	
								<td><button class="btn btn-primary" onclick="copyToClipboard('')">点击复制链接</button></td>
							</tr>
						</tbody>
					</table>

					<table class="table">
					<thead>
						<tr>
							<th>Sing-box订阅链接:</th>
						</tr>
					</thead>
					<tbody>
						<tr>
							<td class="limited-width"></td>	
							<td><button class="btn btn-primary" onclick="copyToClipboard('')">点击复制链接</button></td>
						</tr>
					</tbody>
				</table>
				<br>
				<br>
        </div>
    </div>
</div>
</body>
`;
  } else {
    return `
<br>
<br>

<body>
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h1>Cloudflare-workers/pages-vless代理脚本</h1>
			<hr>
            <p></p>
            <hr>
			<hr>
			<hr>
            <br>
            <br>
            <h3>1:CF-pages/workers/自定义域-vless+ws+tls节点</h3>
			<table class="table">
				<thead>
					<tr>
						<th>节点特色:</th>
						<th>单节点链接如下:</th>
					</tr>
				</thead>
				<tbody>
					<tr>
						<td class="limited-width">启用了TLS加密,<br>如果客户端支持分片(Fragment)功能,可开启,防止域名阻断</td>
						<td class="limited-width"></td>
						<td><button class="btn btn-primary" onclick="copyToClipboard('')">点击复制链接</button></td>
					</tr>
				</tbody>
			</table>
            <h5>客户端参数如下:</h5>
            <ul>
                <li>客户端地址(address):自定义的域名 或者 优选域名 或者 优选IP 或者 反代IP</li>
                <li>端口(port):6个https端口可任意选择(443、8443、2053、2083、2087、2096),或反代IP对应端口</li>
                <li>用户ID(uuid):</li>
                <li>传输协议(network):ws 或者 websocket</li>
                <li>伪装域名(host):</li>
                <li>路径(path):/?ed=2560</li>
                <li>传输安全(TLS):开启</li>
                <li>跳过证书验证(allowlnsecure):false</li>
			</ul>
            <hr>
			<hr>
			<hr>
            <br>
            <br>
			<h3>2:通用、Clash-meta、Sing-box订阅链接如下:</h3>
			<hr>
			<p>注意:以下订阅链接仅6个TLS端口节点</p>
			<hr>
			<table class="table">
					<thead>
						<tr>
							<th>通用订阅链接:</th>
						</tr>
					</thead>
					<tbody>
						<tr>
							<td class="limited-width"></td>	
							<td><button class="btn btn-primary" onclick="copyToClipboard('')">点击复制链接</button></td>
						</tr>
					</tbody>
				</table>	

				<table class="table">
						<thead>
							<tr>
								<th>Clash-meta订阅链接:</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td class="limited-width"></td>	
								<td><button class="btn btn-primary" onclick="copyToClipboard('')">点击复制链接</button></td>
							</tr>
						</tbody>
					</table>

					<table class="table">
					<thead>
						<tr>
							<th>Sing-box订阅链接:</th>
						</tr>
					</thead>
					<tbody>
						<tr>
							<td class="limited-width"></td>	
							<td><button class="btn btn-primary" onclick="copyToClipboard('')">点击复制链接</button></td>
						</tr>
					</tbody>
				</table>
				<br>
				<br>
        </div>
    </div>
</div>
</body>
`;
  }
}

function gettyConfig(userID, hostName) {
	const vlessshare = btoa(`vless://\u0040:?encryption=none&security=none&fp=randomized&type=ws&host=&path=%2F%3Fed%3D2560#CF_V1__\nvless://\u0040:?encryption=none&security=none&fp=randomized&type=ws&host=&path=%2F%3Fed%3D2560#CF_V2__\nvless://\u0040:?encryption=none&security=none&fp=randomized&type=ws&host=&path=%2F%3Fed%3D2560#CF_V3__\nvless://\u0040:?encryption=none&security=none&fp=randomized&type=ws&host=&path=%2F%3Fed%3D2560#CF_V4__\nvless://\u0040:?encryption=none&security=none&fp=randomized&type=ws&host=&path=%2F%3Fed%3D2560#CF_V5__\nvless://\u0040:?encryption=none&security=none&fp=randomized&type=ws&host=&path=%2F%3Fed%3D2560#CF_V6__\nvless://\u0040:?encryption=none&security=none&fp=randomized&type=ws&host=&path=%2F%3Fed%3D2560#CF_V7__\nvless://\u0040:?encryption=none&security=tls&sni=&fp=randomized&type=ws&host=&path=%2F%3Fed%3D2560#CF_V8__\nvless://\u0040:?encryption=none&security=tls&sni=&fp=randomized&type=ws&host=&path=%2F%3Fed%3D2560#CF_V9__\nvless://\u0040:?encryption=none&security=tls&sni=&fp=randomized&type=ws&host=&path=%2F%3Fed%3D2560#CF_V10__\nvless://\u0040:?encryption=none&security=tls&sni=&fp=randomized&type=ws&host=&path=%2F%3Fed%3D2560#CF_V11__\nvless://\u0040:?encryption=none&security=tls&sni=&fp=randomized&type=ws&host=&path=%2F%3Fed%3D2560#CF_V12__\nvless://\u0040:?encryption=none&security=tls&sni=&fp=randomized&type=ws&host=&path=%2F%3Fed%3D2560#CF_V13__`);
		return ``
	}

function getclConfig(userID, hostName) {
return `
port: 7890
allow-lan: true
mode: rule
log-level: info
unified-delay: true
global-client-fingerprint: chrome
dns:
  enable: true
  listen: :53
  ipv6: true
  enhanced-mode: fake-ip
  fake-ip-range: 198.18.0.1/16
  default-nameserver: 
    - 223.5.5.5
    - 114.114.114.114
    - 8.8.8.8
  nameserver:
    - https://dns.alidns.com/dns-query
    - https://doh.pub/dns-query
  fallback:
    - https://1.0.0.1/dns-query
    - tls://dns.google
  fallback-filter:
    geoip: true
    geoip-code: CN
    ipcidr:
      - 240.0.0.0/4

proxies:
- name: CF_V1__
  type: vless
  server: 
  port: 
  uuid: 
  udp: false
  tls: false
  network: ws
  ws-opts:
    path: "/?ed=2560"
    headers:
      Host: 

- name: CF_V2__
  type: vless
  server: 
  port: 
  uuid: 
  udp: false
  tls: false
  network: ws
  ws-opts:
    path: "/?ed=2560"
    headers:
      Host: 

- name: CF_V3__
  type: vless
  server: 
  port: 
  uuid: 
  udp: false
  tls: false
  network: ws
  ws-opts:
    path: "/?ed=2560"
    headers:
      Host: 

- name: CF_V4__
  type: vless
  server: 
  port: 
  uuid: 
  udp: false
  tls: false
  network: ws
  ws-opts:
    path: "/?ed=2560"
    headers:
      Host: 

- name: CF_V5__
  type: vless
  server: 
  port: 
  uuid: 
  udp: false
  tls: false
  network: ws
  ws-opts:
    path: "/?ed=2560"
    headers:
      Host: 

- name: CF_V6__
  type: vless
  server: 
  port: 
  uuid: 
  udp: false
  tls: false
  network: ws
  ws-opts:
    path: "/?ed=2560"
    headers:
      Host: 

- name: CF_V7__
  type: vless
  server: 
  port: 
  uuid: 
  udp: false
  tls: false
  network: ws
  servername: 
  ws-opts:
    path: "/?ed=2560"
    headers:
      Host: 

- name: CF_V8__
  type: vless
  server: 
  port: 
  uuid: 
  udp: false
  tls: true
  network: ws
  servername: 
  ws-opts:
    path: "/?ed=2560"
    headers:
      Host: 

- name: CF_V9__
  type: vless
  server: 
  port: 
  uuid: 
  udp: false
  tls: true
  network: ws
  servername: 
  ws-opts:
    path: "/?ed=2560"
    headers:
      Host: 

- name: CF_V10__
  type: vless
  server: 
  port: 
  uuid: 
  udp: false
  tls: true
  network: ws
  servername: 
  ws-opts:
    path: "/?ed=2560"
    headers:
      Host: 

- name: CF_V11__
  type: vless
  server: 
  port: 
  uuid: 
  udp: false
  tls: true
  network: ws
  servername: 
  ws-opts:
    path: "/?ed=2560"
    headers:
      Host: 

- name: CF_V12__
  type: vless
  server: 
  port: 
  uuid: 
  udp: false
  tls: true
  network: ws
  servername: 
  ws-opts:
    path: "/?ed=2560"
    headers:
      Host: 

- name: CF_V13__
  type: vless
  server: 
  port: 
  uuid: 
  udp: false
  tls: true
  network: ws
  servername: 
  ws-opts:
    path: "/?ed=2560"
    headers:
      Host: 

proxy-groups:
- name: 负载均衡
  type: load-balance
  url: http://www.gstatic.com/generate_204
  interval: 300
  proxies:
    - CF_V1__
    - CF_V2__
    - CF_V3__
    - CF_V4__
    - CF_V5__
    - CF_V6__
    - CF_V7__
    - CF_V8__
    - CF_V9__
    - CF_V10__
    - CF_V11__
    - CF_V12__
    - CF_V13__

- name: 自动选择
  type: url-test
  url: http://www.gstatic.com/generate_204
  interval: 300
  tolerance: 50
  proxies:
    - CF_V1__
    - CF_V2__
    - CF_V3__
    - CF_V4__
    - CF_V5__
    - CF_V6__
    - CF_V7__
    - CF_V8__
    - CF_V9__
    - CF_V10__
    - CF_V11__
    - CF_V12__
    - CF_V13__

- name: 🌍选择代理
  type: select
  proxies:
    - 负载均衡
    - 自动选择
    - DIRECT
    - CF_V1__
    - CF_V2__
    - CF_V3__
    - CF_V4__
    - CF_V5__
    - CF_V6__
    - CF_V7__
    - CF_V8__
    - CF_V9__
    - CF_V10__
    - CF_V11__
    - CF_V12__
    - CF_V13__

rules:
  - GEOIP,LAN,DIRECT
  - GEOIP,CN,DIRECT
  - MATCH,🌍选择代理`
}
	
function getsbConfig(userID, hostName) {
return `{
	  "log": {
		"disabled": false,
		"level": "info",
		"timestamp": true
	  },
	  "experimental": {
		"clash_api": {
		  "external_controller": "127.0.0.1:9090",
		  "external_ui": "ui",
		  "external_ui_download_url": "",
		  "external_ui_download_detour": "",
		  "secret": "",
		  "default_mode": "Rule"
		},
		"cache_file": {
		  "enabled": true,
		  "path": "cache.db",
		  "store_fakeip": true
		}
	  },
	  "dns": {
		"servers": [
		  {
			"tag": "proxydns",
			"address": "tls://8.8.8.8/dns-query",
			"detour": "select"
		  },
		  {
			"tag": "localdns",
			"address": "h3://223.5.5.5/dns-query",
			"detour": "direct"
		  },
		  {
			"address": "rcode://refused",
			"tag": "block"
		  },
		  {
			"tag": "dns_fakeip",
			"address": "fakeip"
		  }
		],
		"rules": [
		  {
			"outbound": "any",
			"server": "localdns",
			"disable_cache": true
		  },
		  {
			"clash_mode": "Global",
			"server": "proxydns"
		  },
		  {
			"clash_mode": "Direct",
			"server": "localdns"
		  },
		  {
			"rule_set": "geosite-cn",
			"server": "localdns"
		  },
		  {
			"rule_set": "geosite-geolocation-!cn",
			"server": "proxydns"
		  },
		  {
			"rule_set": "geosite-geolocation-!cn",
			"query_type": [
			  "A",
			  "AAAA"
			],
			"server": "dns_fakeip"
		  }
		],
		"fakeip": {
		  "enabled": true,
		  "inet4_range": "198.18.0.0/15",
		  "inet6_range": "fc00::/18"
		},
		"independent_cache": true,
		"final": "proxydns"
	  },
	  "inbounds": [
		{
		  "type": "tun",
		  "inet4_address": "172.19.0.1/30",
		  "inet6_address": "fd00::1/126",
		  "auto_route": true,
		  "strict_route": true,
		  "sniff": true,
		  "sniff_override_destination": true,
		  "domain_strategy": "prefer_ipv4"
		}
	  ],
	  "outbounds": [
		{
		  "tag": "select",
		  "type": "selector",
		  "default": "auto",
		  "outbounds": [
			"auto",
			"CF_V1__",
			"CF_V2__",
			"CF_V3__",
			"CF_V4__",
			"CF_V5__",
			"CF_V6__",
			"CF_V7__",
			"CF_V8__",
			"CF_V9__",
			"CF_V10__",
			"CF_V11__",
			"CF_V12__",
			"CF_V13__"
		  ]
		},
		{
		  "server": "",
		  "server_port": ,
		  "tag": "CF_V1__",
		  "packet_encoding": "packetaddr",
		  "transport": {
			"headers": {
			  "Host": [
				""
			  ]
			},
			"path": "/?ed=2560",
			"type": "ws"
		  },
		  "type": "vless",
		  "uuid": ""
		},
		{
		  "server": "",
		  "server_port": ,
		  "tag": "CF_V2__",
		  "packet_encoding": "packetaddr",
		  "transport": {
			"headers": {
			  "Host": [
				""
			  ]
			},
			"path": "/?ed=2560",
			"type": "ws"
		  },
		  "type": "vless",
		  "uuid": ""
		},
		{
		  "server": "",
		  "server_port": ,
		  "tag": "CF_V3__",
		  "packet_encoding": "packetaddr",
		  "transport": {
			"headers": {
			  "Host": [
				""
			  ]
			},
			"path": "/?ed=2560",
			"type": "ws"
		  },
		  "type": "vless",
		  "uuid": ""
		},
		{
		  "server": "",
		  "server_port": ,
		  "tag": "CF_V4__",
		  "packet_encoding": "packetaddr",
		  "transport": {
			"headers": {
			  "Host": [
				""
			  ]
			},
			"path": "/?ed=2560",
			"type": "ws"
		  },
		  "type": "vless",
		  "uuid": ""
		},
		{
		  "server": "",
		  "server_port": ,
		  "tag": "CF_V5__",
		  "packet_encoding": "packetaddr",
		  "transport": {
			"headers": {
			  "Host": [
				""
			  ]
			},
			"path": "/?ed=2560",
			"type": "ws"
		  },
		  "type": "vless",
		  "uuid": ""
		},
		{
		  "server": "",
		  "server_port": ,
		  "tag": "CF_V6__",
		  "packet_encoding": "packetaddr",
		  "transport": {
			"headers": {
			  "Host": [
				""
			  ]
			},
			"path": "/?ed=2560",
			"type": "ws"
		  },
		  "type": "vless",
		  "uuid": ""
		},
		{
		  "server": "",
		  "server_port": ,
		  "tag": "CF_V7__",
		  "packet_encoding": "packetaddr",
		  "transport": {
			"headers": {
			  "Host": [
				""
			  ]
			},
			"path": "/?ed=2560",
			"type": "ws"
		  },
		  "type": "vless",
		  "uuid": ""
		},
		{
		  "server": "",
		  "server_port": ,
		  "tag": "CF_V8__",
		  "tls": {
			"enabled": true,
			"server_name": "",
			"insecure": false,
			"utls": {
			  "enabled": true,
			  "fingerprint": "chrome"
			}
		  },
		  "packet_encoding": "packetaddr",
		  "transport": {
			"headers": {
			  "Host": [
				""
			  ]
			},
			"path": "/?ed=2560",
			"type": "ws"
		  },
		  "type": "vless",
		  "uuid": ""
		},
		{
		  "server": "",
		  "server_port": ,
		  "tag": "CF_V9__",
		  "tls": {
			"enabled": true,
			"server_name": "",
			"insecure": false,
			"utls": {
			  "enabled": true,
			  "fingerprint": "chrome"
			}
		  },
		  "packet_encoding": "packetaddr",
		  "transport": {
			"headers": {
			  "Host": [
				""
			  ]
			},
			"path": "/?ed=2560",
			"type": "ws"
		  },
		  "type": "vless",
		  "uuid": ""
		},
		{
		  "server": "",
		  "server_port": ,
		  "tag": "CF_V10__",
		  "tls": {
			"enabled": true,
			"server_name": "",
			"insecure": false,
			"utls": {
			  "enabled": true,
			  "fingerprint": "chrome"
			}
		  },
		  "packet_encoding": "packetaddr",
		  "transport": {
			"headers": {
			  "Host": [
				""
			  ]
			},
			"path": "/?ed=2560",
			"type": "ws"
		  },
		  "type": "vless",
		  "uuid": ""
		},
		{
		  "server": "",
		  "server_port": ,
		  "tag": "CF_V11__",
		  "tls": {
			"enabled": true,
			"server_name": "",
			"insecure": false,
			"utls": {
			  "enabled": true,
			  "fingerprint": "chrome"
			}
		  },
		  "packet_encoding": "packetaddr",
		  "transport": {
			"headers": {
			  "Host": [
				""
			  ]
			},
			"path": "/?ed=2560",
			"type": "ws"
		  },
		  "type": "vless",
		  "uuid": ""
		},
		{
		  "server": "",
		  "server_port": ,
		  "tag": "CF_V12__",
		  "tls": {
			"enabled": true,
			"server_name": "",
			"insecure": false,
			"utls": {
			  "enabled": true,
			  "fingerprint": "chrome"
			}
		  },
		  "packet_encoding": "packetaddr",
		  "transport": {
			"headers": {
			  "Host": [
				""
			  ]
			},
			"path": "/?ed=2560",
			"type": "ws"
		  },
		  "type": "vless",
		  "uuid": ""
		},
		{
		  "server": "",
		  "server_port": ,
		  "tag": "CF_V13__",
		  "tls": {
			"enabled": true,
			"server_name": "",
			"insecure": false,
			"utls": {
			  "enabled": true,
			  "fingerprint": "chrome"
			}
		  },
		  "packet_encoding": "packetaddr",
		  "transport": {
			"headers": {
			  "Host": [
				""
			  ]
			},
			"path": "/?ed=2560",
			"type": "ws"
		  },
		  "type": "vless",
		  "uuid": ""
		},
		{
		  "tag": "direct",
		  "type": "direct"
		},
		{
		  "tag": "block",
		  "type": "block"
		},
		{
		  "tag": "dns-out",
		  "type": "dns"
		},
		{
		  "tag": "auto",
		  "type": "urltest",
		  "outbounds": [
			"CF_V1__",
			"CF_V2__",
			"CF_V3__",
			"CF_V4__",
			"CF_V5__",
			"CF_V6__",
			"CF_V7__",
			"CF_V8__",
			"CF_V9__",
			"CF_V10__",
			"CF_V11__",
			"CF_V12__",
			"CF_V13__"
		  ],
		  "url": "https://www.gstatic.com/generate_204",
		  "interval": "1m",
		  "tolerance": 50,
		  "interrupt_exist_connections": false
		}
	  ],
	  "route": {
		"rule_set": [
		  {
			"tag": "geosite-geolocation-!cn",
			"type": "remote",
			"format": "binary",
			"url": "https://cdn.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@sing/geo/geosite/geolocation-!cn.srs",
			"download_detour": "select",
			"update_interval": "1d"
		  },
		  {
			"tag": "geosite-cn",
			"type": "remote",
			"format": "binary",
			"url": "https://cdn.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@sing/geo/geosite/geolocation-cn.srs",
			"download_detour": "select",
			"update_interval": "1d"
		  },
		  {
			"tag": "geoip-cn",
			"type": "remote",
			"format": "binary",
			"url": "https://cdn.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@sing/geo/geoip/cn.srs",
			"download_detour": "select",
			"update_interval": "1d"
		  }
		],
		"auto_detect_interface": true,
		"final": "select",
		"rules": [
		  {
			"outbound": "dns-out",
			"protocol": "dns"
		  },
		  {
			"clash_mode": "Direct",
			"outbound": "direct"
		  },
		  {
			"clash_mode": "Global",
			"outbound": "select"
		  },
		  {
			"rule_set": "geoip-cn",
			"outbound": "direct"
		  },
		  {
			"rule_set": "geosite-cn",
			"outbound": "direct"
		  },
		  {
			"ip_is_private": true,
			"outbound": "direct"
		  },
		  {
			"rule_set": "geosite-geolocation-!cn",
			"outbound": "select"
		  }
		]
	  },
	  "ntp": {
		"enabled": true,
		"server": "time.apple.com",
		"server_port": 123,
		"interval": "30m",
		"detour": "direct"
	  }
	}`
}

function getptyConfig(userID, hostName) {
	const vlessshare = btoa(`vless://\u0040:?encryption=none&security=tls&sni=&fp=randomized&type=ws&host=&path=%2F%3Fed%3D2560#CF_V8__\nvless://\u0040:?encryption=none&security=tls&sni=&fp=randomized&type=ws&host=&path=%2F%3Fed%3D2560#CF_V9__\nvless://\u0040:?encryption=none&security=tls&sni=&fp=randomized&type=ws&host=&path=%2F%3Fed%3D2560#CF_V10__\nvless://\u0040:?encryption=none&security=tls&sni=&fp=randomized&type=ws&host=&path=%2F%3Fed%3D2560#CF_V11__\nvless://\u0040:?encryption=none&security=tls&sni=&fp=randomized&type=ws&host=&path=%2F%3Fed%3D2560#CF_V12__\nvless://\u0040:?encryption=none&security=tls&sni=&fp=randomized&type=ws&host=&path=%2F%3Fed%3D2560#CF_V13__`);	
		return ``
	}
	
function getpclConfig(userID, hostName) {
return `
port: 7890
allow-lan: true
mode: rule
log-level: info
unified-delay: true
global-client-fingerprint: chrome
dns:
  enable: true
  listen: :53
  ipv6: true
  enhanced-mode: fake-ip
  fake-ip-range: 198.18.0.1/16
  default-nameserver: 
    - 223.5.5.5
    - 114.114.114.114
    - 8.8.8.8
  nameserver:
    - https://dns.alidns.com/dns-query
    - https://doh.pub/dns-query
  fallback:
    - https://1.0.0.1/dns-query
    - tls://dns.google
  fallback-filter:
    geoip: true
    geoip-code: CN
    ipcidr:
      - 240.0.0.0/4

proxies:
- name: CF_V8__
  type: vless
  server: 
  port: 
  uuid: 
  udp: false
  tls: true
  network: ws
  servername: 
  ws-opts:
    path: "/?ed=2560"
    headers:
      Host: 

- name: CF_V9__
  type: vless
  server: 
  port: 
  uuid: 
  udp: false
  tls: true
  network: ws
  servername: 
  ws-opts:
    path: "/?ed=2560"
    headers:
      Host: 

- name: CF_V10__
  type: vless
  server: 
  port: 
  uuid: 
  udp: false
  tls: true
  network: ws
  servername: 
  ws-opts:
    path: "/?ed=2560"
    headers:
      Host: 

- name: CF_V11__
  type: vless
  server: 
  port: 
  uuid: 
  udp: false
  tls: true
  network: ws
  servername: 
  ws-opts:
    path: "/?ed=2560"
    headers:
      Host: 

- name: CF_V12__
  type: vless
  server: 
  port: 
  uuid: 
  udp: false
  tls: true
  network: ws
  servername: 
  ws-opts:
    path: "/?ed=2560"
    headers:
      Host: 

- name: CF_V13__
  type: vless
  server: 
  port: 
  uuid: 
  udp: false
  tls: true
  network: ws
  servername: 
  ws-opts:
    path: "/?ed=2560"
    headers:
      Host: 

proxy-groups:
- name: 负载均衡
  type: load-balance
  url: http://www.gstatic.com/generate_204
  interval: 300
  proxies:
    - CF_V8__
    - CF_V9__
    - CF_V10__
    - CF_V11__
    - CF_V12__
    - CF_V13__

- name: 自动选择
  type: url-test
  url: http://www.gstatic.com/generate_204
  interval: 300
  tolerance: 50
  proxies:
    - CF_V8__
    - CF_V9__
    - CF_V10__
    - CF_V11__
    - CF_V12__
    - CF_V13__

- name: 🌍选择代理
  type: select
  proxies:
    - 负载均衡
    - 自动选择
    - DIRECT
    - CF_V8__
    - CF_V9__
    - CF_V10__
    - CF_V11__
    - CF_V12__
    - CF_V13__

rules:
  - GEOIP,LAN,DIRECT
  - GEOIP,CN,DIRECT
  - MATCH,🌍选择代理`
}
		
function getpsbConfig(userID, hostName) {
return `{
		  "log": {
			"disabled": false,
			"level": "info",
			"timestamp": true
		  },
		  "experimental": {
			"clash_api": {
			  "external_controller": "127.0.0.1:9090",
			  "external_ui": "ui",
			  "external_ui_download_url": "",
			  "external_ui_download_detour": "",
			  "secret": "",
			  "default_mode": "Rule"
			},
			"cache_file": {
			  "enabled": true,
			  "path": "cache.db",
			  "store_fakeip": true
			}
		  },
		  "dns": {
			"servers": [
			  {
				"tag": "proxydns",
				"address": "tls://8.8.8.8/dns-query",
				"detour": "select"
			  },
			  {
				"tag": "localdns",
				"address": "h3://223.5.5.5/dns-query",
				"detour": "direct"
			  },
			  {
				"address": "rcode://refused",
				"tag": "block"
			  },
			  {
				"tag": "dns_fakeip",
				"address": "fakeip"
			  }
			],
			"rules": [
			  {
				"outbound": "any",
				"server": "localdns",
				"disable_cache": true
			  },
			  {
				"clash_mode": "Global",
				"server": "proxydns"
			  },
			  {
				"clash_mode": "Direct",
				"server": "localdns"
			  },
			  {
				"rule_set": "geosite-cn",
				"server": "localdns"
			  },
			  {
				"rule_set": "geosite-geolocation-!cn",
				"server": "proxydns"
			  },
			  {
				"rule_set": "geosite-geolocation-!cn",
				"query_type": [
				  "A",
				  "AAAA"
				],
				"server": "dns_fakeip"
			  }
			],
			"fakeip": {
			  "enabled": true,
			  "inet4_range": "198.18.0.0/15",
			  "inet6_range": "fc00::/18"
			},
			"independent_cache": true,
			"final": "proxydns"
		  },
		  "inbounds": [
			{
			  "type": "tun",
			  "inet4_address": "172.19.0.1/30",
			  "inet6_address": "fd00::1/126",
			  "auto_route": true,
			  "strict_route": true,
			  "sniff": true,
			  "sniff_override_destination": true,
			  "domain_strategy": "prefer_ipv4"
			}
		  ],
		  "outbounds": [
			{
			  "tag": "select",
			  "type": "selector",
			  "default": "auto",
			  "outbounds": [
				"auto",
				"CF_V8__",
				"CF_V9__",
				"CF_V10__",
				"CF_V11__",
				"CF_V12__",
				"CF_V13__"
			  ]
			},
			{
			  "server": "",
			  "server_port": ,
			  "tag": "CF_V8__",
			  "tls": {
				"enabled": true,
				"server_name": "",
				"insecure": false,
				"utls": {
				  "enabled": true,
				  "fingerprint": "chrome"
				}
			  },
			  "packet_encoding": "packetaddr",
			  "transport": {
				"headers": {
				  "Host": [
					""
				  ]
				},
				"path": "/?ed=2560",
				"type": "ws"
			  },
			  "type": "vless",
			  "uuid": ""
			},
			{
			  "server": "",
			  "server_port": ,
			  "tag": "CF_V9__",
			  "tls": {
				"enabled": true,
				"server_name": "",
				"insecure": false,
				"utls": {
				  "enabled": true,
				  "fingerprint": "chrome"
				}
			  },
			  "packet_encoding": "packetaddr",
			  "transport": {
				"headers": {
				  "Host": [
					""
				  ]
				},
				"path": "/?ed=2560",
				"type": "ws"
			  },
			  "type": "vless",
			  "uuid": ""
			},
			{
			  "server": "",
			  "server_port": ,
			  "tag": "CF_V10__",
			  "tls": {
				"enabled": true,
				"server_name": "",
				"insecure": false,
				"utls": {
				  "enabled": true,
				  "fingerprint": "chrome"
				}
			  },
			  "packet_encoding": "packetaddr",
			  "transport": {
				"headers": {
				  "Host": [
					""
				  ]
				},
				"path": "/?ed=2560",
				"type": "ws"
			  },
			  "type": "vless",
			  "uuid": ""
			},
			{
			  "server": "",
			  "server_port": ,
			  "tag": "CF_V11__",
			  "tls": {
				"enabled": true,
				"server_name": "",
				"insecure": false,
				"utls": {
				  "enabled": true,
				  "fingerprint": "chrome"
				}
			  },
			  "packet_encoding": "packetaddr",
			  "transport": {
				"headers": {
				  "Host": [
					""
				  ]
				},
				"path": "/?ed=2560",
				"type": "ws"
			  },
			  "type": "vless",
			  "uuid": ""
			},
			{
			  "server": "",
			  "server_port": ,
			  "tag": "CF_V12__",
			  "tls": {
				"enabled": true,
				"server_name": "",
				"insecure": false,
				"utls": {
				  "enabled": true,
				  "fingerprint": "chrome"
				}
			  },
			  "packet_encoding": "packetaddr",
			  "transport": {
				"headers": {
				  "Host": [
					""
				  ]
				},
				"path": "/?ed=2560",
				"type": "ws"
			  },
			  "type": "vless",
			  "uuid": ""
			},
			{
			  "server": "",
			  "server_port": ,
			  "tag": "CF_V13__",
			  "tls": {
				"enabled": true,
				"server_name": "",
				"insecure": false,
				"utls": {
				  "enabled": true,
				  "fingerprint": "chrome"
				}
			  },
			  "packet_encoding": "packetaddr",
			  "transport": {
				"headers": {
				  "Host": [
					""
				  ]
				},
				"path": "/?ed=2560",
				"type": "ws"
			  },
			  "type": "vless",
			  "uuid": ""
			},
			{
			  "tag": "direct",
			  "type": "direct"
			},
			{
			  "tag": "block",
			  "type": "block"
			},
			{
			  "tag": "dns-out",
			  "type": "dns"
			},
			{
			  "tag": "auto",
			  "type": "urltest",
			  "outbounds": [
				"CF_V8__",
				"CF_V9__",
				"CF_V10__",
				"CF_V11__",
				"CF_V12__",
				"CF_V13__"
			  ],
			  "url": "https://www.gstatic.com/generate_204",
			  "interval": "1m",
			  "tolerance": 50,
			  "interrupt_exist_connections": false
			}
		  ],
		  "route": {
			"rule_set": [
			  {
				"tag": "geosite-geolocation-!cn",
				"type": "remote",
				"format": "binary",
				"url": "https://cdn.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@sing/geo/geosite/geolocation-!cn.srs",
				"download_detour": "select",
				"update_interval": "1d"
			  },
			  {
				"tag": "geosite-cn",
				"type": "remote",
				"format": "binary",
				"url": "https://cdn.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@sing/geo/geosite/geolocation-cn.srs",
				"download_detour": "select",
				"update_interval": "1d"
			  },
			  {
				"tag": "geoip-cn",
				"type": "remote",
				"format": "binary",
				"url": "https://cdn.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@sing/geo/geoip/cn.srs",
				"download_detour": "select",
				"update_interval": "1d"
			  }
			],
			"auto_detect_interface": true,
			"final": "select",
			"rules": [
			  {
				"outbound": "dns-out",
				"protocol": "dns"
			  },
			  {
				"clash_mode": "Direct",
				"outbound": "direct"
			  },
			  {
				"clash_mode": "Global",
				"outbound": "select"
			  },
			  {
				"rule_set": "geoip-cn",
				"outbound": "direct"
			  },
			  {
				"rule_set": "geosite-cn",
				"outbound": "direct"
			  },
			  {
				"ip_is_private": true,
				"outbound": "direct"
			  },
			  {
				"rule_set": "geosite-geolocation-!cn",
				"outbound": "select"
			  }
			]
		  },
		  "ntp": {
			"enabled": true,
			"server": "time.apple.com",
			"server_port": 123,
			"interval": "30m",
			"detour": "direct"
		  }
		}`;
} 
  1. 点击下方生成 UUID 按钮,然后复制生成的字符串,替换代码第 7 行,让 userID = 生成的 UUID,然后点击 Deploy。

获取节点配置

完成部署后,使用你的 UUIDWorker 域名 替换如下字符串来获得分享链接

vless://UUID@www.visa.com.sg:8880?encryption=none&security=none&type=ws&host=Workers domain&path=%2F%3Fed%3D2048#Workers domain

例子:

> vless://60da4750-617a-42a3-97a2-8ccdc2b45589@www.visa.com.sg:8880?encryption=none&security=none&type=ws&host=freedom.wgx.workers.dev&path=%2F%3Fed%3D2048#freedom.wgx.workers.dev

2024-07-06 更新:

你可以访问你的 workers 域名 + /config 路径来获取配置链接。

e.g. https://freedom.wgx.workers.dev/config (这个网址应该是无效的)

如果你的网络无法打开 workers 域名,你可以使用 https://web.dijk.eu.org/ 这个在线代理工具来访问。

获得配置链接后,导入你的代理客户端,就可以开启科学上网之旅了。