Skip to content

Commit

Permalink
Refactored.
Browse files Browse the repository at this point in the history
  • Loading branch information
bia-pain-bache committed Nov 29, 2024
1 parent f615d1b commit 12aba15
Show file tree
Hide file tree
Showing 15 changed files with 95 additions and 134 deletions.
10 changes: 4 additions & 6 deletions src/authentication/auth.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { SignJWT, jwtVerify } from 'jose';
import nacl from 'tweetnacl';
import { initializeParams, userID, origin } from "../helpers/init";
import { renderLoginPage } from '../pages/login';

async function generateJWTToken (request, env) {
await initializeParams(request, env);
const password = await request.text();
const savedPass = await env.bpb.get('pwd');
if (password !== savedPass) return new Response('Method Not Allowed', { status: 405 });
Expand All @@ -14,7 +12,7 @@ async function generateJWTToken (request, env) {
await env.bpb.put('secretKey', secretKey);
}
const secret = new TextEncoder().encode(secretKey);
const jwtToken = await new SignJWT({ userID })
const jwtToken = await new SignJWT({ userID: globalThis.userID })
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime('24h')
Expand Down Expand Up @@ -82,10 +80,10 @@ export async function resetPassword(request, env) {
}

export async function login(request, env) {
await initializeParams(request, env);
// await initializeParams(request, env);
if (typeof env.bpb !== 'object') throw new Error('KV Dataset is not properly set!', { cause: "init"});
const auth = await Authenticate(request, env);
if (auth) return Response.redirect(`${origin}/panel`, 302);
if (auth) return Response.redirect(`${globalThis.urlOrigin}/panel`, 302);
if (request.method === 'POST') return await generateJWTToken(request, env);
return await renderLoginPage(request, env);
return await renderLoginPage();
}
16 changes: 7 additions & 9 deletions src/cores-configs/clash.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { getConfigAddresses, extractWireguardParams, generateRemark, randomUpperCase, getRandomPath, isIPv6, isIPv4 } from './helpers';
import { initializeParams, userID, trojanPassword, hostName, defaultHttpsPorts } from "../helpers/init";
import { getDataset } from '../kv/handlers';
import { isDomain } from '../helpers/helpers';

Expand Down Expand Up @@ -250,14 +249,14 @@ function buildClashRoutingRules (proxySettings) {
}

function buildClashVLESSOutbound (remark, address, port, host, sni, path, allowInsecure) {
const tls = defaultHttpsPorts.includes(port) ? true : false;
const tls = globalThis.defaultHttpsPorts.includes(port) ? true : false;
const addr = isIPv6(address) ? address.replace(/\[|\]/g, '') : address;
const outbound = {
"name": remark,
"type": "vless",
"server": addr,
"port": +port,
"uuid": userID,
"uuid": globalThis.userID,
"tls": tls,
"network": "ws",
"udp": true,
Expand Down Expand Up @@ -288,7 +287,7 @@ function buildClashTrojanOutbound (remark, address, port, host, sni, path, allow
"type": "trojan",
"server": addr,
"port": +port,
"password": trojanPassword,
"password": globalThis.trojanPassword,
"network": "ws",
"udp": true,
"ws-opts": {
Expand Down Expand Up @@ -455,7 +454,6 @@ export async function getClashWarpConfig(request, env) {
}

export async function getClashNormalConfig (request, env) {
await initializeParams(request, env);
const { proxySettings } = await getDataset(request, env);
let chainProxy;
const {
Expand Down Expand Up @@ -506,7 +504,7 @@ export async function getClashNormalConfig (request, env) {
selector.proxies = ['💦 Best Ping 💥'];
urlTest.name = '💦 Best Ping 💥';
urlTest.interval = +bestVLESSTrojanInterval;
const Addresses = await getConfigAddresses(hostName, cleanIPs, enableIPv6);
const Addresses = await getConfigAddresses(globalThis.hostName, cleanIPs, enableIPv6);
const customCdnAddresses = customCdnAddrs ? customCdnAddrs.split(',') : [];
const totalAddresses = [...Addresses, ...customCdnAddresses];
let proxyIndex = 1, path;
Expand All @@ -522,8 +520,8 @@ export async function getClashNormalConfig (request, env) {
let VLESSOutbound, TrojanOutbound;
const isCustomAddr = customCdnAddresses.includes(addr);
const configType = isCustomAddr ? 'C' : '';
const sni = isCustomAddr ? customCdnSni : randomUpperCase(hostName);
const host = isCustomAddr ? customCdnHost : hostName;
const sni = isCustomAddr ? customCdnSni : randomUpperCase(globalThis.hostName);
const host = isCustomAddr ? customCdnHost : globalThis.hostName;
const remark = generateRemark(protocolIndex, port, addr, cleanIPs, protocol, configType).replace(' : ', ' - ');

if (protocol === 'VLESS') {
Expand All @@ -542,7 +540,7 @@ export async function getClashNormalConfig (request, env) {
urlTest.proxies.push(remark);
}

if (protocol === 'Trojan' && defaultHttpsPorts.includes(port)) {
if (protocol === 'Trojan' && globalThis.defaultHttpsPorts.includes(port)) {
path = `/tr${getRandomPath(16)}${proxyIP ? `/${btoa(proxyIP)}` : ''}`;
TrojanOutbound = buildClashTrojanOutbound(
chainProxy ? `proxy-${proxyIndex}` : remark,
Expand Down
18 changes: 8 additions & 10 deletions src/cores-configs/normalConfigs.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { getConfigAddresses, generateRemark, randomUpperCase, getRandomPath } from './helpers';
import { initializeParams, userID, trojanPassword, hostName, client, defaultHttpsPorts } from "../helpers/init";
import { getDataset } from '../kv/handlers';

export async function getNormalConfigs(request, env) {
await initializeParams(request, env);
const { proxySettings } = await getDataset(request, env);
const {
cleanIPs,
Expand All @@ -20,30 +18,30 @@ export async function getNormalConfigs(request, env) {

let vlessConfs = '', trojanConfs = '', chainProxy = '';
let proxyIndex = 1;
const Addresses = await getConfigAddresses(hostName, cleanIPs, enableIPv6);
const Addresses = await getConfigAddresses(globalThis.hostName, cleanIPs, enableIPv6);
const customCdnAddresses = customCdnAddrs ? customCdnAddrs.split(',') : [];
const totalAddresses = [...Addresses, ...customCdnAddresses];
const alpn = client === 'singbox' ? 'http/1.1' : 'h2,http/1.1';
const trojanPass = encodeURIComponent(trojanPassword);
const earlyData = client === 'singbox'
const alpn = globalThis.client === 'singbox' ? 'http/1.1' : 'h2,http/1.1';
const trojanPass = encodeURIComponent(globalThis.trojanPassword);
const earlyData = globalThis.client === 'singbox'
? '&eh=Sec-WebSocket-Protocol&ed=2560'
: encodeURIComponent('?ed=2560');

ports.forEach(port => {
totalAddresses.forEach((addr, index) => {
const isCustomAddr = index > Addresses.length - 1;
const configType = isCustomAddr ? 'C' : '';
const sni = isCustomAddr ? customCdnSni : randomUpperCase(hostName);
const host = isCustomAddr ? customCdnHost : hostName;
const sni = isCustomAddr ? customCdnSni : randomUpperCase(globalThis.hostName);
const host = isCustomAddr ? customCdnHost : globalThis.hostName;
const path = `${getRandomPath(16)}${proxyIP ? `/${encodeURIComponent(btoa(proxyIP))}` : ''}${earlyData}`;
const vlessRemark = encodeURIComponent(generateRemark(proxyIndex, port, addr, cleanIPs, 'VLESS', configType));
const trojanRemark = encodeURIComponent(generateRemark(proxyIndex, port, addr, cleanIPs, 'Trojan', configType));
const tlsFields = defaultHttpsPorts.includes(port)
const tlsFields = globalThis.defaultHttpsPorts.includes(port)
? `&security=tls&sni=${sni}&fp=randomized&alpn=${alpn}`
: '&security=none';

if (vlessConfigs) {
vlessConfs += `${atob('dmxlc3M6Ly8=')}${userID}@${addr}:${port}?path=/${path}&encryption=none&host=${host}&type=ws${tlsFields}#${vlessRemark}\n`;
vlessConfs += `${atob('dmxlc3M6Ly8=')}${globalThis.userID}@${addr}:${port}?path=/${path}&encryption=none&host=${host}&type=ws${tlsFields}#${vlessRemark}\n`;
}

if (trojanConfigs) {
Expand Down
18 changes: 8 additions & 10 deletions src/cores-configs/sing-box.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { getConfigAddresses, extractWireguardParams, generateRemark, randomUpperCase, getRandomPath, isIPv6 } from './helpers';
import { initializeParams, userID, trojanPassword, hostName, defaultHttpsPorts } from "../helpers/init";
import { getDataset } from '../kv/handlers';
import { isDomain } from '../helpers/helpers';

Expand Down Expand Up @@ -353,13 +352,13 @@ function buildSingBoxRoutingRules (proxySettings) {
function buildSingBoxVLESSOutbound (proxySettings, remark, address, port, host, sni, allowInsecure, isFragment) {
const { enableIPv6, lengthMin, lengthMax, intervalMin, intervalMax, proxyIP } = proxySettings;
const path = `/${getRandomPath(16)}${proxyIP ? `/${btoa(proxyIP)}` : ''}`;
const tls = defaultHttpsPorts.includes(port) ? true : false;
const tls = globalThis.defaultHttpsPorts.includes(port) ? true : false;
const outbound = {
type: "vless",
server: address,
server_port: +port,
domain_strategy: enableIPv6 ? "prefer_ipv4" : "ipv4_only",
uuid: userID,
uuid: globalThis.userID,
tls: {
alpn: "http/1.1",
enabled: true,
Expand Down Expand Up @@ -395,10 +394,10 @@ function buildSingBoxVLESSOutbound (proxySettings, remark, address, port, host,
function buildSingBoxTrojanOutbound (proxySettings, remark, address, port, host, sni, allowInsecure, isFragment) {
const { enableIPv6, lengthMin, lengthMax, intervalMin, intervalMax, proxyIP } = proxySettings;
const path = `/tr${getRandomPath(16)}${proxyIP ? `/${btoa(proxyIP)}` : ''}`;
const tls = defaultHttpsPorts.includes(port) ? true : false;
const tls = globalThis.defaultHttpsPorts.includes(port) ? true : false;
const outbound = {
type: "trojan",
password: trojanPassword,
password: globalThis.trojanPassword,
server: address,
server_port: +port,
domain_strategy: enableIPv6 ? "prefer_ipv4" : "ipv4_only",
Expand Down Expand Up @@ -619,7 +618,6 @@ export async function getSingBoxWarpConfig (request, env, client) {
}

export async function getSingBoxCustomConfig(request, env, isFragment) {
await initializeParams(request, env);
const { proxySettings } = await getDataset(request, env);
let chainProxy;
const {
Expand Down Expand Up @@ -651,7 +649,7 @@ export async function getSingBoxCustomConfig(request, env, isFragment) {
}
}

const Addresses = await getConfigAddresses(hostName, cleanIPs, enableIPv6);
const Addresses = await getConfigAddresses(globalThis.hostName, cleanIPs, enableIPv6);
const customCdnAddresses = customCdnAddrs ? customCdnAddrs.split(',') : [];
const totalAddresses = [...Addresses, ...customCdnAddresses];
const config = structuredClone(singboxConfigTemp);
Expand All @@ -667,7 +665,7 @@ export async function getSingBoxCustomConfig(request, env, isFragment) {
selector.outbounds = ['💦 Best Ping 💥'];
urlTest.interval = `${bestVLESSTrojanInterval}s`;
urlTest.tag = '💦 Best Ping 💥';
const totalPorts = ports.filter(port => isFragment ? defaultHttpsPorts.includes(port) : true);
const totalPorts = ports.filter(port => isFragment ? globalThis.defaultHttpsPorts.includes(port) : true);
let proxyIndex = 1;
const protocols = [
...(vlessConfigs ? ['VLESS'] : []),
Expand All @@ -681,8 +679,8 @@ export async function getSingBoxCustomConfig(request, env, isFragment) {
let VLESSOutbound, TrojanOutbound;
const isCustomAddr = customCdnAddresses.includes(addr);
const configType = isCustomAddr ? 'C' : isFragment ? 'F' : '';
const sni = isCustomAddr ? customCdnSni : randomUpperCase(hostName);
const host = isCustomAddr ? customCdnHost : hostName;
const sni = isCustomAddr ? customCdnSni : randomUpperCase(globalThis.hostName);
const host = isCustomAddr ? customCdnHost : globalThis.hostName;
const remark = generateRemark(protocolIndex, port, addr, cleanIPs, protocol, configType);

if (protocol === 'VLESS') {
Expand Down
23 changes: 11 additions & 12 deletions src/cores-configs/xray.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { resolveDNS, isDomain } from '../helpers/helpers';
import { getConfigAddresses, extractWireguardParams, base64ToDecimal, generateRemark, randomUpperCase, getRandomPath } from './helpers';
import { initializeParams, userID, trojanPassword, hostName, defaultHttpsPorts } from "../helpers/init";
// import { initializeParams, globalThis.userID, globalThis.trojanPassword, globalThis.hostName, globalThis.defaultHttpsPorts } from "../helpers/init";
import { getDataset } from '../kv/handlers';

async function buildXrayDNS (proxySettings, outboundAddrs, domainToStaticIPs, isWorkerLess, isWarp) {
Expand Down Expand Up @@ -285,7 +285,7 @@ function buildXrayVLESSOutbound (tag, address, port, host, sni, proxyIP, isFragm
port: +port,
users: [
{
id: userID,
id: globalThis.userID,
encryption: "none",
level: 8
}
Expand All @@ -308,7 +308,7 @@ function buildXrayVLESSOutbound (tag, address, port, host, sni, proxyIP, isFragm
tag: tag
};

if (defaultHttpsPorts.includes(port)) {
if (globalThis.defaultHttpsPorts.includes(port)) {
outbound.streamSettings.security = "tls";
outbound.streamSettings.tlsSettings = {
allowInsecure: allowInsecure,
Expand Down Expand Up @@ -338,7 +338,7 @@ function buildXrayTrojanOutbound (tag, address, port, host, sni, proxyIP, isFrag
{
address: address,
port: +port,
password: trojanPassword,
password: globalThis.trojanPassword,
level: 8
}
]
Expand All @@ -357,7 +357,7 @@ function buildXrayTrojanOutbound (tag, address, port, host, sni, proxyIP, isFrag
tag: tag
};

if (defaultHttpsPorts.includes(port)) {
if (globalThis.defaultHttpsPorts.includes(port)) {
outbound.streamSettings.security = "tls";
outbound.streamSettings.tlsSettings = {
allowInsecure: allowInsecure,
Expand Down Expand Up @@ -696,15 +696,14 @@ async function buildXrayWorkerLessConfig(proxySettings) {
const config = buildXrayConfig(proxySettings, '💦 BPB F - WorkerLess ⭐', true, false, false, false, false);
config.dns = await buildXrayDNS(proxySettings, [], undefined, true);
config.routing.rules = buildXrayRoutingRules(proxySettings, [], false, false, true, false);
const fakeOutbound = buildXrayVLESSOutbound('fake-outbound', 'google.com', '443', userID, 'google.com', 'google.com', '', true, false);
const fakeOutbound = buildXrayVLESSOutbound('fake-outbound', 'google.com', '443', globalThis.userID, 'google.com', 'google.com', '', true, false);
delete fakeOutbound.streamSettings.sockopt;
fakeOutbound.streamSettings.wsSettings.path = '/';
config.outbounds.push(fakeOutbound);
return config;
}

export async function getXrayCustomConfigs(request, env, isFragment) {
await initializeParams(request, env);
const { proxySettings } = await getDataset(request, env);
let configs = [];
let outbounds = [];
Expand Down Expand Up @@ -739,10 +738,10 @@ export async function getXrayCustomConfigs(request, env, isFragment) {
}
}

const Addresses = await getConfigAddresses(hostName, cleanIPs, enableIPv6);
const Addresses = await getConfigAddresses(globalThis.hostName, cleanIPs, enableIPv6);
const customCdnAddresses = customCdnAddrs ? customCdnAddrs.split(',') : [];
const totalAddresses = isFragment ? [...Addresses] : [...Addresses, ...customCdnAddresses];
const totalPorts = ports.filter(port => isFragment ? defaultHttpsPorts.includes(port): true);
const totalPorts = ports.filter(port => isFragment ? globalThis.defaultHttpsPorts.includes(port): true);
vlessConfigs && protocols.push('VLESS');
trojanConfigs && protocols.push('Trojan');
let proxyIndex = 1;
Expand All @@ -753,8 +752,8 @@ export async function getXrayCustomConfigs(request, env, isFragment) {
for (const addr of totalAddresses) {
const isCustomAddr = customCdnAddresses.includes(addr);
const configType = isCustomAddr ? 'C' : isFragment ? 'F' : '';
const sni = isCustomAddr ? customCdnSni : randomUpperCase(hostName);
const host = isCustomAddr ? customCdnHost : hostName;
const sni = isCustomAddr ? customCdnSni : randomUpperCase(globalThis.hostName);
const host = isCustomAddr ? customCdnHost : globalThis.hostName;
const remark = generateRemark(protocolIndex, port, addr, cleanIPs, protocol, configType);
const customConfig = buildXrayConfig(proxySettings, remark, isFragment, false, chainProxy, false, false);
customConfig.dns = await buildXrayDNS(proxySettings, [addr], undefined);
Expand Down Expand Up @@ -785,7 +784,7 @@ export async function getXrayCustomConfigs(request, env, isFragment) {
const bestPing = await buildXrayBestPingConfig(proxySettings, totalAddresses, chainProxy, outbounds, isFragment);
const finalConfigs = [...configs, bestPing];
if (isFragment) {
const bestFragment = await buildXrayBestFragmentConfig(proxySettings, hostName, chainProxy, outbounds);
const bestFragment = await buildXrayBestFragmentConfig(proxySettings, globalThis.hostName, chainProxy, outbounds);
const workerLessConfig = await buildXrayWorkerLessConfig(proxySettings);
finalConfigs.push(bestFragment, workerLessConfig);
}
Expand Down
6 changes: 2 additions & 4 deletions src/helpers/helpers.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Authenticate } from "../authentication/auth";
import { getDataset, updateDataset } from "../kv/handlers";
import { renderHomePage } from "../pages/home";
import { initializeParams, origin } from "./init";

export 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;
Expand Down Expand Up @@ -42,7 +41,6 @@ export function isDomain(address) {
}

export async function handlePanel(request, env) {
await initializeParams(request, env);
const auth = await Authenticate(request, env);
if (request.method === 'POST') {
if (!auth) return new Response('Unauthorized or expired session!', { status: 401 });
Expand All @@ -52,9 +50,9 @@ export async function handlePanel(request, env) {

const { proxySettings } = await getDataset(request, env);
const pwd = await env.bpb.get('pwd');
if (pwd && !auth) return Response.redirect(`${origin}/login`, 302);
if (pwd && !auth) return Response.redirect(`${globalThis.urlOrigin}/login`, 302);
const isPassSet = pwd?.length >= 8;
return await renderHomePage(request, env, proxySettings, isPassSet);
return await renderHomePage(proxySettings, isPassSet);
}

export async function fallback(request) {
Expand Down
Loading

0 comments on commit 12aba15

Please sign in to comment.