Skip to content

Commit

Permalink
Revised error handling.
Browse files Browse the repository at this point in the history
  • Loading branch information
bia-pain-bache committed Nov 28, 2024
1 parent 0d56d4a commit d74ad7b
Show file tree
Hide file tree
Showing 10 changed files with 21 additions and 43 deletions.
3 changes: 1 addition & 2 deletions src/authentication/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { SignJWT, jwtVerify } from 'jose';
import nacl from 'tweetnacl';
import { initializeParams, userID, origin } from "../helpers/init";
import { renderLoginPage } from '../pages/login';
import { renderErrorPage } from '../pages/error';

async function generateJWTToken (request, env) {
await initializeParams(request, env);
Expand Down Expand Up @@ -84,7 +83,7 @@ export async function resetPassword(request, env) {

export async function login(request, env) {
await initializeParams(request, env);
if (typeof env.bpb !== 'object') return await renderErrorPage(request, env, 'KV Dataset is not properly set!', null, true);
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 (request.method === 'POST') return await generateJWTToken(request, env);
Expand Down
7 changes: 2 additions & 5 deletions src/cores-configs/clash.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
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 { renderErrorPage } from '../pages/error';
import { isDomain } from '../helpers/helpers';

async function buildClashDNS (proxySettings, isChain, isWarp) {
Expand Down Expand Up @@ -415,8 +414,7 @@ function buildClashChainOutbound(chainProxyParams) {
}

export async function getClashWarpConfig(request, env) {
const { kvNotFound, proxySettings, warpConfigs } = await getDataset(request, env);
if (kvNotFound) return await renderErrorPage(request, env, 'KV Dataset is not properly set!', null, true);
const { proxySettings, warpConfigs } = await getDataset(request, env);
const { warpEndpoints } = proxySettings;
const config = structuredClone(clashConfigTemp);
config.dns = await buildClashDNS(proxySettings, true, true);
Expand Down Expand Up @@ -458,8 +456,7 @@ export async function getClashWarpConfig(request, env) {

export async function getClashNormalConfig (request, env) {
await initializeParams(request, env);
const { kvNotFound, proxySettings } = await getDataset(request, env);
if (kvNotFound) return await renderErrorPage(request, env, 'KV Dataset is not properly set!', null, true);
const { proxySettings } = await getDataset(request, env);
let chainProxy;
const {
resolvedRemoteDNS,
Expand Down
4 changes: 1 addition & 3 deletions src/cores-configs/normalConfigs.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import { getConfigAddresses, generateRemark, randomUpperCase, getRandomPath } from './helpers';
import { initializeParams, userID, trojanPassword, hostName, client, defaultHttpsPorts } from "../helpers/init";
import { getDataset } from '../kv/handlers';
import { renderErrorPage } from '../pages/error';

export async function getNormalConfigs(request, env) {
await initializeParams(request, env);
const { kvNotFound, proxySettings } = await getDataset(request, env);
if (kvNotFound) return await renderErrorPage(request, env, 'KV Dataset is not properly set!', null, true);
const { proxySettings } = await getDataset(request, env);
const {
cleanIPs,
proxyIP,
Expand Down
7 changes: 2 additions & 5 deletions 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, isIPv6 } from './helpers';
import { initializeParams, userID, trojanPassword, hostName, defaultHttpsPorts } from "../helpers/init";
import { renderErrorPage } from '../pages/error';
import { getDataset } from '../kv/handlers';
import { isDomain } from '../helpers/helpers';

Expand Down Expand Up @@ -574,8 +573,7 @@ function buildSingBoxChainOutbound (chainProxyParams, enableIPv6) {
}

export async function getSingBoxWarpConfig (request, env, client) {
const { kvNotFound, proxySettings, warpConfigs } = await getDataset(request, env);
if (kvNotFound) return await renderErrorPage(request, env, 'KV Dataset is not properly set!', null, true);
const { proxySettings, warpConfigs } = await getDataset(request, env);
const { warpEndpoints } = proxySettings;
const config = structuredClone(singboxConfigTemp);
const proIndicator = client === 'hiddify' ? ' Pro ' : ' ';
Expand Down Expand Up @@ -622,8 +620,7 @@ export async function getSingBoxWarpConfig (request, env, client) {

export async function getSingBoxCustomConfig(request, env, isFragment) {
await initializeParams(request, env);
const { kvNotFound, proxySettings } = await getDataset(request, env);
if (kvNotFound) return await renderErrorPage(request, env, 'KV Dataset is not properly set!', null, true);
const { proxySettings } = await getDataset(request, env);
let chainProxy;
const {
cleanIPs,
Expand Down
7 changes: 2 additions & 5 deletions src/cores-configs/xray.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,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 { getDataset } from '../kv/handlers';
import { renderErrorPage } from '../pages/error';

async function buildXrayDNS (proxySettings, outboundAddrs, domainToStaticIPs, isWorkerLess, isWarp) {
const {
Expand Down Expand Up @@ -706,8 +705,7 @@ async function buildXrayWorkerLessConfig(proxySettings) {

export async function getXrayCustomConfigs(request, env, isFragment) {
await initializeParams(request, env);
const { kvNotFound, proxySettings } = await getDataset(request, env);
if (kvNotFound) return await renderErrorPage(request, env, 'KV Dataset is not properly set!', null, true);
const { proxySettings } = await getDataset(request, env);
let configs = [];
let outbounds = [];
let protocols = [];
Expand Down Expand Up @@ -802,8 +800,7 @@ export async function getXrayCustomConfigs(request, env, isFragment) {
}

export async function getXrayWarpConfigs (request, env, client) {
const { kvNotFound, proxySettings, warpConfigs } = await getDataset(request, env);
if (kvNotFound) return await renderErrorPage(request, env, 'KV Dataset is not properly set!', null, true);
const { proxySettings, warpConfigs } = await getDataset(request, env);
const xrayWarpConfigs = [];
const xrayWoWConfigs = [];
const xrayWarpOutbounds = [];
Expand Down
4 changes: 1 addition & 3 deletions src/helpers/helpers.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Authenticate } from "../authentication/auth";
import { getDataset, updateDataset } from "../kv/handlers";
import { renderErrorPage } from "../pages/error";
import { renderHomePage } from "../pages/home";
import { initializeParams, origin } from "./init";

Expand Down Expand Up @@ -51,8 +50,7 @@ export async function handlePanel(request, env) {
return new Response('Success', { status: 200 });
}

const { kvNotFound, proxySettings } = await getDataset(request, env);
if (kvNotFound) return await renderErrorPage(request, env, 'KV Dataset is not properly set!', null, true);
const { proxySettings } = await getDataset(request, env);
const pwd = await env.bpb.get('pwd');
if (pwd && !auth) return Response.redirect(`${origin}/login`, 302);
const isPassSet = pwd?.length >= 8;
Expand Down
6 changes: 3 additions & 3 deletions src/helpers/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,16 @@ function initParams(request, env) {
trojanPassword = env.TROJAN_PASS;
const url = new URL(request.url);
pathName = url.pathname;
hostName = request.headers.get('Host');
if (pathName !== '/secrets') {
if (!userID || !trojanPassword) throw new Error("Please set UUID and Trojan password first.");
if (userID && !isValidUUID(userID)) throw new Error(`Invalid UUID: ${userID}`);
if (!userID || !trojanPassword) throw new Error(`Please set UUID and Trojan password first. Please go to 🟢 https://${hostName}/secrets 🟢`, { cause: "init"});
if (userID && !isValidUUID(userID)) throw new Error(`Invalid UUID: ${userID}`, { cause: "init"});
}
dohURL = env.DOH_URL || 'https://cloudflare-dns.com/dns-query';
proxyIP = proxyIPs ? proxyIPs[Math.floor(Math.random() * proxyIPs.length)] : defaultProxyIP;
defaultHttpPorts = ['80', '8080', '2052', '2082', '2086', '2095', '8880'];
defaultHttpsPorts = ['443', '8443', '2053', '2083', '2087', '2096'];
panelVersion = '2.7.7';
hostName = request.headers.get('Host');
const searchParams = new URLSearchParams(url.search);
client = searchParams.get('app');
origin = url.origin;
Expand Down
8 changes: 3 additions & 5 deletions src/kv/handlers.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@ import { fetchWarpConfigs } from '../protocols/warp';
import { isDomain, resolveDNS } from '../helpers/helpers';
import { initializeParams, panelVersion } from '../helpers/init';
import { Authenticate } from '../authentication/auth';
import { renderErrorPage } from '../pages/error';

export async function getDataset(request, env) {
await initializeParams(request, env);
let proxySettings, warpConfigs;
if (typeof env.bpb !== 'object') {
return {kvNotFound: true, proxySettings: null, warpConfigs: null}
throw new Error('KV Dataset is not properly set!', { cause: "init"});
}

try {
Expand All @@ -27,7 +26,7 @@ export async function getDataset(request, env) {
}

if (panelVersion !== proxySettings.panelVersion) proxySettings = await updateDataset(request, env);
return {kvNotFound: false, proxySettings, warpConfigs}
return { proxySettings, warpConfigs }
}

export async function updateDataset (request, env) {
Expand Down Expand Up @@ -166,8 +165,7 @@ export async function updateWarpConfigs(request, env) {
if (!auth) return new Response('Unauthorized', { status: 401 });
if (request.method === 'POST') {
try {
const { kvNotFound, proxySettings } = await getDataset(request, env);
if (kvNotFound) return await renderErrorPage(request, env, 'KV Dataset is not properly set!', null, true);
const { proxySettings } = await getDataset(request, env);
const { error: warpPlusError } = await fetchWarpConfigs(env, proxySettings);
if (warpPlusError) return new Response(warpPlusError, { status: 400 });
return new Response('Warp configs updated successfully', { status: 200 });
Expand Down
14 changes: 4 additions & 10 deletions src/pages/error.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import { initializeParams, panelVersion } from "../helpers/init";

export async function renderErrorPage (request, env, message, error, refer) {
await initializeParams(request, env);
export async function renderErrorPage (error) {
const errorPage = `
<!DOCTYPE html>
<html lang="en">
Expand Down Expand Up @@ -40,13 +37,10 @@ export async function renderErrorPage (request, env, message, error, refer) {
</head>
<body>
<div id="error-container">
<h1>BPB Panel <span style="font-size: smaller;">${panelVersion}</span> 💦</h1>
<h1>BPB Panel 💦</h1>
<div id="error-message">
<h2>${message} ${refer
? 'Please try again or refer to <a href="https://github.com/bia-pain-bache/BPB-Worker-Panel/blob/main/README.md">documents</a>'
: ''}
</h2>
<p><b>${error ? `⚠️ ${error.stack.toString()}` : ''}</b></p>
<h2>❌ Something went wrong!</h2>
<p><b>${error ? `⚠️ ${error.cause ? error.message.toString() : error.stack.toString()}` : ''}</b></p>
</div>
</div>
<script>
Expand Down
4 changes: 2 additions & 2 deletions src/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { renderSecretsPage } from './pages/secrets';

export default {
async fetch(request, env) {
try {
try {
const upgradeHeader = request.headers.get('Upgrade');
await initializeParams(request, env);
if (!upgradeHeader || upgradeHeader !== 'websocket') {
Expand Down Expand Up @@ -65,7 +65,7 @@ export default {
: await vlessOverWSHandler(request, env);
}
} catch (err) {
return await renderErrorPage(request, env, 'Something went wrong!', err, false);
return await renderErrorPage(err);
}
}
};

0 comments on commit d74ad7b

Please sign in to comment.