• About
  • Disclaimer
  • Privacy Policy
  • Contact
Sunday, June 15, 2025
Cyber Defense GO
  • Login
  • Home
  • Cyber Security
  • Artificial Intelligence
  • Machine Learning
  • Data Analysis
  • Computer Networking
  • Disaster Restoration
No Result
View All Result
  • Home
  • Cyber Security
  • Artificial Intelligence
  • Machine Learning
  • Data Analysis
  • Computer Networking
  • Disaster Restoration
No Result
View All Result
Cyber Defense Go
No Result
View All Result
Home Computer Networking

Use V2rayN (V2ray Shopper) to Defend Your On-line Privateness & Bypass Web Censorship – 51 Safety

Md Sazzad Hossain by Md Sazzad Hossain
0
Use V2rayN (V2ray Shopper) to Defend Your On-line Privateness & Bypass Web Censorship – 51 Safety
585
SHARES
3.2k
VIEWS
Share on FacebookShare on Twitter

You might also like

Detailed Comparability » Community Interview

Addressing Vulnerabilities in Positioning, Navigation and Timing (PNT) Companies

Powering All Ethernet AI Networking


// model base on commit 5a112a0a0994b8bb834427ac84133501407f6413, time is 2024-10-11 04:49:19 UTC.
// @ts-ignore
import { join } from ‘cloudflare:sockets’;
// Tips on how to generate your individual UUID:
// [Windows] Press “Win + R”, enter cmd and run:  Powershell -NoExit -Command “https://www.51sec.org/?p=5022::NewGuid()”
let userID = ‘d342d11e-d424-4583-b36e-524ab1f0afa4’;
let proxyIP = ”;

if (!isValidUUID(userID)) {
throw new Error(‘uuid just isn’t legitimate’);
}
export default {
/**
* @param {import(“@cloudflare/workers-types”).Request} request
* @param {{UUID: string, PROXYIP: string}} env
* @param {import(“@cloudflare/workers-types”).ExecutionContext} ctx
* @returns {Promise}
*/
async fetch(request, env, ctx) {
strive {
userID = env.UUID || userID;
proxyIP = env.PROXYIP || proxyIP;
const upgradeHeader = request.headers.get(‘Improve’);
if (!upgradeHeader || upgradeHeader !== ‘websocket’) {
const url = new URL(request.url);
swap (url.pathname) {
case ‘/’:
return new Response(JSON.stringify(request.cf), { standing: 200 });
case `/${userID}`: {
const vlessConfig = getVLESSConfig(userID, request.headers.get(‘Host’));
return new Response(`${vlessConfig}`, {
standing: 200,
headers: {
“Content material-Sort”: “textual content/plain;charset=utf-8”,
}
});
}
default:
return new Response(‘Not discovered’, { standing: 404 });
}
} else {
return await vlessOverWSHandler(request);
}
} catch (err) {
/** @kind {Error} */ let e = err;
return new Response(e.toString());
}
},
};



/**
 * 
 * @param {import(“@cloudflare/workers-types”).Request} request
 */
async operate vlessOverWSHandler(request) {
/** @kind {import(“@cloudflare/workers-types”).WebSocket[]} */
// @ts-ignore
const webSocketPair = new WebSocketPair();
const [client, webSocket] = Object.values(webSocketPair);
webSocket.settle for();
let handle = ”;
let portWithRandomLog = ”;
const log = (/** @kind {string} */ data, /** @kind undefined */ occasion) => {
console.log(`[${address}:${portWithRandomLog}] ${data}`, occasion || ”);
};
const earlyDataHeader = request.headers.get(‘sec-websocket-protocol’) || ”;
const readableWebSocketStream = makeReadableWebSocketStream(webSocket, earlyDataHeader, log);
/** @kind { null}*/
let remoteSocketWapper = {
worth: null,
};
let udpStreamWrite = null;
let isDns = false;
// ws –> distant
readableWebSocketStream.pipeTo(new WritableStream({
async write(chunk, controller) {
if (isDns && udpStreamWrite) {
return udpStreamWrite(chunk);
}
if (remoteSocketWapper.worth) {
const author = remoteSocketWapper.worth.writable.getWriter()
await author.write(chunk);
author.releaseLock();
return;
}
const {
hasError,
message,
portRemote = 443,
addressRemote = ”,
rawDataIndex,
vlessVersion = new Uint8Array([0, 0]),
isUDP,
} = processVlessHeader(chunk, userID);
handle = addressRemote;
portWithRandomLog = `${portRemote}–${Math.random()} ${isUDP ? ‘udp ‘ : ‘tcp ‘
} `;
if (hasError) {
// controller.error(message);
throw new Error(message); // cf appears has bug, controller.error is not going to finish stream
// webSocket.shut(1000, message);
return;
}
// if UDP however port not DNS port, shut it
if (isUDP) {
if (portRemote === 53) {
isDns = true;
} else {
// controller.error(‘UDP proxy solely allow for DNS which is port 53’);
throw new Error(‘UDP proxy solely allow for DNS which is port 53’); // cf appears has bug, controller.error is not going to finish stream
return;
}
}
// [“version”, “附加信息长度 N”]
const vlessResponseHeader = new Uint8Array([vlessVersion[0], 0]);
const rawClientData = chunk.slice(rawDataIndex);
// TODO: help udp right here when cf runtime has udp help
if (isDns) {
const { write } = await handleUDPOutBound(webSocket, vlessResponseHeader, log);
udpStreamWrite = write;
udpStreamWrite(rawClientData);
return;
}
handleTCPOutBound(remoteSocketWapper, addressRemote, portRemote, rawClientData, webSocket, vlessResponseHeader, log);
},
shut() {
log(`readableWebSocketStream is shut`);
},
abort(motive) {
log(`readableWebSocketStream is abort`, JSON.stringify(motive));
},
})).catch((err) => {
log(‘readableWebSocketStream pipeTo error’, err);
});
return new Response(null, {
standing: 101,
// @ts-ignore
webSocket: shopper,
});
}
/**
 * Handles outbound TCP connections.
 *
 * @param {any} remoteSocket 
 * @param {string} addressRemote The distant handle to connect with.
 * @param {quantity} portRemote The distant port to connect with.
 * @param {Uint8Array} rawClientData The uncooked shopper information to write down.
 * @param {import(“@cloudflare/workers-types”).WebSocket} webSocket The WebSocket to go the distant socket to.
 * @param {Uint8Array} vlessResponseHeader The VLESS response header.
 * @param {operate} log The logging operate.
 * @returns {Promise} The distant socket.
 */
async operate handleTCPOutBound(remoteSocket, addressRemote, portRemote, rawClientData, webSocket, vlessResponseHeader, log,) {
async operate connectAndWrite(handle, port) {
/** @kind {import(“@cloudflare/workers-types”).Socket} */
const tcpSocket = join({
hostname: handle,
port: port,
});
remoteSocket.worth = tcpSocket;
log(`related to ${handle}:${port}`);
const author = tcpSocket.writable.getWriter();
await author.write(rawClientData); // first write, nomal is tls shopper good day
author.releaseLock();
return tcpSocket;
}
// if the cf join tcp socket don’t have any incoming information, we retry to redirect ip
async operate retry() {
const tcpSocket = await connectAndWrite(proxyIP || addressRemote, portRemote)
// irrespective of retry success or not, shut websocket
tcpSocket.closed.catch(error => {
console.log(‘retry tcpSocket closed error’, error);
}).lastly(() => {
safeCloseWebSocket(webSocket);
})
remoteSocketToWS(tcpSocket, webSocket, vlessResponseHeader, null, log);
}
const tcpSocket = await connectAndWrite(addressRemote, portRemote);
// when remoteSocket is prepared, go to websocket
// distant–> ws
remoteSocketToWS(tcpSocket, webSocket, vlessResponseHeader, retry, log);
}
/**
 * 
 * @param {import(“@cloudflare/workers-types”).WebSocket} webSocketServer
 * @param {string} earlyDataHeader for ws 0rtt
 * @param {(data: string)=> void} log for ws 0rtt
 */
operate makeReadableWebSocketStream(webSocketServer, earlyDataHeader, log) {
let readableStreamCancel = false;
const stream = new ReadableStream({
begin(controller) {
webSocketServer.addEventListener(‘message’, (occasion) => {
if (readableStreamCancel) {
return;
}
const message = occasion.information;
controller.enqueue(message);
});
// The occasion signifies that the shopper closed the shopper -> server stream.
// Nonetheless, the server -> shopper stream remains to be open till you name shut() on the server aspect.
// The WebSocket protocol says {that a} separate shut message have to be despatched in every path to totally shut the socket.
webSocketServer.addEventListener(‘shut’, () => {
// shopper ship shut, want shut server
// if stream is cancel, skip controller.shut
safeCloseWebSocket(webSocketServer);
if (readableStreamCancel) {
return;
}
controller.shut();
}
);
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 cease learn if stream is full, we are able to implement backpressure
// https://streams.spec.whatwg.org/#example-rs-push-backpressure
},
cancel(motive) {
// 1. pipe WritableStream has error, this cancel will referred to as, so ws deal with server shut into right here
// 2. if readableStream is cancel, all controller.shut/enqueue want skip,
// 3. however from testing controller.error nonetheless work even when readableStream is cancel
if (readableStreamCancel) {
return;
}
log(`ReadableStream was canceled, attributable to ${motive}`)
readableStreamCancel = true;
safeCloseWebSocket(webSocketServer);
}
});
return stream;
}
// https://xtls.github.io/improvement/protocols/vless.html
// https://github.com/zizifn/excalidraw-backup/blob/primary/v2ray-protocol.excalidraw
/**
 * 
 * @param { ArrayBuffer} vlessBuffer 
 * @param {string} userID 
 * @returns 
 */
operate processVlessHeader(
vlessBuffer,
userID
) {
if (vlessBuffer.byteLength < 24) {
return {
hasError: true,
message: ‘invalid information’,
};
}
const model = new Uint8Array(vlessBuffer.slice(0, 1));
let isValidUser = false;
let isUDP = false;
if (stringify(new Uint8Array(vlessBuffer.slice(1, 17))) === userID) {
isValidUser = true;
}
if (!isValidUser) {
return {
hasError: true,
message: ‘invalid person’,
};
}
const optLength = new Uint8Array(vlessBuffer.slice(17, 18))[0];
//skip go 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 ${command} just isn’t help, command 01-tcp,02-udp,03-mux`,
};
}
const portIndex = 18 + optLength + 1;
const portBuffer = vlessBuffer.slice(portIndex, portIndex + 2);
// port is big-Endian in uncooked information and so forth 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–> area title addressLength=addressBuffer[1]
// 3–> ipv6  addressLength =16
const addressType = addressBuffer[0];
let addressLength = 0;
let addressValueIndex = addressIndex + 1;
let addressValue = ”;
swap (addressType) {
case 1:
addressLength = 4;
addressValue = new Uint8Array(
vlessBuffer.slice(addressValueIndex, addressValueIndex + addressLength)
).be a part of(‘.’);
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.be a part of(‘:’);
// appears no want add [] for ipv6
break;
default:
return {
hasError: true,
message: `invild  addressType is ${addressType}`,
};
}
if (!addressValue) {
return {
hasError: true,
message: `addressValue is empty, addressType is ${addressType}`,
};
}
return {
hasError: false,
addressRemote: addressValue,
addressType,
portRemote,
rawDataIndex: addressValueIndex + addressLength,
vlessVersion: model,
isUDP,
};
}

/**
 * 
 * @param {import(“@cloudflare/workers-types”).Socket} remoteSocket 
 * @param {import(“@cloudflare/workers-types”).WebSocket} webSocket 
 * @param {ArrayBuffer} vlessResponseHeader 
 * @param null retry
 * @param {*} log 
 */
async operate remoteSocketToWS(remoteSocket, webSocket, vlessResponseHeader, retry, log) {
// distant–> ws
let remoteChunkCount = 0;
let chunks = [];
/** @kind null */
let vlessHeader = vlessResponseHeader;
let hasIncomingData = false; // examine if remoteSocket has incoming information
await remoteSocket.readable
.pipeTo(
new WritableStream({
begin() {
},
/**
* 
* @param {Uint8Array} chunk 
* @param {*} controller 
*/
async write(chunk, controller) {
hasIncomingData = true;
// remoteChunkCount++;
if (webSocket.readyState !== WS_READY_STATE_OPEN) {
controller.error(
‘webSocket.readyState just isn’t open, perhaps shut’
);
}
if (vlessHeader) {
webSocket.ship(await new Blob([vlessHeader, chunk]).arrayBuffer());
vlessHeader = null;
} else {
// appears no want price restrict this, CF appears repair this??..
// if (remoteChunkCount > 20000) {
// // cf one package deal is 4096 byte(4kb),  4096 * 20000 = 80M
// await delay(1);
// }
webSocket.ship(chunk);
}
},
shut() {
log(`remoteConnection!.readable is shut with hasIncomingData is ${hasIncomingData}`);
// safeCloseWebSocket(webSocket); // no want server shut websocket frist for some case will casue HTTP ERR_CONTENT_LENGTH_MISMATCH challenge, shopper will ship shut occasion anyway.
},
abort(motive) {
console.error(`remoteConnection!.readable abort`, motive);
},
})
)
.catch((error) => error
);
safeCloseWebSocket(webSocket);
);
// appears is cf join socket have error,
// 1. Socket.closed may have error
// 2. Socket.readable might be shut with none information coming
if (hasIncomingData === false && retry) {
log(`retry`)
retry();
}
}
/**
 * 
 * @param {string} base64Str 
 * @returns 
 */
operate base64ToArrayBuffer(base64Str) {
if (!base64Str) {
return { error: null };
}
strive {
// go use modified Base64 for URL rfc4648 which js atob not help
base64Str = base64Str.change(/-/g, ‘+’).change(/_/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 isn’t actual UUID validation
 * @param {string} uuid 
 */
operate 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.check(uuid);
}
const WS_READY_STATE_OPEN = 1;
const WS_READY_STATE_CLOSING = 2;
/**
 * Usually, WebSocket is not going to has exceptions when shut.
 * @param {import(“@cloudflare/workers-types”).WebSocket} socket
 */
operate safeCloseWebSocket(socket) {
strive {
if (socket.readyState === WS_READY_STATE_OPEN || socket.readyState === WS_READY_STATE_CLOSING) {
socket.shut();
}
} catch (error) {
console.error(‘safeCloseWebSocket error’, error);
}
}
const byteToHex = [];
for (let i = 0; i < 256; ++i) {
byteToHex.push((i + 256).toString(16).slice(1));
}
operate 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();
}
operate 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 operate handleUDPOutBound(webSocket, vlessResponseHeader, log) {
let isVlessHeaderSent = false;
const transformStream = new TransformStream({
begin(controller) {
},
rework(chunk, controller) {
// udp message 2 byte is the the size of udp information
// TODO: this could have bug, beacsue perhaps udp chunk may 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) {
}
});
// solely deal with dns udp for now
transformStream.readable.pipeTo(new WritableStream({
async write(chunk) {
const resp = await fetch(‘https://1.1.1.1/dns-query’,
{
methodology: ‘POST’,
headers: {
‘content-type’: ‘utility/dns-message’,
},
physique: 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 size is ${udpSize}`);
if (isVlessHeaderSent) {
webSocket.ship(await new Blob([udpSizeBuffer, dnsQueryResult]).arrayBuffer());
} else {
webSocket.ship(await new Blob([vlessResponseHeader, udpSizeBuffer, dnsQueryResult]).arrayBuffer());
isVlessHeaderSent = true;
}
}
}
})).catch((error) => {
log(‘dns udp has error’ + error)
});
const author = transformStream.writable.getWriter();
return {
/**
* 
* @param {Uint8Array} chunk 
*/
write(chunk) {
author.write(chunk);
}
};
}
/**
 * 
 * @param {string} userID 
 * @param null hostName
 * @returns {string}
 */
operate getVLESSConfig(userID, hostName) {
const vlessMain = `vless://${userID}u0040${hostName}:443?encryption=none&safety=tls&sni=${hostName}&fp=randomized&kind=ws&host=${hostName}&path=%2Fpercent3Fedpercent3D2048#${hostName}`
return `
################################################################
v2ray
—————————————————————
${vlessMain}
—————————————————————
################################################################
clash-meta
—————————————————————
– kind: vless
  title: ${hostName}
  server: ${hostName}
  port: 443
  uuid: ${userID}
  community: ws
  tls: true
  udp: false
  sni: ${hostName}
  client-fingerprint: chrome
  ws-opts:
    path: “/?ed=2048”
    headers:
      host: ${hostName}
—————————————————————
################################################################
`;
}

Tags: BypassCensorshipClientInternetOnlinePrivacyProtectSecurityV2rayV2rayN
Previous Post

What’s MERN Stack: All the things You Have to Know?

Next Post

The Way forward for Enterprise Connectivity: Wi-Fi 7 and OpenRoaming

Md Sazzad Hossain

Md Sazzad Hossain

Related Posts

Detailed Comparability » Community Interview
Computer Networking

Detailed Comparability » Community Interview

by Md Sazzad Hossain
June 15, 2025
Addressing Vulnerabilities in Positioning, Navigation and Timing (PNT) Companies
Computer Networking

Addressing Vulnerabilities in Positioning, Navigation and Timing (PNT) Companies

by Md Sazzad Hossain
June 14, 2025
Powering All Ethernet AI Networking
Computer Networking

Powering All Ethernet AI Networking

by Md Sazzad Hossain
June 14, 2025
5G is Shifting Downstream to Enterprises
Computer Networking

5G is Shifting Downstream to Enterprises

by Md Sazzad Hossain
June 14, 2025
That is Extending to GreenOps – IT Connection
Computer Networking

AWS Summit Sydney – Accelerating AI from Prospects to Manufacturing – IT Connection

by Md Sazzad Hossain
June 13, 2025
Next Post
The Way forward for Enterprise Connectivity: Wi-Fi 7 and OpenRoaming

The Way forward for Enterprise Connectivity: Wi-Fi 7 and OpenRoaming

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recommended

Triangle Forecasting: Why Conventional Affect Estimates Are Inflated (And The best way to Repair Them)

Triangle Forecasting: Why Conventional Affect Estimates Are Inflated (And The best way to Repair Them)

February 9, 2025
DPRK Hackers Exploit LinkedIn to Infect Builders with Infostealers

DPRK Hackers Exploit LinkedIn to Infect Builders with Infostealers

April 15, 2025

Categories

  • Artificial Intelligence
  • Computer Networking
  • Cyber Security
  • Data Analysis
  • Disaster Restoration
  • Machine Learning

CyberDefenseGo

Welcome to CyberDefenseGo. We are a passionate team of technology enthusiasts, cybersecurity experts, and AI innovators dedicated to delivering high-quality, insightful content that helps individuals and organizations stay ahead of the ever-evolving digital landscape.

Recent

Predicting Insurance coverage Prices with Linear Regression

Predicting Insurance coverage Prices with Linear Regression

June 15, 2025
Detailed Comparability » Community Interview

Detailed Comparability » Community Interview

June 15, 2025

Search

No Result
View All Result

© 2025 CyberDefenseGo - All Rights Reserved

No Result
View All Result
  • Home
  • Cyber Security
  • Artificial Intelligence
  • Machine Learning
  • Data Analysis
  • Computer Networking
  • Disaster Restoration

© 2025 CyberDefenseGo - All Rights Reserved

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In