fix: option to toggle on/off system proxy env variables (#2724)

fix: option to toggle on/off system proxy env variables
This commit is contained in:
lohit 2024-08-30 11:44:29 +05:30 committed by GitHub
parent 93080de2a8
commit c1ec95dc29
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
10 changed files with 547 additions and 388 deletions

View File

@ -6,14 +6,28 @@ import * as Yup from 'yup';
import toast from 'react-hot-toast';
import { IconEye, IconEyeOff } from '@tabler/icons';
import { useState } from 'react';
import { useMemo } from 'react';
import { cloneDeep } from 'lodash';
const ProxySettings = ({ proxyConfig: _proxyConfig, onUpdate }) => {
const proxyConfig = useMemo(() => {
const proxyConfigCopy = cloneDeep(_proxyConfig);
// backward compatibility check
if (proxyConfigCopy?.enabled == 'true') proxyConfigCopy.enabled = true;
if (proxyConfigCopy?.enabled == 'false') proxyConfigCopy.enabled = false;
proxyConfigCopy.enabled = ['string', 'boolean'].includes(typeof proxyConfigCopy?.enabled)
? proxyConfigCopy?.enabled
: 'global';
return proxyConfigCopy;
}, [_proxyConfig]);
const ProxySettings = ({ proxyConfig, onUpdate }) => {
const proxySchema = Yup.object({
enabled: Yup.string().oneOf(['global', 'true', 'false']),
enabled: Yup.mixed().oneOf([false, true, 'global']),
protocol: Yup.string().oneOf(['http', 'https', 'socks4', 'socks5']),
hostname: Yup.string()
.when('enabled', {
is: 'true',
is: true,
then: (hostname) => hostname.required('Specify the hostname for your proxy.'),
otherwise: (hostname) => hostname.nullable()
})
@ -26,7 +40,7 @@ const ProxySettings = ({ proxyConfig, onUpdate }) => {
.transform((_, val) => (val ? Number(val) : null)),
auth: Yup.object()
.when('enabled', {
is: 'true',
is: true,
then: Yup.object({
enabled: Yup.boolean(),
username: Yup.string()
@ -49,7 +63,7 @@ const ProxySettings = ({ proxyConfig, onUpdate }) => {
const formik = useFormik({
initialValues: {
enabled: proxyConfig.enabled || 'global',
enabled: proxyConfig.enabled,
protocol: proxyConfig.protocol || 'http',
hostname: proxyConfig.hostname || '',
port: proxyConfig.port || '',
@ -65,13 +79,6 @@ const ProxySettings = ({ proxyConfig, onUpdate }) => {
proxySchema
.validate(values, { abortEarly: true })
.then((validatedProxy) => {
// serialize 'enabled' to boolean
if (validatedProxy.enabled === 'true') {
validatedProxy.enabled = true;
} else if (validatedProxy.enabled === 'false') {
validatedProxy.enabled = false;
}
onUpdate(validatedProxy);
})
.catch((error) => {
@ -84,7 +91,7 @@ const ProxySettings = ({ proxyConfig, onUpdate }) => {
useEffect(() => {
formik.setValues({
enabled: proxyConfig.enabled === true ? 'true' : proxyConfig.enabled === false ? 'false' : 'global',
enabled: proxyConfig.enabled,
protocol: proxyConfig.protocol || 'http',
hostname: proxyConfig.hostname || '',
port: proxyConfig.port || '',
@ -118,41 +125,50 @@ const ProxySettings = ({ proxyConfig, onUpdate }) => {
/>
</label>
<div className="flex items-center">
<label className="flex items-center">
<label className="flex items-center cursor-pointer">
<input
type="radio"
name="enabled"
value="global"
checked={formik.values.enabled === 'global'}
onChange={formik.handleChange}
className="mr-1"
className="mr-1 cursor-pointer"
/>
global
</label>
<label className="flex items-center ml-4">
<label className="flex items-center ml-4 cursor-pointer">
<input
type="radio"
name="enabled"
value={'true'}
checked={formik.values.enabled === 'true'}
onChange={formik.handleChange}
className="mr-1"
checked={formik.values.enabled === true}
onChange={(e) => {
formik.setFieldValue('enabled', true);
}}
className="mr-1 cursor-pointer"
/>
enabled
</label>
<label className="flex items-center ml-4">
<label className="flex items-center ml-4 cursor-pointer">
<input
type="radio"
name="enabled"
value={'false'}
checked={formik.values.enabled === 'false'}
onChange={formik.handleChange}
className="mr-1"
checked={formik.values.enabled === false}
onChange={(e) => {
formik.setFieldValue('enabled', false);
}}
className="mr-1 cursor-pointer"
/>
disabled
</label>
</div>
</div>
{formik.values.enabled === 'global' ? (
<div className="opacity-50">Global proxy can be configured in the app preferences.</div>
) : null}
{formik.values.enabled === true ? (
<>
<div className="mb-3 flex items-center">
<label className="settings-label" htmlFor="protocol">
Protocol
@ -298,7 +314,11 @@ const ProxySettings = ({ proxyConfig, onUpdate }) => {
className="btn btn-sm absolute right-0"
onClick={() => setPasswordVisible(!passwordVisible)}
>
{passwordVisible ? <IconEyeOff size={18} strokeWidth={1.5} /> : <IconEye size={18} strokeWidth={1.5} />}
{passwordVisible ? (
<IconEyeOff size={18} strokeWidth={1.5} />
) : (
<IconEye size={18} strokeWidth={1.5} />
)}
</button>
</div>
{formik.touched.auth?.password && formik.errors.auth?.password ? (
@ -326,6 +346,8 @@ const ProxySettings = ({ proxyConfig, onUpdate }) => {
<div className="ml-3 text-red-500">{formik.errors.bypassProxy}</div>
) : null}
</div>
</>
) : null}
<div className="mt-6">
<button type="submit" className="submit btn btn-sm btn-secondary">
Save

View File

@ -2,7 +2,7 @@ import styled from 'styled-components';
const StyledWrapper = styled.div`
.settings-label {
width: 80px;
width: 100px;
}
.textbox {

View File

@ -8,17 +8,33 @@ import StyledWrapper from './StyledWrapper';
import { useDispatch, useSelector } from 'react-redux';
import { IconEye, IconEyeOff } from '@tabler/icons';
import { useState } from 'react';
import { useMemo } from 'react';
import { cloneDeep } from 'lodash';
const ProxySettings = ({ close }) => {
const preferences = useSelector((state) => state.app.preferences);
const _preferences = useSelector((state) => state.app.preferences);
const systemProxyEnvVariables = useSelector((state) => state.app.systemProxyEnvVariables);
const { http_proxy, https_proxy, no_proxy } = systemProxyEnvVariables || {};
const dispatch = useDispatch();
const preferences = useMemo(() => {
const preferencesCopy = cloneDeep(_preferences);
// backward compatibility check
if (typeof preferencesCopy?.proxy?.enabled === 'boolean') {
preferencesCopy.proxy.mode = preferencesCopy?.proxy?.enabled ? 'on' : 'off';
} else {
preferencesCopy.proxy.mode =
typeof preferencesCopy?.proxy?.mode === 'string' ? preferencesCopy?.proxy?.mode : 'off';
}
return preferencesCopy;
}, [_preferences]);
const proxySchema = Yup.object({
enabled: Yup.boolean(),
mode: Yup.string().oneOf(['off', 'on', 'system']),
protocol: Yup.string().required().oneOf(['http', 'https', 'socks4', 'socks5']),
hostname: Yup.string()
.when('enabled', {
is: true,
is: 'on',
then: (hostname) => hostname.required('Specify the hostname for your proxy.'),
otherwise: (hostname) => hostname.nullable()
})
@ -31,7 +47,7 @@ const ProxySettings = ({ close }) => {
.transform((_, val) => (val ? Number(val) : null)),
auth: Yup.object()
.when('enabled', {
is: true,
is: 'on',
then: Yup.object({
enabled: Yup.boolean(),
username: Yup.string()
@ -54,7 +70,7 @@ const ProxySettings = ({ close }) => {
const formik = useFormik({
initialValues: {
enabled: preferences.proxy.enabled || false,
mode: preferences.proxy.mode,
protocol: preferences.proxy.protocol || 'http',
hostname: preferences.proxy.hostname || '',
port: preferences.proxy.port || 0,
@ -94,7 +110,7 @@ const ProxySettings = ({ close }) => {
useEffect(() => {
formik.setValues({
enabled: preferences.proxy.enabled || false,
mode: preferences.proxy.mode,
protocol: preferences.proxy.protocol || 'http',
hostname: preferences.proxy.hostname || '',
port: preferences.proxy.port || '',
@ -109,14 +125,77 @@ const ProxySettings = ({ close }) => {
return (
<StyledWrapper>
<h1 className="font-medium mb-3">Global Proxy Settings</h1>
<form className="bruno-form" onSubmit={formik.handleSubmit}>
<div className="mb-3 flex items-center">
<label className="settings-label" htmlFor="enabled">
Enabled
<label className="settings-label" htmlFor="protocol">
Mode
</label>
<div className="flex items-center">
<label className="flex items-center cursor-pointer">
<input
type="radio"
name="mode"
value="false"
checked={formik.values.mode === 'off'}
onChange={(e) => {
formik.setFieldValue('mode', 'off');
}}
className="mr-1 cursor-pointer"
/>
off
</label>
<label className="flex items-center ml-4 cursor-pointer">
<input
type="radio"
name="mode"
value="true"
checked={formik.values.mode === 'on'}
onChange={(e) => {
formik.setFieldValue('mode', 'on');
}}
className="mr-1 cursor-pointer"
/>
on
</label>
<label className="flex items-center ml-4 cursor-pointer">
<input
type="radio"
name="mode"
value="system"
checked={formik.values.mode === 'system'}
onChange={formik.handleChange}
className="mr-1 cursor-pointer"
/>
system
</label>
<input type="checkbox" name="enabled" checked={formik.values.enabled} onChange={formik.handleChange} />
</div>
</div>
{formik?.values?.mode === 'system' ? (
<div className="mb-3 flex items-start pb-3">
<div className="flex flex-col gap-2 justify-start items-start">
<div className="mb-3 flex items-center">
<label className="settings-label" htmlFor="http_proxy">
http_proxy
</label>
<div className="opacity-80">{http_proxy || '-'}</div>
</div>
<div className="mb-3 flex items-center">
<label className="settings-label" htmlFor="https_proxy">
https_proxy
</label>
<div className="opacity-80">{https_proxy || '-'}</div>
</div>
<div className="mb-3 flex items-center">
<label className="settings-label" htmlFor="no_proxy">
no_proxy
</label>
<div className="opacity-80">{no_proxy || '-'}</div>
</div>
</div>
</div>
) : null}
{formik?.values?.mode === 'on' ? (
<>
<div className="mb-3 flex items-center">
<label className="settings-label" htmlFor="protocol">
Protocol
@ -168,7 +247,6 @@ const ProxySettings = ({ close }) => {
</label>
</div>
</div>
<div className="mb-3 flex items-center">
<label className="settings-label" htmlFor="hostname">
Hostname
@ -291,6 +369,8 @@ const ProxySettings = ({ close }) => {
<div className="ml-3 text-red-500">{formik.errors.bypassProxy}</div>
) : null}
</div>
</>
) : null}
<div className="mt-6">
<button type="submit" className="submit btn btn-md btn-secondary">
Save

View File

@ -1,5 +1,10 @@
import { useEffect } from 'react';
import { showPreferences, updateCookies, updatePreferences } from 'providers/ReduxStore/slices/app';
import {
showPreferences,
updateCookies,
updatePreferences,
updateSystemProxyEnvVariables
} from 'providers/ReduxStore/slices/app';
import {
brunoConfigUpdateEvent,
collectionAddDirectoryEvent,
@ -136,6 +141,10 @@ const useIpcEvents = () => {
dispatch(updatePreferences(val));
});
const removeSystemProxyEnvUpdatesListener = ipcRenderer.on('main:load-system-proxy-env', (val) => {
dispatch(updateSystemProxyEnvVariables(val));
});
const removeCookieUpdateListener = ipcRenderer.on('main:cookies-update', (val) => {
dispatch(updateCookies(val));
});
@ -155,6 +164,7 @@ const useIpcEvents = () => {
removeShowPreferencesListener();
removePreferencesUpdatesListener();
removeCookieUpdateListener();
removeSystemProxyEnvUpdatesListener();
};
}, [isElectron]);
};

View File

@ -27,7 +27,8 @@ const initialState = {
}
},
cookies: [],
taskQueue: []
taskQueue: [],
systemProxyEnvVariables: {}
};
export const appSlice = createSlice({
@ -72,6 +73,9 @@ export const appSlice = createSlice({
},
removeAllTasksFromQueue: (state) => {
state.taskQueue = [];
},
updateSystemProxyEnvVariables: (state, action) => {
state.systemProxyEnvVariables = action.payload;
}
}
});
@ -89,7 +93,8 @@ export const {
updateCookies,
insertTaskIntoQueue,
removeTaskFromQueue,
removeAllTasksFromQueue
removeAllTasksFromQueue,
updateSystemProxyEnvVariables
} = appSlice.actions;
export const savePreferences = (preferences) => (dispatch, getState) => {

View File

@ -8,7 +8,9 @@ const axios = require('axios');
*/
function makeAxiosInstance() {
/** @type {axios.AxiosInstance} */
const instance = axios.create();
const instance = axios.create({
proxy: false
});
instance.interceptors.request.use((config) => {
config.headers['request-start-time'] = Date.now();

View File

@ -49,7 +49,9 @@ const checkConnection = (host, port) =>
*/
function makeAxiosInstance() {
/** @type {axios.AxiosInstance} */
const instance = axios.create();
const instance = axios.create({
proxy: false
});
instance.interceptors.request.use(async (config) => {
const url = URL.parse(config.url);

View File

@ -167,19 +167,22 @@ const configureRequest = async (
// proxy configuration
let proxyConfig = get(brunoConfig, 'proxy', {});
let proxyEnabled = get(proxyConfig, 'enabled', 'global');
if (proxyEnabled === 'global') {
let proxyMode = get(proxyConfig, 'enabled', 'global');
if (proxyMode === 'global') {
proxyConfig = preferencesUtil.getGlobalProxyConfig();
proxyEnabled = get(proxyConfig, 'enabled', false);
proxyMode = get(proxyConfig, 'mode', false);
}
// proxyMode is true, if the collection-level proxy is enabled.
// proxyMode is 'on', if the app-level proxy mode is turned on.
if (proxyMode === true || proxyMode === 'on') {
const shouldProxy = shouldUseProxy(request.url, get(proxyConfig, 'bypassProxy', ''));
if (proxyEnabled === true && shouldProxy) {
if (shouldProxy) {
const proxyProtocol = interpolateString(get(proxyConfig, 'protocol'), interpolationOptions);
const proxyHostname = interpolateString(get(proxyConfig, 'hostname'), interpolationOptions);
const proxyPort = interpolateString(get(proxyConfig, 'port'), interpolationOptions);
const proxyAuthEnabled = get(proxyConfig, 'auth.enabled', false);
const socksEnabled = proxyProtocol.includes('socks');
let uriPort = isUndefined(proxyPort) || isNull(proxyPort) ? '' : `:${proxyPort}`;
let proxyUri;
if (proxyAuthEnabled) {
@ -190,7 +193,6 @@ const configureRequest = async (
} else {
proxyUri = `${proxyProtocol}://${proxyHostname}${uriPort}`;
}
if (socksEnabled) {
request.httpsAgent = new SocksProxyAgent(
proxyUri,
@ -204,12 +206,36 @@ const configureRequest = async (
);
request.httpAgent = new HttpProxyAgent(proxyUri);
}
}
} else if (proxyMode === 'system') {
const { http_proxy, https_proxy, no_proxy } = preferencesUtil.getSystemProxyEnvVariables();
const shouldUseSystemProxy = shouldUseProxy(request.url, no_proxy || '');
if (shouldUseSystemProxy) {
try {
if (http_proxy?.length) {
new URL(http_proxy);
request.httpAgent = new HttpProxyAgent(http_proxy);
}
} catch (error) {
throw new Error('Invalid system http_proxy');
}
try {
if (https_proxy?.length) {
new URL(https_proxy);
request.httpsAgent = new PatchedHttpsProxyAgent(
https_proxy,
Object.keys(httpsAgentRequestFields).length > 0 ? { ...httpsAgentRequestFields } : undefined
);
}
} catch (error) {
throw new Error('Invalid system https_proxy');
}
}
} else if (Object.keys(httpsAgentRequestFields).length > 0) {
request.httpsAgent = new https.Agent({
...httpsAgentRequestFields
});
}
const axiosInstance = makeAxiosInstance();
if (request.oauth2) {

View File

@ -1,5 +1,5 @@
const { ipcMain } = require('electron');
const { getPreferences, savePreferences } = require('../store/preferences');
const { getPreferences, savePreferences, preferencesUtil } = require('../store/preferences');
const { isDirectory } = require('../utils/filesystem');
const { openCollection } = require('../app/collections');
``;
@ -9,6 +9,10 @@ const registerPreferencesIpc = (mainWindow, watcher, lastOpenedCollections) => {
const preferences = getPreferences();
mainWindow.webContents.send('main:load-preferences', preferences);
const systemProxyVars = preferencesUtil.getSystemProxyEnvVariables();
const { http_proxy, https_proxy, no_proxy } = systemProxyVars || {};
mainWindow.webContents.send('main:load-system-proxy-env', { http_proxy, https_proxy, no_proxy });
// reload last opened collections
const lastOpened = lastOpenedCollections.getAll();

View File

@ -27,7 +27,7 @@ const defaultPreferences = {
codeFontSize: 14
},
proxy: {
enabled: false,
mode: 'off',
protocol: 'http',
hostname: '',
port: null,
@ -59,7 +59,7 @@ const preferencesSchema = Yup.object().shape({
codeFontSize: Yup.number().min(1).max(32).nullable()
}),
proxy: Yup.object({
enabled: Yup.boolean(),
mode: Yup.string().oneOf(['off', 'on', 'system']),
protocol: Yup.string().oneOf(['http', 'https', 'socks4', 'socks5']),
hostname: Yup.string().max(1024),
port: Yup.number().min(1).max(65535).nullable(),
@ -136,6 +136,14 @@ const preferencesUtil = {
},
shouldSendCookies: () => {
return get(getPreferences(), 'request.sendCookies', true);
},
getSystemProxyEnvVariables: () => {
const { http_proxy, HTTP_PROXY, https_proxy, HTTPS_PROXY, no_proxy, NO_PROXY } = process.env;
return {
http_proxy: http_proxy || HTTP_PROXY,
https_proxy: https_proxy || HTTPS_PROXY,
no_proxy: no_proxy || NO_PROXY
};
}
};