Skip to content

Commit

Permalink
Bug fixes, added country flags.
Browse files Browse the repository at this point in the history
  • Loading branch information
bia-pain-bache committed Oct 31, 2024
1 parent e80e1d0 commit 4d7a99b
Show file tree
Hide file tree
Showing 11 changed files with 52 additions and 52 deletions.
6 changes: 5 additions & 1 deletion src/authentication/auth.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { SignJWT, jwtVerify } from 'jose';
import nacl from 'tweetnacl';
import { configs } from '../helpers/config.js';
let userID = configs.userID;

export async function generateJWTToken (secretKey) {
export async function generateJWTToken (env, secretKey) {
userID = env.UUID || userID;
const secret = new TextEncoder().encode(secretKey);
return await new SignJWT({ userID })
.setProtectedHeader({ alg: 'HS256' })
Expand Down
5 changes: 1 addition & 4 deletions src/cores/clash.js → src/cores-configs/clash.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { getConfigAddresses, extractWireguardParams, generateRemark, randomUpperCase, getRandomPath, isIPv6 } from './helpers.js';
import { configs } from '../helpers/config.js';
import { isValidUUID } from '../helpers/helpers.js';
let userID = configs.userID;
let trojanPassword = configs.userID;
const defaultHttpsPorts = configs.defaultHttpsPorts;
Expand Down Expand Up @@ -315,12 +314,10 @@ export async function getClashWarpConfig(proxySettings, warpConfigs) {
return config;
}

export async function getClashNormalConfig (env, proxySettings) {
export async function getClashNormalConfig (env, hostName, proxySettings) {
let chainProxy;
userID = env.UUID || userID;
if (!isValidUUID(userID)) throw new Error(`Invalid UUID: ${userID}`);
trojanPassword = env.TROJAN_PASS || trojanPassword;
const hostName = globalThis.hostName;
const {
cleanIPs,
proxyIP,
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
import { getConfigAddresses, generateRemark, randomUpperCase, getRandomPath } from './helpers.js';
import { configs } from '../helpers/config.js';
import { isValidUUID } from '../helpers/helpers.js';
let userID = configs.userID;
let trojanPassword = configs.userID;
const defaultHttpsPorts = configs.defaultHttpsPorts;

export async function getNormalConfigs(env, proxySettings, client) {
export async function getNormalConfigs(env, hostName, proxySettings, client) {
userID = env.UUID || userID;
if (!isValidUUID(userID)) throw new Error(`Invalid UUID: ${userID}`);
trojanPassword = env.TROJAN_PASS || trojanPassword;
const hostName = globalThis.hostName;
const {
cleanIPs,
proxyIP,
Expand Down
5 changes: 1 addition & 4 deletions src/cores/sing-box.js → src/cores-configs/sing-box.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { getConfigAddresses, extractWireguardParams, generateRemark, randomUpperCase, getRandomPath } from './helpers.js';
import { configs } from '../helpers/config.js';
import { isValidUUID } from '../helpers/helpers.js';
let userID = configs.userID;
let trojanPassword = configs.userID;
const defaultHttpsPorts = configs.defaultHttpsPorts;
Expand Down Expand Up @@ -550,12 +549,10 @@ export async function getSingBoxWarpConfig (proxySettings, warpConfigs, client)
return config;
}

export async function getSingBoxCustomConfig(env, proxySettings, isFragment) {
export async function getSingBoxCustomConfig(env, hostName, proxySettings, isFragment) {
let chainProxyOutbound;
userID = env.UUID || userID;
if (!isValidUUID(userID)) throw new Error(`Invalid UUID: ${userID}`);
trojanPassword = env.TROJAN_PASS || trojanPassword;
const hostName = globalThis.hostName;
const {
cleanIPs,
ports,
Expand Down
8 changes: 3 additions & 5 deletions src/cores/xray.js → src/cores-configs/xray.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { resolveDNS, isDomain, isValidUUID } from '../helpers/helpers.js';
import { resolveDNS, isDomain } from '../helpers/helpers.js';
import { getConfigAddresses, extractWireguardParams, base64ToDecimal, generateRemark, randomUpperCase, getRandomPath } from './helpers.js';
import { configs } from '../helpers/config.js';
let userID = configs.userID;
Expand Down Expand Up @@ -634,11 +634,9 @@ async function buildXrayWorkerLessConfig(proxySettings) {
return config;
}

export async function getXrayCustomConfigs(env, proxySettings, isFragment) {
export async function getXrayCustomConfigs(env, hostName, proxySettings, isFragment) {
userID = env.UUID || userID;
if (!isValidUUID(userID)) throw new Error(`Invalid UUID: ${userID}`);
trojanPassword = env.TROJAN_PASS || trojanPassword;
const hostName = globalThis.hostName;
let configs = [];
let outbounds = [];
let protocols = [];
Expand Down Expand Up @@ -737,7 +735,7 @@ export async function getXrayWarpConfigs (proxySettings, warpConfigs, client) {
const endpointHost = endpoint.split(':')[0];
let warpConfig = buildXrayConfig(proxySettings, `💦 ${index + 1} - Warp${proIndicator}🇮🇷`, false, false, false, undefined, true);
let WoWConfig = buildXrayConfig(proxySettings, `💦 ${index + 1} - WoW${proIndicator}🌍`, false, false, true, undefined, true);
warpConfig.dns = WoWConfig.dns = await buildXrayDNS(proxySettings, [endpointHost], undefined, false, true);
warpConfig.dns = WoWConfig.dns = await buildXrayDNS(proxySettings, [endpointHost], undefined, false, false, true);
warpConfig.routing.rules = buildXrayRoutingRules(proxySettings, [endpointHost], false, false, false);
WoWConfig.routing.rules = buildXrayRoutingRules(proxySettings, [endpointHost], true, false, false);
const warpOutbound = buildXrayWarpOutbound(proxySettings, warpConfigs, endpoint, false, client);
Expand Down
2 changes: 1 addition & 1 deletion src/helpers/config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const proxyIPs = ['bpb.yousef.isegaro.com'];
export const configs = {
userID: '89b3cbba-e6ac-485a-9481-976a0415eab9',
dohURL: 'https://cloudflare-dns.com/dns-query',
proxyIPs: ['bpb.yousef.isegaro.com'],
proxyIP: proxyIPs[Math.floor(Math.random() * proxyIPs.length)],
trojanPassword: 'bpb-trojan',
defaultHttpPorts: ['80', '8080', '2052', '2082', '2086', '2095', '8880'],
Expand Down
2 changes: 2 additions & 0 deletions src/kv/handlers.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { fetchWgConfig } from '../protocols/warp.js';
import { isDomain, resolveDNS } from '../helpers/helpers.js';
import { configs } from '../helpers/config.js';
const { panelVersion } = configs;

export async function getDataset(env) {
let proxySettings, warpConfigs;
Expand Down
26 changes: 15 additions & 11 deletions src/pages/homePage.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
import { configs } from '../helpers/config.js';
import { isValidUUID } from '../helpers/helpers.js';
const { defaultHttpPorts, defaultHttpsPorts, panelVersion } = configs;
let userID = configs.userID;

export function renderHomePage (request, env, proxySettings, isPassSet) {
const hostName = globalThis.hostName;
export function renderHomePage (request, env, hostName, proxySettings, isPassSet) {
userID = env.UUID || userID;
if (!isValidUUID(userID)) throw new Error(`Invalid UUID: ${userID}`);
const {
remoteDNS,
localDNS,
Expand Down Expand Up @@ -54,7 +51,9 @@ export function renderHomePage (request, env, proxySettings, isPassSet) {
let httpPortsBlock = '', httpsPortsBlock = '';
const allPorts = [...(hostName.includes('workers.dev') ? defaultHttpPorts : []), ...defaultHttpsPorts];
let regionNames = new Intl.DisplayNames(['en'], {type: 'region'});
const cfCountry = regionNames.of(request.cf.country);
const countryCode = request.cf.country;
const flag = String.fromCodePoint(...[...countryCode].map(c => 0x1F1E6 + c.charCodeAt(0) - 65));
const cfCountry = `${regionNames.of(countryCode)} ${flag}`;

allPorts.forEach(port => {
const id = `port-${port}`;
Expand Down Expand Up @@ -93,7 +92,7 @@ export function renderHomePage (request, env, proxySettings, isPassSet) {
--input-background-color: white;
--header-shadow: 2px 2px 4px rgba(0, 0, 0, 0.25);
}
body { font-family: system-ui; background-color: var(--background-color); color: var(--color) }
body { font-family: Twemoji Country Flags, system-ui; background-color: var(--background-color); color: var(--color) }
body.dark-mode {
--color: white;
--primary-color: #09639F;
Expand Down Expand Up @@ -1073,7 +1072,11 @@ export function renderHomePage (request, env, proxySettings, isPassSet) {
</div>
<button id="darkModeToggle" class="floating-button">
<i id="modeIcon" class="fa fa-2x fa-adjust" style="color: var(--background-color);" aria-hidden="true"></i>
</button>
</button>
<script type="module" defer>
import { polyfillCountryFlagEmojis } from "https://cdn.skypack.dev/country-flag-emoji-polyfill";
polyfillCountryFlagEmojis();
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
<script>
const defaultHttpsPorts = ['443', '8443', '2053', '2083', '2087', '2096'];
Expand Down Expand Up @@ -1197,17 +1200,18 @@ export function renderHomePage (request, env, proxySettings, isPassSet) {
});
const fetchIPInfo = async () => {
const updateUI = (ip = '-', country = '-', city = '-', isp = '-') => {
const updateUI = (ip = '-', country = '-', country_code = '-', city = '-', isp = '-') => {
const flag = String.fromCodePoint(...[...country_code].map(c => 0x1F1E6 + c.charCodeAt(0) - 65));
document.getElementById('ip').textContent = ip;
document.getElementById('country').textContent = country;
document.getElementById('country').textContent = country + ' ' + flag;
document.getElementById('city').textContent = city;
document.getElementById('isp').textContent = isp.toUpperCase();
};
try {
const response = await fetch('https://ipwho.is/');
const { ip, country, city, connection } = await response.json();
updateUI(ip, country, city, connection.isp);
const { ip, country, country_code, city, connection } = await response.json();
updateUI(ip, country, country_code, city, connection.isp);
} catch (error) {
console.error('Error fetching IP address:', error);
updateUI();
Expand Down
1 change: 0 additions & 1 deletion src/protocols/vless.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ export async function vlessOverWSHandler(request, env) {
/** @type {import("@cloudflare/workers-types").WebSocket[]} */
// @ts-ignore
userID = env.UUID || userID;
if (!isValidUUID(userID)) throw new Error(`Invalid UUID: ${userID}`);
proxyIP = env.PROXYIP || proxyIP;
const webSocketPair = new WebSocketPair();
const [client, webSocket] = Object.values(webSocketPair);
Expand Down
44 changes: 23 additions & 21 deletions src/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,35 +7,37 @@ import { generateJWTToken, generateSecretKey, Authenticate } from './authenticat
import { renderHomePage } from './pages/homePage.js';
import { renderLoginPage } from './pages/loginPage.js';
import { renderErrorPage } from './pages/errorPage.js';
import { getXrayCustomConfigs, getXrayWarpConfigs } from './cores/xray.js';
import { getSingBoxCustomConfig, getSingBoxWarpConfig } from './cores/sing-box.js';
import { getClashNormalConfig, getClashWarpConfig } from './cores/clash.js';
import { getNormalConfigs } from './cores/normalConfigs.js';
globalThis.hostName = '';
import { getXrayCustomConfigs, getXrayWarpConfigs } from './cores-configs/xray.js';
import { getSingBoxCustomConfig, getSingBoxWarpConfig } from './cores-configs/sing-box.js';
import { getClashNormalConfig, getClashWarpConfig } from './cores-configs/clash.js';
import { getNormalConfigs } from './cores-configs/normalConfigs.js';
import { configs } from './helpers/config.js';
import { isValidUUID } from './helpers/helpers.js';

export default {
async fetch(request, env) {
try {
const upgradeHeader = request.headers.get('Upgrade');
const url = new URL(request.url);
if (!upgradeHeader || upgradeHeader !== 'websocket') {
globalThis.hostName = request.headers.get('Host');
const userID = env.UUID || configs.userID;
if (!isValidUUID(userID)) throw new Error(`Invalid UUID: ${userID}`);
const hostName = request.headers.get('Host');
const searchParams = new URLSearchParams(url.search);
const client = searchParams.get('app');
const { kvNotFound, proxySettings: settings, warpConfigs } = await getDataset(env);
const { kvNotFound, proxySettings, warpConfigs } = await getDataset(env);
if (kvNotFound) {
const errorPage = renderErrorPage('KV Dataset is not properly set!', null, true);
return new Response(errorPage, { status: 200, headers: {'Content-Type': 'text/html'}});
}

switch (url.pathname) {

switch (url.pathname) {
case '/update-warp':
const Auth = await Authenticate(request, env);
if (!Auth) return new Response('Unauthorized', { status: 401 });
if (request.method === 'POST') {
try {
const { error: warpPlusError } = await fetchWgConfig(env, settings);
const { error: warpPlusError } = await fetchWgConfig(env, proxySettings);
if (warpPlusError) {
return new Response(warpPlusError, { status: 400 });
} else {
Expand All @@ -52,7 +54,7 @@ export default {

case `/sub/${userID}`:
if (client === 'sfa') {
const BestPingSFA = await getSingBoxCustomConfig(env, settings, false);
const BestPingSFA = await getSingBoxCustomConfig(env, hostName, proxySettings, false);
return new Response(JSON.stringify(BestPingSFA, null, 4), {
status: 200,
headers: {
Expand All @@ -64,7 +66,7 @@ export default {
}

if (client === 'clash') {
const BestPingClash = await getClashNormalConfig(env, settings);
const BestPingClash = await getClashNormalConfig(env, hostName, proxySettings);
return new Response(JSON.stringify(BestPingClash, null, 4), {
status: 200,
headers: {
Expand All @@ -76,7 +78,7 @@ export default {
}

if (client === 'xray') {
const xrayFullConfigs = await getXrayCustomConfigs(env, settings, false);
const xrayFullConfigs = await getXrayCustomConfigs(env, hostName, proxySettings, false);
return new Response(JSON.stringify(xrayFullConfigs, null, 4), {
status: 200,
headers: {
Expand All @@ -87,7 +89,7 @@ export default {
});
}

const normalConfigs = await getNormalConfigs(env, settings, client);
const normalConfigs = await getNormalConfigs(env, hostName, proxySettings, client);
return new Response(normalConfigs, {
status: 200,
headers: {
Expand All @@ -99,8 +101,8 @@ export default {

case `/fragsub/${userID}`:
let fragConfigs = client === 'hiddify'
? await getSingBoxCustomConfig(env, settings, true)
: await getXrayCustomConfigs(env, settings, true);
? await getSingBoxCustomConfig(env, hostName, proxySettings, true)
: await getXrayCustomConfigs(env, hostName, proxySettings, true);

return new Response(JSON.stringify(fragConfigs, null, 4), {
status: 200,
Expand All @@ -113,7 +115,7 @@ export default {

case `/warpsub/${userID}`:
if (client === 'clash') {
const clashWarpConfig = await getClashWarpConfig(settings, warpConfigs);
const clashWarpConfig = await getClashWarpConfig(proxySettings, warpConfigs);
return new Response(JSON.stringify(clashWarpConfig, null, 4), {
status: 200,
headers: {
Expand All @@ -125,7 +127,7 @@ export default {
}

if (client === 'singbox' || client === 'hiddify') {
const singboxWarpConfig = await getSingBoxWarpConfig(settings, warpConfigs, client);
const singboxWarpConfig = await getSingBoxWarpConfig(proxySettings, warpConfigs, client);
return new Response(JSON.stringify(singboxWarpConfig, null, 4), {
status: 200,
headers: {
Expand All @@ -136,7 +138,7 @@ export default {
});
}

const warpConfig = await getXrayWarpConfigs(settings, warpConfigs, client);
const warpConfig = await getXrayWarpConfigs(proxySettings, warpConfigs, client);
return new Response(JSON.stringify(warpConfig, null, 4), {
status: 200,
headers: {
Expand All @@ -162,7 +164,7 @@ export default {
const pwd = await env.bpb.get('pwd');
if (pwd && !isAuth) return Response.redirect(`${url.origin}/login`, 302);
const isPassSet = pwd?.length >= 8;
const homePage = renderHomePage(request, env, settings, isPassSet);
const homePage = renderHomePage(request, env, hostName, proxySettings, isPassSet);
return new Response(homePage, {
status: 200,
headers: {
Expand Down Expand Up @@ -197,7 +199,7 @@ export default {
const savedPass = await env.bpb.get('pwd');

if (password === savedPass) {
const jwtToken = await generateJWTToken(secretKey);
const jwtToken = await generateJWTToken(env, secretKey);
const cookieHeader = `jwtToken=${jwtToken}; HttpOnly; Secure; Max-Age=${7 * 24 * 60 * 60}; Path=/; SameSite=Strict`;
return new Response('Success', {
status: 200,
Expand Down

0 comments on commit 4d7a99b

Please sign in to comment.