diff --git a/_worker.js b/_worker.js index a0e0154..a7cecfb 100644 --- a/_worker.js +++ b/_worker.js @@ -113,7 +113,12 @@ export default { return new Response(`${fakeConfig}`, { status: 200 }); case `/${userID}`: { await sendMessage(`#获取订阅 ${FileName}`, request.headers.get('CF-Connecting-IP'), `UA: ${UA}\n域名: ${url.hostname}\n入口: ${url.pathname + url.search}`); - if ((!sub || sub == '') && (addresses.length + addressesapi.length + addressesnotls.length + addressesnotlsapi.length + addressescsv.length) == 0) sub = 'vless-4ca.pages.dev'; + 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'; + } const vlessConfig = await getVLESSConfig(userID, request.headers.get('Host'), sub, UA, RproxyIP, url); const now = Date.now(); //const timestamp = Math.floor(now / 1000); @@ -204,7 +209,7 @@ export default { }; /** - * + * 处理 VLESS over WebSocket 的请求 * @param {import("@cloudflare/workers-types").Request} request */ async function vlessOverWSHandler(request) { @@ -214,36 +219,45 @@ async function vlessOverWSHandler(request) { 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(`[${address}:${portWithRandomLog}] ${info}`, 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; - // ws --> remote + // 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, @@ -254,44 +268,47 @@ async function vlessOverWSHandler(request) { vlessVersion = new Uint8Array([0, 0]), isUDP, } = processVlessHeader(chunk, userID); + // 设置地址和端口信息,用于日志 address = addressRemote; - portWithRandomLog = `${portRemote}--${Math.random()} ${isUDP ? 'udp ' : 'tcp ' - } `; + portWithRandomLog = `${portRemote}--${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); + // 如果有错误,抛出异常 + throw new Error(message); return; } - // if UDP but port not DNS port, close it + // 如果是 UDP 且端口不是 DNS 端口(53),则关闭连接 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 + throw new Error('UDP 代理仅对 DNS(53 端口)启用'); return; } } - // ["version", "附加信息长度 N"] + // 构建 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 出站连接 ${addressRemote}:${portRemote}`); handleTCPOutBound(remoteSocketWapper, addressType, addressRemote, portRemote, rawClientData, webSocket, vlessResponseHeader, log); }, close() { - log(`readableWebSocketStream is close`); + log(`readableWebSocketStream 已关闭`); }, abort(reason) { - log(`readableWebSocketStream is abort`, JSON.stringify(reason)); + log(`readableWebSocketStream 已中止`, JSON.stringify(reason)); }, })).catch((err) => { - log('readableWebSocketStream pipeTo error', err); + log('readableWebSocketStream 管道错误', err); }); + // 返回一个 WebSocket 升级的响应 return new Response(null, { status: 101, // @ts-ignore @@ -300,155 +317,203 @@ async function vlessOverWSHandler(request) { } /** - * Handles outbound TCP connections. + * 处理出站 TCP 连接。 * - * @param {any} remoteSocket - * @param {number} addressType The remote address type to connect to. - * @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} The remote socket. + * @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} 异步操作的 Promise */ async function handleTCPOutBound(remoteSocket, addressType, addressRemote, portRemote, rawClientData, webSocket, vlessResponseHeader, log,) { + /** + * 连接远程服务器并写入数据 + * @param {string} address 要连接的地址 + * @param {number} port 要连接的端口 + * @param {boolean} socks 是否使用 SOCKS5 代理连接 + * @returns {Promise} 连接后的 TCP Socket + */ async function connectAndWrite(address, port, socks = false) { /** @type {import("@cloudflare/workers-types").Socket} */ + log(`connected to ${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==')}${address}${atob('LmlwLjA5MDIyNy54eXo=')}`; + // 如果指定使用 SOCKS5 代理,则通过 SOCKS5 协议连接;否则直接连接 const tcpSocket = socks ? await socks5Connect(addressType, address, port, log) : connect({ hostname: address, port: port, }); remoteSocket.value = tcpSocket; - log(`connected to ${address}:${port}`); + //log(`connected to ${address}:${port}`); const writer = tcpSocket.writable.getWriter(); - await writer.write(rawClientData); // first write, normal is tls client hello + // 首次写入,通常是 TLS 客户端 Hello 消息 + await writer.write(rawClientData); writer.releaseLock(); return tcpSocket; } - // if the cf connect tcp socket have no incoming data, we retry to redirect ip + /** + * 重试函数:当 Cloudflare 的 TCP Socket 没有传入数据时,我们尝试重定向 IP + * 这可能是因为某些网络问题导致的连接失败 + */ async function retry() { if (enableSocks) { + // 如果启用了 SOCKS5,通过 SOCKS5 代理重试连接 tcpSocket = await connectAndWrite(addressRemote, portRemote, true); } else { + // 否则,尝试使用预设的代理 IP(如果有)或原始地址重试连接 tcpSocket = await connectAndWrite(proxyIP || addressRemote, portRemote); } - // no matter retry success or not, close websocket + // 无论重试是否成功,都要关闭 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); - // when remoteSocket is ready, pass to websocket - // remote--> ws + // 当远程 Socket 就绪时,将其传递给 WebSocket + // 建立从远程服务器到 WebSocket 的数据流,用于将远程服务器的响应发送回客户端 + // 如果连接失败或无数据,retry 函数将被调用进行重试 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 + * 将 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); }); - // 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. + // 监听 WebSocket 的关闭事件 + // 注意:这个事件意味着客户端关闭了客户端 -> 服务器的流 + // 但是,服务器 -> 客户端的流仍然打开,直到在服务器端调用 close() + // WebSocket 协议要求在每个方向上都要发送单独的关闭消息,以完全关闭 Socket webSocketServer.addEventListener('close', () => { - // client send close, need close server - // if stream is cancel, skip controller.close + // 客户端发送了关闭信号,需要关闭服务器端 safeCloseWebSocket(webSocketServer); + // 如果流未被取消,则关闭控制器 if (readableStreamCancel) { return; } controller.close(); - } - ); + }); + + // 监听 WebSocket 的错误事件 webSocketServer.addEventListener('error', (err) => { - log('webSocketServer has error'); + log('WebSocket 服务器发生错误'); + // 将错误传递给控制器 controller.error(err); - } - ); - // for ws 0rtt + }); + + // 处理 WebSocket 0-RTT(零往返时间)的早期数据 + // 0-RTT 允许在完全建立连接之前发送数据,提高了效率 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 + // 这里可以实现反压机制 + // 如果 WebSocket 可以在流满时停止读取,我们就可以实现反压 + // 参考: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 + // 流被取消的几种情况: + // 1. 当管道的 WritableStream 有错误时,这个取消函数会被调用,所以在这里处理 WebSocket 服务器的关闭 + // 2. 如果 ReadableStream 被取消,所有 controller.close/enqueue 都需要跳过 + // 3. 但是经过测试,即使 ReadableStream 被取消,controller.error 仍然有效 if (readableStreamCancel) { return; } - log(`ReadableStream was canceled, due to ${reason}`) + log(`可读流被取消,原因是 ${reason}`); 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 /** - * - * @param { ArrayBuffer} vlessBuffer - * @param {string} userID - * @returns + * 解析 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', + message: `invalid user ${(new Uint8Array(vlessBuffer.slice(1, 17)))}`, }; } + // 获取附加选项的长度(第 17 个字节) const optLength = new Uint8Array(vlessBuffer.slice(17, 18))[0]; - //skip opt for now + // 暂时跳过附加选项 + // 解析命令(紧跟在选项之后的 1 个字节) + // 0x01: TCP, 0x02: UDP, 0x03: MUX(多路复用) const command = new Uint8Array( vlessBuffer.slice(18 + optLength, 18 + optLength + 1) )[0]; @@ -457,53 +522,64 @@ function processVlessHeader(vlessBuffer, userID) { // 0x02 UDP // 0x03 MUX if (command === 1) { + // TCP 命令,不需特殊处理 } else if (command === 2) { + // UDP 命令 isUDP = true; } else { + // 不支持的命令 return { hasError: true, message: `command ${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 addressLength =4 - // 2--> domain name addressLength=addressBuffer[1] - // 3--> ipv6 addressLength =16 + // 地址类型: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) ); - // 2001:0db8:85a3:0000:0000:8a2e:0370:7334 + // 每 2 字节构成 IPv6 地址的一部分 const ipv6 = []; for (let i = 0; i < 8; i++) { ipv6.push(dataView.getUint16(i * 2).toString(16)); @@ -512,11 +588,14 @@ function processVlessHeader(vlessBuffer, userID) { // seems no need add [] for ipv6 break; default: + // 无效的地址类型 return { hasError: true, - message: `invild addressType is ${addressType}`, + message: `invild addressType is ${addressType}`, }; } + + // 确保地址不为空 if (!addressValue) { return { hasError: true, @@ -524,56 +603,67 @@ function processVlessHeader(vlessBuffer, userID) { }; } + // 返回解析结果 return { hasError: false, - addressRemote: addressValue, - addressType, - portRemote, - rawDataIndex: addressValueIndex + addressLength, - vlessVersion: version, - isUDP, + addressRemote: addressValue, // 解析后的远程地址 + addressType, // 地址类型 + portRemote, // 远程端口 + rawDataIndex: addressValueIndex + addressLength, // 原始数据的实际起始位置 + vlessVersion: version, // VLESS 协议版本 + isUDP, // 是否是 UDP 请求 }; } /** + * 将远程 Socket 的数据转发到 WebSocket * - * @param {import("@cloudflare/workers-types").Socket} remoteSocket - * @param {import("@cloudflare/workers-types").WebSocket} webSocket - * @param {ArrayBuffer} vlessResponseHeader - * @param {(() => Promise) | null} retry - * @param {*} log + * @param {import("@cloudflare/workers-types").Socket} remoteSocket 远程服务器的 Socket 连接 + * @param {import("@cloudflare/workers-types").WebSocket} webSocket 客户端的 WebSocket 连接 + * @param {ArrayBuffer} vlessResponseHeader VLESS 协议的响应头部 + * @param {(() => Promise) | null} retry 重试函数,当没有数据时调用 + * @param {*} log 日志函数 */ async function remoteSocketToWS(remoteSocket, webSocket, vlessResponseHeader, retry, log) { - // remote--> ws + // 将数据从远程服务器转发到 WebSocket let remoteChunkCount = 0; let chunks = []; /** @type {ArrayBuffer | null} */ let vlessHeader = vlessResponseHeader; - let hasIncomingData = false; // check if remoteSocket has incoming data + let hasIncomingData = false; // 检查远程 Socket 是否有传入数据 + + // 使用管道将远程 Socket 的可读流连接到一个可写流 await remoteSocket.readable .pipeTo( new WritableStream({ start() { + // 初始化时不需要任何操作 }, /** - * - * @param {Uint8Array} chunk - * @param {*} controller + * 处理每个数据块 + * @param {Uint8Array} chunk 数据块 + * @param {*} controller 控制器 */ async write(chunk, controller) { - hasIncomingData = true; - // remoteChunkCount++; + 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; + vlessHeader = null; // 清空头部,之后不再发送 } else { - // seems no need rate limit this, CF seems fix this??.. + // 直接发送数据块 + // 以前这里有流量控制代码,限制大量数据的发送速率 + // 但现在 Cloudflare 似乎已经修复了这个问题 // if (remoteChunkCount > 20000) { // // cf one package is 4096 byte(4kb), 4096 * 20000 = 80M // await delay(1); @@ -582,157 +672,228 @@ async function remoteSocketToWS(remoteSocket, webSocket, vlessResponseHeader, re } }, close() { + // 当远程连接的可读流关闭时 log(`remoteConnection!.readable is close with hasIncomingData is ${hasIncomingData}`); - // 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. + // 不需要主动关闭 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); }); - // seems is cf connect socket have error, - // 1. Socket.closed will have error - // 2. Socket.readable will be close without any data coming + // 处理 Cloudflare 连接 Socket 的特殊错误情况 + // 1. Socket.closed 将有错误 + // 2. Socket.readable 将关闭,但没有任何数据 if (hasIncomingData === false && retry) { - log(`retry`) - retry(); + log(`retry`); + retry(); // 调用重试函数,尝试重新建立连接 } } /** + * 将 Base64 编码的字符串转换为 ArrayBuffer * - * @param {string} base64Str - * @returns + * @param {string} base64Str Base64 编码的输入字符串 + * @returns {{ earlyData: ArrayBuffer | undefined, error: Error | null }} 返回解码后的 ArrayBuffer 或错误 */ function base64ToArrayBuffer(base64Str) { + // 如果输入为空,直接返回空结果 if (!base64Str) { return { error: null }; } try { - // go use modified Base64 for URL rfc4648 which js atob not support + // 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 }; } } /** - * This is not real UUID validation - * @param {string} uuid + * 这不是真正的 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); } -const WS_READY_STATE_OPEN = 1; -const WS_READY_STATE_CLOSING = 2; +// WebSocket 的两个重要状态常量 +const WS_READY_STATE_OPEN = 1; // WebSocket 处于开放状态,可以发送和接收消息 +const WS_READY_STATE_CLOSING = 2; // WebSocket 正在关闭过程中 + /** - * Normally, WebSocket will not has exceptions when close. - * @param {import("@cloudflare/workers-types").WebSocket} socket + * 安全地关闭 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) { - 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 格式 + // 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("Stringified UUID is invalid"); + throw TypeError(`生成的 UUID 不符合规范 ${uuid}`); + //uuid = userID; } return uuid; } /** - * - * @param {ArrayBuffer} udpChunk - * @param {import("@cloudflare/workers-types").WebSocket} webSocket - * @param {ArrayBuffer} vlessResponseHeader - * @param {(string)=> void} log + * 处理 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) { - // no matter which DNS server client send, we alwasy use hard code one. - // beacsue someof DNS server is not support DNS over TCP - try { - const dnsServer = '8.8.4.4'; // change to 1.1.1.1 after cf fix connect own ip bug - const dnsPort = 53; - /** @type {ArrayBuffer | null} */ - let vlessHeader = vlessResponseHeader; - /** @type {import("@cloudflare/workers-types").Socket} */ - const tcpSocket = connect({ - hostname: dnsServer, - port: dnsPort, - }); + // 无论客户端发送到哪个 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 服务的标准端口 - log(`connected to ${dnsServer}:${dnsPort}`); - const writer = tcpSocket.writable.getWriter(); - await writer.write(udpChunk); - writer.releaseLock(); - await tcpSocket.readable.pipeTo(new WritableStream({ - async write(chunk) { - if (webSocket.readyState === WS_READY_STATE_OPEN) { - if (vlessHeader) { - webSocket.send(await new Blob([vlessHeader, chunk]).arrayBuffer()); - vlessHeader = null; - } else { - webSocket.send(chunk); - } - } - }, - close() { - log(`dns server(${dnsServer}) tcp is close`); - }, - abort(reason) { - console.error(`dns server(${dnsServer}) tcp is abort`, reason); - }, - })); - } catch (error) { - console.error( - `handleDNSQuery have exception, error: ${error.message}` - ); - } + /** @type {ArrayBuffer | null} */ + let vlessHeader = vlessResponseHeader; // 保存 VLESS 响应头部,用于后续发送 + + /** @type {import("@cloudflare/workers-types").Socket} */ + // 与指定的 DNS 服务器建立 TCP 连接 + const tcpSocket = connect({ + hostname: dnsServer, + port: dnsPort, + }); + + log(`连接到 ${dnsServer}:${dnsPort}`); // 记录连接信息 + 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 服务器(${dnsServer}) TCP 连接已关闭`); // 记录连接关闭信息 + }, + abort(reason) { + console.error(`DNS 服务器(${dnsServer}) TCP 连接异常中断`, reason); // 记录异常中断原因 + }, + })); + } catch (error) { + // 捕获并记录任何可能发生的错误 + console.error( + `handleDNSQuery 函数发生异常,错误信息: ${error.message}` + ); + } } /** - * - * @param {number} addressType - * @param {string} addressRemote - * @param {number} portRemote - * @param {function} log The logging function. + * 建立 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; - // Connect to the SOCKS server + // 连接到 SOCKS5 代理服务器 const socket = connect({ - hostname, - port, + hostname, // SOCKS5 服务器的主机名 + port, // SOCKS5 服务器的端口 }); - // Request head format (Worker -> Socks Server): + // 请求头格式(Worker -> SOCKS5 服务器): // +----+----------+----------+ // |VER | NMETHODS | METHODS | // +----+----------+----------+ @@ -740,115 +901,119 @@ async function socks5Connect(addressType, addressRemote, portRemote, log) { // +----+----------+----------+ // https://en.wikipedia.org/wiki/SOCKS#SOCKS5 - // For METHODS: - // 0x00 NO AUTHENTICATION REQUIRED - // 0x02 USERNAME/PASSWORD https://datatracker.ietf.org/doc/html/rfc1929 + // 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('sent socks greeting'); + log('已发送 SOCKS5 问候消息'); const reader = socket.readable.getReader(); const encoder = new TextEncoder(); let res = (await reader.read()).value; - // Response format (Socks Server -> Worker): + // 响应格式(SOCKS5 服务器 -> Worker): // +----+--------+ // |VER | METHOD | // +----+--------+ // | 1 | 1 | // +----+--------+ if (res[0] !== 0x05) { - log(`socks server version error: ${res[0]} expected: 5`); + log(`SOCKS5 服务器版本错误: 收到 ${res[0]},期望是 5`); return; } if (res[1] === 0xff) { - log("no acceptable methods"); + log("服务器不接受任何认证方法"); return; } - // if return 0x0502 + // 如果返回 0x0502,表示需要用户名/密码认证 if (res[1] === 0x02) { - log("socks server needs auth"); + log("SOCKS5 服务器需要认证"); if (!username || !password) { - log("please provide 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) + 1, // 认证子协议版本 + username.length, // 用户名长度 + ...encoder.encode(username), // 用户名 + password.length, // 密码长度 + ...encoder.encode(password) // 密码 ]); await writer.write(authRequest); res = (await reader.read()).value; - // expected 0x0100 + // 期望返回 0x0100 表示认证成功 if (res[0] !== 0x01 || res[1] !== 0x00) { - log("fail to auth socks server"); + log("SOCKS5 服务器认证失败"); return; } } - // Request data format (Worker -> Socks Server): + // 请求数据格式(Worker -> SOCKS5 服务器): // +----+-----+-------+------+----------+----------+ // |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT | // +----+-----+-------+------+----------+----------+ // | 1 | 1 | X'00' | 1 | Variable | 2 | // +----+-----+-------+------+----------+----------+ - // ATYP: address type of following address - // 0x01: IPv4 address - // 0x03: Domain name - // 0x04: IPv6 address - // DST.ADDR: desired destination address - // DST.PORT: desired destination port in network octet order + // ATYP: 地址类型 + // 0x01: IPv4 地址 + // 0x03: 域名 + // 0x04: IPv6 地址 + // DST.ADDR: 目标地址 + // DST.PORT: 目标端口(网络字节序) // addressType - // 1--> ipv4 addressLength =4 - // 2--> domain name - // 3--> ipv6 addressLength =16 + // 1 --> IPv4 地址长度 = 4 + // 2 --> 域名 + // 3 --> IPv6 地址长度 = 16 let DSTADDR; // DSTADDR = ATYP + DST.ADDR switch (addressType) { - case 1: + case 1: // IPv4 DSTADDR = new Uint8Array( [1, ...addressRemote.split('.').map(Number)] ); break; - case 2: + case 2: // 域名 DSTADDR = new Uint8Array( [3, addressRemote.length, ...encoder.encode(addressRemote)] ); break; - case 3: + 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(`invild addressType is ${addressType}`); + log(`无效的地址类型: ${addressType}`); 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('sent socks request'); + log('已发送 SOCKS5 请求'); res = (await reader.read()).value; - // Response format (Socks Server -> Worker): + // 响应格式(SOCKS5 服务器 -> Worker): // +----+-----+-------+------+----------+----------+ // |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT | // +----+-----+-------+------+----------+----------+ // | 1 | 1 | X'00' | 1 | Variable | 2 | // +----+-----+-------+------+----------+----------+ if (res[1] === 0x00) { - log("socks connection opened"); + log("SOCKS5 连接已建立"); } else { - log("fail to open socks connection"); + log("SOCKS5 连接建立失败"); return; } writer.releaseLock(); @@ -858,67 +1023,125 @@ async function socks5Connect(addressType, addressRemote, portRemote, log) { /** + * SOCKS5 代理地址解析器 + * 此函数用于解析 SOCKS5 代理地址字符串,提取出用户名、密码、主机名和端口号 * - * @param {string} address + * @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('Invalid SOCKS address format'); + throw new Error('无效的 SOCKS 地址格式:认证部分必须是 "username:password" 的形式'); } [username, password] = formers; } + + // 解析服务器地址部分 const latters = latter.split(":"); + // 从末尾提取端口号(因为 IPv6 地址中也包含冒号) port = Number(latters.pop()); if (isNaN(port)) { - throw new Error('Invalid SOCKS address format'); + 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('Invalid SOCKS address format'); + 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==')}${hostname}${atob('LmlwLjA5MDIyNy54eXo=')}`; + // 返回解析后的结果 return { - username, - password, - hostname, - port, + 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解码 - content = content.replace(new RegExp(fakeUserID, 'g'), userID).replace(new RegExp(fakeHostName, 'g'), hostName); - if (isBase64) content = btoa(content);//Base64编码 - + 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} 双重哈希后的小写十六进制字符串 + */ 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(); + return secondHex.toLowerCase(); // 返回小写的十六进制字符串 } +/** + * 解析并清理环境变量中的地址列表 + * 这个函数用于处理包含多个地址的环境变量 + * 它会移除所有的空白字符、引号等,并将地址列表转换为数组 + * + * @param {string} envadd 包含地址列表的环境变量值 + * @returns {Promise} 清理和分割后的地址数组 + */ async function ADD(envadd) { - var addtext = envadd.replace(/[ |"'\r\n]+/g, ',').replace(/,+/g, ','); // 将双引号、单引号和换行符替换为逗号 - //console.log(addtext); + // 将制表符、双引号、单引号和换行符都替换为逗号 + // 然后将连续的多个逗号替换为单个逗号 + 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); + if (addtext.charAt(addtext.length - 1) == ',') addtext = addtext.slice(0, addtext.length - 1); + + // 使用逗号分割字符串,得到地址数组 const add = addtext.split(','); - //console.log(add); - return add ; + + return add; } const 啥啥啥_写的这是啥啊 = 'dmxlc3M='; @@ -978,7 +1201,30 @@ async function getVLESSConfig(userID, hostName, sub, UA, RproxyIP, _url) { const Config = 配置信息(userID , hostName); const v2ray = Config[0]; const clash = Config[1]; - // 如果sub为空,则显示原始内容 + 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 订阅器 = `您的订阅内容由 ${sub} 提供维护支持, 自动获取ProxyIP: ${RproxyIP}`; if (!sub || sub == '') { @@ -995,19 +1241,19 @@ async function getVLESSConfig(userID, hostName, sub, UA, RproxyIP, _url) { Subscribe / sub 订阅地址, 支持 Base64、clash-meta、sing-box 订阅格式, ${订阅器} --------------------------------------------------------------- 快速自适应订阅地址: -https://${hostName}/${userID} +https://${proxyhost}${hostName}/${userID} Base64订阅地址: -https://${hostName}/${userID}?sub -https://${hostName}/${userID}?b64 -https://${hostName}/${userID}?base64 +https://${proxyhost}${hostName}/${userID}?sub +https://${proxyhost}${hostName}/${userID}?b64 +https://${proxyhost}${hostName}/${userID}?base64 clash订阅地址: -https://${hostName}/${userID}?clash +https://${proxyhost}${hostName}/${userID}?clash singbox订阅地址: -https://${hostName}/${userID}?sb -https://${hostName}/${userID}?singbox +https://${proxyhost}${hostName}/${userID}?sb +https://${proxyhost}${hostName}/${userID}?singbox --------------------------------------------------------------- ################################################################ v2ray