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 2, 2024
1 parent a0d8aaa commit a0473bb
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 75 deletions.
6 changes: 3 additions & 3 deletions src/kv/handlers.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { fetchWgConfig } from '../protocols/warp';
import { fetchWarpConfigs } from '../protocols/warp';
import { isDomain, resolveDNS } from '../helpers/helpers';
import { initializeParams, panelVersion } from '../helpers/init';
import { Authenticate } from '../authentication/auth';
Expand All @@ -21,7 +21,7 @@ export async function getDataset(request, env) {

if (!proxySettings) {
proxySettings = await updateDataset(request, env);
const { error, configs } = await fetchWgConfig(env, proxySettings);
const { error, configs } = await fetchWarpConfigs(env, proxySettings);
if (error) throw new Error(`An error occurred while getting Warp configs - ${error}`);
warpConfigs = configs;
}
Expand Down Expand Up @@ -166,7 +166,7 @@ export async function updateWarpConfigs(request, env) {
try {
const { kvNotFound, proxySettings } = await getDataset(request, env);
if (kvNotFound) return await renderErrorPage(request, env, 'KV Dataset is not properly set!', null, true);
const { error: warpPlusError } = await fetchWgConfig(env, proxySettings);
const { error: warpPlusError } = await fetchWarpConfigs(env, proxySettings);
if (warpPlusError) return new Response(warpPlusError, { status: 400 });
return new Response('Warp configs updated successfully', { status: 200 });
} catch (error) {
Expand Down
50 changes: 22 additions & 28 deletions src/pages/homePage.js
Original file line number Diff line number Diff line change
Expand Up @@ -1163,14 +1163,13 @@ export async function renderHomePage (request, env, proxySettings, isPassSet) {
document.body.style.cursor = 'default';
refreshBtn.innerHTML = refreshButtonVal;
if (response.ok) {
alert('✅ Panel settings reset to default successfully! 😎');
window.location.reload(true);
} else {
if (!response.ok) {
const errorMessage = await response.text();
console.error(errorMessage, response.status);
alert('⚠️ An error occured, Please try again!\\n⛔ ' + errorMessage);
}
}
alert('✅ Panel settings reset to default successfully! 😎');
window.location.reload(true);
} catch (error) {
console.error('Error:', error);
}
Expand All @@ -1183,14 +1182,11 @@ export async function renderHomePage (request, env, proxySettings, isPassSet) {
}
darkModeToggle.addEventListener('click', () => {
const isDarkMode = document.body.classList.toggle('dark-mode');
if (isDarkMode) {
localStorage.setItem('darkMode', 'enabled');
} else {
localStorage.setItem('darkMode', 'disabled');
}
localStorage.setItem('darkMode', isDarkMode ? 'enabled' : 'disabled');
});
if (${!isPassSet}) {
const isPassSet = ${isPassSet};
if (!isPassSet) {
forcedPassChange = true;
changePass.click();
}
Expand Down Expand Up @@ -1239,13 +1235,15 @@ export async function renderHomePage (request, env, proxySettings, isPassSet) {
document.body.style.cursor = 'default';
refreshBtn.innerHTML = refreshButtonVal;
if (response.ok) {
${isWarpPlus} ? alert('✅ Warp configs upgraded to PLUS successfully! 😎') : alert('✅ Warp configs updated successfully! 😎');
} else {
if (!response.ok) {
const errorMessage = await response.text();
console.error(errorMessage, response.status);
alert('⚠️ An error occured, Please try again!\\n⛔ ' + errorMessage);
}
}
${isWarpPlus
? `alert('✅ Warp configs upgraded to PLUS successfully! 😎');`
: `alert('✅ Warp configs updated successfully! 😎');`
}
} catch (error) {
console.error('Error:', error);
}
Expand Down Expand Up @@ -1372,14 +1370,14 @@ export async function renderHomePage (request, env, proxySettings, isPassSet) {
});
const invalidIPs = [...cleanIPs, proxyIP, ...customCdnAddrs, customCdnHost, customCdnSni]?.filter(value => {
if (value !== "") {
if (value) {
const trimmedValue = value.trim();
return !validIPDomain.test(trimmedValue);
}
});
const invalidEndpoints = warpEndpoints?.filter(value => {
if (value !== "") {
if (value) {
const trimmedValue = value.trim();
return !validEndpoint.test(trimmedValue);
}
Expand Down Expand Up @@ -1410,7 +1408,7 @@ export async function renderHomePage (request, env, proxySettings, isPassSet) {
return false;
}
if (isCustomCdn && !(customCdnAddrs.length > 0 && customCdnHost && customCdnSni)) {
if (isCustomCdn && !(customCdnAddrs.length && customCdnHost && customCdnSni)) {
alert('⛔ All "Custom" fields should be filled or deleted together! 🫤');
return false;
}
Expand All @@ -1429,15 +1427,14 @@ export async function renderHomePage (request, env, proxySettings, isPassSet) {
document.body.style.cursor = 'default';
applyButton.value = applyButtonVal;
if (response.ok) {
alert('✅ Parameters applied successfully 😎');
window.location.reload();
} else {
if (!response.ok) {
const errorMessage = await response.text();
console.error(errorMessage, response.status);
alert('⚠️ Session expired! Please login again.');
window.location.href = '/login';
}
}
alert('✅ Parameters applied successfully 😎');
window.location.reload();
} catch (error) {
console.error('Error:', error);
}
Expand All @@ -1452,11 +1449,8 @@ export async function renderHomePage (request, env, proxySettings, isPassSet) {
credentials: 'same-origin'
});
if (response.ok) {
window.location.href = '/login';
} else {
console.error('Failed to log out:', response.status);
}
if (!response.ok) console.error('Failed to log out:', response.status);
window.location.href = '/login';
} catch (error) {
console.error('Error:', error);
}
Expand Down
5 changes: 2 additions & 3 deletions src/pages/loginPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,13 +132,12 @@ export async function renderLoginPage (request, env) {
body: password
});
if (response.ok) {
window.location.href = '/panel';
} else {
if (!response.ok) {
passwordError.textContent = '⚠️ Wrong Password!';
const errorMessage = await response.text();
console.error('Login failed:', errorMessage);
}
window.location.href = '/panel';
} catch (error) {
console.error('Error during login:', error);
}
Expand Down
81 changes: 40 additions & 41 deletions src/protocols/warp.js
Original file line number Diff line number Diff line change
@@ -1,60 +1,60 @@
import nacl from 'tweetnacl';

export async function fetchWgConfig (env, proxySettings) {
export async function fetchWarpConfigs (env, proxySettings) {
let warpConfigs = [];
const apiBaseUrl = 'https://api.cloudflareclient.com/v0a4005/reg';

const { warpPlusLicense } = proxySettings;
const warpKeys = [generateKeyPair(), generateKeyPair()];
const warpKeys = [ generateKeyPair(), generateKeyPair() ];
const commonPayload = {
install_id: "",
fcm_token: "",
tos: new Date().toISOString(),
type: "Android",
model: 'PC',
locale: 'en_US',
warp_enabled: true
};

for(let i = 0; i < 2; i++) {
const accountResponse = await fetch(apiBaseUrl, {
const fetchAccount = async (key) => {
const response = await fetch(apiBaseUrl, {
method: 'POST',
headers: {
'User-Agent': 'insomnia/8.6.1',
'Content-Type': 'application/json'
},
body: JSON.stringify({
key: warpKeys[i].publicKey,
install_id: "",
fcm_token: "",
tos: new Date().toISOString(),
type: "Android",
model: 'PC',
locale: 'en_US',
warp_enabled: true
})
body: JSON.stringify({ ...commonPayload, key: key.publicKey })
});
return await response.json();
};

const accountData = await accountResponse.json();
warpConfigs.push ({
privateKey: warpKeys[i].privateKey,
const updateAccount = async (accountData, key) => {
const response = await fetch(`${apiBaseUrl}/${accountData.id}/account`, {
method: 'PUT',
headers: {
'User-Agent': 'insomnia/8.6.1',
'Content-Type': 'application/json',
'Authorization': `Bearer ${accountData.token}`
},
body: JSON.stringify({ ...commonPayload, key: key.publicKey, license: warpPlusLicense })
});
return {
status: response.status,
data: await response.json()
};
};

for (const key of warpKeys) {
const accountData = await fetchAccount(key);
warpConfigs.push({
privateKey: key.privateKey,
account: accountData
});

if (warpPlusLicense) {
const response = await fetch(`${apiBaseUrl}/${accountData.id}/account`, {
method: 'PUT',
headers: {
'User-Agent': 'insomnia/8.6.1',
'Content-Type': 'application/json',
'Authorization': `Bearer ${accountData.token}`
},
body: JSON.stringify({
key: warpKeys[i].publicKey,
install_id: "",
fcm_token: "",
tos: new Date().toISOString(),
type: "Android",
model: 'PC',
locale: 'en_US',
warp_enabled: true,
license: warpPlusLicense
})
});

const responseData = await response.json();
if(response.status !== 200 && !responseData.success) return { error: responseData.errors[0]?.message, configs: null}
const { status, data: responseData } = await updateAccount(accountData, key);
if (status !== 200 && !responseData.success) {
return { error: responseData.errors[0]?.message, configs: null };
}
}
}

Expand All @@ -72,6 +72,5 @@ const generateKeyPair = () => {
let publicKey = nacl.scalarMult.base(privateKey);
const publicKeyBase64 = base64Encode(publicKey);
const privateKeyBase64 = base64Encode(privateKey);

return { publicKey: publicKeyBase64, privateKey: privateKeyBase64 };
};

0 comments on commit a0473bb

Please sign in to comment.