init cf worker code

This commit is contained in:
etfans 2023-05-28 00:54:56 +08:00
parent 04e25f5130
commit b7e037de56
20 changed files with 18244 additions and 0 deletions

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
.DS_Store
/node_modules
*-lock.*
*.lock
*.log

View File

@ -0,0 +1,72 @@
{
"log": {
"loglevel": "debug"
},
"inbounds": [
{
"listen": "0.0.0.0",
"port": "4080",
"protocol": "socks",
"settings": {
"auth": "noauth",
"udp": true,
"ip": "0.0.0.0"
}
},
{
"listen": "0.0.0.0",
"port": "4081",
"protocol": "http"
}
],
"dns": {
"servers": ["8.8.8.8"]
},
"outbounds": [
{
"protocol": "vless",
"settings": {
"vnext": [
{
"address": "127.0.0.1",
"port": 8788,
"users": [
{
"id": "1a403b79-039b-4dc2-9b45-1ad13197b99a",
"encryption": "none",
"level": 0
}
]
}
]
},
"streamSettings": {
"network": "ws",
"wsSettings": {
"path": "/vless"
}
// "security": "tls"
},
"tag": "zizi-ws"
},
{
"protocol": "freedom",
"tag": "direct"
}
],
"routing": {
"domainStrategy": "IPIfNonMatch",
"rules": [
{
"type": "field",
"ip": ["8.8.8.8"],
"outboundTag": "zizi-ws"
},
{
"type": "field",
"ip": ["geoip:private"],
"outboundTag": "zizi-ws"
}
]
}
}

View File

@ -0,0 +1,72 @@
{
"log": {
"loglevel": "debug"
},
"inbounds": [
{
"listen": "0.0.0.0",
"port": "4080",
"protocol": "socks",
"settings": {
"auth": "noauth",
"udp": true,
"ip": "0.0.0.0"
}
},
{
"listen": "0.0.0.0",
"port": "4081",
"protocol": "http"
}
],
"dns": {
"servers": ["8.8.8.8"]
},
"outbounds": [
{
"protocol": "vless",
"settings": {
"vnext": [
{
"address": "127.0.0.1",
"port": 8787,
"users": [
{
"id": "1a403b79-039b-4dc2-9b45-1ad13197b99a",
"encryption": "none",
"level": 0
}
]
}
]
},
"streamSettings": {
"network": "ws"
// "wsSettings": {
// "path": "/node-vless"
// }
// "security": "tls"
},
"tag": "zizi-ws"
},
{
"protocol": "freedom",
"tag": "direct"
}
],
"routing": {
"domainStrategy": "IPIfNonMatch",
"rules": [
{
"type": "field",
"ip": ["8.8.8.8"],
"outboundTag": "zizi-ws"
},
{
"type": "field",
"ip": ["geoip:private"],
"outboundTag": "zizi-ws"
}
]
}
}

1
dist/README.md vendored Normal file
View File

@ -0,0 +1 @@
This folder contains the built output assets for the worker "cf-worker-ws-dev" generated at 2023-05-26T18:01:56.750Z.

2971
dist/cidr.js vendored Normal file

File diff suppressed because it is too large Load Diff

8
dist/cidr.js.map vendored Normal file

File diff suppressed because one or more lines are too long

16
jsonconfig.json Normal file
View File

@ -0,0 +1,16 @@
{
"compilerOptions": {
"noEmit": true,
"module": "esnext",
"target": "ES2022",
"lib": ["ES2022"],
"strict": true,
"alwaysStrict": true,
"preserveConstEnums": true,
"moduleResolution": "node",
"sourceMap": true,
"types": ["@cloudflare/workers-types"]
},
"include": ["src"],
"exclude": ["node_modules", "dist", "test"]
}

21
package.json Normal file
View File

@ -0,0 +1,21 @@
{
"name": "edgetunnel",
"version": "1.0.0",
"description": "Delete code, but keep the project for the sake of memories. I'm only create this project for fun, for try new things and for learn by doing. **I'm even not write any outside marketing post for this project. Just for my own fun...** But I feel emotional damage by the community.",
"main": "index.js",
"scripts": {
"deploy": "wrangler deploy",
"dev-vless": "wrangler dev src/worker-vless.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@cloudflare/workers-types": "^4.20230518.0",
"wrangler": "^3.0.1"
},
"dependencies": {
"ip-cidr": "^3.1.0",
"ip-range-check": "^0.2.0",
"ipaddr.js": "^2.0.1"
}
}

7188
src/worker-vless.js Normal file

File diff suppressed because it is too large Load Diff

6548
test/cidr.js Normal file

File diff suppressed because it is too large Load Diff

73
test/webstream.mjs Normal file
View File

@ -0,0 +1,73 @@
let isCancel = false;
const readableStream = new ReadableStream({
start(controller) {
let count = 0;
controller.enqueue(`Chunk ${count}`);
count++;
controller.enqueue(`Chunk ${count}`);
// controller.error(new Error('uuid is not valid'));
// setTimeout(() => {
// console.log('ReadableStream was closed------valid22-------.');
// controller.error(new Error('uuid is not valid22'));
// }, 1000);
// const intervalId = setInterval(() => {
// if(!isCancel){
// controller.enqueue(`Chunk ${count}`);
// }
// // controller.enqueue(`Chunk ${count}`);
// count++;
// if (count > 5) {
// console.log('ReadableStream was closed-------------.');
// // controller.close()
// controller.error(new Error('uuid is not valid'));
// // clearInterval(intervalId);
// }
// }, 1000);
},
async pull(controller) {
console.log('ReadableStream Pulling data...');
// await new Promise((resolve) => setTimeout(resolve, 2000));
},
cancel() {
isCancel = true;
console.log('ReadableStream was canceled.');
},
});
const writableStream = new WritableStream({
write(chunk, controller) {
console.log(`Received data: ${chunk}`);
if(chunk === 'Chunk 1'){
controller.error('eroorooororo')
return;
}
// throw new Error('uuid is not valid');
// setTimeout( ()=>{
// try {
// throw new Error('setTimeout hasve error valid');
// }catch(error){
// console.log('////setTimeout hasve error valid');
// }
// }, 2000)
// controller.error(new Error('Received error'));
if(chunk === 'Chunk 3'){
throw new Error('uuid is not valid');
}
},
close() {
console.log('WritableStream was closed');
},
abort() {
console.log('WritableStream was aborted');
}
});
readableStream.pipeTo(writableStream).catch((err) => {
console.log('-----------------------error-------------------');
console.log(err);
});

View File

@ -0,0 +1,11 @@
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
const address = url.searchParams.get("address");
if(!address){
return new Response('not pass address', { status: 200 });
}
const resp = fetch(`http://${address}/cdn-cgi/trace`);
return new Response((await resp).body, { status: 200 });
}
};

View File

@ -0,0 +1,22 @@
export default {
/**
* @param {import("@cloudflare/workers-types").Request} request
* @param {{uuid: string}} env
* @param {import("@cloudflare/workers-types").ExecutionContext} ctx
* @returns {Promise<Response>}
*/
async fetch(request, env, ctx) {
const headers = {};
for (const [name, value] of request.headers.entries()) {
headers[name] = value;
}
const result = {
"http-header": headers,
"cf": request.cf
}
const headersJson = JSON.stringify(result);
console.log(headersJson);
return new Response(headersJson, { status: 200 });
}
};

33
test/worker/cidr.js Normal file
View File

@ -0,0 +1,33 @@
import IPCIDR from 'ip-cidr';
const chunk = '0'.repeat(1024 * 5);
export default {
async fetch(request, env, ctx) {
const isin = checkIPInCIDR("192.168.1.1", "102.1.5.2/24");
return new Response(null, {
status: 101
});
},
};
function checkIPInCIDR(ip, cidr) {
const cidrObject = new IPCIDR(cidr);
// Check if the IP address is valid
// if (!cidrObject.isValidAddress(ip)) {
// return false;
// }
// Check if the IP address is within the CIDR range
return cidrObject.contains(ip);
}
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}

1029
test/worker/ipaddr-test.js Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,55 @@
export default {
async fetch(request, env, ctx) {
const upgradeHeader = request.headers.get('Upgrade');
if (!upgradeHeader || upgradeHeader !== 'websocket') {
return new Response('not websocket', { status: 200 });
}
const webSocketPair = new WebSocketPair();
const [client, webSocket] = Object.values(webSocketPair);
webSocket.accept();
let count = 0;
const readableStream = new ReadableStream({
start(controller) {
setInterval(() => {
controller.enqueue(count);
count++;
}, 500)
},
async pull(controller) {
},
cancel() {
console.log('ReadableStream was canceled.');
},
});
const writableStream = new WritableStream({
write(chunk, controller) {
console.log(`Received data: ${chunk}`);
webSocket.send(`Received data: ${chunk}`);
if (chunk === 3) {
controller.error('eroorooororo')
return;
}
},
close() {
console.log('WritableStream was closed');
},
abort() {
console.log('WritableStream was aborted');
}
});
readableStream.pipeTo(writableStream).catch((error) => {
console.log('pipeTo error', error);
webSocket.close();
});
webSocket.addEventListener('close', () => {
console.log('close');
});
return new Response(null, {
status: 101,
webSocket: client,
});
}
};

View File

@ -0,0 +1,46 @@
import { connect } from 'cloudflare:sockets';
export default {
async fetch(request, env, ctx) {
console.log('start fetch');
const cloudflare = 'www.cloudflare.com';
const floodgap = 'gopher.floodgap.com';
let host = floodgap;
const isFloodgap = request.url.includes('floodgap');
const iscloudflare = request.url.includes('cloudflare');
if (isFloodgap) {
host = floodgap;
}
if (iscloudflare) {
host = cloudflare;
}
try {
const socket = connect(
{
hostname: host,
port: 443,
},
{
secureTransport: 'on',
}
);
console.log('start conneted', host);
const writer = socket.writable.getWriter();
const encoder = new TextEncoder();
const encoded = encoder.encode(
`GET / HTTP/1.1\r\nHost: ${host}\r\nUser-Agent: curl/8.0.1\r\nAccept: */*\r\n\r\n`
);
await writer.write(encoded);
console.log('write end');
return new Response(socket.readable, {
headers: { 'Content-Type': 'text/plain' },
});
} catch (error) {
return new Response('Socket connection failed: ' + error, {
status: 500,
});
}
},
};

View File

@ -0,0 +1,6 @@
name = "cf-worker-http-header" # todo
main = "./cf-worker-http-header.js"
compatibility_date = "2023-05-26"
[vars]
UUID = "example_dev_token"

View File

@ -0,0 +1,60 @@
const chunk = '0'.repeat(1024 * 5);
export default {
async fetch(request, env, ctx) {
try {
console.log('---------------');
const webSocketPair = new WebSocketPair();
/** @type {import("@cloudflare/workers-types").WebSocket[]} */
const [client, webSocket] = Object.values(webSocketPair);
webSocket.accept();
let btyes = 0;
// (async () => {
// const repose = await fetch('http://speed.cloudflare.com/__down?bytes=1145141919810')
// const body = repose.body;
// const reader = body?.getReader();
// let packets = [];
// while (true && reader) {
// const { done, value } = await reader.read();
// packets.push(value);
// console.log(btyes += value?.length || 0);
// if (packets.length > 100) {
// webSocket.send(value || '');
// await delay(2);
// packets = [];
// }
// if (done) {
// break;
// }
// }
// })()
console.log('---------------');
(async () => {
let packets = [];
console.log('---------------');
while (true) {
console.log(btyes += chunk?.length || 0);
webSocket.send(chunk || '');
await delay(1)
}
})()
// console.log(btyes += chunk?.length || 0);
// webSocket.send(chunk || '');
return new Response(null, {
status: 101,
webSocket: client,
});
} catch (err) {
/** @type {Error} */ let e = err;
return new Response(e.toString());
}
},
};
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}

7
wrangler.toml Normal file
View File

@ -0,0 +1,7 @@
name = "cf-worker-ws-dev" # todo
#main = "test/worker/cf-cdn-cgi-trace2.js"
main = "src/worker-vless.js"
compatibility_date = "2023-05-26"
[vars]
UUID = "example_dev_token"