Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: valid url check #1428

Merged
merged 6 commits into from
Mar 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 22 additions & 14 deletions electron/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,10 +141,11 @@ function createWindow() {
// Open default browser when direct to external
win.webContents.on('new-window', function (e, url) {
e.preventDefault();
if (!isValidURL(url)) {
const { isValid, finalURL } = isValidURL(url);
if (!isValid) {
return;
}
require('electron').shell.openExternal(url);
require('electron').shell.openExternal(finalURL);
});

// Hot Reloading
Expand Down Expand Up @@ -191,16 +192,17 @@ app.on('ready', async function () {
await new Promise(resolve => setTimeout(resolve, 20_000));

const autoUpdateExpireTime = store.get('autoUpdateExpireTime');
if(!autoUpdateExpireTime) {
if (!autoUpdateExpireTime) {
autoUpdater.checkForUpdatesAndNotify();
}
});

app.on('web-contents-created', (event, contents) => {

if (contents.getType() == 'window') {
contents.on('will-navigate', (event, url) => {
if (!isValidURL(url)) {
const { isValid } = isValidURL(url);
if (!isValid) {
event.preventDefault();
return;
}
Expand All @@ -211,38 +213,44 @@ app.on('web-contents-created', (event, contents) => {
// blocks any new windows from being opened
contents.setWindowOpenHandler((detail) => {

if (isValidURL(detail.url)) {
return {action: 'allow'};
const { isValid } = isValidURL(detail.url);

if (isValid) {
return { action: 'allow' };
}

console.log('open url reject, not valid', detail.url);
return {action: 'deny'};
return { action: 'deny' };
})

// new-window api deprecated, but still working for now
contents.on('new-window', (event, url, frameName, disposition, options) => {
options.webPreferences = {
...options.webPreferences,
javascript: false,
};

if (!isValidURL(url)) {

const { isValid, finalURL } = isValidURL(url);

if (!isValid) {
event.preventDefault();
return;
}

require('electron').shell.openExternal(url);
require('electron').shell.openExternal(finalURL);
})

contents.on('will-navigate', (event, url) => {
if (!isValidURL(url)) {
const { isValid } = isValidURL(url);
if (!isValid) {
event.preventDefault();
}
})

// blocks 301/302 redirect if the url is not valid
contents.on('will-redirect', (event, url) => {
if (!isValidURL(url)) {
const { isValid } = isValidURL(url);
if (!isValid) {
event.preventDefault();
}
})
Expand Down
31 changes: 21 additions & 10 deletions electron/utils.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
export function isValidURL(str: string) {
const regex = new RegExp(
'^(http[s]?:\\/\\/(www\\.)?|www\\.){1}([0-9A-Za-z-\\.@:%_+~#=]+)+((\\.[a-zA-Z]{2,3})+)(/(.)*)?(\\?(.)*)?', // lgtm [js/redos]
);

const withoutPrefixRegex = new RegExp(
'^([0-9A-Za-z-\\.@:%_+~#=]+)+((\\.[a-zA-Z]{2,3})+)(/(.)*)?(\\?(.)*)?', // lgtm [js/redos]
);
return regex.test(str) || withoutPrefixRegex.test(str);
import { URL } from 'url';

interface ValidURLCheckResult {
isValid: boolean;
finalURL: string;
}


export function isValidURL(str: string): ValidURLCheckResult {
try {
if (!str.startsWith('https://') && !str.startsWith('http://')) {
str = 'https://' + str;
}
const parsedUrl = new URL(str);
const regex = /^([a-zA-Z0-9-_.:]+)+$/;
return {
isValid: regex.test(parsedUrl.host),
finalURL: str
};
} catch (e) {
return { isValid: false, finalURL: str };
}
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"main": "build/electron/main.js",
"private": true,
"scripts": {
"run-audit": "yarn audit-ci --high -a 1094574 1096494 1096640",
"run-audit": "yarn audit-ci --high -a 1094574 1096494 1096698 1096729 1096804",
"start": "node scripts/start.js",
"build": "cross-env NODE_OPTIONS=--max_old_space_size=8192 && yarn clean-builds && node scripts/build.js",
"test": "node scripts/test.js --watchAll=false",
Expand Down
15 changes: 8 additions & 7 deletions src/pages/dapp/dapp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import logoFerroProtocol from './assets/ferro.png';

import AddressBar from './components/AddressBar/AddressBar';
import SavedTab from './components/Tabs/SavedTab';
import { isLocalhostURL, isValidURL } from '../../utils/utils';
import { isValidURL } from '../../utils/utils';
import { IWebviewNavigationState, WebviewState } from './browser/useWebviewStatusInfo';
import { useBookmark } from './hooks/useBookmark';
import { useShowDisclaimer } from './hooks/useShowDisclaimer';
Expand Down Expand Up @@ -242,14 +242,15 @@ const DappPage = () => {
}}
onSearch={value => {
setSelectedDapp(undefined);
// detect whether it's a domain
if (isValidURL(value) || isLocalhostURL(value)) {
const { isValid, finalURL } = isValidURL(value);
if (isValid) {
// jump to website
setSelectedURL(value);
} else {
// google search
setSelectedURL(`https://www.google.com/search?q=${value}`);
setSelectedURL(finalURL);
}
// else {
// // google search
// setSelectedURL(`https://www.google.com/search?q=${finalURL}`);
// }
}}
/>
{shouldShowBrowser && (
Expand Down
39 changes: 38 additions & 1 deletion src/utils/utils.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { bech32ToEVMAddress } from './utils';
import { bech32ToEVMAddress, isValidURL } from './utils';

describe('Testing Common utils functions', () => {
it('Test decoding Bech32 address ', () => {
Expand All @@ -10,3 +10,40 @@ describe('Testing Common utils functions', () => {
expect(decoded1).toBe('0xffd3a0042C75DDa5d41e7aa620ecB970237F513a');
});
});

// const invalidURLs = [
// "smb://domain.com",
// "vvs.finance\x00%00file:///etc/passwd",
// "https://vvs.finance\x00%00file:///etc/passwd",
// "ms-msdt:id%20PCWDiagnostic%20%2Fmoreoptions%20false%20%2Fskip%20true%20%2Fparam%20IT_BrowseForFile%3D%22%5Cattacker.comsmb_sharemalicious_executable.exe%22%20%2Fparam%20IT_SelectProgram%3D%22NotListed%22%20%2Fparam%20IT_AutoTroubleshoot%3D%22ts_AUTO%22",
// "search-ms:query=malicious_executable.exe&crumb=location:%5C%[5Cattacker.com](<http://5cattacker.com/>)%5Csmb_share%5Ctools&displayname=Important%20update",
// "ms-officecmd:%7B%22id%22:3,%22LocalProviders.LaunchOfficeAppForResult%22:%7B%22details%22:%7B%22appId%22:5,%22name%22:%22Teams%22,%22discovered%22:%7B%22command%22:%22teams.exe%22,%22uri%22:%22msteams%22%7D%7D,%22filename%22:%22a:/b/%2520--disable-gpu-sandbox%2520--gpu-launcher=%22C:%5CWindows%5CSystem32%5Ccmd%2520/c%2520ping%252016843009%2520&&%2520%22%22%7D%7D",
// "mailto:abc.com",
// "file:/net/attacker.tld/path/to/export",
// "ms-excel:ofv|u|https://www.cmu.edu/blackboard/files/evaluate/tests-example.xls",
// "http://fulcrom.finance:7890",
// "https://fulcrom.finance:7890",
// "https://abc:adsof@crypto.com",
// "vvs.",
// ".vvs",
// ]

// const validURLs = [
// "fulcrom.finance",
// "http://www.google.com",
// "https://fulcrom.finance",
// ]

// describe('valid url checks', () => {
// validURLs.forEach(url => {
// it(`${url} is valid`, () => {
// expect(isValidURL(url)).toBe(true);
// })
// });

// invalidURLs.forEach(url => {
// it(`${url} is invalid`, () => {
// expect(isValidURL(url)).toBe(false);
// })
// });
// });
31 changes: 21 additions & 10 deletions src/utils/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -210,9 +210,9 @@ export function getChainName(name: string | undefined = '', config: WalletConfig
return name.replace('Chain', 'Goerli Testnet');

case SupportedChainName.CRONOS_TENDERMINT: {
if(config.network.chainId.indexOf('croeseid-4') !== -1)
if (config.network.chainId.indexOf('croeseid-4') !== -1)
return name.replace('Chain', 'Testnet Croeseid 4');

return name.replace('Chain', 'Testnet Croeseid 5');
}
default:
Expand Down Expand Up @@ -306,17 +306,28 @@ export function isLocalhostURL(str: string) {
}
}

export function isValidURL(str: string) {
const regex = new RegExp(
'^(http[s]?:\\/\\/(www\\.)?|www\\.){1}([0-9A-Za-z-\\.@:%_+~#=]+)+((\\.[a-zA-Z]{2,3})+)(/(.)*)?(\\?(.)*)?', // lgtm [js/redos]
);
interface ValidURLCheckResult {
isValid: boolean;
finalURL: string;
}

const withoutPrefixRegex = new RegExp(
'^([0-9A-Za-z-\\.@:%_+~#=]+)+((\\.[a-zA-Z]{2,3})+)(/(.)*)?(\\?(.)*)?', // lgtm [js/redos]
);
return regex.test(str) || withoutPrefixRegex.test(str);
export function isValidURL(str: string): ValidURLCheckResult {
try {
// if (!str.startsWith('https://') && !str.startsWith('http://')) {
// str = 'https://' + str;
// }
const parsedUrl = new URL(str);
const regex = /^([a-zA-Z0-9-_.:]+)+$/;
return {
isValid: regex.test(parsedUrl.host),
finalURL: str
};
} catch (e) {
return { isValid: false, finalURL: str };
}
}


export function addHTTPsPrefixIfNeeded(str: string) {
if (str.startsWith('http://') || str.startsWith('https://')) {
return str;
Expand Down
Loading
Loading