Skip to content

fix: system proxy resolver logic updates - #6273

Merged
bijin-bruno merged 1 commit into
usebruno:mainfrom
lohit-bruno:system_proxy_updates
Jan 29, 2026
Merged

bijin-bruno merged 1 commit into
usebruno:mainfrom
lohit-bruno:system_proxy_updates

Conversation

@lohit-bruno

@lohit-bruno lohit-bruno commented Dec 2, 2025 •

Copy link
Copy Markdown
Collaborator

jira

Description

Contribution Checklist:

  • The pull request only addresses one issue or adds one feature.
  • The pull request does not introduce any breaking changes
  • I have added screenshots or gifs to help explain the change if applicable.
  • I have read the contribution guidelines.
  • Create an issue and link to the pull request.

Note: Keeping the PR small and focused helps make it easier to review and merge. If you have multiple changes you want to make, please consider submitting them as separate pull requests.

Publishing to New Package Managers

Please see here for more information.

Summary by CodeRabbit

  • New Features

    • Cross-platform system proxy detection and a System Proxy view in Preferences showing detected http/https/no_proxy values.
  • Improvements

    • CLI and app apply detected system proxy appropriately for HTTP vs HTTPS.
    • Preferences fetch system proxy on demand; related state/actions clarified.
    • UI styling refinements for the system proxy section.
  • Tests

    • Extensive unit and integration tests for system proxy detection and URL normalization.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Dec 2, 2025 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

Failed to post review comments

Walkthrough

Adds a cross-platform system proxy detection subsystem (getSystemProxy) with platform resolvers, reworks IPC to fetch system proxy on-demand, updates CLI/Electron proxy handling to use detected system proxy, migrates preference proxy shape, and adds UI/state components to display system proxy values.

Changes

Cohort / File(s) Summary
UI Components
packages/bruno-app/src/components/Preferences/ProxySettings/index.js, packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js, packages/bruno-app/src/components/Preferences/ProxySettings/StyledWrapper.js
Replaces inline system-proxy rendering with a new SystemProxy component that dispatches getSystemProxyVariables thunk; adds loading/error/source UI and styling.
Redux + IPC (renderer)
packages/bruno-app/src/providers/ReduxStore/slices/app.js, packages/bruno-app/src/providers/App/useIpcEvents.js
Renames systemProxyEnvVariables → systemProxyVariables, action updateSystemProxyEnvVariables → updateSystemProxyVariables, adds getSystemProxyVariables thunk; removes eager IPC listener for system proxy push.
Electron IPC & Preferences
packages/bruno-electron/src/ipc/preferences.js, packages/bruno-electron/src/store/preferences.js
Removes eager emission of system proxy on renderer ready; adds handler renderer:get-system-proxy-variables (calls getSystemProxy); migrates default/global proxy shape and preference migrations to new nested proxy structure.
Electron Networking / Certs
packages/bruno-electron/src/ipc/network/cert-utils.js
When proxy mode resolves to system, awaits getSystemProxy() and overwrites proxyConfig with resolved system proxy config.
Electron Proxy Utilities
packages/bruno-electron/src/utils/proxy-util.js
Replaces direct HttpProxyAgent with a TimelineHttpProxyAgent wrapper (timeline logging, validation, keepAlive); applies proxy agents conditionally based on request scheme and provided proxyConfig.
CLI Proxy Handling
packages/bruno-cli/src/runner/run-single-request.js, packages/bruno-cli/src/utils/proxy-util.js
Replaces env-based system proxy sourcing with getSystemProxy() from @usebruno/requests; awaits system proxy, selects http_proxy or https_proxy based on request scheme, and adds explicit errors for invalid system proxies.
Requests Library Exports
packages/bruno-requests/src/index.ts, packages/bruno-requests/src/network/index.ts
Re-exports getSystemProxy from the new system-proxy module; consolidates makeAxiosInstance export location.
System Proxy Core & Types
packages/bruno-requests/src/network/system-proxy/index.ts, packages/bruno-requests/src/network/system-proxy/types.ts
Adds SystemProxyResolver with in-flight deduplication, environment-first logic, platform delegation, and top-level getSystemProxy(); defines ProxyConfiguration, ProxyResolver, and options types.
Normalization & Exec Utilities
packages/bruno-requests/src/network/system-proxy/utils/common.ts, .../common.spec.ts
Adds execFileAsync/safeExec, normalizeProxyUrl, and normalizeNoProxy utilities with unit tests.
Windows resolver & tests
packages/bruno-requests/src/network/system-proxy/utils/windows.ts, .../windows.spec.ts
Adds WindowsProxyResolver with multiple detectors (Internet Options, WinHTTP, env fallbacks) and comprehensive tests.
macOS resolver & tests
packages/bruno-requests/src/network/system-proxy/utils/macos.ts, .../macos.spec.ts
Adds MacOSProxyResolver parsing scutil output and tests covering many scenarios.
Linux resolver & tests
packages/bruno-requests/src/network/system-proxy/utils/linux.ts, .../linux.spec.ts
Adds LinuxProxyResolver covering GNOME/KDE/environment/systemd detectors and tests.
Integration tests
packages/bruno-requests/src/network/system-proxy/index.spec.js
Adds integration tests for SystemProxyResolver (platform routing, env precedence, timeouts, error handling).
Removed / Simplified helpers
packages/bruno-cli/src/utils/proxy-util.js, packages/bruno-app/src/providers/App/useIpcEvents.js
Removes legacy getSystemProxyEnvVariables helper and related IPC push flow; code now uses centralized getSystemProxy.
Tests / Migrations
packages/bruno-electron/tests/store/proxy-preferences.spec.js, packages/bruno-app/...
Adds migration tests for default proxy injection and other test coverage for new behavior.

Sequence Diagram(s)

sequenceDiagram
    participant UI as React UI
    participant Redux as Redux slice
    participant Renderer as Renderer (ipcRenderer)
    participant Main as Main (ipcMain)
    participant Requests as bruno-requests:getSystemProxy
    participant Resolver as Platform Resolver

    UI->>Redux: dispatch(getSystemProxyVariables())
    Redux->>Renderer: ipcRenderer.invoke('renderer:get-system-proxy-variables')
    Renderer->>Main: IPC invoke -> renderer:get-system-proxy-variables
    Main->>Requests: getSystemProxy()
    Requests->>Requests: read environment variables
    alt env vars present
        Requests-->>Main: return ProxyConfiguration (source: environment)
    else
        Requests->>Resolver: detect(platform) with timeout
        Resolver-->>Requests: ProxyConfiguration (source: platform)
    end
    Main-->>Renderer: ProxyConfiguration
    Renderer-->>Redux: resolved data
    Redux->>UI: updateSystemProxyVariables
    UI->>UI: render http_proxy / https_proxy / no_proxy / source
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

Suggested reviewers

  • naman-bruno
  • bijin-bruno

Poem

🌐 Bruno asks the system where the proxies hide,
Windows, Mac, Linux each now give a guide,
Thunks and IPC fetch the truth on demand,
Agents log timelines as connections expand,
Network paths aligned — let requests glide 🚀

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 19.05% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: a refactoring of system proxy resolver logic to use a new getSystemProxy function instead of environment variables.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/bruno-cli/src/runner/run-single-request.js (2)

306-313: Duplicate getSystemProxy() call detected.

getSystemProxy() is called here at line 306 and again at line 353. This function performs OS-level detection (spawning scutil on macOS, reading registry on Windows, etc.), which is unnecessarily expensive to run twice.

Store the result and reuse it:

+  let systemProxy = null;
+  
   if (noproxy) {
     // If noproxy flag is set, don't use any proxy
     proxyMode = 'off';
   } else if (collectionProxyEnabled === true) {
     // If collection proxy is enabled, use it
     proxyConfig = collectionProxyConfig;
     proxyMode = 'on';
   } else if (collectionProxyEnabled === 'global') {
     // If collection proxy is set to 'global', use system proxy
-    const systemProxy = await getSystemProxy();
-    const { http_proxy, https_proxy } = systemProxy;
+    systemProxy = await getSystemProxy();
+    const { http_proxy, https_proxy } = systemProxy;
     if (http_proxy?.length || https_proxy?.length) {
       proxyMode = 'system';
     }

Then at line 353, reuse systemProxy instead of calling getSystemProxy() again.


351-389: Refactor to reuse system proxy result and improve error handling.

The current implementation has two issues:

  1. Duplicate call to getSystemProxy() (see previous comment)
  2. Inner throws at lines 365 and 378 are caught by the outer catch at line 385, which silently falls back to no proxy. This hides configuration errors from the user.
   } else if (proxyMode === 'system') {
-    try {
-      const systemProxy = await getSystemProxy();
-      const { http_proxy, https_proxy, no_proxy } = systemProxy;
+      const { http_proxy, https_proxy, no_proxy } = systemProxy || {};
       const shouldUseSystemProxy = shouldUseProxy(request.url, no_proxy || '');
       const parsedUrl = parseUrl(request.url);
       const isHttpsRequest = parsedUrl.protocol === 'https:';
+      
       if (shouldUseSystemProxy) {
-        try {
-          if (http_proxy?.length && !isHttpsRequest) {
+        if (http_proxy?.length && !isHttpsRequest) {
+          try {
             new URL(http_proxy);
             request.httpAgent = new HttpProxyAgent(http_proxy);
+          } catch (error) {
+            console.log(chalk.yellow('Warning: Invalid system http_proxy URL, skipping proxy'));
           }
-        } catch (error) {
-          throw new Error('Invalid system http_proxy');
         }
-        try {
-          if (https_proxy?.length && isHttpsRequest) {
+        if (https_proxy?.length && isHttpsRequest) {
+          try {
             new URL(https_proxy);
-            request.httpsAgent = new PatchedHttpsProxyAgent(https_proxy,
+            request.httpsAgent = new PatchedHttpsProxyAgent(
+              https_proxy,
               Object.keys(httpsAgentRequestFields).length > 0 ? { ...httpsAgentRequestFields } : undefined);
-          } else {
-            request.httpsAgent = new https.Agent({
-              ...httpsAgentRequestFields
-            });
+          } catch (error) {
+            console.log(chalk.yellow('Warning: Invalid system https_proxy URL, using direct connection'));
+            request.httpsAgent = new https.Agent({ ...httpsAgentRequestFields });
           }
-        } catch (error) {
-          throw new Error('Invalid system https_proxy');
+        } else if (isHttpsRequest) {
+          request.httpsAgent = new https.Agent({ ...httpsAgentRequestFields });
         }
       } else {
-        request.httpsAgent = new https.Agent({
-          ...httpsAgentRequestFields
-        });
+        request.httpsAgent = new https.Agent({ ...httpsAgentRequestFields });
       }
-    } catch (error) {
-      request.httpsAgent = new https.Agent({
-        ...httpsAgentRequestFields
-      });
-    }
   } else if (Object.keys(httpsAgentRequestFields).length > 0) {
🧹 Nitpick comments (10)
packages/bruno-app/src/components/Preferences/ProxySettings/index.js (1)

161-165: Minor: Consider removing redundant wrapper div.

The SystemProxy component already has its own wrapper with styling. The outer div at line 162 adds mb-3 pt-1 text-muted system-proxy-settings but the inner component also uses system-proxy-settings. This may cause style conflicts or redundancy.

         {formik?.values?.mode === 'system' ? (
-          <div className="mb-3 pt-1 text-muted system-proxy-settings">
-            <SystemProxy />
-          </div>
+          <SystemProxy />
         ) : null}
packages/bruno-requests/src/network/system-proxy/utils/windows.ts (2)

118-160: Significant code duplication between getSystemProxyEnvironment and getUserEnvironmentProxy.

Both methods parse registry output identically. Consider extracting a shared helper:

+  private parseEnvironmentProxyFromRegistry(stdout: string): ProxyConfiguration | null {
+    const lines = stdout.split('\n');
+    let http_proxy: string | null = null;
+    let https_proxy: string | null = null;
+    let no_proxy: string | null = null;
+
+    for (const line of lines) {
+      const trimmedLine = line.trim();
+      if (trimmedLine.includes('HTTP_PROXY') && trimmedLine.includes('REG_SZ')) {
+        const match = trimmedLine.match(/HTTP_PROXY\s+REG_SZ\s+(.+)/);
+        if (match) http_proxy = normalizeProxyUrl(match[1].trim());
+      }
+      if (trimmedLine.includes('HTTPS_PROXY') && trimmedLine.includes('REG_SZ')) {
+        const match = trimmedLine.match(/HTTPS_PROXY\s+REG_SZ\s+(.+)/);
+        if (match) https_proxy = normalizeProxyUrl(match[1].trim(), 'https');
+      }
+      if (trimmedLine.includes('NO_PROXY') && trimmedLine.includes('REG_SZ')) {
+        const match = trimmedLine.match(/NO_PROXY\s+REG_SZ\s+(.+)/);
+        if (match) no_proxy = normalizeNoProxy(match[1].trim());
+      }
+    }
+
+    if (http_proxy || https_proxy) {
+      return { http_proxy, https_proxy, no_proxy, source: 'windows-system' };
+    }
+    return null;
+  }

Also applies to: 162-204


34-44: Silent error swallowing may hide configuration issues.

Each detection method catches errors and continues, but the outer catch (lines 47-49) will also rethrow after all methods fail. Consider logging individual method failures for debugging:

         } catch (error) {
           // Continue to next method if this one fails
+          // console.debug(`Detection method failed: ${error instanceof Error ? error.message : String(error)}`);
           continue;
         }

This is optional; just flagging for visibility during troubleshooting.

packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js (3)

36-39: Nested ternary is hard to read.

Consider using an object lookup:

+const sourceLabels = {
+  'environment': 'Environment Variables',
+  'windows-system': 'Windows System Settings',
+  'macos-system': 'macOS System Settings',
+  'linux-system': 'Linux System Settings'
+};
+
 <div>
-  {source === 'environment' ? 'Environment Variables'
-    : source === 'windows-system' ? 'Windows System Settings'
-      : source === 'macos-system' ? 'macOS System Settings'
-        : source === 'linux-system' ? 'Linux System Settings' : source}
+  {sourceLabels[source] || source}
 </div>

10-12: Consider adding loading/error feedback.

The component dispatches getSystemProxyVariables but doesn't track loading state. Users may see stale or empty values briefly. If the IPC call fails, there's no error indication.


14-69: Unnecessary fragment wrapper.

The <></> wrapper is not needed since the component returns a single <div> element.

   return (
-    <>
       <div className="mb-3 text-muted system-proxy-settings space-y-4">
         ...
       </div>
-    </>
   );
packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts (1)

161-168: Fragile mock setup depends on implicit call order.

The combination of mockReturnValue(false) followed by two mockReturnValueOnce(true) relies on knowing exact internal call order of existsSync. If the implementation changes call order, this test breaks silently.

Consider being explicit:

-      // Mock all previous methods to fail
-      mockExistsSync.mockReturnValue(false);
-
-      // Mock systemd conf directory to exist
-      mockExistsSync.mockReturnValueOnce(true);
-
-      // Mock systemd proxy file to exist
-      mockExistsSync.mockReturnValueOnce(true);
+      mockExistsSync.mockImplementation((path: string) => {
+        if (path === '/etc/environment') return false;
+        if (path === '/etc/systemd/system.conf.d') return true;
+        if (path.includes('proxy.conf')) return true;
+        return false;
+      });
packages/bruno-app/src/providers/ReduxStore/slices/app.js (1)

201-210: Minor promise chaining issue.

The .then((variables) => { dispatch(...) }).then(resolve) chain resolves with undefined since the dispatch callback returns nothing. This works but is slightly confusing.

 export const getSystemProxyVariables = () => (dispatch, getState) => {
   return new Promise((resolve, reject) => {
     const { ipcRenderer } = window;
     ipcRenderer.invoke('renderer:get-system-proxy-variables')
       .then((variables) => {
         dispatch(updateSystemProxyVariables(variables));
+        resolve(variables);
-      })
-      .then(resolve).catch(reject);
+      }).catch(reject);
   });
 };
packages/bruno-requests/src/network/system-proxy/utils/linux.ts (1)

175-243: Consider simplifying the parsing loop.

The nested loops with multiple regex patterns per variable could be simplified. However, the current implementation is correct and readable enough.

One minor improvement: you could build a single combined regex pattern upfront instead of iterating per variable, but this is optional given the small, fixed list.

packages/bruno-requests/src/network/system-proxy/index.ts (1)

65-67: detectWithTimeout is a pass-through wrapper.

This method just calls detectByPlatform — the commandTimeout is passed to individual detectors. The method name is slightly misleading since no additional timeout wrapper exists here.

Consider either:

  1. Removing this wrapper and calling detectByPlatform directly, or
  2. Adding an actual Promise.race timeout if you want a hard cap beyond individual command timeouts
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9bbcf7e and 5f22e87.

📒 Files selected for processing (24)
  • packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js (1 hunks)
  • packages/bruno-app/src/components/Preferences/ProxySettings/index.js (2 hunks)
  • packages/bruno-app/src/components/ResponsePane/index.js (1 hunks)
  • packages/bruno-app/src/providers/App/useIpcEvents.js (1 hunks)
  • packages/bruno-app/src/providers/ReduxStore/slices/app.js (4 hunks)
  • packages/bruno-cli/src/runner/run-single-request.js (4 hunks)
  • packages/bruno-cli/src/utils/proxy-util.js (1 hunks)
  • packages/bruno-electron/src/ipc/network/cert-utils.js (2 hunks)
  • packages/bruno-electron/src/ipc/preferences.js (2 hunks)
  • packages/bruno-electron/src/store/preferences.js (2 hunks)
  • packages/bruno-electron/src/utils/proxy-util.js (5 hunks)
  • packages/bruno-requests/src/index.ts (1 hunks)
  • packages/bruno-requests/src/network/index.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/index.spec.js (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/index.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/types.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/common.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/common.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/linux.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/macos.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/macos.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/windows.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/windows.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single parameters
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses. Keep 'em tight
Space before and after the arrow in arrow functions. () => {} is good
No space between function name and parentheses. func() not func ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Avoid single line abstractions where all that's being done is increasing the call stack with one additional function
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • packages/bruno-requests/src/network/system-proxy/types.ts
  • packages/bruno-app/src/components/ResponsePane/index.js
  • packages/bruno-electron/src/ipc/network/cert-utils.js
  • packages/bruno-requests/src/network/system-proxy/utils/macos.spec.ts
  • packages/bruno-requests/src/network/system-proxy/utils/common.ts
  • packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js
  • packages/bruno-cli/src/runner/run-single-request.js
  • packages/bruno-requests/src/index.ts
  • packages/bruno-requests/src/network/index.ts
  • packages/bruno-electron/src/ipc/preferences.js
  • packages/bruno-requests/src/network/system-proxy/utils/linux.ts
  • packages/bruno-requests/src/network/system-proxy/utils/windows.ts
  • packages/bruno-requests/src/network/system-proxy/index.spec.js
  • packages/bruno-requests/src/network/system-proxy/utils/macos.ts
  • packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts
  • packages/bruno-requests/src/network/system-proxy/index.ts
  • packages/bruno-requests/src/network/system-proxy/utils/windows.spec.ts
  • packages/bruno-cli/src/utils/proxy-util.js
  • packages/bruno-electron/src/utils/proxy-util.js
  • packages/bruno-app/src/components/Preferences/ProxySettings/index.js
  • packages/bruno-requests/src/network/system-proxy/utils/common.spec.ts
  • packages/bruno-app/src/providers/App/useIpcEvents.js
  • packages/bruno-electron/src/store/preferences.js
  • packages/bruno-app/src/providers/ReduxStore/slices/app.js
🧬 Code graph analysis (13)
packages/bruno-app/src/components/ResponsePane/index.js (6)
packages/bruno-app/src/components/FolderSettings/index.js (1)
  • getTabClassname (69-73)
packages/bruno-app/src/components/CollectionSettings/index.js (1)
  • getTabClassname (83-87)
packages/bruno-app/src/components/RequestPane/HttpRequestPane/index.js (2)
  • getTabClassname (83-87)
  • selectTab (27-34)
packages/bruno-app/src/components/ResponsePane/StatusCode/index.js (1)
  • getTabClassname (8-16)
packages/bruno-app/src/components/RunnerResults/ResponsePane/index.js (2)
  • getTabClassname (83-87)
  • selectTab (36-36)
packages/bruno-app/src/components/RequestPane/GraphQLRequestPane/index.js (2)
  • getTabClassname (123-127)
  • selectTab (54-61)
packages/bruno-electron/src/ipc/network/cert-utils.js (5)
packages/bruno-requests/src/index.ts (1)
  • getSystemProxy (10-10)
packages/bruno-requests/src/network/index.ts (1)
  • getSystemProxy (3-3)
packages/bruno-requests/src/network/system-proxy/index.ts (2)
  • getSystemProxy (22-44)
  • getSystemProxy (106-120)
packages/bruno-electron/src/utils/proxy-util.js (1)
  • proxyConfig (379-379)
packages/bruno-app/src/components/CollectionSettings/index.js (1)
  • proxyConfig (42-42)
packages/bruno-requests/src/network/system-proxy/utils/macos.spec.ts (1)
packages/bruno-requests/src/network/system-proxy/utils/macos.ts (1)
  • MacOSProxyDetector (8-122)
packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js (1)
packages/bruno-app/src/providers/ReduxStore/slices/app.js (2)
  • getSystemProxyVariables (201-210)
  • getSystemProxyVariables (201-210)
packages/bruno-requests/src/network/system-proxy/utils/linux.ts (2)
packages/bruno-requests/src/network/system-proxy/types.ts (2)
  • ProxyDetector (8-10)
  • ProxyConfiguration (1-6)
packages/bruno-requests/src/network/system-proxy/utils/common.ts (2)
  • normalizeProxyUrl (13-23)
  • normalizeNoProxy (30-40)
packages/bruno-requests/src/network/system-proxy/utils/windows.ts (3)
packages/bruno-requests/src/network/system-proxy/types.ts (2)
  • ProxyDetector (8-10)
  • ProxyConfiguration (1-6)
packages/bruno-requests/src/network/system-proxy/index.ts (1)
  • ProxyConfiguration (122-122)
packages/bruno-requests/src/network/system-proxy/utils/common.ts (2)
  • normalizeProxyUrl (13-23)
  • normalizeNoProxy (30-40)
packages/bruno-requests/src/network/system-proxy/index.spec.js (4)
packages/bruno-requests/src/network/system-proxy/index.ts (3)
  • SystemProxyDetector (8-102)
  • getSystemProxy (22-44)
  • getSystemProxy (106-120)
packages/bruno-requests/src/network/system-proxy/utils/windows.ts (1)
  • WindowsProxyDetector (16-235)
packages/bruno-requests/src/network/system-proxy/utils/macos.ts (1)
  • MacOSProxyDetector (8-122)
packages/bruno-requests/src/network/system-proxy/utils/linux.ts (1)
  • LinuxProxyDetector (24-244)
packages/bruno-requests/src/network/system-proxy/utils/macos.ts (2)
packages/bruno-requests/src/network/system-proxy/types.ts (2)
  • ProxyDetector (8-10)
  • ProxyConfiguration (1-6)
packages/bruno-requests/src/network/system-proxy/utils/common.ts (2)
  • normalizeProxyUrl (13-23)
  • normalizeNoProxy (30-40)
packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts (1)
packages/bruno-requests/src/network/system-proxy/utils/linux.ts (1)
  • LinuxProxyDetector (24-244)
packages/bruno-requests/src/network/system-proxy/utils/windows.spec.ts (1)
packages/bruno-requests/src/network/system-proxy/utils/windows.ts (1)
  • WindowsProxyDetector (16-235)
packages/bruno-electron/src/utils/proxy-util.js (2)
packages/bruno-cli/src/runner/run-single-request.js (4)
  • proxyUri (324-324)
  • proxyConfig (292-292)
  • parsedUrl (356-356)
  • parseUrl (3-3)
packages/bruno-cli/src/utils/proxy-util.js (3)
  • shouldUseProxy (16-63)
  • parsedUrl (26-26)
  • parseUrl (1-1)
packages/bruno-app/src/components/Preferences/ProxySettings/index.js (1)
packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js (1)
  • SystemProxy (5-70)
packages/bruno-requests/src/network/system-proxy/utils/common.spec.ts (1)
packages/bruno-requests/src/network/system-proxy/utils/common.ts (2)
  • normalizeProxyUrl (13-23)
  • normalizeNoProxy (30-40)
🪛 ast-grep (0.40.0)
packages/bruno-requests/src/network/system-proxy/utils/linux.ts

[warning] 208-208: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(^export\\s+${varName}\\s*=\\s*(.+)$, 'i')
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html

(regexp-from-variable)


[warning] 209-209: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(^${varName}\\s*=\\s*(.+)$, 'i')
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html

(regexp-from-variable)

🪛 Biome (2.1.2)
packages/bruno-electron/src/utils/proxy-util.js

[error] 88-103: This constructor has code paths that return without calling super().

If this is intentional, add an explicit throw statement in unsupported paths.

(lint/correctness/noUnreachableSuper)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Playwright E2E Tests
  • GitHub Check: CLI Tests
  • GitHub Check: Unit Tests
  • GitHub Check: SSL Tests - Linux
  • GitHub Check: SSL Tests - macOS
  • GitHub Check: SSL Tests - Windows
🔇 Additional comments (35)
packages/bruno-requests/src/network/system-proxy/types.ts (1)

1-15: System proxy type definitions look consistent and usable.

ProxyConfiguration, ProxyDetector, and SystemProxyDetectorOptions align well with the new detection flow and env-style proxy fields.

packages/bruno-electron/src/utils/proxy-util.js (2)

337-340: System proxy handling and HTTP proxy agent options look coherent.

  • httpProxyAgentOptions with keepAlive: true and the new TimelineHttpProxyAgent wiring for both manual (proxyMode === 'on') and system proxies integrate cleanly with the existing timeline agent pattern.
  • In system mode, splitting behavior by protocol (http_proxy for non‑HTTPS, https_proxy for HTTPS) and validating via new URL(...) before constructing agents gives clear, actionable error messages when system proxy values are malformed.
  • Fallback to a non‑proxy https.Agent when system proxies are disabled by no_proxy or missing also looks reasonable.

Also applies to: 365-368, 379-407


86-105: Derived agent constructor should always call super (and fail fast if proxy is missing).

The subclass returned by createTimelineHttpAgentClass only calls super when options?.proxy is set and BaseAgentClass.name === 'HttpProxyAgent'. Other code paths fall through without calling super, which violates class constructor requirements and can lead to runtime errors if the factory is used differently in the future.

Given that a proxy URI is always required here, restructure to:

  • Unconditionally destructure proxy and options
  • Throw if proxy is missing
  • Always call super(proxyUri, httpProxyAgentOptions) before accessing this
  • Remove the fragile BaseAgentClass.name check
-function createTimelineHttpAgentClass(BaseAgentClass) {
-  return class extends BaseAgentClass {
-    constructor(options, timeline) {
-      // For proxy agents, the first argument is the proxy URI and the second is options
-      if (options?.proxy) {
-        if (BaseAgentClass.name === 'HttpProxyAgent') {
-          const { proxy: proxyUri, httpProxyAgentOptions } = options;
-          super(proxyUri, httpProxyAgentOptions);
-          this.timeline = Array.isArray(timeline) ? timeline : [];
-          // Log the proxy details
-          this.timeline.push({
-            timestamp: new Date(),
-            type: 'info',
-            message: `Using proxy: ${proxyUri}`
-          });
-        }
-      }
-    }
-  };
-}
+function createTimelineHttpAgentClass(BaseAgentClass) {
+  return class extends BaseAgentClass {
+    constructor(options, timeline) {
+      const { proxy: proxyUri, httpProxyAgentOptions } = options || {};
+
+      if (!proxyUri) {
+        throw new Error('TimelineHttpProxyAgent requires a "proxy" option');
+      }
+
+      // For proxy agents, the first argument is the proxy URI and the second is options
+      super(proxyUri, httpProxyAgentOptions);
+
+      this.timeline = Array.isArray(timeline) ? timeline : [];
+      this.timeline.push({
+        timestamp: new Date(),
+        type: 'info',
+        message: `Using proxy: ${proxyUri}`
+      });
+    }
+  };
+}

Ensure all call sites pass options.proxy and test against your Node/Electron versions.

packages/bruno-app/src/components/ResponsePane/index.js (1)

160-165: Adding data-testid on the Headers tab is a clean, non-invasive test hook.

Nice way to make the Headers tab easy to target in tests without affecting runtime behavior.

packages/bruno-requests/src/index.ts (1)

8-10: Re-exporting getSystemProxy from the package entrypoint looks correct.

This cleanly surfaces the new system proxy API alongside existing exports without breaking the current public surface.

packages/bruno-electron/src/ipc/network/cert-utils.js (1)

4-4: Good integration of shared getSystemProxy into Electron’s proxy resolution.

For collections using the global proxy config, resolving proxyMode to 'system' and then delegating to await getSystemProxy() centralizes system proxy detection in the requests layer and keeps this IPC helper focused on wiring.

Also applies to: 105-122

packages/bruno-requests/src/network/index.ts (1)

1-3: Network module export of getSystemProxy is consistent with the new API surface.

This keeps the network entrypoint aligned with the package entrypoint and downstream Electron usage.

packages/bruno-electron/src/store/preferences.js (1)

30-30: Defaulting global proxy mode to 'system' is consistent and backward-tolerant.

Changing the default mode to 'system' in both defaultPreferences and getGlobalProxyConfig aligns behavior for new installs while still allowing existing saved preferences to override it through the merge logic.

Also applies to: 195-196

packages/bruno-cli/src/utils/proxy-util.js (1)

82-85: Verify no remaining imports of getSystemProxyEnvVariables exist in the codebase.

The module now exports only shouldUseProxy and PatchedHttpsProxyAgent. Ensure that getSystemProxyEnvVariables is not imported or used anywhere else in the project before merging.

packages/bruno-app/src/components/Preferences/ProxySettings/index.js (1)

11-11: LGTM on the import.

Clean import of the new SystemProxy component. The explicit /index suffix is consistent with the codebase style.

packages/bruno-app/src/providers/App/useIpcEvents.js (1)

2-6: LGTM on the import cleanup.

Removal of updateSystemProxyEnvVariables is consistent with the architectural shift to on-demand IPC-based proxy detection. The new flow correctly fetches system proxy data via the getSystemProxyVariables thunk when the SystemProxy component mounts.

packages/bruno-requests/src/network/system-proxy/utils/common.spec.ts (2)

1-25: Good test coverage for normalizeProxyUrl.

Tests cover the key scenarios: missing protocol, existing protocols, empty strings, SOCKS variants, and URLs without ports. The assertions align correctly with the implementation in common.ts.


27-64: Comprehensive tests for normalizeNoProxy.

Excellent coverage of delimiter variations, whitespace handling, and edge cases. The complex patterns test at line 61-63 properly validates CIDR, wildcards, and <local> patterns.

packages/bruno-electron/src/ipc/preferences.js (2)

6-6: LGTM on the import.

Clean import of getSystemProxy from the @usebruno/requests package.


51-55: Consider adding error handling for robustness.

The handler works but doesn't catch errors from getSystemProxy(). If the system proxy detection fails (e.g., scutil command fails on macOS), the rejection propagates to the renderer. Ensure the Redux thunk handles this gracefully.

packages/bruno-requests/src/network/system-proxy/utils/macos.spec.ts (3)

1-22: LGTM on the test setup.

Clean mock setup for child_process.exec and util.promisify. The beforeEach correctly resets mocks between tests.


24-128: Solid coverage for proxy detection scenarios.

Tests properly validate HTTP/HTTPS combinations, default port fallbacks, and enabled/disabled states. Assertions match the expected ProxyConfiguration shape.


235-247: Good error handling coverage.

Tests correctly verify that command failures and invalid output formats throw appropriate errors.

packages/bruno-cli/src/runner/run-single-request.js (2)

3-3: LGTM on the import.

Using Node's built-in url.parse for protocol detection.


19-20: LGTM on the updated imports.

Clean imports for the new proxy utilities and getSystemProxy from @usebruno/requests.

packages/bruno-requests/src/network/system-proxy/utils/windows.ts (1)

8-14: Good use of an enum to restrict commands.

This approach mitigates command injection by whitelisting allowed shell commands. Clean pattern.

packages/bruno-requests/src/network/system-proxy/utils/common.ts (1)

1-40: Clean utility functions with good documentation.

Both helpers are well-documented, handle edge cases appropriately, and follow consistent patterns. The regex for protocol detection is correct and the no_proxy normalization handles multiple delimiter formats.

packages/bruno-requests/src/network/system-proxy/index.spec.js (1)

37-78: Good test coverage across detection scenarios.

Tests cover environment variable priority, platform routing, error fallbacks, caching behavior, and the public getSystemProxy function. Solid integration test suite.

Also applies to: 80-116, 118-154, 156-195, 197-210

packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts (2)

40-126: Good coverage for gsettings scenarios.

Tests cover manual proxy, identical HTTP/HTTPS proxies, non-manual mode handling, and empty ignore lists. Well-structured mocking of sequential gsettings calls.


186-223: Error handling tests are comprehensive.

Covers gsettings unavailable, missing schema, and no configuration found scenarios. All properly assert the expected error message.

packages/bruno-app/src/providers/ReduxStore/slices/app.js (1)

46-47: LGTM on the renamed state field.

Consistent rename from systemProxyEnvVariables to systemProxyVariables — makes sense given it now captures system-level proxy config, not just environment variables.

packages/bruno-requests/src/network/system-proxy/utils/macos.ts (1)

88-121: LGTM on proxy configuration builder.

Good handling of HTTP/HTTPS proxies with appropriate default ports and proper normalization. The <local> append for ExcludeSimpleHostnames is a nice touch.

packages/bruno-requests/src/network/system-proxy/utils/windows.spec.ts (3)

1-22: LGTM on test setup.

Clean mocking of node:child_process and node:util. The beforeEach properly resets mocks between tests.


24-84: Solid coverage for Internet Options detection.

Good test cases for single proxy, protocol-specific, and fallback scenarios. The mock chaining for fallback behavior is well structured.


231-377: Thorough edge case coverage.

Tests for existing prefixes, empty overrides, disabled proxies, decimal values, and complex bypass lists provide good confidence in parsing robustness.

packages/bruno-requests/src/network/system-proxy/utils/linux.ts (3)

10-22: Good use of enum for command allowlisting.

Prevents command injection by constraining shell commands to known-safe values.


59-92: LGTM on GNOME gsettings detection.

Properly checks for manual mode, parses host/port pairs, and handles the gsettings array format for ignore-hosts.


206-223: Static analysis warning is a false positive.

The varName comes from the hardcoded proxyVars array (line 176), not user input. No ReDoS risk here.

packages/bruno-requests/src/network/system-proxy/index.ts (2)

8-44: Well-designed caching and concurrency control.

The activeDetection promise coalescing prevents redundant concurrent detections. Cache TTL of 60s is reasonable for proxy settings that rarely change.


106-120: LGTM on the exported getSystemProxy function.

Environment variables taking precedence over system detection is a sensible default — allows users to override system proxy easily.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
packages/bruno-requests/src/network/system-proxy/index.ts (1)

97-101: Race condition: clearing activeDetection during in-flight detection.

Line 100 sets activeDetection = null, which can cause duplicate detections if clearCache() is called while a detection is in progress. The next getSystemProxy() call (line 29) won't find the active detection and will start a new one.

Choose one approach:

Option 1 (recommended): Preserve in-flight detection

 clearCache(): void {
   this.cachedResult = null;
   this.cacheTimestamp = 0;
-  this.activeDetection = null;
+  // Keep activeDetection to avoid duplicate in-flight requests
 }

Option 2: Implement force-refresh semantics

-clearCache(): void {
+async clearCache(): Promise<void> {
+  // Wait for any in-flight detection to complete before clearing
+  if (this.activeDetection) {
+    await this.activeDetection.catch(() => {});
+  }
   this.cachedResult = null;
   this.cacheTimestamp = 0;
   this.activeDetection = null;
 }
🧹 Nitpick comments (4)
packages/bruno-electron/src/ipc/network/cert-utils.js (1)

116-119: Use strict equality.

Line 116 uses loose equality (==) instead of strict equality (===).

Apply this diff:

-    if (proxyMode == 'system') {
+    if (proxyMode === 'system') {
packages/bruno-requests/src/network/system-proxy/utils/linux.ts (1)

206-223: Static analysis flag is a false positive, but pattern pre-compilation would improve performance.

The static analyzer warns about RegExp construction from variables (lines 208-209), but varName comes from the hardcoded proxyVars array (line 176), not user input, so there's no ReDoS risk.

For better performance, consider pre-compiling the patterns:

+  // Pre-compiled patterns for known proxy variables
+  private readonly PROXY_PATTERNS = [
+    'http_proxy', 'https_proxy', 'no_proxy', 'all_proxy',
+    'HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY', 'ALL_PROXY'
+  ].flatMap((varName) => [
+    { regex: new RegExp(`^export\\s+${varName}\\s*=\\s*(.+)$`, 'i'), varName },
+    { regex: new RegExp(`^${varName}\\s*=\\s*(.+)$`, 'i'), varName }
+  ]);
+
   private parseProxyFromContent(content: string): ProxyConfiguration | null {
-    const proxyVars = ['http_proxy', 'https_proxy', 'no_proxy', 'all_proxy', 'HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY', 'ALL_PROXY'];
     const proxies: Record<string, string> = {};

     const lines = content.split('\n');
     for (const line of lines) {
       const trimmedLine = line.trim();

       // Skip comments and empty lines
       if (!trimmedLine || trimmedLine.startsWith('#')) {
         continue;
       }

       // ... systemd handling ...

-      // Handle different formats: VAR=value, export VAR=value, VAR="value", etc.
-      for (const varName of proxyVars) {
-        const patterns = [
-          new RegExp(`^export\\s+${varName}\\s*=\\s*(.+)$`, 'i'),
-          new RegExp(`^${varName}\\s*=\\s*(.+)$`, 'i')
-        ];
-
-        for (const pattern of patterns) {
-          const match = trimmedLine.match(pattern);
-          if (match) {
-            let value = match[1].trim();
-            // Remove surrounding quotes
-            value = value.replace(/^["']|["']$/g, '');
-            proxies[varName.toLowerCase()] = value;
-            break;
-          }
+      for (const { regex, varName } of this.PROXY_PATTERNS) {
+        const match = trimmedLine.match(regex);
+        if (match) {
+          let value = match[1].trim();
+          value = value.replace(/^["']|["']$/g, '');
+          proxies[varName.toLowerCase()] = value;
+          break;
         }
       }
     }
packages/bruno-electron/src/utils/proxy-util.js (1)

379-407: System proxy selection & validation behaviour is clearer; watch expectations around env formats

The updated proxyMode === 'system' logic:

  • Destructures { http_proxy, https_proxy, no_proxy } from proxyConfig || {} and uses shouldUseProxy(requestConfig.url, no_proxy || '') to respect no_proxy.
  • Differentiates HTTP vs HTTPS requests via parseUrl(requestConfig.url) and parsedUrl.protocol === 'https:', using http_proxy only for non‑HTTPS and https_proxy only for HTTPS.
  • Validates each configured system proxy with new URL(...) and wraps failures in explicit error messages: Invalid system http_proxy "…" / Invalid system https_proxy "…", which is a nice debugging improvement.
  • Reuses the same timeline‑enabled agents as the manual proxy mode, so HTTP/HTTPS system proxies now benefit from the same logging.

Two things to keep in mind:

  • This behaviour assumes http_proxy / https_proxy are full URLs acceptable to new URL(...) (including a scheme). If your system‑proxy detection can emit bare host:port values, those will now be rejected; confirm that upstream always normalizes to proper URLs.
  • Because the HTTP/system proxy agents push Using proxy: ${proxyUri} into the timeline, any credentials embedded in http_proxy / https_proxy will end up in diagnostic output. If that’s a concern for your users, consider redacting the userinfo segment before logging.

Functionally this change looks sound; the main follow‑up is just to verify the expected shape of the system proxy values fed into proxyConfig.

packages/bruno-cli/src/runner/run-single-request.js (1)

3-3: Prefer new URL() over legacy url.parse for protocol detection

You import parseUrl just to read parsedUrl.protocol, while elsewhere in this file you already use the global URL constructor. For consistency and to avoid the legacy url API, you can drop the import and do:

-const parseUrl = require('url').parse;

and later:

-        const parsedUrl = parseUrl(request.url);
-        const isHttpsRequest = parsedUrl.protocol === 'https:';
+        const parsedUrl = new URL(request.url);
+        const isHttpsRequest = parsedUrl.protocol === 'https:';

This keeps everything on the WHATWG URL path and removes an extra dependency.

Also applies to: 356-357

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5f22e87 and 73ef5b7.

📒 Files selected for processing (24)
  • packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js (1 hunks)
  • packages/bruno-app/src/components/Preferences/ProxySettings/index.js (2 hunks)
  • packages/bruno-app/src/components/ResponsePane/index.js (1 hunks)
  • packages/bruno-app/src/providers/App/useIpcEvents.js (1 hunks)
  • packages/bruno-app/src/providers/ReduxStore/slices/app.js (4 hunks)
  • packages/bruno-cli/src/runner/run-single-request.js (4 hunks)
  • packages/bruno-cli/src/utils/proxy-util.js (1 hunks)
  • packages/bruno-electron/src/ipc/network/cert-utils.js (2 hunks)
  • packages/bruno-electron/src/ipc/preferences.js (2 hunks)
  • packages/bruno-electron/src/store/preferences.js (2 hunks)
  • packages/bruno-electron/src/utils/proxy-util.js (5 hunks)
  • packages/bruno-requests/src/index.ts (1 hunks)
  • packages/bruno-requests/src/network/index.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/index.spec.js (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/index.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/types.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/common.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/common.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/linux.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/macos.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/macos.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/windows.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/windows.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (14)
  • packages/bruno-app/src/components/ResponsePane/index.js
  • packages/bruno-requests/src/network/system-proxy/index.spec.js
  • packages/bruno-app/src/components/Preferences/ProxySettings/index.js
  • packages/bruno-app/src/providers/ReduxStore/slices/app.js
  • packages/bruno-requests/src/network/system-proxy/utils/macos.spec.ts
  • packages/bruno-requests/src/network/system-proxy/utils/common.ts
  • packages/bruno-requests/src/index.ts
  • packages/bruno-requests/src/network/system-proxy/types.ts
  • packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js
  • packages/bruno-requests/src/network/system-proxy/utils/macos.ts
  • packages/bruno-requests/src/network/system-proxy/utils/windows.spec.ts
  • packages/bruno-electron/src/ipc/preferences.js
  • packages/bruno-requests/src/network/index.ts
  • packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single parameters
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses. Keep 'em tight
Space before and after the arrow in arrow functions. () => {} is good
No space between function name and parentheses. func() not func ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Avoid single line abstractions where all that's being done is increasing the call stack with one additional function
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • packages/bruno-requests/src/network/system-proxy/utils/common.spec.ts
  • packages/bruno-cli/src/runner/run-single-request.js
  • packages/bruno-cli/src/utils/proxy-util.js
  • packages/bruno-requests/src/network/system-proxy/utils/windows.ts
  • packages/bruno-app/src/providers/App/useIpcEvents.js
  • packages/bruno-requests/src/network/system-proxy/utils/linux.ts
  • packages/bruno-electron/src/utils/proxy-util.js
  • packages/bruno-requests/src/network/system-proxy/index.ts
  • packages/bruno-electron/src/store/preferences.js
  • packages/bruno-electron/src/ipc/network/cert-utils.js
🧬 Code graph analysis (2)
packages/bruno-requests/src/network/system-proxy/utils/common.spec.ts (1)
packages/bruno-requests/src/network/system-proxy/utils/common.ts (2)
  • normalizeProxyUrl (13-23)
  • normalizeNoProxy (30-40)
packages/bruno-requests/src/network/system-proxy/index.ts (7)
packages/bruno-requests/src/network/system-proxy/types.ts (2)
  • ProxyConfiguration (1-6)
  • SystemProxyDetectorOptions (12-15)
packages/bruno-requests/src/network/system-proxy/utils/windows.ts (1)
  • WindowsProxyDetector (16-235)
packages/bruno-requests/src/network/system-proxy/utils/macos.ts (1)
  • MacOSProxyDetector (8-118)
packages/bruno-requests/src/network/system-proxy/utils/linux.ts (1)
  • LinuxProxyDetector (24-244)
packages/bruno-requests/src/network/system-proxy/utils/common.ts (2)
  • normalizeProxyUrl (13-23)
  • normalizeNoProxy (30-40)
packages/bruno-requests/src/index.ts (1)
  • getSystemProxy (10-10)
packages/bruno-requests/src/network/index.ts (1)
  • getSystemProxy (3-3)
🪛 ast-grep (0.40.0)
packages/bruno-requests/src/network/system-proxy/utils/linux.ts

[warning] 208-208: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(^export\\s+${varName}\\s*=\\s*(.+)$, 'i')
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html

(regexp-from-variable)


[warning] 209-209: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(^${varName}\\s*=\\s*(.+)$, 'i')
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html

(regexp-from-variable)

🪛 Biome (2.1.2)
packages/bruno-electron/src/utils/proxy-util.js

[error] 88-103: This constructor has code paths that return without calling super().

If this is intentional, add an explicit throw statement in unsupported paths.

(lint/correctness/noUnreachableSuper)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Unit Tests
  • GitHub Check: Playwright E2E Tests
  • GitHub Check: CLI Tests
  • GitHub Check: SSL Tests - Windows
  • GitHub Check: SSL Tests - macOS
  • GitHub Check: SSL Tests - Linux
🔇 Additional comments (12)
packages/bruno-cli/src/utils/proxy-util.js (1)

82-85: Export surface change looks good; confirm no remaining callers of removed helper

module.exports now only exposes shouldUseProxy and PatchedHttpsProxyAgent, which matches the PR's move toward centralized system-proxy handling elsewhere. No issues with the remaining exports.

Please confirm that any prior consumers of the removed helper (e.g., getSystemProxyEnvVariables) have been updated or removed across the repo so there are no lingering import errors.

packages/bruno-app/src/providers/App/useIpcEvents.js (1)

2-6: Import of updatePreferences is consistent and necessary

The added updatePreferences named import matches its usage in the 'main:load-preferences' handler below and aligns with existing import style; no issues from this change in this file.

packages/bruno-electron/src/store/preferences.js (1)

30-30: LGTM - Default proxy mode updated to 'system'.

The default proxy mode change from 'off' to 'system' is consistent across both defaultPreferences (line 30) and getGlobalProxyConfig (line 195). This aligns with the PR's system proxy detection feature.

Also applies to: 195-195

packages/bruno-requests/src/network/system-proxy/utils/common.spec.ts (1)

1-64: LGTM - Comprehensive test coverage.

The test suite thoroughly covers edge cases for both normalizeProxyUrl and normalizeNoProxy utilities, including empty inputs, protocol handling, delimiter normalization, and whitespace handling.

packages/bruno-requests/src/network/system-proxy/utils/windows.ts (2)

9-50: LGTM - Well-structured detection with command injection prevention.

The AllowedWindowsCommands enum effectively prevents command injection, and the cascading fallback strategy (Internet Settings → WinHTTP → System/User environment) provides robust detection across different Windows configurations.


147-154: Past review comment addressed.

The normalization for environment-based proxy URLs has been implemented as suggested in the previous review. The code now applies normalizeProxyUrl and normalizeNoProxy to registry-derived values.

packages/bruno-requests/src/network/system-proxy/utils/linux.ts (1)

11-57: LGTM - Robust Linux proxy detection.

The command injection prevention via AllowedLinuxCommands enum and the cascading detection strategy (GNOME GSettings → KDE → environment files → systemd) provide comprehensive coverage across different Linux desktop environments and configurations.

packages/bruno-requests/src/network/system-proxy/index.ts (2)

22-44: LGTM - Effective caching and concurrency control.

The implementation prevents duplicate concurrent detections by checking activeDetection (lines 29-31) and properly clears it in the finally block (line 42) after caching the result.


106-120: LGTM - Sensible environment variable precedence and error handling.

The function prioritizes environment variables (lines 107-113) over system detection, which is correct behavior. The try-catch fallback (lines 115-119) ensures a valid ProxyConfiguration is always returned, even if system detection fails.

packages/bruno-electron/src/utils/proxy-util.js (2)

337-340: Centralized httpProxyAgentOptions definition looks good

Pulling the HTTP proxy agent options (currently keepAlive: true) into a shared httpProxyAgentOptions constant keeps the setupProxyAgents branches consistent and makes it easier to tune behaviour in one place. No issues from a logic/readability standpoint.


365-368: Wiring TimelineHttpProxyAgent for explicit HTTP proxies is consistent with the new helper

The proxyMode === 'on' HTTP branch now instantiates TimelineHttpProxyAgent with { proxy: proxyUri, httpProxyAgentOptions }, which matches the expected shape of the new createTimelineHttpAgentClass helper and cleanly separates HTTP proxy handling from the TLS-aware TimelineHttpsProxyAgent.

Once the constructor of createTimelineHttpAgentClass is tightened up as suggested above, this call site should be safe and future-proof.

packages/bruno-cli/src/runner/run-single-request.js (1)

291-293: Harden system proxy handling: avoid hard failures on detection errors and surface invalid proxy config

Two coupled concerns here:

  1. Unprotected getSystemProxy() during mode selection can abort the whole request

When collectionProxyEnabled === 'global' you call getSystemProxy() outside a try/catch. If this call rejects (e.g., platform-specific detector fails), the error bubbles to the outermost runSingleRequest try/catch and the request is returned as an overall error instead of just falling back to direct connectivity. That's a behavioral regression relative to the "best-effort" nature of system proxies.

  1. Invalid system proxies are silently ignored

Inside the proxyMode === 'system' branch, thrown errors like 'Invalid system http_proxy' are immediately swallowed by the catch block at Line 385, which only sets request.httpsAgent without logging or rethrowing. Users won't see why system proxy was skipped.

  1. getSystemProxy() is called twice

You first call it while deciding proxyMode, then again inside the system branch. This duplication makes error handling unnecessarily complex.

Suggested direction

  • Fetch systemProxy once at initialization and reuse it throughout.
  • Wrap the initial detection in a local try/catch so a detector failure simply leaves proxyMode = 'off'.
  • Log invalid proxies instead of silently ignoring them.

Relevant sections: lines 305–311 (proxy mode selection), 352–385 (system proxy handling).

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/bruno-electron/src/utils/proxy-util.js (1)

136-141: Same credential redaction needed here.

The createTimelineAgentClass also logs proxy URIs at line 140. Apply the same credential redaction approach to avoid leaking secrets.

♻️ Duplicate comments (1)
packages/bruno-electron/src/utils/proxy-util.js (1)

99-104: Redact credentials from proxy URI before logging.

The proxy URI may contain embedded credentials (e.g., http://user:[email protected]:8080). Logging the full URI leaks secrets into the timeline. Consider parsing and redacting userinfo before logging.

+      // Redact credentials from proxy URI for logging
+      let safeProxyUri = proxyUri;
+      try {
+        const parsed = new URL(proxyUri);
+        if (parsed.username || parsed.password) {
+          parsed.username = parsed.username ? '***' : '';
+          parsed.password = parsed.password ? '***' : '';
+          safeProxyUri = parsed.toString();
+        }
+      } catch (e) {
+        // If parsing fails, use a generic message
+        safeProxyUri = '[proxy]';
+      }
       this.timeline.push({
         timestamp: new Date(),
         type: 'info',
-        message: `Using proxy: ${proxyUri}`
+        message: `Using proxy: ${safeProxyUri}`
       });

Based on past review comments, this concern was previously flagged.

🧹 Nitpick comments (7)
packages/bruno-electron/src/utils/proxy-util.js (1)

400-400: Minor formatting: add space after comma.

Per coding guidelines, maintain consistent spacing around spread operators.

-            { proxy: https_proxy,...tlsOptions },
+            { proxy: https_proxy, ...tlsOptions },
packages/bruno-app/src/components/Preferences/ProxySettings/index.js (1)

11-11: Consider simplifying the import path.

The /index suffix is unnecessary since ES modules resolve directory imports to index.js by default.

-import SystemProxy from './SystemProxy/index';
+import SystemProxy from './SystemProxy';
packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js (2)

10-12: Consider adding loading/error state handling.

The component dispatches the IPC call on mount but doesn't handle loading or error states. If the IPC call is slow or fails, users see stale or no data without feedback.

+const [isLoading, setIsLoading] = useState(true);
+
 useEffect(() => {
-  dispatch(getSystemProxyVariables());
+  dispatch(getSystemProxyVariables())
+    .finally(() => setIsLoading(false));
 }, [dispatch]);

You'd also need to import useState and conditionally render a loading indicator.


36-39: Nested ternary is hard to read.

Consider using a mapping object or switch statement for source label resolution.

+const SOURCE_LABELS = {
+  'environment': 'Environment Variables',
+  'windows-system': 'Windows System Settings',
+  'macos-system': 'macOS System Settings',
+  'linux-system': 'Linux System Settings'
+};

-{source === 'environment' ? 'Environment Variables'
-  : source === 'windows-system' ? 'Windows System Settings'
-    : source === 'macos-system' ? 'macOS System Settings'
-      : source === 'linux-system' ? 'Linux System Settings' : source}
+{SOURCE_LABELS[source] || source}
packages/bruno-requests/src/network/system-proxy/utils/windows.ts (1)

131-145: Use case-insensitive matching for registry proxy environment variable names.

Windows registry stores environment variable names case-insensitively but case-preservingly, so users may set http_proxy, Http_Proxy, or HTTP_PROXY when persisting these values. The current string matching only catches uppercase variants. Apply case-insensitive matching consistently:

-if (trimmedLine.includes('HTTP_PROXY') && trimmedLine.includes('REG_SZ')) {
-  const match = trimmedLine.match(/HTTP_PROXY\s+REG_SZ\s+(.+)/);
+if (trimmedLine.toUpperCase().includes('HTTP_PROXY') && trimmedLine.includes('REG_SZ')) {
+  const match = trimmedLine.match(/HTTP_PROXY\s+REG_SZ\s+(.+)/i);

Apply the same pattern to HTTPS_PROXY and NO_PROXY checks in both getSystemProxyEnvironment and getUserEnvironmentProxy.

packages/bruno-requests/src/network/system-proxy/utils/linux.ts (1)

206-223: Static analysis ReDoS warning is a false positive.

The proxyVars array is a hardcoded constant containing safe alphanumeric strings with underscores. No user input flows into the regex construction.

However, creating RegExp objects inside nested loops is inefficient. Consider pre-compiling the patterns:

+// Pre-compile patterns for proxy variable detection
+const PROXY_VAR_PATTERNS = ['http_proxy', 'https_proxy', 'no_proxy', 'all_proxy', 'HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY', 'ALL_PROXY']
+  .flatMap((varName) => [
+    { varName: varName.toLowerCase(), pattern: new RegExp(`^export\\s+${varName}\\s*=\\s*(.+)$`, 'i') },
+    { varName: varName.toLowerCase(), pattern: new RegExp(`^${varName}\\s*=\\s*(.+)$`, 'i') }
+  ]);

 private parseProxyFromContent(content: string): ProxyConfiguration | null {
-  const proxyVars = ['http_proxy', 'https_proxy', 'no_proxy', 'all_proxy', 'HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY', 'ALL_PROXY'];
   const proxies: Record<string, string> = {};
   // ...
   for (const line of lines) {
     // ... systemd handling ...
     
-    for (const varName of proxyVars) {
-      const patterns = [
-        new RegExp(`^export\\s+${varName}\\s*=\\s*(.+)$`, 'i'),
-        new RegExp(`^${varName}\\s*=\\s*(.+)$`, 'i')
-      ];
-      for (const pattern of patterns) {
-        const match = trimmedLine.match(pattern);
-        if (match) {
-          // ...
-        }
-      }
-    }
+    for (const { varName, pattern } of PROXY_VAR_PATTERNS) {
+      const match = trimmedLine.match(pattern);
+      if (match) {
+        let value = match[1].trim();
+        value = value.replace(/^["']|["']$/g, '');
+        proxies[varName] = value;
+        break;
+      }
+    }
   }
 }
packages/bruno-requests/src/network/system-proxy/utils/macos.ts (1)

101-109: Replace <local> with explicit bypass entries for cross-platform compatibility.

The <local> token is not a standard proxy bypass syntax—it's a Windows/IE-specific convention. macOS itself doesn't recognize it, and downstream consumers (curl, Docker, other platforms, or even Bruno's own proxy configuration serialization) won't interpret it correctly. Use explicit portable entries instead: localhost, 127.0.0.1, ::1, and any internal domain patterns. This ensures the bypass list works consistently across platforms.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 73ef5b7 and c23eb0b.

📒 Files selected for processing (24)
  • packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js (1 hunks)
  • packages/bruno-app/src/components/Preferences/ProxySettings/index.js (2 hunks)
  • packages/bruno-app/src/components/ResponsePane/index.js (1 hunks)
  • packages/bruno-app/src/providers/App/useIpcEvents.js (1 hunks)
  • packages/bruno-app/src/providers/ReduxStore/slices/app.js (4 hunks)
  • packages/bruno-cli/src/runner/run-single-request.js (4 hunks)
  • packages/bruno-cli/src/utils/proxy-util.js (1 hunks)
  • packages/bruno-electron/src/ipc/network/cert-utils.js (2 hunks)
  • packages/bruno-electron/src/ipc/preferences.js (2 hunks)
  • packages/bruno-electron/src/store/preferences.js (2 hunks)
  • packages/bruno-electron/src/utils/proxy-util.js (5 hunks)
  • packages/bruno-requests/src/index.ts (1 hunks)
  • packages/bruno-requests/src/network/index.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/index.spec.js (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/index.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/types.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/common.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/common.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/linux.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/macos.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/macos.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/windows.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/windows.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (12)
  • packages/bruno-electron/src/store/preferences.js
  • packages/bruno-requests/src/network/system-proxy/index.spec.js
  • packages/bruno-requests/src/network/system-proxy/utils/common.spec.ts
  • packages/bruno-requests/src/network/index.ts
  • packages/bruno-electron/src/ipc/preferences.js
  • packages/bruno-requests/src/network/system-proxy/index.ts
  • packages/bruno-requests/src/index.ts
  • packages/bruno-requests/src/network/system-proxy/utils/windows.spec.ts
  • packages/bruno-requests/src/network/system-proxy/utils/common.ts
  • packages/bruno-cli/src/runner/run-single-request.js
  • packages/bruno-app/src/providers/App/useIpcEvents.js
  • packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single parameters
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses. Keep 'em tight
Space before and after the arrow in arrow functions. () => {} is good
No space between function name and parentheses. func() not func ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Avoid single line abstractions where all that's being done is increasing the call stack with one additional function
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • packages/bruno-app/src/components/ResponsePane/index.js
  • packages/bruno-cli/src/utils/proxy-util.js
  • packages/bruno-app/src/components/Preferences/ProxySettings/index.js
  • packages/bruno-requests/src/network/system-proxy/utils/macos.spec.ts
  • packages/bruno-requests/src/network/system-proxy/utils/macos.ts
  • packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js
  • packages/bruno-electron/src/utils/proxy-util.js
  • packages/bruno-app/src/providers/ReduxStore/slices/app.js
  • packages/bruno-requests/src/network/system-proxy/utils/linux.ts
  • packages/bruno-electron/src/ipc/network/cert-utils.js
  • packages/bruno-requests/src/network/system-proxy/types.ts
  • packages/bruno-requests/src/network/system-proxy/utils/windows.ts
🧬 Code graph analysis (8)
packages/bruno-app/src/components/Preferences/ProxySettings/index.js (1)
packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js (1)
  • SystemProxy (5-70)
packages/bruno-requests/src/network/system-proxy/utils/macos.spec.ts (1)
packages/bruno-requests/src/network/system-proxy/utils/macos.ts (1)
  • MacOSProxyDetector (8-118)
packages/bruno-requests/src/network/system-proxy/utils/macos.ts (2)
packages/bruno-requests/src/network/system-proxy/types.ts (2)
  • ProxyDetector (8-10)
  • ProxyConfiguration (1-6)
packages/bruno-requests/src/network/system-proxy/utils/common.ts (2)
  • normalizeProxyUrl (13-23)
  • normalizeNoProxy (30-40)
packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js (1)
packages/bruno-app/src/providers/ReduxStore/slices/app.js (2)
  • getSystemProxyVariables (201-210)
  • getSystemProxyVariables (201-210)
packages/bruno-electron/src/utils/proxy-util.js (1)
packages/bruno-cli/src/utils/proxy-util.js (3)
  • shouldUseProxy (16-63)
  • parsedUrl (26-26)
  • parseUrl (1-1)
packages/bruno-app/src/providers/ReduxStore/slices/app.js (2)
packages/bruno-app/src/utils/network/ws-event-listeners.js (1)
  • window (8-8)
packages/bruno-app/src/providers/App/ConfirmAppClose/index.js (1)
  • window (7-7)
packages/bruno-requests/src/network/system-proxy/utils/linux.ts (2)
packages/bruno-requests/src/network/system-proxy/types.ts (2)
  • ProxyDetector (8-10)
  • ProxyConfiguration (1-6)
packages/bruno-requests/src/network/system-proxy/utils/common.ts (2)
  • normalizeProxyUrl (13-23)
  • normalizeNoProxy (30-40)
packages/bruno-electron/src/ipc/network/cert-utils.js (3)
packages/bruno-requests/src/network/system-proxy/index.ts (2)
  • getSystemProxy (22-44)
  • getSystemProxy (106-120)
packages/bruno-electron/src/utils/proxy-util.js (1)
  • proxyConfig (381-381)
packages/bruno-app/src/components/CollectionSettings/index.js (1)
  • proxyConfig (42-42)
🪛 ast-grep (0.40.0)
packages/bruno-requests/src/network/system-proxy/utils/linux.ts

[warning] 208-208: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(^export\\s+${varName}\\s*=\\s*(.+)$, 'i')
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html

(regexp-from-variable)


[warning] 209-209: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(^${varName}\\s*=\\s*(.+)$, 'i')
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html

(regexp-from-variable)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: SSL Tests - Windows
  • GitHub Check: SSL Tests - macOS
  • GitHub Check: SSL Tests - Linux
  • GitHub Check: CLI Tests
  • GitHub Check: Playwright E2E Tests
  • GitHub Check: Unit Tests
🔇 Additional comments (25)
packages/bruno-electron/src/utils/proxy-util.js (3)

339-341: LGTM!

The httpProxyAgentOptions with keepAlive: true is appropriate for connection reuse.


367-369: LGTM!

The integration of TimelineHttpProxyAgent for HTTP proxy handling is consistent with the HTTPS proxy pattern.


381-413: System proxy logic looks correct.

The routing logic correctly:

  • Uses http_proxy for non-HTTPS requests
  • Uses https_proxy for HTTPS requests
  • Falls back to a standard HTTPS agent when no proxy applies

One note: ensure upstream callers provide proxyConfig with the expected shape ({ http_proxy, https_proxy, no_proxy }). The code already defends against missing proxyConfig with the proxyConfig || {} pattern, but verify callers consistently provide the required properties.

packages/bruno-electron/src/ipc/network/cert-utils.js (2)

4-4: Verification of getSystemProxy API import could not be completed.

The import addition appears structurally sound, but verification of the getSystemProxy API export and ProxyConfiguration type signature could not be performed due to repository access limitations. To ensure correctness, manually verify:

  • The getSystemProxy function is properly exported from @usebruno/requests
  • The returned ProxyConfiguration structure matches expectations in consuming code (especially proxy-util.js which destructures http_proxy, https_proxy, no_proxy)
  • Error handling from getSystemProxy() aligns with the application's proxy fallback strategy

116-119: Use strict equality for string comparison.

Line 116 should use strict equality (===) instead of loose equality (==). This follows JavaScript best practices and prevents unintended type coercion. Apply the following change:

-    if (proxyMode == 'system') {
+    if (proxyMode === 'system') {
       const systemProxyConfig = await getSystemProxy();
       proxyConfig = systemProxyConfig;
     }

Verify that getSystemProxy() returns an object with the standard Node.js proxy environment variable fields: http_proxy, https_proxy, and no_proxy.

packages/bruno-app/src/components/ResponsePane/index.js (1)

162-162: LGTM!

Good addition of data-testid for testing purposes. Clean and non-intrusive.

packages/bruno-app/src/components/Preferences/ProxySettings/index.js (1)

161-164: LGTM!

Clean integration of the SystemProxy component. The conditional rendering based on formik.values.mode === 'system' is appropriate.

packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js (1)

14-68: LGTM on the component structure.

The read-only display with fallbacks (|| '-') and clear user guidance about OS documentation is well done.

packages/bruno-requests/src/network/system-proxy/utils/macos.spec.ts (3)

1-22: LGTM on test setup.

Clean mocking of child_process and util modules. The beforeEach properly resets mocks between tests.


207-227: Test now properly validates malformed input handling.

The input at line 214 (HTTPSProxy proxy.usebruno.com) lacks the colon separator, correctly testing graceful degradation. The expectation that https_proxy is null while http_proxy is parsed confirms the parser handles partial malformation.


230-242: LGTM on error handling tests.

Good coverage of both command failure and invalid output scenarios.

packages/bruno-requests/src/network/system-proxy/utils/windows.ts (4)

9-14: Good security practice with command allowlist.

Using an enum to constrain shell commands prevents injection vulnerabilities. Clean approach.


25-44: LGTM on detection strategy waterfall.

The ordered fallback through four detection methods with graceful error handling is robust. Each method failing silently allows the next to attempt detection.


206-234: LGTM on parseProxyString implementation.

Correctly handles both protocol-specific (http=proxy1:8080;https=proxy2:8080) and single-proxy formats. Normalization is properly applied.


221-226: Verify single-proxy format for HTTPS.

When a single proxy is used for all protocols, both http_proxy and https_proxy get the same normalized URL. However, normalizeProxyUrl(proxyServer) defaults to http:// scheme. Downstream consumers expecting https:// for https_proxy may behave unexpectedly.

Is it intentional that https_proxy uses http:// scheme when a single proxy is configured? Some proxy clients require matching schemes.

packages/bruno-cli/src/utils/proxy-util.js (1)

82-85: Verify no remaining usages of removed getSystemProxyEnvVariables.

The export was removed from module.exports. Confirm no callers remain in the CLI package to avoid runtime errors.

packages/bruno-app/src/providers/ReduxStore/slices/app.js (2)

46-47: State shape update looks correct.

The rename from systemProxyEnvVariables to systemProxyVariables aligns with the broader refactor for system proxy detection.


93-95: Reducer rename is consistent.

updateSystemProxyVariables correctly updates the renamed state field.

packages/bruno-requests/src/network/system-proxy/utils/macos.ts (2)

8-22: Clean implementation of macOS proxy detection.

The detector correctly uses scutil --proxy, applies reasonable timeouts, and handles the dictionary output format. The use of normalizeProxyUrl and normalizeNoProxy from common utilities ensures consistency.


41-82: Parsing logic handles scutil output correctly.

The recursive dictionary and array parsing covers typical scutil --proxy output. One minor observation: if HTTPPort or HTTPSPort are explicitly set to 0 in the config, the fallback to default ports (80/443) would override that. This is likely acceptable since port 0 is invalid for proxies.

packages/bruno-requests/src/network/system-proxy/utils/linux.ts (4)

10-22: Good security practice with AllowedLinuxCommands enum.

Using an enum of pre-defined commands prevents command injection vulnerabilities. This is a solid pattern for system command execution.


32-56: Detection strategy chain is well-designed.

The fallback approach (GNOME → KDE → /etc/environment → systemd) covers major Linux environments. Swallowing errors per-method and continuing to the next is appropriate here.


59-91: GSettings parsing handles gsettings output quirks correctly.

The single-quote stripping on line 72 and array bracket handling on line 81 properly account for gsettings' output format.


146-173: Systemd proxy detection covers common config locations.

Reading from /etc/systemd/system.conf.d/ with fallback files is a reasonable approach. Note that this won't detect proxies set via systemctl set-environment, but that's acceptable for a file-based detection strategy.

packages/bruno-requests/src/network/system-proxy/types.ts (1)

1-15: Type definitions are well-structured.

Clear interfaces for ProxyConfiguration, ProxyDetector, and SystemProxyDetectorOptions. The source union type properly distinguishes between environment and platform-specific sources.

The question about SystemProxyDetectorOptions defining cacheTimeout and commandTimeout while ProxyDetector.detect() uses timeoutMs should be verified against the implementation to confirm these options are wired correctly and understand whether they serve different purposes (e.g., cache vs. command execution timeout) or if there's a naming inconsistency that needs alignment.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/bruno-cli/src/runner/run-single-request.js (1)

304-313: Refactor to avoid duplicate system proxy fetch.

The system proxy is fetched twice:

  • Line 306: To determine if system proxy should be used
  • Line 353: To actually apply the system proxy configuration

This is inefficient and could lead to inconsistencies if the system proxy changes between calls. Cache the result from the first call and reuse it.

Apply this diff to cache and reuse the system proxy:

     let proxyMode = 'off';
     let proxyConfig = {};
+    let systemProxyConfig = null;
 
     const collectionProxyConfig = get(brunoConfig, 'proxy', {});
     const collectionProxyEnabled = get(collectionProxyConfig, 'enabled', false);
     
     if (noproxy) {
       // If noproxy flag is set, don't use any proxy
       proxyMode = 'off';
     } else if (collectionProxyEnabled === true) {
       // If collection proxy is enabled, use it
       proxyConfig = collectionProxyConfig;
       proxyMode = 'on';
     } else if (collectionProxyEnabled === 'global') {
       // If collection proxy is set to 'global', use system proxy
-      const systemProxy = await getSystemProxy();
-      const { http_proxy, https_proxy } = systemProxy;
+      systemProxyConfig = await getSystemProxy();
+      const { http_proxy, https_proxy } = systemProxyConfig;
       if (http_proxy?.length || https_proxy?.length) {
         proxyMode = 'system';
       }
     } else {
       proxyMode = 'off';
     }
 
     // ... existing code ...
 
     } else if (proxyMode === 'system') {
       try {
-        const systemProxy = await getSystemProxy();
-        const { http_proxy, https_proxy, no_proxy } = systemProxy;
+        const { http_proxy, https_proxy, no_proxy } = systemProxyConfig;
         const shouldUseSystemProxy = shouldUseProxy(request.url, no_proxy || '');

Also applies to: 351-389

♻️ Duplicate comments (2)
packages/bruno-requests/src/network/system-proxy/index.ts (1)

97-101: Avoid clearing activeDetection inside clearCache to preserve dedup semantics

If clearCache() is called while a detection is in progress, setting activeDetection = null allows the next getSystemProxy() call to start a second detection instead of reusing the in‑flight one. That defeats the in-flight dedup behavior and can cause duplicate work.

Since clearCache() cannot actually cancel the existing Promise, it’s safer to leave activeDetection untouched here and only reset the cached value and timestamp:

  clearCache(): void {
    this.cachedResult = null;
    this.cacheTimestamp = 0;
-    this.activeDetection = null;
  }

If you really need “force refresh even if one is in flight”, I’d make that an explicit API (e.g. refresh()) and document the semantics.

packages/bruno-electron/src/utils/proxy-util.js (1)

98-105: Avoid logging or throwing full proxy URIs that may contain credentials

Right now the timeline entries and error messages include the raw proxy URI. If the proxy URI contains user:pass@host, this will leak credentials into logs/timelines and possibly the UI.

Consider redacting userinfo before logging or including it in error text. One way to do this:

 class PatchedHttpsProxyAgent extends HttpsProxyAgent {
   constructor(proxy, opts) {
     super(proxy, opts);
     this.constructorOpts = opts;
   }
 }
 
+function redactProxyUri(uri) {
+  try {
+    const url = new URL(uri);
+    if (url.username || url.password) {
+      url.username = '***';
+      url.password = '***';
+    }
+    return url.toString();
+  } catch {
+    return uri;
+  }
+}
+
 function createTimelineHttpAgentClass(BaseAgentClass) {
@@
-      this.timeline.push({
-        timestamp: new Date(),
-        type: 'info',
-        message: `Using proxy: ${proxyUri}`
-      });
+      this.timeline.push({
+        timestamp: new Date(),
+        type: 'info',
+        message: `Using proxy: ${redactProxyUri(proxyUri)}`
+      });
-        this.timeline.push({
-          timestamp: new Date(),
-          type: 'info',
-          message: `Using proxy: ${proxyUri}`,
-        });
+        this.timeline.push({
+          timestamp: new Date(),
+          type: 'info',
+          message: `Using proxy: ${redactProxyUri(proxyUri)}`,
+        });
-        throw new Error(`Invalid system http_proxy "${http_proxy}": ${error.message}`);
+        throw new Error(`Invalid system http_proxy "${redactProxyUri(http_proxy)}": ${error.message}`);
-        throw new Error(`Invalid system https_proxy "${https_proxy}": ${error.message}`);
+        throw new Error(`Invalid system https_proxy "${redactProxyUri(https_proxy)}": ${error.message}`);

Also applies to: 137-141, 393-393, 408-408

🧹 Nitpick comments (8)
packages/bruno-cli/src/runner/run-single-request.js (1)

360-379: Consider simplifying nested try-catch blocks.

The nested try-catch blocks for http_proxy and https_proxy validation add complexity. While the logic is correct, consider extracting proxy validation to a helper function for better readability.

Example helper function:

const validateAndSetProxy = (proxyUrl, proxyType, agentType, agentOptions) => {
  try {
    if (proxyUrl?.length) {
      new URL(proxyUrl);
      if (agentType === 'http') {
        request.httpAgent = new HttpProxyAgent(proxyUrl);
      } else {
        request.httpsAgent = new PatchedHttpsProxyAgent(proxyUrl, agentOptions);
      }
      return true;
    }
    return false;
  } catch (error) {
    throw new Error(`Invalid system ${proxyType}_proxy`);
  }
};
packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js (1)

13-18: Move SOURCE_LABELS outside the component.

This constant is recreated on every render. Since it never changes, define it at module scope for better performance.

+const SOURCE_LABELS = {
+  'environment': 'Environment Variables',
+  'windows-system': 'Windows System Settings',
+  'macos-system': 'macOS System Settings',
+  'linux-system': 'Linux System Settings'
+};
+
 const SystemProxy = () => {
   const dispatch = useDispatch();
   const systemProxyVariables = useSelector((state) => state.app.systemProxyVariables);
   const { source, http_proxy, https_proxy, no_proxy } = systemProxyVariables || {};
   const [isFetching, setIsFetching] = useState(true);
   const [error, setError] = useState(null);
-
-  const SOURCE_LABELS = {
-    'environment': 'Environment Variables',
-    'windows-system': 'Windows System Settings',
-    'macos-system': 'macOS System Settings',
-    'linux-system': 'Linux System Settings'
-  };
packages/bruno-requests/src/network/system-proxy/utils/macos.ts (1)

41-82: Consider edge case: array terminator detection.

The array parsing loop at line 62 terminates on any line containing }. If an array element itself contains } (unlikely but possible in edge cases), parsing would terminate early.

This is a minor edge case since proxy exception lists typically contain hostnames/IPs, but worth noting.

packages/bruno-requests/src/network/system-proxy/types.ts (1)

1-6: Consider simplifying nullability syntax.

The fields use both ? (optional) and | null. This is redundant—? already allows undefined. If you want to explicitly allow null values (distinct from missing keys), the current approach is fine. Otherwise, simplify:

 export interface ProxyConfiguration {
-  http_proxy?: string | null;
-  https_proxy?: string | null;
-  no_proxy?: string | null;
+  http_proxy?: string;
+  https_proxy?: string;
+  no_proxy?: string;
   source: 'environment' | 'windows-system' | 'macos-system' | 'linux-system';
 }
packages/bruno-requests/src/network/system-proxy/utils/linux.ts (1)

153-180: Hardcoded systemd file paths may miss configurations.

The detector only checks proxy.conf and environment.conf in /etc/systemd/system.conf.d/. Some distributions or users may use different filenames.

Consider using readdir to scan all .conf files in the directory:

-      const systemdFiles = ['proxy.conf', 'environment.conf'];
+      const { readdir } = require('node:fs/promises');
+      const files = await readdir(systemdConfDir);
+      const systemdFiles = files.filter((f) => f.endsWith('.conf'));
packages/bruno-requests/src/network/system-proxy/index.ts (2)

16-20: Prefer ?? over || for numeric option defaults

Using || means an explicit 0 for cacheTimeout or commandTimeout is treated as “unset” and replaced with the default, which makes it impossible to intentionally disable caching/timeouts with 0.

You can make the intent clearer and allow 0 as a valid value by switching to nullish coalescing:

  constructor(options: SystemProxyDetectorOptions = {}) {
    this.platform = platform();
-    this.cacheTimeout = options.cacheTimeout || 60000; // 60 seconds default
-    this.commandTimeout = options.commandTimeout || 10000; // 10 seconds default
+    this.cacheTimeout = options.cacheTimeout ?? 60000; // 60 seconds default
+    this.commandTimeout = options.commandTimeout ?? 10000; // 10 seconds default
  }

65-67: detectWithTimeout is currently a pass‑through abstraction

Right now detectWithTimeout just forwards to detectByPlatform and adds only an extra stack frame. Given the guideline to avoid single-line abstractions, either:

  • Inline it in detectSystemProxy:
-      const result = await this.detectWithTimeout();
+      const result = await this.detectByPlatform();

and drop detectWithTimeout, or

  • Add actual timeout behavior here (e.g. Promise.race with a timer) and a short JSDoc explaining that it owns the timeout semantics.
packages/bruno-electron/src/utils/proxy-util.js (1)

86-96: Optional: simplify createTimelineHttpAgentClass options shape

The current pattern:

  • Call sites pass { proxy, httpProxyAgentOptions }.
  • The factory immediately unpacks { proxy: proxyUri, httpProxyAgentOptions } and forwards httpProxyAgentOptions to super.

Functionally this is fine, but you could make the HTTP factory mirror createTimelineAgentClass and accept { proxy, ...agentOptions }, merging in keepAlive: true internally. That would:

  • Remove the extra httpProxyAgentOptions wrapper, and
  • Keep the “options” contract consistent across the timeline agent factories.

Purely a readability/API-tidy suggestion; not a blocker.

Also applies to: 339-341, 367-370, 387-391

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c23eb0b and 5f3416b.

📒 Files selected for processing (24)
  • packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js (1 hunks)
  • packages/bruno-app/src/components/Preferences/ProxySettings/index.js (2 hunks)
  • packages/bruno-app/src/components/ResponsePane/index.js (1 hunks)
  • packages/bruno-app/src/providers/App/useIpcEvents.js (1 hunks)
  • packages/bruno-app/src/providers/ReduxStore/slices/app.js (4 hunks)
  • packages/bruno-cli/src/runner/run-single-request.js (4 hunks)
  • packages/bruno-cli/src/utils/proxy-util.js (1 hunks)
  • packages/bruno-electron/src/ipc/network/cert-utils.js (2 hunks)
  • packages/bruno-electron/src/ipc/preferences.js (2 hunks)
  • packages/bruno-electron/src/store/preferences.js (2 hunks)
  • packages/bruno-electron/src/utils/proxy-util.js (4 hunks)
  • packages/bruno-requests/src/index.ts (1 hunks)
  • packages/bruno-requests/src/network/index.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/index.spec.js (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/index.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/types.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/common.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/common.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/linux.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/macos.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/macos.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/windows.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/windows.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (8)
  • packages/bruno-requests/src/network/system-proxy/utils/macos.spec.ts
  • packages/bruno-requests/src/network/system-proxy/utils/common.spec.ts
  • packages/bruno-cli/src/utils/proxy-util.js
  • packages/bruno-app/src/providers/App/useIpcEvents.js
  • packages/bruno-app/src/providers/ReduxStore/slices/app.js
  • packages/bruno-app/src/components/ResponsePane/index.js
  • packages/bruno-requests/src/network/system-proxy/index.spec.js
  • packages/bruno-requests/src/network/system-proxy/utils/common.ts
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single parameters
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses. Keep 'em tight
Space before and after the arrow in arrow functions. () => {} is good
No space between function name and parentheses. func() not func ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Avoid single line abstractions where all that's being done is increasing the call stack with one additional function
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • packages/bruno-electron/src/store/preferences.js
  • packages/bruno-app/src/components/Preferences/ProxySettings/index.js
  • packages/bruno-requests/src/network/system-proxy/utils/windows.ts
  • packages/bruno-requests/src/network/system-proxy/index.ts
  • packages/bruno-requests/src/network/system-proxy/types.ts
  • packages/bruno-electron/src/ipc/network/cert-utils.js
  • packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js
  • packages/bruno-cli/src/runner/run-single-request.js
  • packages/bruno-requests/src/network/system-proxy/utils/windows.spec.ts
  • packages/bruno-electron/src/utils/proxy-util.js
  • packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts
  • packages/bruno-electron/src/ipc/preferences.js
  • packages/bruno-requests/src/network/index.ts
  • packages/bruno-requests/src/network/system-proxy/utils/macos.ts
  • packages/bruno-requests/src/network/system-proxy/utils/linux.ts
  • packages/bruno-requests/src/index.ts
🧠 Learnings (1)
📚 Learning: 2025-12-02T07:26:37.751Z
Learnt from: CR
Repo: usebruno/bruno PR: 0
File: CODING_STANDARDS.md:0-0
Timestamp: 2025-12-02T07:26:37.751Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Applied to files:

  • packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts
🧬 Code graph analysis (8)
packages/bruno-electron/src/store/preferences.js (1)
packages/bruno-cli/src/runner/prepare-request.js (1)
  • get (1-1)
packages/bruno-requests/src/network/system-proxy/types.ts (1)
packages/bruno-requests/src/network/system-proxy/index.ts (1)
  • ProxyConfiguration (122-122)
packages/bruno-electron/src/ipc/network/cert-utils.js (3)
packages/bruno-requests/src/index.ts (1)
  • getSystemProxy (10-10)
packages/bruno-requests/src/network/index.ts (1)
  • getSystemProxy (3-3)
packages/bruno-requests/src/network/system-proxy/index.ts (2)
  • getSystemProxy (22-44)
  • getSystemProxy (106-120)
packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js (1)
packages/bruno-app/src/providers/ReduxStore/slices/app.js (2)
  • getSystemProxyVariables (201-211)
  • getSystemProxyVariables (201-211)
packages/bruno-electron/src/utils/proxy-util.js (1)
packages/bruno-cli/src/utils/proxy-util.js (3)
  • shouldUseProxy (16-63)
  • parsedUrl (26-26)
  • parseUrl (1-1)
packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts (2)
packages/bruno-requests/src/network/system-proxy/index.spec.js (1)
  • detector (11-11)
packages/bruno-requests/src/network/system-proxy/utils/linux.ts (1)
  • LinuxProxyDetector (31-244)
packages/bruno-electron/src/ipc/preferences.js (2)
packages/bruno-requests/src/index.ts (1)
  • getSystemProxy (10-10)
packages/bruno-requests/src/network/system-proxy/index.ts (2)
  • getSystemProxy (22-44)
  • getSystemProxy (106-120)
packages/bruno-requests/src/network/system-proxy/utils/macos.ts (2)
packages/bruno-requests/src/network/system-proxy/types.ts (2)
  • ProxyDetector (8-10)
  • ProxyConfiguration (1-6)
packages/bruno-requests/src/network/system-proxy/utils/common.ts (2)
  • normalizeProxyUrl (13-23)
  • normalizeNoProxy (30-40)
🪛 ast-grep (0.40.0)
packages/bruno-requests/src/network/system-proxy/utils/linux.ts

[warning] 26-26: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(^export\\s+${varName}\\s*=\\s*(.+)$, 'i')
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html

(regexp-from-variable)


[warning] 27-27: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(^${varName}\\s*=\\s*(.+)$, 'i')
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html

(regexp-from-variable)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: CLI Tests
  • GitHub Check: SSL Tests - Windows
  • GitHub Check: Playwright E2E Tests
  • GitHub Check: SSL Tests - macOS
  • GitHub Check: SSL Tests - Linux
  • GitHub Check: Unit Tests
🔇 Additional comments (24)
packages/bruno-electron/src/store/preferences.js (1)

30-30: LGTM!

The default proxy mode change to 'system' is consistent across both the defaultPreferences object and the getGlobalProxyConfig fallback. The validation schema already supports this value.

Also applies to: 195-195

packages/bruno-requests/src/network/index.ts (1)

1-3: LGTM!

Clean export structure for the network module's public API.

packages/bruno-app/src/components/Preferences/ProxySettings/index.js (1)

11-11: LGTM!

Clean refactoring that delegates system proxy rendering to a dedicated component, improving modularity and maintainability.

Also applies to: 163-163

packages/bruno-requests/src/index.ts (1)

8-10: LGTM!

The new getSystemProxy export expands the public API surface appropriately for the system proxy feature.

packages/bruno-electron/src/ipc/preferences.js (1)

52-55: LGTM!

Clean on-demand IPC handler for system proxy data. The async implementation is correct, and this approach is more efficient than the previous eager-loading pattern.

packages/bruno-requests/src/network/system-proxy/utils/windows.spec.ts (1)

1-400: LGTM!

Comprehensive test suite with excellent coverage of Windows proxy detection scenarios:

  • Multiple detection sources (Registry, WinHTTP, Environment variables)
  • Edge cases (protocol prefixes, empty bypass lists, disabled proxies)
  • Error handling (access denied, malformed output)

The test organization is clear and the mock setup is appropriate for testing system-level operations.

packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js (2)

20-25: LGTM on the data fetch pattern.

The useEffect properly dispatches, handles errors, and cleans up loading state via .finally(). The dispatch dependency is correctly included.


27-89: Clean UI implementation with proper error and loading states.

The component correctly handles all display states: loading spinner, error banner, and the read-only proxy values. The fallback to '-' for empty values is user-friendly.

packages/bruno-requests/src/network/system-proxy/utils/windows.ts (4)

8-14: Good use of command allowlist to prevent injection.

The enum constrains shell commands to a fixed set, mitigating command injection risks.


25-50: Detection cascade is well structured.

The ordered fallback approach ensures robust detection across different Windows proxy configurations. Error handling correctly continues to the next method on failure.


147-154: Normalization applied correctly after previous review feedback.

The environment registry methods now properly normalize URLs via normalizeProxyUrl and normalizeNoProxy, ensuring consistent output format.

Also applies to: 191-198


222-227: The suggestion is not necessary; using the same proxy address for both HTTP and HTTPS traffic is standard behavior.

When a single proxy is configured in Windows Internet Options, the same proxy address (host:port) is applied to both HTTP and HTTPS traffic. The protocol prefix (http=, https=) indicates the traffic type, not a different proxy server. Setting both http_proxy and https_proxy to the same normalized URL is correct and aligns with Windows proxy conventions.

Likely an incorrect or invalid review comment.

packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts (2)

1-38: Comprehensive mock setup for Linux detector tests.

The mocking strategy correctly isolates the detector from system dependencies. Using jest.clearAllMocks() in beforeEach ensures clean state between tests.


93-99: Stray comment removed as per previous review.

The // ? debug marker flagged in the past review is no longer present.

packages/bruno-requests/src/network/system-proxy/utils/macos.ts (2)

71-75: Dead code branches removed as per previous review.

The boolean parsing branches for '1' and '0' that were unreachable have been cleaned up. The logic now correctly parses integers and falls back to string values.


84-117: Solid proxy configuration building logic.

The method correctly:

  • Checks enable flags before using proxy values
  • Applies sensible port defaults (80/443)
  • Handles ExceptionsList arrays
  • Appends <local> for ExcludeSimpleHostnames
  • Normalizes output via helper functions
packages/bruno-requests/src/network/system-proxy/types.ts (1)

8-15: Well-defined interfaces for the detector pattern.

The ProxyDetector interface provides a clean contract for platform-specific implementations. SystemProxyDetectorOptions offers sensible configuration points.

packages/bruno-requests/src/network/system-proxy/utils/linux.ts (5)

24-29: Static analysis ReDoS warning is a false positive.

The varName values come from a hardcoded array of known proxy variable names, not user input. The patterns are safe.


10-22: Good command allowlist with stderr suppression.

The enum constrains commands and redirects stderr to /dev/null to handle missing tools gracefully.


66-99: Well-implemented gsettings detection.

Correctly checks for 'manual' mode before reading proxy values. The quote stripping and ignore-hosts parsing are handled properly.


101-139: KDE proxy detection with clear type documentation.

The ProxyType value comments are helpful. Only manual configuration (type 1) is handled, which is appropriate for deterministic proxy settings.


182-243: Robust content parsing with multiple format support.

The parseProxyFromContent method handles:

  • Shell variable formats (VAR=value, export VAR=value)
  • Quoted values (single and double)
  • Systemd directives (Environment=, DefaultEnvironment=)
  • ALL_PROXY fallback

The implementation is thorough.

packages/bruno-requests/src/network/system-proxy/index.ts (1)

104-120: Environment‑first singleton API looks solid

The exported getSystemProxy correctly:

  • Reads and normalizes env proxy variables once
  • Short‑circuits to env when http_proxy/https_proxy (or all_proxy) are present
  • Falls back to the shared SystemProxyDetector and degrades to env again on error

This is a good, resilient shape for callers in CLI/Electron contexts.

packages/bruno-electron/src/utils/proxy-util.js (1)

381-385: Confirm invariants for requestConfig.url and proxyConfig in system proxy mode

This branch assumes:

  • requestConfig.url is always a non-empty string (used directly in parseUrl(requestConfig.url)), and
  • proxyConfig carries lowercase keys http_proxy, https_proxy, no_proxy.

If those invariants ever change (e.g. url missing/undefined, or keys normalized differently), this block can either throw earlier than expected or silently skip the system proxy.

If that’s not already enforced at the call site, consider a light guard here (early-return if !requestConfig.url) or normalizing proxyConfig keys once upstream.

Also applies to: 387-391, 396-408

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

♻️ Duplicate comments (2)
packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts (1)

154-182: Mock ordering may cause flaky behavior.

The mockReturnValue(false) at line 161 sets the default, but execution order matters: getEnvironmentFileProxy checks /etc/environment before getSystemdProxy checks the systemd directory. The mockReturnValueOnce calls at lines 164 and 167 may not align with actual call order.

Use path-based mock or explicit sequential ordering:

-      // Mock all previous methods to fail
-      mockExistsSync.mockReturnValue(false);
-
-      // Mock systemd conf directory to exist
-      mockExistsSync.mockReturnValueOnce(true);
-
-      // Mock systemd proxy file to exist
-      mockExistsSync.mockReturnValueOnce(true);
+      // Mock /etc/environment to not exist, then systemd dir and file to exist
+      mockExistsSync
+        .mockReturnValueOnce(false)  // /etc/environment
+        .mockReturnValueOnce(true)   // /etc/systemd/system.conf.d
+        .mockReturnValueOnce(true);  // proxy.conf file
packages/bruno-electron/src/utils/proxy-util.js (1)

86-107: Redact credentials from proxy URI before logging.

The super() issue from the previous review has been resolved—the constructor now either throws before super() (which is valid) or calls super() before accessing this.

However, the credential leakage issue remains: Line 103 logs the full proxyUri, which may contain credentials in the format http://user:[email protected]. Redact the userinfo portion before adding it to the timeline.

Apply this diff to redact credentials:

+      // Redact credentials from proxy URI for logging
+      const redactedProxyUri = proxyUri.replace(/\/\/([^:]+):([^@]+)@/, '//$1:***@');
+
       this.timeline = Array.isArray(timeline) ? timeline : [];
       // Log the proxy details
       this.timeline.push({
         timestamp: new Date(),
         type: 'info',
-        message: `Using proxy: ${proxyUri}`
+        message: `Using proxy: ${redactedProxyUri}`
       });
🧹 Nitpick comments (1)
packages/bruno-requests/src/network/system-proxy/index.ts (1)

58-69: Consider instantiating platform resolvers once.

New resolver instances are created on each detection call. For better efficiency, instantiate them once during construction and reuse.

 export class SystemProxyResolver {
   private platform: string;
   private commandTimeout: number;
+  private windowsResolver?: WindowsProxyResolver;
+  private macosResolver?: MacOSProxyResolver;
+  private linuxResolver?: LinuxProxyResolver;
   private activeDetection: Promise<ProxyConfiguration> | null = null;

   constructor(options: SystemProxyResolverOptions = {}) {
     this.platform = platform();
     this.commandTimeout = options.commandTimeout || 10000;
+    // Initialize platform-specific resolver
+    if (this.platform === 'win32') {
+      this.windowsResolver = new WindowsProxyResolver();
+    } else if (this.platform === 'darwin') {
+      this.macosResolver = new MacOSProxyResolver();
+    } else if (this.platform === 'linux') {
+      this.linuxResolver = new LinuxProxyResolver();
+    }
   }
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5f3416b and 2c17f1d.

📒 Files selected for processing (24)
  • packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js (1 hunks)
  • packages/bruno-app/src/components/Preferences/ProxySettings/index.js (2 hunks)
  • packages/bruno-app/src/components/ResponsePane/index.js (1 hunks)
  • packages/bruno-app/src/providers/App/useIpcEvents.js (1 hunks)
  • packages/bruno-app/src/providers/ReduxStore/slices/app.js (4 hunks)
  • packages/bruno-cli/src/runner/run-single-request.js (3 hunks)
  • packages/bruno-cli/src/utils/proxy-util.js (1 hunks)
  • packages/bruno-electron/src/ipc/network/cert-utils.js (2 hunks)
  • packages/bruno-electron/src/ipc/preferences.js (2 hunks)
  • packages/bruno-electron/src/store/preferences.js (2 hunks)
  • packages/bruno-electron/src/utils/proxy-util.js (4 hunks)
  • packages/bruno-requests/src/index.ts (1 hunks)
  • packages/bruno-requests/src/network/index.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/index.spec.js (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/index.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/types.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/common.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/common.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/linux.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/macos.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/macos.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/windows.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/windows.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (15)
  • packages/bruno-app/src/components/ResponsePane/index.js
  • packages/bruno-electron/src/ipc/network/cert-utils.js
  • packages/bruno-requests/src/network/system-proxy/utils/macos.spec.ts
  • packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js
  • packages/bruno-requests/src/index.ts
  • packages/bruno-cli/src/runner/run-single-request.js
  • packages/bruno-requests/src/network/system-proxy/types.ts
  • packages/bruno-cli/src/utils/proxy-util.js
  • packages/bruno-requests/src/network/index.ts
  • packages/bruno-requests/src/network/system-proxy/utils/common.spec.ts
  • packages/bruno-requests/src/network/system-proxy/utils/common.ts
  • packages/bruno-app/src/providers/ReduxStore/slices/app.js
  • packages/bruno-app/src/providers/App/useIpcEvents.js
  • packages/bruno-app/src/components/Preferences/ProxySettings/index.js
  • packages/bruno-electron/src/store/preferences.js
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation, never tabs
Use single quotes for strings instead of double quotes
Always add semicolons at the end of statements
No trailing commas in code
Always use parentheses around parameters in arrow functions, even for single parameters
For multiline constructs, put opening braces on the same line with a minimum of 2 elements for multiline formatting
No newlines inside function parentheses
Space before and after the arrow in arrow functions: () => {}
No space between function name and parentheses: func() not func ()
Semicolons should go at the end of the line, not on a new line
Function names should be concise and descriptive
Add JSDoc comments to provide details to abstractions
Avoid single-line abstractions where all that is being done is increasing the call stack with one additional function
Add meaningful comments to explain complex code flow instead of obvious comments

Files:

  • packages/bruno-requests/src/network/system-proxy/utils/windows.ts
  • packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts
  • packages/bruno-electron/src/ipc/preferences.js
  • packages/bruno-requests/src/network/system-proxy/utils/macos.ts
  • packages/bruno-requests/src/network/system-proxy/utils/linux.ts
  • packages/bruno-requests/src/network/system-proxy/index.spec.js
  • packages/bruno-electron/src/utils/proxy-util.js
  • packages/bruno-requests/src/network/system-proxy/index.ts
  • packages/bruno-requests/src/network/system-proxy/utils/windows.spec.ts
**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

Add tests for any new functionality or meaningful changes; update corresponding tests when code is added, removed, or significantly modified

Files:

  • packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts
  • packages/bruno-requests/src/network/system-proxy/index.spec.js
  • packages/bruno-requests/src/network/system-proxy/utils/windows.spec.ts
🧠 Learnings (1)
📚 Learning: 2025-12-03T08:09:57.124Z
Learnt from: CR
Repo: usebruno/bruno PR: 0
File: CODING_STANDARDS.md:0-0
Timestamp: 2025-12-03T08:09:57.124Z
Learning: Applies to **/*.{test,spec}.{js,jsx,ts,tsx} : Add tests for any new functionality or meaningful changes; update corresponding tests when code is added, removed, or significantly modified

Applied to files:

  • packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts
  • packages/bruno-requests/src/network/system-proxy/index.spec.js
  • packages/bruno-requests/src/network/system-proxy/utils/windows.spec.ts
🧬 Code graph analysis (3)
packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts (1)
packages/bruno-requests/src/network/system-proxy/utils/linux.ts (1)
  • LinuxProxyResolver (31-245)
packages/bruno-electron/src/utils/proxy-util.js (1)
packages/bruno-cli/src/utils/proxy-util.js (2)
  • shouldUseProxy (16-63)
  • parseUrl (1-1)
packages/bruno-requests/src/network/system-proxy/utils/windows.spec.ts (1)
packages/bruno-requests/src/network/system-proxy/utils/windows.ts (1)
  • WindowsProxyResolver (16-236)
🪛 ast-grep (0.40.0)
packages/bruno-requests/src/network/system-proxy/utils/linux.ts

[warning] 26-26: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(^export\\s+${varName}\\s*=\\s*(.+)$, 'i')
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html

(regexp-from-variable)


[warning] 27-27: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(^${varName}\\s*=\\s*(.+)$, 'i')
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html

(regexp-from-variable)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Playwright E2E Tests
  • GitHub Check: CLI Tests
  • GitHub Check: Unit Tests
  • GitHub Check: SSL Tests - Linux
  • GitHub Check: SSL Tests - macOS
  • GitHub Check: SSL Tests - Windows
🔇 Additional comments (39)
packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts (3)

1-38: LGTM! Test setup is well-structured.

Mocks are correctly configured for all required dependencies, and the beforeEach properly initializes the detector and clears mocks between tests.


40-126: LGTM! gsettings test coverage is thorough.

Tests properly cover manual proxy detection, identical proxies, non-manual mode fallback, and empty ignore hosts scenarios.


185-222: LGTM! Error handling tests are comprehensive.

Covers gsettings unavailable, schema not installed, and no configuration found scenarios.

packages/bruno-requests/src/network/system-proxy/utils/windows.spec.ts (5)

1-23: LGTM! Clean test setup.

Mock configuration and beforeEach initialization are correct.


24-84: LGTM! Registry detection tests are thorough.

Covers single proxy, protocol-specific proxy, and fallback to WinHTTP scenarios.


86-157: LGTM! WinHTTP detection coverage is solid.

Tests direct access handling, single/protocol-specific proxies, and "(none)" bypass list correctly.


159-229: LGTM! Environment detection tests are complete.

Covers system-wide and user-specific proxy environment variables with proper fallback chain.


231-399: LGTM! Edge cases and error handling are comprehensive.

Good coverage of prefix handling, decimal ProxyEnable values, malformed output, and complex bypass lists.

packages/bruno-electron/src/ipc/preferences.js (1)

6-7: LGTM! Import added correctly.

packages/bruno-requests/src/network/system-proxy/utils/windows.ts (7)

1-14: LGTM! Clean setup with injection prevention.

Using an enum for allowed commands is a good security practice.


16-50: LGTM! Detection flow is well-structured.

Ordered fallback chain with proper error handling at each step.


52-92: LGTM! Registry parsing handles edge cases correctly.

Supports both hex (0x1) and decimal (1) ProxyEnable values.


94-116: LGTM! WinHTTP detection is robust.

Correctly identifies "Direct access" as no-proxy scenario.


118-160: LGTM! System environment detection with proper normalization.

The past review issue regarding missing normalization has been addressed.


162-204: LGTM! User environment detection mirrors system environment logic.

Consistent implementation with proper normalization.


206-236: LGTM! Proxy string parsing handles both formats correctly.

Protocol-specific (http=...;https=...) and single proxy formats are properly handled.

packages/bruno-requests/src/network/system-proxy/index.spec.js (4)

1-35: LGTM! Test setup and teardown are correct.

Timer cleanup order is now proper: runOnlyPendingTimers() executes pending timers before clearAllTimers() removes them.


37-78: LGTM! Environment variable tests are thorough.

Covers lowercase/uppercase priority, fallback behavior, and null handling.


80-116: LGTM! Platform routing tests verify correct detector delegation.

Each platform test properly mocks os.platform() and verifies the correct resolver is invoked.


118-169: LGTM! Error handling and fallback tests are comprehensive.

Covers detection failure fallback and timeout graceful handling.

packages/bruno-requests/src/network/system-proxy/utils/macos.ts (4)

1-22: LGTM! Clean setup with proper timeout handling.

Uses scutil --proxy for macOS proxy detection with configurable timeout.


24-39: LGTM! Output parsing is robust.

Validates input, finds dictionary section, and delegates to parsing helpers.


41-82: LGTM! Configuration parsing handles all value types.

Arrays, integers, and strings are correctly parsed from scutil output.


84-118: LGTM! Proxy configuration builder is correct.

Properly handles HTTP/HTTPS enables, default ports, ExceptionsList, and ExcludeSimpleHostnames.

packages/bruno-requests/src/network/system-proxy/utils/linux.ts (6)

1-29: LGTM! Safe command enumeration and pattern precompilation.

The static analysis ReDoS warning on lines 26-27 is a false positive—varName comes from a hardcoded array of trusted proxy variable names (http_proxy, https_proxy, etc.), not user input. The patterns are compiled once at module load time.


31-64: LGTM! Detection flow with proper fallback chain.

Tries gsettings → KDE → /etc/environment → systemd in order, returning on first success.


66-99: LGTM! gsettings parsing handles GNOME proxy settings correctly.

Properly checks for manual mode and cleans quoted values.


101-139: LGTM! KDE proxy detection is well-documented.

ProxyType value meanings are documented, and only manual configuration (type 1) is handled.


141-181: LGTM! File-based proxy detection is robust.

Both /etc/environment and systemd configuration directory are checked with proper null guards.


183-245: LGTM! Content parsing handles multiple formats.

Supports shell VAR=value, export VAR=value, and systemd Environment= directives with proper quote removal. ALL_PROXY fallback is correctly implemented.

packages/bruno-requests/src/network/system-proxy/index.ts (6)

1-6: LGTM!

Imports are well-organized and follow the coding guidelines.


8-16: LGTM!

Class structure and constructor are clean. The 10-second default timeout is reasonable for system proxy detection.


18-33: LGTM!

In-flight deduplication is correctly implemented. The finally block ensures activeDetection is cleared after the promise settles, preventing duplicate concurrent detections.


71-84: LGTM!

Environment variable handling is comprehensive with proper fallback chain and normalization.


87-103: LGTM!

The singleton pattern and environment variable precedence are appropriate. Environment variables correctly take precedence over system detection, matching expected behavior for proxy configuration in most CLI tools.


105-105: LGTM!

Type re-export for convenience.

packages/bruno-electron/src/utils/proxy-util.js (3)

339-341: LGTM—keepAlive for HTTP proxy agents.

The httpProxyAgentOptions with keepAlive: true improves connection reuse for HTTP proxy agents.


380-391: System proxy protocol detection looks correct.

The logic correctly routes http_proxy to non-HTTPS requests (Line 387: !isHttpsRequest) and https_proxy to HTTPS requests (Line 396), aligning with standard proxy conventions. URL validation with new URL() is appropriate.


396-406: HTTPS proxy setup properly uses PatchedHttpsProxyAgent.

The conditional application of https_proxy only for HTTPS requests (Line 396: isHttpsRequest) and the use of PatchedHttpsProxyAgent with tlsOptions ensure TLS settings are correctly propagated. The fallback to a regular HTTPS agent (lines 403-406) is appropriate.

Comment on lines +51 to +55

ipcMain.handle('renderer:get-system-proxy-variables', async () => {
const systemProxyConfig = await getSystemProxy();
return systemProxyConfig;
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Add error handling to prevent unhandled rejection.

If getSystemProxy() throws (e.g., detection fails on all platforms), the renderer receives an unhandled promise rejection. Wrap in try/catch to return a graceful fallback or propagate a meaningful error.

   ipcMain.handle('renderer:get-system-proxy-variables', async () => {
-    const systemProxyConfig = await getSystemProxy();
-    return systemProxyConfig;
+    try {
+      const systemProxyConfig = await getSystemProxy();
+      return systemProxyConfig;
+    } catch (error) {
+      console.error('Failed to get system proxy:', error);
+      return {
+        http_proxy: null,
+        https_proxy: null,
+        no_proxy: null,
+        source: 'environment'
+      };
+    }
   });
🤖 Prompt for AI Agents
In packages/bruno-electron/src/ipc/preferences.js around lines 51 to 55, the
ipcMain handler calls getSystemProxy() without error handling which can produce
an unhandled rejection; wrap the await call in a try/catch, log or process the
error inside the catch, and then either return a safe fallback (e.g., null or an
empty config) or throw a meaningful Error that the renderer can handle so the
promise always resolves or rejects with a controlled value and no unhandled
rejection occurs.

Comment on lines 392 to 394
} catch (error) {
throw new Error('Invalid system http_proxy');
throw new Error(`Invalid system http_proxy "${http_proxy}": ${error.message}`);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Redact credentials from proxy URIs in error messages.

Including the raw proxy URI values (http_proxy, https_proxy) in error messages risks leaking credentials if they are embedded in the URI format http://user:[email protected]. Error messages may appear in logs or user-facing dialogs.

Redact the userinfo before interpolating:

+      const redactedHttpProxy = http_proxy ? http_proxy.replace(/\/\/([^:]+):([^@]+)@/, '//$1:***@') : http_proxy;
       } catch (error) {
-        throw new Error(`Invalid system http_proxy "${http_proxy}": ${error.message}`);
+        throw new Error(`Invalid system http_proxy "${redactedHttpProxy}": ${error.message}`);
       }

Apply the same pattern for https_proxy at Line 408:

+      const redactedHttpsProxy = https_proxy ? https_proxy.replace(/\/\/([^:]+):([^@]+)@/, '//$1:***@') : https_proxy;
       } catch (error) {
-        throw new Error(`Invalid system https_proxy "${https_proxy}": ${error.message}`);
+        throw new Error(`Invalid system https_proxy "${redactedHttpsProxy}": ${error.message}`);
       }

Also applies to: 407-409

🤖 Prompt for AI Agents
In packages/bruno-electron/src/utils/proxy-util.js around lines 392-394 and
407-409, the code interpolates raw proxy URIs into error messages which can leak
credentials; parse each proxy string with the URL constructor (or equivalent),
detect username/password in the URL, replace the userinfo with a redaction (e.g.
remove username/password or set them to "[REDACTED]"), then interpolate the
sanitized URL into the thrown Error (and keep including error.message); if URL
parsing fails, fall back to a safe placeholder like "<invalid-proxy>" so no raw
credentials are logged.

Comment on lines +35 to +52
private async detectSystemProxy(): Promise<ProxyConfiguration> {
const startTime = Date.now();

try {
const result = await this.detectWithTimeout();

// Log slow detections
const detectionTime = Date.now() - startTime;
if (detectionTime > 5000) {
console.warn(`System proxy detection took ${detectionTime}ms`);
}

return result;
} catch (error) {
console.warn(`System proxy detection failed after ${Date.now() - startTime}ms:`, error instanceof Error ? error.message : String(error));
return this.getEnvironmentVariables();
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Fallback might hide detection failures.

The catch block silently falls back to environment variables, which could mask code bugs or configuration issues in platform-specific detectors. Consider logging the error type or adding telemetry to track detection failures.

That said, the fallback behavior may be intentional for resilience. If so, document the design choice.

🤖 Prompt for AI Agents
In packages/bruno-requests/src/network/system-proxy/index.ts around lines 35–52,
the catch block quietly falls back to environment variables which can hide
detector failures; update the catch to log the error type and details (e.g.,
error.name and error.message and/or stack) and emit a telemetry/event hook (or
call a provided metrics reporter) with the failure reason and duration so
failures are observable, and add a short inline comment or JSDoc above
detectSystemProxy explaining that the fallback is intentional for resilience (or
change behavior if it should instead surface errors).

@lohit-bruno lohit-bruno changed the title fix: system proxy detection logic updates fix: system proxy resolver logic updates Dec 3, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/bruno-app/src/components/ResponsePane/index.js (1)

178-181: Headers tab test id addition is clean and non-invasive

Adding data-testid="response-headers-tab" gives a stable selector for tests without affecting behavior. You may optionally mirror this on other tabs for consistency in test selectors, but it’s not required.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2c17f1d and 8c3cab9.

📒 Files selected for processing (3)
  • packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js (1 hunks)
  • packages/bruno-app/src/components/Preferences/ProxySettings/index.js (2 hunks)
  • packages/bruno-app/src/components/ResponsePane/index.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings. For JSX/TSX attributes, use double quotes (e.g., )
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single params
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses
Space before and after the arrow in arrow functions. () => {} is good
No space between function name and parentheses. func() not func ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • packages/bruno-app/src/components/ResponsePane/index.js
  • packages/bruno-app/src/components/Preferences/ProxySettings/index.js
🧠 Learnings (1)
📚 Learning: 2025-12-02T09:45:31.709Z
Learnt from: sid-bruno
Repo: usebruno/bruno PR: 6266
File: packages/bruno-app/src/components/ResponsePane/ResponseCopy/index.js:38-38
Timestamp: 2025-12-02T09:45:31.709Z
Learning: In the ResponseCopy component (packages/bruno-app/src/components/ResponsePane/ResponseCopy/index.js), the copy button is intentionally disabled using `!response.data` to prevent copying stream resets which result in empty strings.

Applied to files:

  • packages/bruno-app/src/components/ResponsePane/index.js
🧬 Code graph analysis (1)
packages/bruno-app/src/components/ResponsePane/index.js (7)
packages/bruno-app/src/components/ResponsePane/StatusCode/index.js (1)
  • getTabClassname (8-16)
packages/bruno-app/src/components/RunnerResults/ResponsePane/index.js (2)
  • getTabClassname (85-89)
  • selectTab (36-36)
packages/bruno-app/src/components/FolderSettings/index.js (1)
  • getTabClassname (70-74)
packages/bruno-app/src/components/CollectionSettings/index.js (1)
  • getTabClassname (94-98)
packages/bruno-app/src/components/ResponsePane/GrpcResponsePane/index.js (1)
  • selectTab (30-37)
packages/bruno-app/src/components/RequestPane/GraphQLRequestPane/index.js (1)
  • selectTab (86-91)
packages/bruno-app/src/components/RequestPane/HttpRequestPane/index.js (1)
  • selectTab (84-89)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Playwright E2E Tests
  • GitHub Check: Unit Tests
  • GitHub Check: CLI Tests
  • GitHub Check: SSL Tests - Linux
  • GitHub Check: SSL Tests - Windows
  • GitHub Check: SSL Tests - macOS
🔇 Additional comments (1)
packages/bruno-app/src/components/Preferences/ProxySettings/index.js (1)

11-11: SystemProxy wiring for “system” mode looks correct

Importing SystemProxy and rendering it only when mode === 'system' keeps the new UI isolated from manual proxy settings and matches the existing mode switch pattern. No issues spotted with this integration.

Also applies to: 161-165

@dbrglc

dbrglc commented Dec 12, 2025

Copy link
Copy Markdown
Contributor

Resolve #5980

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Note

Due to the large number of review comments, Critical severity comments were prioritized as inline comments.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/bruno-app/src/components/CollectionSettings/ProxySettings/index.js (2)

186-192: InfoTip content doesn't match actual mode values.

The tooltip describes "global", "enabled", and "disable" but the actual radio button labels and values are "Inherit", "On", and "Off". Update the InfoTip to match:

              <InfoTip infotipId="request-var">
                <div>
                  <ul>
-                   <li><span style={{ width: '50px', display: 'inline-block' }}>global</span> - use global proxy config</li>
-                   <li><span style={{ width: '50px', display: 'inline-block' }}>enabled</span> - use collection proxy config</li>
-                   <li><span style={{ width: '50px', display: 'inline-block' }}>disable</span> - disable proxy</li>
+                   <li><span style={{ width: '50px', display: 'inline-block' }}>inherit</span> - use global proxy config</li>
+                   <li><span style={{ width: '50px', display: 'inline-block' }}>on</span> - use collection proxy config</li>
+                   <li><span style={{ width: '50px', display: 'inline-block' }}>off</span> - disable proxy</li>
                  </ul>
                </div>
              </InfoTip>

130-135: Port conversion of empty string returns 0, not ''.

When e.target.value is an empty string, Number('') evaluates to 0, not ''. This means the ternary on line 131 never actually returns '', and instead 0 gets passed to validation. The validation passes 0 (since it's falsy and hits the early return), but storing 0 as a port is likely unintended.

 const handlePortChange = (e) => {
-  const port = e.target.value ? Number(e.target.value) : '';
+  const port = e.target.value === '' ? '' : Number(e.target.value);
   if (validatePortOnChange(port)) {
     updateProxy({ port });
   }
 };
♻️ Duplicate comments (2)
tests/proxy-settings/collections/proxy-inherit/request.bru (1)

1-15: Same fixture placement concern as proxy-object collection.

This collection has the same placement pattern issue as proxy-object/request.bru. Refer to the verification comment on that file.

tests/proxy-settings/collections/proxy-inherit/package.json (1)

1-4: Same fixture placement concern as request.bru files.

This package.json is part of the proxy-inherit collection that has the placement concern already flagged in request.bru.

🟠 Major comments (28)
tests/proxy-settings/with-proxy-turned-OFF/collection_proxy_INHERIT_with_app_proxy_FALSE/collection_proxy_INHERIT_with_app_proxy_FALSE.spec.ts-4-34 (1)

4-34: Promote use of test.step for better test reporting.

Per coding guidelines, use test.step to organize test phases. This makes generated reports easier to read and debug when tests fail.

Consider restructuring both tests like this:

-  test('developer mode - should succeed when proxy server not running', async ({ pageWithUserData: page }) => {
+  test('developer mode - should succeed when proxy server not running', async ({ pageWithUserData: page }) => {
     const locators = buildCommonLocators(page);

-    // Configure developer mode
-    await setSandboxMode(page, 'proxy-inherit', 'developer');
+    await test.step('Configure developer mode', async () => {
+      await setSandboxMode(page, 'proxy-inherit', 'developer');
+    });

-    // Open request and send
-    await page.getByText('test-request').click();
-    await locators.request.sendButton().click();
+    await test.step('Open request and send', async () => {
+      await page.getByText('test-request').click();
+      await locators.request.sendButton().click();
+    });

-    // Collection proxy INHERIT uses app proxy FALSE - should succeed (no proxy used)
-    await locators.response.statusCode().waitFor({ state: 'visible' });
-    await expect(locators.response.statusCode()).toHaveText(/200/);
+    await test.step('Verify response without proxy', async () => {
+      await locators.response.statusCode().waitFor({ state: 'visible' });
+      await expect(locators.response.statusCode()).toHaveText(/200/);
+    });
   });

Apply the same pattern to the safe mode test.

tests/proxy-settings/with-proxy-turned-OFF/collection_proxy_FALSE_with_app_proxy_SYSTEM/collection_proxy_FALSE_with_app_proxy_SYSTEM.spec.ts-10-13 (1)

10-13: Use delete to properly clean up environment variables.

Setting environment variables to empty strings doesn't remove them from process.env. Use delete instead to ensure proper cleanup.

Apply this diff:

  test.afterAll(() => {
-    process.env.http_proxy = '';
-    process.env.https_proxy = '';
+    delete process.env.http_proxy;
+    delete process.env.https_proxy;
  });
tests/proxy-settings/with-proxy-turned-OFF/collection_proxy_FALSE_with_app_proxy_SYSTEM/collection_proxy_FALSE_with_app_proxy_SYSTEM.spec.ts-30-43 (1)

30-43: Wrap test actions in test.step, use locator variables, and clarify .nth(1) usage.

Similar to the developer mode test, this should use test.step for better reporting and define locator variables. Additionally, the .nth(1) usage on line 37 suggests multiple 'test-request' elements exist—consider using a more specific locator or adding a comment explaining why the second element is selected.

As per coding guidelines, consider this refactor:

  test('safe mode - should succeed when proxy server not running', async ({ pageWithUserData: page }) => {
    const locators = buildCommonLocators(page);
+   // Selecting second test-request element (safe mode request)
+   const testRequestLocator = page.getByText('test-request').nth(1);

-   // Configure safe mode
-   await setSandboxMode(page, 'proxy-false', 'safe');
+   await test.step('Configure safe mode', async () => {
+     await setSandboxMode(page, 'proxy-false', 'safe');
+   });

-   // Open request and send
-   await page.getByText('test-request').nth(1).click();
-   await locators.request.sendButton().click();
+   await test.step('Open request and send', async () => {
+     await testRequestLocator.click();
+     await locators.request.sendButton().click();
+   });

-   // Collection proxy FALSE ignores app proxy SYSTEM - should succeed (no proxy used)
-   await locators.response.statusCode().waitFor({ state: 'visible' });
-   await expect(locators.response.statusCode()).toHaveText(/200/);
+   await test.step('Verify response status is 200', async () => {
+     await locators.response.statusCode().waitFor({ state: 'visible' });
+     await expect(locators.response.statusCode()).toHaveText(/200/);
+   });
  });
tests/proxy-settings/with-proxy-turned-OFF/collection_proxy_FALSE_with_app_proxy_SYSTEM/collection_proxy_FALSE_with_app_proxy_SYSTEM.spec.ts-15-28 (1)

15-28: Wrap test actions in test.step for better reporting and use locator variables.

According to coding guidelines, promote the use of test.step for easier-to-read reports, and define locator variables instead of using page.getByText() inline.

As per coding guidelines, consider this refactor:

  test('developer mode - should succeed when proxy server not running', async ({ pageWithUserData: page }) => {
    const locators = buildCommonLocators(page);
+   const testRequestLocator = page.getByText('test-request');

-   // Configure developer mode
-   await setSandboxMode(page, 'proxy-false', 'developer');
+   await test.step('Configure developer mode', async () => {
+     await setSandboxMode(page, 'proxy-false', 'developer');
+   });

-   // Open request and send
-   await page.getByText('test-request').click();
-   await locators.request.sendButton().click();
+   await test.step('Open request and send', async () => {
+     await testRequestLocator.click();
+     await locators.request.sendButton().click();
+   });

-   // Collection proxy FALSE ignores app proxy SYSTEM - should succeed (no proxy used)
-   await locators.response.statusCode().waitFor({ state: 'visible' });
-   await expect(locators.response.statusCode()).toHaveText(/200/);
+   await test.step('Verify response status is 200', async () => {
+     await locators.response.statusCode().waitFor({ state: 'visible' });
+     await expect(locators.response.statusCode()).toHaveText(/200/);
+   });
  });
tests/proxy-settings/with-proxy-turned-ON/collection_proxy_FALSE_with_app_proxy_CONFIG/collection_proxy_FALSE_with_app_proxy_CONFIG.spec.ts-25-38 (1)

25-38: Apply the same improvements: use test.step and locator variables.

This test has the same structural issues as the developer mode test. Additionally, line 32 uses .nth(1) which assumes a specific ordering of elements—consider using a more specific locator if possible.

 test('safe mode - should succeed when proxy server is running', async ({ pageWithUserData: page }) => {
   const locators = buildCommonLocators(page);
+  const testRequestLocator = page.getByText('test-request').nth(1);

-  // Configure safe mode
-  await setSandboxMode(page, 'proxy-false', 'safe');
-
-  // Open request and send
-  await page.getByText('test-request').nth(1).click();
-  await locators.request.sendButton().click();
-
-  // Collection proxy FALSE ignores app proxy - should succeed (no proxy used)
-  await locators.response.statusCode().waitFor({ state: 'visible' });
-  await expect(locators.response.statusCode()).toHaveText(/200/);
+  await test.step('Configure safe mode', async () => {
+    await setSandboxMode(page, 'proxy-false', 'safe');
+  });
+
+  await test.step('Send request', async () => {
+    await testRequestLocator.click();
+    await locators.request.sendButton().click();
+  });
+
+  await test.step('Verify response', async () => {
+    await locators.response.statusCode().waitFor({ state: 'visible' });
+    await expect(locators.response.statusCode()).toHaveText(/200/);
+  });
 });
tests/proxy-settings/with-proxy-turned-ON/collection_proxy_FALSE_with_app_proxy_CONFIG/collection_proxy_FALSE_with_app_proxy_CONFIG.spec.ts-10-23 (1)

10-23: Use test.step and locator variables for better readability.

Per the coding guidelines, promote test.step usage to make generated reports easier to read, and use locator variables instead of inline selectors.

 test('developer mode - should succeed when proxy server is running', async ({ pageWithUserData: page }) => {
   const locators = buildCommonLocators(page);
+  const testRequestLocator = page.getByText('test-request');

-  // Configure developer mode
-  await setSandboxMode(page, 'proxy-false', 'developer');
-
-  // Open request and send
-  await page.getByText('test-request').click();
-  await locators.request.sendButton().click();
-
-  // Collection proxy FALSE ignores app proxy - should succeed (no proxy used)
-  await locators.response.statusCode().waitFor({ state: 'visible' });
-  await expect(locators.response.statusCode()).toHaveText(/200/);
+  await test.step('Configure developer mode', async () => {
+    await setSandboxMode(page, 'proxy-false', 'developer');
+  });
+
+  await test.step('Send request', async () => {
+    await testRequestLocator.click();
+    await locators.request.sendButton().click();
+  });
+
+  await test.step('Verify response', async () => {
+    await locators.response.statusCode().waitFor({ state: 'visible' });
+    await expect(locators.response.statusCode()).toHaveText(/200/);
+  });
 });
tests/proxy-settings/with-proxy-turned-OFF/collection_proxy_INHERIT_with_app_proxy_CONFIG/collection_proxy_INHERIT_with_app_proxy_CONFIG.spec.ts-20-33 (1)

20-33: Apply same improvements: test.step and reduced timeout.

Same issues as the first test—missing test.step structure and excessive 2-minute timeout.

Apply this refactor:

-  test('safe mode - should fail when proxy server not running', async ({ pageWithUserData: page }) => {
+  test('safe mode - should fail when proxy server not running', async ({ pageWithUserData: page }) => {
     const locators = buildCommonLocators(page);
 
-    // Configure safe mode
-    await setSandboxMode(page, 'proxy-inherit', 'safe');
+    await test.step('Configure safe mode', async () => {
+      await setSandboxMode(page, 'proxy-inherit', 'safe');
+    });
 
-    // Open request and send
-    await page.getByText('test-request').nth(1).click();
-    await locators.request.sendButton().click();
+    await test.step('Open and send request', async () => {
+      await page.getByText('test-request').nth(1).click();
+      await locators.request.sendButton().click();
+    });
 
-    // Expect proxy error
-    await expect(page.getByText('ECONNREFUSED', { exact: false }))
-      .toBeVisible({ timeout: 2 * 60 * 1000 });
+    await test.step('Verify proxy connection error', async () => {
+      await expect(page.getByText('ECONNREFUSED', { exact: false }))
+        .toBeVisible({ timeout: 30000 });
+    });
   });
tests/proxy-settings/with-proxy-turned-OFF/collection_proxy_INHERIT_with_app_proxy_CONFIG/collection_proxy_INHERIT_with_app_proxy_CONFIG.spec.ts-5-18 (1)

5-18: Use test.step for better reporting and reduce excessive timeout.

Per coding guidelines, promote test.step usage for easier-to-read reports. Additionally, the 2-minute timeout for ECONNREFUSED seems excessive—connection refusal typically happens within seconds.

Apply this refactor to improve test structure:

-  test('developer mode - should fail when proxy server not running', async ({ pageWithUserData: page }) => {
+  test('developer mode - should fail when proxy server not running', async ({ pageWithUserData: page }) => {
     const locators = buildCommonLocators(page);
 
-    // Configure developer mode
-    await setSandboxMode(page, 'proxy-inherit', 'developer');
+    await test.step('Configure developer mode', async () => {
+      await setSandboxMode(page, 'proxy-inherit', 'developer');
+    });
 
-    // Open request and send
-    await page.getByText('test-request').click();
-    await locators.request.sendButton().click();
+    await test.step('Open and send request', async () => {
+      await page.getByText('test-request').click();
+      await locators.request.sendButton().click();
+    });
 
-    // Expect proxy error
-    await expect(page.getByText('ECONNREFUSED', { exact: false }))
-      .toBeVisible({ timeout: 2 * 60 * 1000 });
+    await test.step('Verify proxy connection error', async () => {
+      await expect(page.getByText('ECONNREFUSED', { exact: false }))
+        .toBeVisible({ timeout: 30000 });
+    });
   });
tests/proxy-settings/with-proxy-turned-ON/collection_proxy_INHERIT_with_app_proxy_SYSTEM/collection_proxy_INHERIT_with_app_proxy_SYSTEM.spec.ts-11-12 (1)

11-12: Use uppercase environment variable names for proxy configuration.

Standard proxy environment variables are uppercase (HTTP_PROXY, HTTPS_PROXY). While some libraries check both cases, lowercase variants are non-standard and may not be recognized by all proxy resolution libraries, potentially causing tests to pass incorrectly.

-    process.env.http_proxy = 'http://127.0.0.1:8091';
-    process.env.https_proxy = 'http://127.0.0.1:8091';
+    process.env.HTTP_PROXY = 'http://127.0.0.1:8091';
+    process.env.HTTPS_PROXY = 'http://127.0.0.1:8091';
tests/proxy-settings/with-proxy-turned-ON/collection_proxy_INHERIT_with_app_proxy_SYSTEM/collection_proxy_INHERIT_with_app_proxy_SYSTEM.spec.ts-20-48 (1)

20-48: Use test.step to improve test report readability.

As per coding guidelines, structure tests with test.step for clearer reporting. Break down each test into logical steps (configure mode, send request, verify response).

Example for the first test:

 test('developer mode - should succeed when proxy server is running', async ({ pageWithUserData: page }) => {
-  const locators = buildCommonLocators(page);
-
-  // Configure developer mode
-  await setSandboxMode(page, 'proxy-inherit', 'developer');
-
-  // Open request and send
-  await page.getByText('test-request').click();
-  await locators.request.sendButton().click();
-
-  // Collection proxy INHERIT uses app proxy SYSTEM - should succeed (proxy working)
-  await locators.response.statusCode().waitFor({ state: 'visible' });
-  await expect(locators.response.statusCode()).toHaveText(/200/);
+  await test.step('Configure developer mode', async () => {
+    await setSandboxMode(page, 'proxy-inherit', 'developer');
+  });
+
+  await test.step('Send test request', async () => {
+    const locators = buildCommonLocators(page);
+    await page.getByText('test-request').click();
+    await locators.request.sendButton().click();
+  });
+
+  await test.step('Verify successful response via proxy', async () => {
+    const locators = buildCommonLocators(page);
+    await locators.response.statusCode().waitFor({ state: 'visible' });
+    await expect(locators.response.statusCode()).toHaveText(/200/);
+  });
 });

Apply similar restructuring to the safe mode test.

tests/proxy-settings/with-proxy-turned-ON/collection_proxy_INHERIT_with_app_proxy_FALSE/collection_proxy_INHERIT_with_app_proxy_FALSE.spec.ts-25-38 (1)

25-38: Refactor to use test.step for better test reporting.

As per coding guidelines, test.step should be promoted for easier-to-read reports. Break down the test into logical steps.

 test('safe mode - should succeed when proxy server is running', async ({ pageWithUserData: page }) => {
-  const locators = buildCommonLocators(page);
-
-  // Configure safe mode
-  await setSandboxMode(page, 'proxy-inherit', 'safe');
-
-  // Open request and send
-  await page.getByText('test-request').nth(1).click();
-  await locators.request.sendButton().click();
-
-  // Collection proxy INHERIT uses app proxy FALSE - should succeed (no proxy used)
-  await locators.response.statusCode().waitFor({ state: 'visible' });
-  await expect(locators.response.statusCode()).toHaveText(/200/);
+  const locators = buildCommonLocators(page);
+
+  await test.step('Configure safe mode', async () => {
+    await setSandboxMode(page, 'proxy-inherit', 'safe');
+  });
+
+  await test.step('Send test request', async () => {
+    await page.getByText('test-request').nth(1).click();
+    await locators.request.sendButton().click();
+  });
+
+  await test.step('Verify 200 response (no proxy used)', async () => {
+    await locators.response.statusCode().waitFor({ state: 'visible' });
+    await expect(locators.response.statusCode()).toHaveText(/200/);
+  });
 });
tests/proxy-settings/with-proxy-turned-ON/collection_proxy_INHERIT_with_app_proxy_FALSE/collection_proxy_INHERIT_with_app_proxy_FALSE.spec.ts-10-23 (1)

10-23: Refactor to use test.step for better test reporting.

As per coding guidelines, test.step should be promoted for easier-to-read reports. Break down the test into logical steps.

 test('developer mode - should succeed when proxy server is running', async ({ pageWithUserData: page }) => {
-  const locators = buildCommonLocators(page);
-
-  // Configure developer mode
-  await setSandboxMode(page, 'proxy-inherit', 'developer');
-
-  // Open request and send
-  await page.getByText('test-request').click();
-  await locators.request.sendButton().click();
-
-  // Collection proxy INHERIT uses app proxy FALSE - should succeed (no proxy used)
-  await locators.response.statusCode().waitFor({ state: 'visible' });
-  await expect(locators.response.statusCode()).toHaveText(/200/);
+  const locators = buildCommonLocators(page);
+
+  await test.step('Configure developer mode', async () => {
+    await setSandboxMode(page, 'proxy-inherit', 'developer');
+  });
+
+  await test.step('Send test request', async () => {
+    await page.getByText('test-request').click();
+    await locators.request.sendButton().click();
+  });
+
+  await test.step('Verify 200 response (no proxy used)', async () => {
+    await locators.response.statusCode().waitFor({ state: 'visible' });
+    await expect(locators.response.statusCode()).toHaveText(/200/);
+  });
 });
tests/proxy-settings/with-proxy-turned-OFF/collection_proxy_INHERIT_with_app_proxy_SYSTEM/collection_proxy_INHERIT_with_app_proxy_SYSTEM.spec.ts-30-43 (1)

30-43: Add test.step blocks, reduce timeout, and improve selector robustness.

Similar to the first test, this needs test.step organization and a reduced timeout. Additionally, .getByText('test-request').nth(1) is brittle and order-dependent—consider using more specific locators (e.g., by role, data-testid, or unique text).

Apply this diff:

   test('safe mode - should fail when proxy server not running', async ({ pageWithUserData: page }) => {
     const locators = buildCommonLocators(page);
 
-    // Configure safe mode
-    await setSandboxMode(page, 'proxy-inherit', 'safe');
-
-    // Open request and send
-    await page.getByText('test-request').nth(1).click();
-    await locators.request.sendButton().click();
-
-    // Expect proxy error
-    await expect(page.getByText('ECONNREFUSED', { exact: false }))
-      .toBeVisible({ timeout: 2 * 60 * 1000 });
+    await test.step('Configure safe mode', async () => {
+      await setSandboxMode(page, 'proxy-inherit', 'safe');
+    });
+
+    await test.step('Send request and verify connection failure', async () => {
+      await page.getByText('test-request').nth(1).click();
+      await locators.request.sendButton().click();
+      await expect(page.getByText('ECONNREFUSED', { exact: false }))
+        .toBeVisible({ timeout: 10000 });
+    });
   });

Consider using a more robust selector strategy to avoid reliance on element order. For example, if each request has a unique identifier or role, prefer that over positional selectors.

As per coding guidelines, test.step usage is essential for readable test reports.

tests/proxy-settings/with-proxy-turned-OFF/collection_proxy_INHERIT_with_app_proxy_SYSTEM/collection_proxy_INHERIT_with_app_proxy_SYSTEM.spec.ts-15-28 (1)

15-28: Add test.step blocks and reduce excessive timeout.

Per coding guidelines, use test.step to organize test actions for better report readability. Additionally, the 2-minute timeout for ECONNREFUSED is excessive—connection refused errors occur immediately when a server is unreachable.

Apply this diff to improve test organization and timeout:

   test('developer mode - should fail when proxy server not running', async ({ pageWithUserData: page }) => {
     const locators = buildCommonLocators(page);
 
-    // Configure developer mode
-    await setSandboxMode(page, 'proxy-inherit', 'developer');
-
-    // Open request and send
-    await page.getByText('test-request').click();
-    await locators.request.sendButton().click();
-
-    // Expect proxy error
-    await expect(page.getByText('ECONNREFUSED', { exact: false }))
-      .toBeVisible({ timeout: 2 * 60 * 1000 });
+    await test.step('Configure developer mode', async () => {
+      await setSandboxMode(page, 'proxy-inherit', 'developer');
+    });
+
+    await test.step('Send request and verify connection failure', async () => {
+      await page.getByText('test-request').click();
+      await locators.request.sendButton().click();
+      await expect(page.getByText('ECONNREFUSED', { exact: false }))
+        .toBeVisible({ timeout: 10000 });
+    });
   });

As per coding guidelines, test.step usage improves generated report readability.

tests/proxy-settings/with-proxy-turned-ON/collection_proxy_FALSE_with_app_proxy_SYSTEM/collection_proxy_FALSE_with_app_proxy_SYSTEM.spec.ts-35-48 (1)

35-48: Add test.step and improve selector robustness.

Two suggestions:

  1. Use test.step for better reporting (same as previous test).
  2. Line 42 uses .nth(1) which assumes ordering and is fragile. Consider using a more specific locator.

Apply similar test.step pattern and consider more robust selectors for consistency with test best practices.

tests/proxy-settings/with-proxy-turned-OFF/collection_proxy_CONFIG_with_app_proxy_FALSE/collection_proxy_CONFIG_with_app_proxy_FALSE.spec.ts-20-33 (1)

20-33: Add test.step and improve selector robustness.

Two suggestions:

  1. Use test.step for better reporting (same as previous test).
  2. Line 27 uses .nth(1) which assumes ordering and is fragile. Consider using a more specific locator or text match.

Apply similar test.step pattern as suggested for the first test. For the selector issue, consider if there's a unique identifier or if the test data can be structured to avoid relying on element order.

tests/proxy-settings/server/helpers/platform.js-30-53 (1)

30-53: Add logging to error handler and validate port input.

Line 52 has an empty catch block that silently swallows all errors, making debugging difficult. At minimum, log the error. Additionally, validate the port parameter to prevent potential command injection.

 function killProcessOnPort(port) {
+  // Validate port is a number to prevent command injection
+  if (!Number.isInteger(port) || port < 0 || port > 65535) {
+    throw new Error(`Invalid port: ${port}`);
+  }
+
   const platform = detectPlatform();

   try {
     switch (platform) {
       case 'macos':
+      case 'linux':
         execCommand(`lsof -ti :${port} | xargs kill -9`);
         break;
-      case 'linux':
-        execCommand(`lsof -ti :${port} | xargs kill -9`);
-        break;
       case 'windows':
         const result = execCommandSilent(`netstat -ano | findstr :${port}`);
         const lines = result.toString().split('\n');
         for (const line of lines) {
           const match = line.trim().match(/\s+(\d+)$/);
           if (match) {
             execCommandSilent(`taskkill /F /PID ${match[1]}`);
           }
         }
         break;
     }
-  } catch (error) {}
+  } catch (error) {
+    // Process might not exist on port, log for debugging
+    console.warn(`Failed to kill process on port ${port}:`, error.message);
+  }
 }
tests/proxy-settings/with-proxy-turned-ON/collection_proxy_FALSE_with_app_proxy_SYSTEM/collection_proxy_FALSE_with_app_proxy_SYSTEM.spec.ts-20-33 (1)

20-33: Add test.step for improved test reporting.

Consider wrapping logical test sections in test.step to make the generated reports more readable, consistent with Playwright best practices.

 test('developer mode - should succeed when proxy server is running', async ({ pageWithUserData: page }) => {
   const locators = buildCommonLocators(page);

-  // Configure developer mode
-  await setSandboxMode(page, 'proxy-false', 'developer');
+  await test.step('Configure developer mode', async () => {
+    await setSandboxMode(page, 'proxy-false', 'developer');
+  });

-  // Open request and send
-  await page.getByText('test-request').click();
-  await locators.request.sendButton().click();
+  await test.step('Send test request', async () => {
+    await page.getByText('test-request').click();
+    await locators.request.sendButton().click();
+  });

-  // Collection proxy FALSE ignores app proxy - should succeed (no proxy used)
-  await locators.response.statusCode().waitFor({ state: 'visible' });
-  await expect(locators.response.statusCode()).toHaveText(/200/);
+  await test.step('Verify successful response without proxy', async () => {
+    await locators.response.statusCode().waitFor({ state: 'visible' });
+    await expect(locators.response.statusCode()).toHaveText(/200/);
+  });
 });

As per coding guidelines, promoting the use of test.step makes reports easier to read.

tests/proxy-settings/with-proxy-turned-OFF/collection_proxy_CONFIG_with_app_proxy_FALSE/collection_proxy_CONFIG_with_app_proxy_FALSE.spec.ts-5-18 (1)

5-18: Add test.step for improved test reporting.

Consider wrapping logical test sections in test.step to make the generated reports more readable. This aligns with the coding guidelines for Playwright tests.

 test('developer mode - should fail when proxy server not running', async ({ pageWithUserData: page }) => {
   const locators = buildCommonLocators(page);

-  // Configure developer mode
-  await setSandboxMode(page, 'proxy-object', 'developer');
+  await test.step('Configure developer mode', async () => {
+    await setSandboxMode(page, 'proxy-object', 'developer');
+  });

-  // Open request and send
-  await page.getByText('test-request').click();
-  await locators.request.sendButton().click();
+  await test.step('Send test request', async () => {
+    await page.getByText('test-request').click();
+    await locators.request.sendButton().click();
+  });

-  // Expect proxy error
-  await expect(page.getByText('ECONNREFUSED', { exact: false }))
-    .toBeVisible({ timeout: 2 * 60 * 1000 });
+  await test.step('Verify proxy connection error', async () => {
+    await expect(page.getByText('ECONNREFUSED', { exact: false }))
+      .toBeVisible({ timeout: 2 * 60 * 1000 });
+  });
 });

As per coding guidelines, promoting the use of test.step makes reports easier to read.

.github/actions/proxy/linux/run-cli-tests-with-proxy-off/action.yml-62-62 (1)

62-62: Use unset for environment variable cleanup.

Using export HTTPS_PROXY= may not properly unset the variable on all systems. Use unset HTTPS_PROXY instead for reliable cleanup.

-        export HTTPS_PROXY=
+        unset HTTPS_PROXY
tests/proxy-settings/server/index.js-20-28 (1)

20-28: Fix server.listen callback signature.

The server.listen() callback doesn't receive an error parameter in Node.js. Errors should be handled via the server's 'error' event listener instead.

   return new Promise((resolve, reject) => {
-    server.listen(port, (error) => {
-      if (error) {
-        reject(error);
-      } else {
-        resolve(server);
-      }
+    server.on('error', (error) => {
+      reject(error);
+    });
+
+    server.listen(port, () => {
+      resolve(server);
     });
   });
tests/proxy-settings/with-proxy-turned-ON/collection_proxy_CONFIG_with_app_proxy_FALSE/collection_proxy_CONFIG_with_app_proxy_FALSE.spec.ts-10-23 (1)

10-23: Use test.step for better test reporting.

Per coding guidelines, wrap logical test phases in test.step blocks to improve readability of generated reports.

 test('developer mode - should succeed when proxy server is running', async ({ pageWithUserData: page }) => {
   const locators = buildCommonLocators(page);
 
-  // Configure developer mode
-  await setSandboxMode(page, 'proxy-object', 'developer');
-
-  // Open request and send
-  await page.getByText('test-request').click();
-  await locators.request.sendButton().click();
-
-  // Collection proxy CONFIG uses proxy - should succeed (proxy working)
-  await locators.response.statusCode().waitFor({ state: 'visible' });
-  await expect(locators.response.statusCode()).toHaveText(/200/);
+  await test.step('Configure developer mode', async () => {
+    await setSandboxMode(page, 'proxy-object', 'developer');
+  });
+
+  await test.step('Send request and verify response', async () => {
+    await page.getByText('test-request').click();
+    await locators.request.sendButton().click();
+
+    await locators.response.statusCode().waitFor({ state: 'visible' });
+    await expect(locators.response.statusCode()).toHaveText(/200/);
+  });
 });
tests/proxy-settings/with-proxy-turned-ON/collection_proxy_INHERIT_with_app_proxy_CONFIG/collection_proxy_INHERIT_with_app_proxy_CONFIG.spec.ts-10-23 (1)

10-23: Use test.step for better test reporting.

Per coding guidelines, wrap logical test phases in test.step blocks to improve readability of generated reports.

 test('developer mode - should succeed when proxy server is running', async ({ pageWithUserData: page }) => {
   const locators = buildCommonLocators(page);
 
-  // Configure developer mode
-  await setSandboxMode(page, 'proxy-inherit', 'developer');
-
-  // Open request and send
-  await page.getByText('test-request').click();
-  await locators.request.sendButton().click();
-
-  // Collection proxy INHERIT uses app proxy CONFIG - should succeed (proxy working)
-  await locators.response.statusCode().waitFor({ state: 'visible' });
-  await expect(locators.response.statusCode()).toHaveText(/200/);
+  await test.step('Configure developer mode', async () => {
+    await setSandboxMode(page, 'proxy-inherit', 'developer');
+  });
+
+  await test.step('Send request and verify response', async () => {
+    await page.getByText('test-request').click();
+    await locators.request.sendButton().click();
+
+    await locators.response.statusCode().waitFor({ state: 'visible' });
+    await expect(locators.response.statusCode()).toHaveText(/200/);
+  });
 });
tests/proxy-settings/with-proxy-turned-ON/collection_proxy_INHERIT_with_app_proxy_CONFIG/collection_proxy_INHERIT_with_app_proxy_CONFIG.spec.ts-25-38 (1)

25-38: Use test.step for better test reporting.

Per coding guidelines, wrap logical test phases in test.step blocks to improve readability of generated reports.

 test('safe mode - should succeed when proxy server is running', async ({ pageWithUserData: page }) => {
   const locators = buildCommonLocators(page);
 
-  // Configure safe mode
-  await setSandboxMode(page, 'proxy-inherit', 'safe');
-
-  // Open request and send
-  await page.getByText('test-request').nth(1).click();
-  await locators.request.sendButton().click();
-
-  // Collection proxy INHERIT uses app proxy CONFIG - should succeed (proxy working)
-  await locators.response.statusCode().waitFor({ state: 'visible' });
-  await expect(locators.response.statusCode()).toHaveText(/200/);
+  await test.step('Configure safe mode', async () => {
+    await setSandboxMode(page, 'proxy-inherit', 'safe');
+  });
+
+  await test.step('Send request and verify response', async () => {
+    await page.getByText('test-request').nth(1).click();
+    await locators.request.sendButton().click();
+
+    await locators.response.statusCode().waitFor({ state: 'visible' });
+    await expect(locators.response.statusCode()).toHaveText(/200/);
+  });
 });
tests/proxy-settings/with-proxy-turned-ON/collection_proxy_CONFIG_with_app_proxy_FALSE/collection_proxy_CONFIG_with_app_proxy_FALSE.spec.ts-25-38 (1)

25-38: Use test.step for better test reporting.

Per coding guidelines, wrap logical test phases in test.step blocks to improve readability of generated reports.

 test('safe mode - should succeed when proxy server is running', async ({ pageWithUserData: page }) => {
   const locators = buildCommonLocators(page);
 
-  // Configure safe mode
-  await setSandboxMode(page, 'proxy-object', 'safe');
-
-  // Open request and send
-  await page.getByText('test-request').nth(1).click();
-  await locators.request.sendButton().click();
-
-  // Collection proxy CONFIG uses proxy - should succeed (proxy working)
-  await locators.response.statusCode().waitFor({ state: 'visible' });
-  await expect(locators.response.statusCode()).toHaveText(/200/);
+  await test.step('Configure safe mode', async () => {
+    await setSandboxMode(page, 'proxy-object', 'safe');
+  });
+
+  await test.step('Send request and verify response', async () => {
+    await page.getByText('test-request').nth(1).click();
+    await locators.request.sendButton().click();
+
+    await locators.response.statusCode().waitFor({ state: 'visible' });
+    await expect(locators.response.statusCode()).toHaveText(/200/);
+  });
 });
tests/proxy-settings/with-proxy-turned-ON/collection_proxy_CONFIG_with_app_proxy_CONFIG/collection_proxy_CONFIG_with_app_proxy_CONFIG.spec.ts-10-23 (1)

10-23: Use test.step for better test reporting.

Per coding guidelines, wrap logical test phases in test.step blocks to improve readability of generated reports.

 test('developer mode - should succeed when proxy server is running', async ({ pageWithUserData: page }) => {
   const locators = buildCommonLocators(page);
 
-  // Configure developer mode
-  await setSandboxMode(page, 'proxy-object', 'developer');
-
-  // Open request and send
-  await page.getByText('test-request').click();
-  await locators.request.sendButton().click();
-
-  // Collection proxy CONFIG uses proxy - should succeed (proxy working)
-  await locators.response.statusCode().waitFor({ state: 'visible' });
-  await expect(locators.response.statusCode()).toHaveText(/200/);
+  await test.step('Configure developer mode', async () => {
+    await setSandboxMode(page, 'proxy-object', 'developer');
+  });
+
+  await test.step('Send request and verify response', async () => {
+    await page.getByText('test-request').click();
+    await locators.request.sendButton().click();
+
+    await locators.response.statusCode().waitFor({ state: 'visible' });
+    await expect(locators.response.statusCode()).toHaveText(/200/);
+  });
 });
tests/proxy-settings/with-proxy-turned-ON/collection_proxy_CONFIG_with_app_proxy_CONFIG/collection_proxy_CONFIG_with_app_proxy_CONFIG.spec.ts-25-38 (1)

25-38: Use test.step for better test reporting.

Per coding guidelines, wrap logical test phases in test.step blocks to improve readability of generated reports.

 test('safe mode - should succeed when proxy server is running', async ({ pageWithUserData: page }) => {
   const locators = buildCommonLocators(page);
 
-  // Configure safe mode
-  await setSandboxMode(page, 'proxy-object', 'safe');
-
-  // Open request and send
-  await page.getByText('test-request').nth(1).click();
-  await locators.request.sendButton().click();
-
-  // Collection proxy CONFIG uses proxy - should succeed (proxy working)
-  await locators.response.statusCode().waitFor({ state: 'visible' });
-  await expect(locators.response.statusCode()).toHaveText(/200/);
+  await test.step('Configure safe mode', async () => {
+    await setSandboxMode(page, 'proxy-object', 'safe');
+  });
+
+  await test.step('Send request and verify response', async () => {
+    await page.getByText('test-request').nth(1).click();
+    await locators.request.sendButton().click();
+
+    await locators.response.statusCode().waitFor({ state: 'visible' });
+    await expect(locators.response.statusCode()).toHaveText(/200/);
+  });
 });
tests/proxy-settings/server/proxy.js-150-159 (1)

150-159: server.listen callback doesn't receive an error parameter.

The listen callback is only invoked on successful bind. Errors are emitted via the 'error' event on the server. This means error is always undefined in the callback.

 return new Promise((resolve, reject) => {
+  proxy.on('error', (error) => {
+    reject(error);
+  });
-  proxy.listen(port, (error) => {
-    if (error) {
-      reject(error);
-    } else {
-      console.log(`🔄 Proxy server running on http://localhost:${port}`);
-      resolve(proxy);
-    }
+  proxy.listen(port, () => {
+    console.log(`🔄 Proxy server running on http://localhost:${port}`);
+    resolve(proxy);
   });
 });
🟡 Minor comments (10)
tests/proxy-settings/with-proxy-turned-ON/collection_proxy_INHERIT_with_app_proxy_SYSTEM/collection_proxy_INHERIT_with_app_proxy_SYSTEM.spec.ts-16-17 (1)

16-17: Properly delete environment variables in cleanup.

Setting environment variables to empty strings doesn't remove them. Use delete to properly clean up and avoid test pollution.

-    process.env.http_proxy = '';
-    process.env.https_proxy = '';
+    delete process.env.HTTP_PROXY;
+    delete process.env.HTTPS_PROXY;

Committable suggestion skipped: line range outside the PR's diff.

tests/proxy-settings/with-proxy-turned-ON/collection_proxy_FALSE_with_app_proxy_SYSTEM/collection_proxy_FALSE_with_app_proxy_SYSTEM.spec.ts-15-18 (1)

15-18: Fix environment variable cleanup.

Setting environment variables to empty strings doesn't remove them from the environment. Use delete to properly clean up.

 test.afterAll(() => {
-  process.env.http_proxy = '';
-  process.env.https_proxy = '';
+  delete process.env.http_proxy;
+  delete process.env.https_proxy;
 });
tests/proxy-settings/collections/proxy-false/report.json-1-64 (1)

1-64: Remove absolute path and hardcoded date from committed test report.

This file contains an absolute local path (/Users/lohit/Documents/code/bruno/... on line 61) and a hardcoded future date (Thu, 25 Sep 2025 on line 36). These prevent portability across machines and cause unnecessary version control drift.

Either exclude this file with **/report.json in .gitignore or generate it dynamically during test runs without committing it to the repository. If this serves as a golden file for comparison, use relative paths and normalize timestamps.

.github/actions/proxy/macos/run-cli-tests-with-proxy-off/action.yml-52-54 (1)

52-54: Comment/code mismatch.

Comment says "HTTP_PROXY" but the code sets HTTPS_PROXY. Update for consistency.

         # Test with system proxy environment variables set
-        echo "Running with HTTP_PROXY environment variable..."
+        echo "Running with HTTPS_PROXY environment variable..."
         export HTTPS_PROXY=http://127.0.0.1:8091
packages/bruno-electron/tests/store/proxy-preferences.spec.js-210-216 (1)

210-216: Test name is misleading.

The test description says "default proxy: false" but the assertion expects 'system'. Update the description to match the actual expected behavior.

-    test('should use default proxy: false when no proxy config exists', () => {
+    test('should use default proxy: "system" when no proxy config exists', () => {
       mockStoreData.preferences = {};

       const result = getPreferences();

       expect(result.proxy).toBe('system');
     });
.github/actions/proxy/macos/run-cli-tests-with-proxy-on/action.yml-45-47 (1)

45-47: Comment/code mismatch (same as proxy-off action).

Comment says "HTTP_PROXY" but code sets HTTPS_PROXY.

         # Test with system proxy environment variables set
-        echo "Running with HTTP_PROXY environment variable..."
+        echo "Running with HTTPS_PROXY environment variable..."
         export HTTPS_PROXY=http://127.0.0.1:8091
.github/actions/proxy/macos/run-cli-tests-with-proxy-on/action.yml-51-53 (1)

51-53: Typo in error message.

"occured" → "occurred"

         grep '"status": "pass"' report.json || {
-          echo "Test failed: error occured while proxying request."
+          echo "Test failed: error occurred while proxying request."
           exit 1
         }
.github/actions/proxy/linux/run-cli-tests-with-proxy-on/action.yml-45-47 (1)

45-47: Comment/code mismatch: mentions HTTP_PROXY but sets HTTPS_PROXY.

The echo says "HTTP_PROXY environment variable" but line 47 exports HTTPS_PROXY. Update for consistency.

         # Test with system proxy environment variables set
-        echo "Running with HTTP_PROXY environment variable..."
+        echo "Running with HTTPS_PROXY environment variable..."
         export HTTPS_PROXY=http://127.0.0.1:8091
.github/actions/proxy/linux/run-cli-tests-with-proxy-on/action.yml-51-53 (1)

51-53: Typo: "occured" → "occurred".

         grep '"status": "pass"' report.json || {
-          echo "Test failed: error occured while proxying request."
+          echo "Test failed: error occurred while proxying request."
           exit 1
         }
packages/bruno-electron/src/ipc/network/cert-utils.js-149-154 (1)

149-154: Unreachable fallback returns 'inherit' instead of 'system'.

Line 153 returns { proxyMode: 'inherit', proxyConfig: {} } as a final fallback. However:

  1. This branch appears unreachable given the conditions above (all cases seem covered).
  2. If it were reached, returning 'inherit' doesn't resolve to a final mode—it would need further resolution.

Consider returning 'system' to match the default behavior, or remove this unreachable code.

-  return { proxyMode: 'inherit', proxyConfig: {} };
+  // Fallback to system proxy (defensive, should not be reached)
+  return { proxyMode: 'system', proxyConfig: {} };

@@ -0,0 +1,18 @@
name: 'run e2e tests with proxy OFF - linux'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Fix incorrect action name.

The action name states "linux" but this is a macOS action. The artifact name correctly identifies "macos" on line 16.

Apply this diff:

-name: 'run e2e tests with proxy OFF - linux'
+name: 'run e2e tests with proxy OFF - macos'
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
name: 'run e2e tests with proxy OFF - linux'
name: 'run e2e tests with proxy OFF - macos'
🤖 Prompt for AI Agents
In .github/actions/proxy/macos/run-e2e-tests-with-proxy-off/action.yml around
lines 1 to 1, the action name string incorrectly says "linux"; update the name
value to accurately reference macOS (e.g., change "run e2e tests with proxy OFF
- linux" to "run e2e tests with proxy OFF - macos") so the action name matches
the macOS context and artifact naming.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/bruno-electron/src/utils/proxy-util.js (1)

136-140: Credential leakage in timeline logging.

Same issue here - proxyUri may contain credentials and is logged directly. Apply the same redaction pattern.

♻️ Duplicate comments (5)
packages/bruno-electron/src/utils/proxy-util.js (2)

390-392: Redact credentials from proxy URIs in error messages.

This was flagged in a previous review and remains unaddressed. The raw http_proxy value may contain credentials.

       } catch (error) {
+        const redactedProxy = http_proxy ? http_proxy.replace(/\/\/([^:]+):([^@]+)@/, '//$1:***@') : http_proxy;
-        throw new Error(`Invalid system http_proxy "${http_proxy}": ${error.message}`);
+        throw new Error(`Invalid system http_proxy "${redactedProxy}": ${error.message}`);
       }

405-407: Same credential leakage issue for https_proxy.

Apply the same redaction pattern here.

       } catch (error) {
+        const redactedProxy = https_proxy ? https_proxy.replace(/\/\/([^:]+):([^@]+)@/, '//$1:***@') : https_proxy;
-        throw new Error(`Invalid system https_proxy "${https_proxy}": ${error.message}`);
+        throw new Error(`Invalid system https_proxy "${redactedProxy}": ${error.message}`);
       }
packages/bruno-electron/src/ipc/preferences.js (1)

42-45: Add error handling to prevent unhandled rejection.

The getSystemProxy() call lacks error handling. If detection fails on all platforms, the renderer receives an unhandled promise rejection.

Apply this fix:

   ipcMain.handle('renderer:get-system-proxy-variables', async () => {
-    const systemProxyConfig = await getSystemProxy();
-    return systemProxyConfig;
+    try {
+      const systemProxyConfig = await getSystemProxy();
+      return systemProxyConfig;
+    } catch (error) {
+      console.error('Failed to get system proxy:', error);
+      return {
+        http_proxy: null,
+        https_proxy: null,
+        no_proxy: null,
+        source: 'environment'
+      };
+    }
   });
packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts (1)

154-182: Mock ordering may cause flaky behavior.

The mockReturnValue(false) at line 161 sets a default, but the subsequent mockReturnValueOnce(true) calls at lines 164 and 167 may not align with actual existsSync call order in the implementation.

Consider explicit ordering to match execution flow:

-      // Mock all previous methods to fail
-      mockExistsSync.mockReturnValue(false);
-
-      // Mock systemd conf directory to exist
-      mockExistsSync.mockReturnValueOnce(true);
-
-      // Mock systemd proxy file to exist
-      mockExistsSync.mockReturnValueOnce(true);
+      // Mock /etc/environment to not exist, then systemd dir and file to exist
+      mockExistsSync
+        .mockReturnValueOnce(false)  // /etc/environment
+        .mockReturnValueOnce(true)   // /etc/systemd/system.conf.d
+        .mockReturnValueOnce(true);  // proxy.conf file
packages/bruno-requests/src/network/system-proxy/index.ts (1)

54-56: Misleading method name - detectWithTimeout has no timeout logic.

This method simply delegates to detectByPlatform(). The actual timeout handling occurs in the individual platform resolvers. Consider removing this indirection.

-  private async detectWithTimeout(): Promise<ProxyConfiguration> {
-    return await this.detectByPlatform();
-  }
-
   private async detectSystemProxy(): Promise<ProxyConfiguration> {
     const startTime = Date.now();

     try {
-      const result = await this.detectWithTimeout();
+      const result = await this.detectByPlatform();
🧹 Nitpick comments (12)
packages/bruno-requests/src/network/system-proxy/utils/common.spec.ts (1)

3-25: Good test coverage for normalizeProxyUrl.

Tests cover the main scenarios well. Consider adding a test for the defaultProtocol parameter override (e.g., passing 'https' as second argument).

it('should use custom default protocol when specified', () => {
  expect(normalizeProxyUrl('proxy.usebruno.com:8080', 'https')).toBe('https://proxy.usebruno.com:8080');
});
packages/bruno-requests/src/network/system-proxy/utils/linux.ts (3)

73-77: Consider parallelizing gsettings calls.

These sequential execAsync calls could be parallelized with Promise.all for better performance:

-      const { stdout: httpHost } = await execAsync(AllowedLinuxCommands.GSETTINGS_HTTP_HOST, execOpts);
-      const { stdout: httpPort } = await execAsync(AllowedLinuxCommands.GSETTINGS_HTTP_PORT, execOpts);
-      const { stdout: httpsHost } = await execAsync(AllowedLinuxCommands.GSETTINGS_HTTPS_HOST, execOpts);
-      const { stdout: httpsPort } = await execAsync(AllowedLinuxCommands.GSETTINGS_HTTPS_PORT, execOpts);
-      const { stdout: ignoreHosts } = await execAsync(AllowedLinuxCommands.GSETTINGS_IGNORE_HOSTS, execOpts);
+      const [
+        { stdout: httpHost },
+        { stdout: httpPort },
+        { stdout: httpsHost },
+        { stdout: httpsPort },
+        { stdout: ignoreHosts }
+      ] = await Promise.all([
+        execAsync(AllowedLinuxCommands.GSETTINGS_HTTP_HOST, execOpts),
+        execAsync(AllowedLinuxCommands.GSETTINGS_HTTP_PORT, execOpts),
+        execAsync(AllowedLinuxCommands.GSETTINGS_HTTPS_HOST, execOpts),
+        execAsync(AllowedLinuxCommands.GSETTINGS_HTTPS_PORT, execOpts),
+        execAsync(AllowedLinuxCommands.GSETTINGS_IGNORE_HOSTS, execOpts)
+      ]);

119-121: Same parallelization opportunity for KDE proxy calls.

-      const { stdout: httpProxy } = await execAsync(AllowedLinuxCommands.KDE_HTTP_PROXY, execOpts);
-      const { stdout: httpsProxy } = await execAsync(AllowedLinuxCommands.KDE_HTTPS_PROXY, execOpts);
-      const { stdout: noProxy } = await execAsync(AllowedLinuxCommands.KDE_NO_PROXY, execOpts);
+      const [
+        { stdout: httpProxy },
+        { stdout: httpsProxy },
+        { stdout: noProxy }
+      ] = await Promise.all([
+        execAsync(AllowedLinuxCommands.KDE_HTTP_PROXY, execOpts),
+        execAsync(AllowedLinuxCommands.KDE_HTTPS_PROXY, execOpts),
+        execAsync(AllowedLinuxCommands.KDE_NO_PROXY, execOpts)
+      ]);

79-86: Port values aren't validated as numeric.

cleanHttpPort and cleanHttpsPort are used directly without verifying they're valid port numbers. Non-numeric values would result in malformed proxy URLs.

       const cleanHttpPort = httpPort.trim();
+      const httpPortNum = parseInt(cleanHttpPort, 10);
       const cleanHttpsPort = httpsPort.trim();
+      const httpsPortNum = parseInt(cleanHttpsPort, 10);

-      const http_proxy = cleanHttpHost && cleanHttpPort ? normalizeProxyUrl(`${cleanHttpHost}:${cleanHttpPort}`) : null;
-      const https_proxy = cleanHttpsHost && cleanHttpsPort ? normalizeProxyUrl(`${cleanHttpsHost}:${cleanHttpsPort}`, 'https') : null;
+      const http_proxy = cleanHttpHost && !isNaN(httpPortNum) ? normalizeProxyUrl(`${cleanHttpHost}:${httpPortNum}`) : null;
+      const https_proxy = cleanHttpsHost && !isNaN(httpsPortNum) ? normalizeProxyUrl(`${cleanHttpsHost}:${httpsPortNum}`, 'https') : null;
packages/bruno-requests/src/network/system-proxy/index.spec.js (3)

81-91: Mock setup timing may cause flaky tests.

The WindowsProxyResolver.mockImplementation() is called after new SystemProxyResolver(). If the resolver instantiates the Windows resolver in its constructor, the mock won't be applied in time. Consider setting up the mock implementation before creating testResolver.

     it('should route to Windows detector on win32', async () => {
-      // Create a new detector instance after mocking the platform
       os.platform.mockReturnValue('win32');
-      const testResolver = new SystemProxyResolver();
       const { WindowsProxyResolver } = require('./utils/windows');
       const mockDetect = jest.fn().mockResolvedValue({ source: 'windows-system' });
       WindowsProxyResolver.mockImplementation(() => ({ detect: mockDetect }));
+      // Create resolver after mock is configured
+      const testResolver = new SystemProxyResolver();
 
       await testResolver.getSystemProxy();
       expect(mockDetect).toHaveBeenCalled();
     });

93-103: Same mock timing issue as Windows test.

Apply the same fix: set up MacOSProxyResolver.mockImplementation() before creating testResolver.


105-115: Same mock timing issue as Windows/macOS tests.

Apply the same fix: set up LinuxProxyResolver.mockImplementation() before creating testResolver.

packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js (1)

13-18: Consider moving SOURCE_LABELS outside the component.

The constant is recreated on every render. Moving it outside the component avoids unnecessary object allocation.

+const SOURCE_LABELS = {
+  'environment': 'Environment Variables',
+  'windows-system': 'Windows System Settings',
+  'macos-system': 'macOS System Settings',
+  'linux-system': 'Linux System Settings'
+};
+
 const SystemProxy = () => {
   const dispatch = useDispatch();
   const systemProxyVariables = useSelector((state) => state.app.systemProxyVariables);
   const { source, http_proxy, https_proxy, no_proxy } = systemProxyVariables || {};
   const [isFetching, setIsFetching] = useState(true);
   const [error, setError] = useState(null);
-
-  const SOURCE_LABELS = {
-    'environment': 'Environment Variables',
-    'windows-system': 'Windows System Settings',
-    'macos-system': 'macOS System Settings',
-    'linux-system': 'Linux System Settings'
-  };
packages/bruno-app/src/providers/ReduxStore/slices/app.js (1)

218-228: Consider simplifying the Promise wrapper.

The explicit new Promise wrapper is unnecessary since ipcRenderer.invoke already returns a Promise. The pattern is consistent with other thunks in this file, but could be cleaner.

 export const getSystemProxyVariables = () => (dispatch, getState) => {
-  return new Promise((resolve, reject) => {
-    const { ipcRenderer } = window;
-    ipcRenderer.invoke('renderer:get-system-proxy-variables')
-      .then((variables) => {
-        dispatch(updateSystemProxyVariables(variables));
-        return variables;
-      })
-      .then(resolve).catch(reject);
-  });
+  const { ipcRenderer } = window;
+  return ipcRenderer.invoke('renderer:get-system-proxy-variables')
+    .then((variables) => {
+      dispatch(updateSystemProxyVariables(variables));
+      return variables;
+    });
 };
packages/bruno-requests/src/network/system-proxy/index.ts (2)

18-33: Potential race condition on concurrent completion.

If two callers invoke getSystemProxy() nearly simultaneously and the first completes, activeDetection is set to null in the finally block. A third caller arriving at that moment starts a fresh detection rather than sharing the in-flight result from the second call.

This is likely acceptable for typical usage, but worth documenting the behavior.


71-84: getEnvironmentVariables is public but appears to be an internal utility.

If this method is intended for external use, consider adding JSDoc. Otherwise, mark it private to clarify the API surface.

-  getEnvironmentVariables(): ProxyConfiguration {
+  private getEnvironmentVariables(): ProxyConfiguration {

Note: If you keep it public for the top-level getSystemProxy function, extract it as a standalone utility or document it.

packages/bruno-requests/src/network/system-proxy/utils/windows.ts (1)

118-160: Consider extracting duplicate registry parsing logic.

getSystemProxyEnvironment and getUserEnvironmentProxy share nearly identical parsing logic. A helper method would reduce duplication.

+  private parseRegistryProxyOutput(stdout: string): ProxyConfiguration | null {
+    const lines = stdout.split('\n');
+    let http_proxy: string | null = null;
+    let https_proxy: string | null = null;
+    let no_proxy: string | null = null;
+
+    for (const line of lines) {
+      const trimmedLine = line.trim();
+
+      if (trimmedLine.toUpperCase().includes('HTTP_PROXY') && trimmedLine.includes('REG_SZ')) {
+        const match = trimmedLine.match(/HTTP_PROXY\s+REG_SZ\s+(.+)/i);
+        if (match) http_proxy = match[1].trim();
+      }
+
+      if (trimmedLine.toUpperCase().includes('HTTPS_PROXY') && trimmedLine.includes('REG_SZ')) {
+        const match = trimmedLine.match(/HTTPS_PROXY\s+REG_SZ\s+(.+)/i);
+        if (match) https_proxy = match[1].trim();
+      }
+
+      if (trimmedLine.toUpperCase().includes('NO_PROXY') && trimmedLine.includes('REG_SZ')) {
+        const match = trimmedLine.match(/NO_PROXY\s+REG_SZ\s+(.+)/i);
+        if (match) no_proxy = match[1].trim();
+      }
+    }
+
+    if (http_proxy || https_proxy) {
+      return {
+        http_proxy: http_proxy ? normalizeProxyUrl(http_proxy) : null,
+        https_proxy: https_proxy ? normalizeProxyUrl(https_proxy, 'https') : null,
+        no_proxy: no_proxy ? normalizeNoProxy(no_proxy) : null,
+        source: 'windows-system'
+      };
+    }
+
+    return null;
+  }

Also applies to: 162-204

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ae421ab and 80103c9.

📒 Files selected for processing (23)
  • packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js (1 hunks)
  • packages/bruno-app/src/components/Preferences/ProxySettings/index.js (2 hunks)
  • packages/bruno-app/src/providers/App/useIpcEvents.js (1 hunks)
  • packages/bruno-app/src/providers/ReduxStore/slices/app.js (4 hunks)
  • packages/bruno-cli/src/runner/run-single-request.js (3 hunks)
  • packages/bruno-cli/src/utils/proxy-util.js (1 hunks)
  • packages/bruno-electron/src/ipc/network/cert-utils.js (2 hunks)
  • packages/bruno-electron/src/ipc/preferences.js (2 hunks)
  • packages/bruno-electron/src/store/preferences.js (2 hunks)
  • packages/bruno-electron/src/utils/proxy-util.js (5 hunks)
  • packages/bruno-requests/src/index.ts (1 hunks)
  • packages/bruno-requests/src/network/index.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/index.spec.js (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/index.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/types.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/common.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/common.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/linux.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/macos.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/macos.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/windows.spec.ts (1 hunks)
  • packages/bruno-requests/src/network/system-proxy/utils/windows.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/bruno-cli/src/utils/proxy-util.js
  • packages/bruno-cli/src/runner/run-single-request.js
  • packages/bruno-electron/src/store/preferences.js
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings. For JSX/TSX attributes, use double quotes (e.g., )
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single params
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses
Space before and after the arrow in arrow functions. () => {} is good
No space between function name and parentheses. func() not func ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • packages/bruno-requests/src/network/system-proxy/utils/windows.spec.ts
  • packages/bruno-electron/src/ipc/network/cert-utils.js
  • packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js
  • packages/bruno-app/src/providers/ReduxStore/slices/app.js
  • packages/bruno-requests/src/network/system-proxy/utils/linux.ts
  • packages/bruno-requests/src/network/system-proxy/utils/common.ts
  • packages/bruno-requests/src/network/system-proxy/index.ts
  • packages/bruno-requests/src/network/system-proxy/types.ts
  • packages/bruno-requests/src/index.ts
  • packages/bruno-electron/src/ipc/preferences.js
  • packages/bruno-requests/src/network/system-proxy/utils/macos.ts
  • packages/bruno-requests/src/network/system-proxy/utils/windows.ts
  • packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts
  • packages/bruno-requests/src/network/index.ts
  • packages/bruno-requests/src/network/system-proxy/utils/macos.spec.ts
  • packages/bruno-electron/src/utils/proxy-util.js
  • packages/bruno-app/src/providers/App/useIpcEvents.js
  • packages/bruno-app/src/components/Preferences/ProxySettings/index.js
  • packages/bruno-requests/src/network/system-proxy/index.spec.js
  • packages/bruno-requests/src/network/system-proxy/utils/common.spec.ts
🧠 Learnings (3)
📚 Learning: 2025-12-05T20:31:33.005Z
Learnt from: CR
Repo: usebruno/bruno PR: 0
File: CODING_STANDARDS.md:0-0
Timestamp: 2025-12-05T20:31:33.005Z
Learning: Applies to **/*.test.{js,jsx,ts,tsx} : Add tests for any new functionality or meaningful changes. If code is added, removed, or significantly modified, corresponding tests should be updated or created

Applied to files:

  • packages/bruno-requests/src/network/system-proxy/utils/windows.spec.ts
  • packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts
📚 Learning: 2025-12-05T20:31:33.005Z
Learnt from: CR
Repo: usebruno/bruno PR: 0
File: CODING_STANDARDS.md:0-0
Timestamp: 2025-12-05T20:31:33.005Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Applied to files:

  • packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts
📚 Learning: 2025-12-02T07:24:50.311Z
Learnt from: bijin-bruno
Repo: usebruno/bruno PR: 6263
File: packages/bruno-requests/src/auth/oauth2-helper.ts:249-249
Timestamp: 2025-12-02T07:24:50.311Z
Learning: In OAuth2 Basic Auth headers for Bruno, clientSecret is optional and can be omitted. When constructing the Authorization header in `packages/bruno-requests/src/auth/oauth2-helper.ts`, use `clientSecret || ''` instead of `clientSecret!` to properly handle cases where only clientId is provided, per community requests.

Applied to files:

  • packages/bruno-electron/src/utils/proxy-util.js
🧬 Code graph analysis (13)
packages/bruno-requests/src/network/system-proxy/utils/windows.spec.ts (1)
packages/bruno-requests/src/network/system-proxy/utils/windows.ts (1)
  • WindowsProxyResolver (16-236)
packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js (1)
packages/bruno-app/src/providers/ReduxStore/slices/app.js (2)
  • getSystemProxyVariables (218-228)
  • getSystemProxyVariables (218-228)
packages/bruno-requests/src/network/system-proxy/utils/linux.ts (2)
packages/bruno-requests/src/network/system-proxy/types.ts (2)
  • ProxyResolver (8-10)
  • ProxyConfiguration (1-6)
packages/bruno-requests/src/network/system-proxy/utils/common.ts (2)
  • normalizeProxyUrl (13-23)
  • normalizeNoProxy (30-40)
packages/bruno-requests/src/network/system-proxy/index.ts (5)
packages/bruno-requests/src/network/system-proxy/types.ts (2)
  • ProxyConfiguration (1-6)
  • SystemProxyResolverOptions (12-15)
packages/bruno-requests/src/network/system-proxy/utils/windows.ts (1)
  • WindowsProxyResolver (16-236)
packages/bruno-requests/src/network/system-proxy/utils/macos.ts (1)
  • MacOSProxyResolver (8-118)
packages/bruno-requests/src/network/system-proxy/utils/linux.ts (1)
  • LinuxProxyResolver (31-245)
packages/bruno-requests/src/network/system-proxy/utils/common.ts (2)
  • normalizeProxyUrl (13-23)
  • normalizeNoProxy (30-40)
packages/bruno-requests/src/network/system-proxy/types.ts (1)
packages/bruno-requests/src/network/system-proxy/index.ts (1)
  • ProxyConfiguration (105-105)
packages/bruno-electron/src/ipc/preferences.js (4)
packages/bruno-electron/src/index.js (1)
  • registerPreferencesIpc (39-39)
packages/bruno-electron/src/ipc/network/cert-utils.js (1)
  • systemProxyConfig (124-124)
packages/bruno-requests/src/index.ts (1)
  • getSystemProxy (10-10)
packages/bruno-requests/src/network/system-proxy/index.ts (2)
  • getSystemProxy (18-33)
  • getSystemProxy (89-103)
packages/bruno-requests/src/network/system-proxy/utils/macos.ts (2)
packages/bruno-requests/src/network/system-proxy/types.ts (2)
  • ProxyResolver (8-10)
  • ProxyConfiguration (1-6)
packages/bruno-requests/src/network/system-proxy/utils/common.ts (2)
  • normalizeProxyUrl (13-23)
  • normalizeNoProxy (30-40)
packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts (1)
packages/bruno-requests/src/network/system-proxy/utils/linux.ts (1)
  • LinuxProxyResolver (31-245)
packages/bruno-requests/src/network/system-proxy/utils/macos.spec.ts (1)
packages/bruno-requests/src/network/system-proxy/utils/macos.ts (1)
  • MacOSProxyResolver (8-118)
packages/bruno-electron/src/utils/proxy-util.js (1)
packages/bruno-cli/src/utils/proxy-util.js (2)
  • shouldUseProxy (16-63)
  • parseUrl (1-1)
packages/bruno-app/src/components/Preferences/ProxySettings/index.js (1)
packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js (1)
  • SystemProxy (6-87)
packages/bruno-requests/src/network/system-proxy/index.spec.js (4)
packages/bruno-requests/src/network/system-proxy/index.ts (3)
  • SystemProxyResolver (8-85)
  • getSystemProxy (18-33)
  • getSystemProxy (89-103)
packages/bruno-requests/src/network/system-proxy/utils/windows.ts (1)
  • WindowsProxyResolver (16-236)
packages/bruno-requests/src/network/system-proxy/utils/macos.ts (1)
  • MacOSProxyResolver (8-118)
packages/bruno-requests/src/network/system-proxy/utils/linux.ts (1)
  • LinuxProxyResolver (31-245)
packages/bruno-requests/src/network/system-proxy/utils/common.spec.ts (1)
packages/bruno-requests/src/network/system-proxy/utils/common.ts (2)
  • normalizeProxyUrl (13-23)
  • normalizeNoProxy (30-40)
🪛 ast-grep (0.40.0)
packages/bruno-requests/src/network/system-proxy/utils/linux.ts

[warning] 26-26: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(^export\\s+${varName}\\s*=\\s*(.+)$, 'i')
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html

(regexp-from-variable)


[warning] 27-27: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(^${varName}\\s*=\\s*(.+)$, 'i')
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html

(regexp-from-variable)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Unit Tests
  • GitHub Check: SSL Tests - Linux
  • GitHub Check: SSL Tests - Windows
  • GitHub Check: SSL Tests - macOS
  • GitHub Check: CLI Tests
  • GitHub Check: Playwright E2E Tests
🔇 Additional comments (49)
packages/bruno-app/src/providers/App/useIpcEvents.js (1)

5-5: Migration to on-demand system proxy retrieval is complete.

The old main:load-system-proxy-env IPC channel and updateSystemProxyEnvVariables Redux action have been fully removed. The new renderer:get-system-proxy-variables IPC handler is properly registered in the Electron main process and invoked through the getSystemProxyVariables Redux thunk in the renderer. The SystemProxy component correctly uses the new mechanism.

packages/bruno-requests/src/network/system-proxy/utils/common.spec.ts (1)

27-64: Comprehensive tests for normalizeNoProxy.

Good coverage of edge cases including mixed delimiters, whitespace handling, and null inputs.

packages/bruno-electron/src/utils/proxy-util.js (2)

337-339: Good addition of keepAlive option.

Enabling keepAlive for HTTP proxy agents improves connection reuse.


378-382: System proxy logic correctly determines request protocol.

Good use of parseUrl to determine if the request is HTTPS, ensuring the appropriate proxy is applied.

packages/bruno-requests/src/network/system-proxy/utils/common.ts (2)

13-23: Clean implementation of normalizeProxyUrl.

The regex for protocol detection is correct and handles various protocol schemes. Good JSDoc documentation.


30-40: normalizeNoProxy handles edge cases well.

The split regex /[;,\s]+/ correctly handles mixed delimiters. Note that consecutive delimiters are naturally handled by the filter.

packages/bruno-requests/src/network/system-proxy/utils/linux.ts (3)

24-29: Static analysis false positive - ReDoS risk is mitigated.

The regex is constructed from a hardcoded array of known proxy variable names, not user input. The pattern is safe.


10-22: Good use of enum to prevent command injection.

Whitelisting commands via enum is a solid security practice.


31-64: Well-structured detection flow with graceful fallback.

The ordered detection methods with try-catch fallback is a robust approach. Good error message propagation.

packages/bruno-requests/src/network/index.ts (1)

1-3: Clean public API export.

The getSystemProxy re-export follows the existing barrel pattern and provides a clean public API surface.

packages/bruno-requests/src/index.ts (1)

9-10: LGTM!

Clean addition that follows the existing export patterns in this file. The new getSystemProxy export provides a clean public API surface for system proxy resolution.

packages/bruno-app/src/components/Preferences/ProxySettings/index.js (2)

11-11: LGTM!

Clean import following the existing import structure.


161-165: LGTM!

Good refactor. Delegating system proxy display to a dedicated SystemProxy component improves separation of concerns. The component handles its own loading states and error handling per the external context.

packages/bruno-electron/src/ipc/network/cert-utils.js (2)

4-4: LGTM!

Import follows the established pattern and correctly pulls from the @usebruno/requests package.


123-126: The config shape handling is already correct. When proxyMode === 'system', the code destructures http_proxy, https_proxy, and no_proxy from proxyConfig (line 379). When proxyMode === 'on', it accesses protocol, hostname, port, and auth.* properties. Each proxy mode branch uses only the properties present in its respective configuration shape, so no compatibility issues exist.

Likely an incorrect or invalid review comment.

packages/bruno-requests/src/network/system-proxy/index.spec.js (5)

1-8: LGTM!

Proper mocking setup for dependencies. Mocking node:os and platform-specific resolvers allows isolated testing of the resolver's routing logic.


29-35: LGTM!

Timer cleanup order is correct - pending timers are flushed before clearing. Good attention to preventing Jest open handle warnings.


37-77: LGTM!

Good coverage of environment variable precedence (lowercase over uppercase) and fallback behavior. Tests are clear and well-structured.


118-154: LGTM!

Good coverage of error handling scenarios including detection failures and timeouts with proper fallback to environment variables.


156-169: LGTM!

Good test for the exported getSystemProxy function ensuring it correctly returns environment-based proxy configuration.

packages/bruno-requests/src/network/system-proxy/utils/macos.spec.ts (6)

3-11: LGTM!

Clean mock setup. The promisify mock correctly returns the function as-is, which works since mockExec returns a Promise directly.


24-50: LGTM!

Comprehensive test case covering HTTP/HTTPS proxy detection with exceptions list and ExcludeSimpleHostnames. Good coverage of the happy path.


52-70: LGTM!

Good edge case: verifies disabled proxies (HTTPEnable/HTTPSEnable = 0) return null values.


72-86: LGTM!

Good test for default port behavior (80 for HTTP, 443 for HTTPS) when ports aren't specified.


207-227: LGTM!

This now correctly tests malformed input - line 214 is missing the colon separator (HTTPSProxy proxy.usebruno.com instead of HTTPSProxy : proxy.usebruno.com). The test verifies graceful handling by returning https_proxy: null.


230-242: LGTM!

Good error handling coverage for command failures and invalid output formats.

packages/bruno-requests/src/network/system-proxy/utils/windows.spec.ts (5)

1-22: LGTM! Clean test setup and mocking.

The mock configuration properly isolates child_process and util modules. The beforeEach hook correctly reinstantiates the resolver and clears mocks between tests for deterministic behavior.


24-84: Solid test coverage for registry detection.

The tests properly verify single proxy, protocol-specific parsing, and fallback behavior. The mock chaining pattern (mockRejectedValueOnce → mockResolvedValueOnce) correctly simulates the fallback scenario.


86-157: Comprehensive WinHTTP detection tests.

Good coverage of direct access handling, single/protocol-specific proxies, and the (none) bypass list case. The test at line 87-93 correctly verifies that direct access causes detection to fail and fall through.


159-377: Excellent edge case and fallback coverage.

The tests properly verify the fallback chain order (Internet Options → WinHTTP → System Env → User Env). Edge cases like decimal ProxyEnable values, existing URL prefixes, and complex bypass lists are well covered.


379-399: Error handling tests are adequate.

The tests verify that detection failures propagate correctly with the expected error message. Good coverage of access denied and malformed output scenarios.

packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js (2)

6-25: LGTM! Clean hook usage and error handling.

The component properly manages loading and error states. The useEffect correctly chains .then(), .catch(), and .finally() to handle all outcomes. The dispatch dependency is correctly specified.


27-86: Clean render logic with good UX.

The conditional rendering for loading state, error display, and source labels is well implemented. The fallback to - for missing proxy values provides clear feedback to users.

packages/bruno-requests/src/network/system-proxy/types.ts (2)

1-6: Well-defined type contract for proxy configuration.

The ProxyConfiguration interface properly captures the proxy data structure with a discriminated source field. The literal union type ensures type safety across platform-specific implementations.


8-15: Clean interface definitions.

ProxyResolver provides a clear contract for platform-specific detectors. SystemProxyResolverOptions offers sensible configuration points for timeout tuning.

packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts (3)

1-38: Clean test setup with comprehensive mocking.

The module mocks properly isolate all external dependencies. The beforeEach hook correctly wires up the mocks and clears state between tests.


40-126: Solid gsettings proxy detection tests.

Good coverage of manual proxy configuration, identical HTTP/HTTPS proxies, non-manual mode handling, and empty ignore hosts. The mock sequence correctly simulates the gsettings command chain.


185-222: Adequate error handling test coverage.

Tests correctly verify that detection failures propagate with the expected 'Linux proxy detection failed' message across various failure scenarios.

packages/bruno-requests/src/network/system-proxy/utils/macos.ts (5)

1-7: Clean imports and setup.

Proper use of Node.js modules with promisify for async command execution. Imports from shared types and common utilities maintain consistency across platform resolvers.


8-22: Well-structured detect() method.

The method properly configures execution options with sensible defaults (10s timeout, 1MB buffer). Error wrapping provides clear context for debugging.


24-39: Robust output parsing entry point.

Input validation and dictionary detection are handled correctly. The flow delegates cleanly to parsing and configuration building.


41-82: Solid scutil output parsing.

The parser correctly handles key-value pairs, nested arrays, and integer conversion. The loop structure with explicit index management is clear.


84-117: Clean proxy configuration building.

The builder correctly checks enable flags before constructing URLs, uses sensible port defaults, and properly handles the ExcludeSimpleHostnames setting by appending <local>.

packages/bruno-app/src/providers/ReduxStore/slices/app.js (2)

48-49: LGTM!

State property addition is clean and correctly initialized as an empty object.


107-109: LGTM!

Reducer correctly updates state with the payload.

packages/bruno-requests/src/network/system-proxy/index.ts (1)

87-103: LGTM!

The top-level getSystemProxy function correctly prioritizes environment variables before falling back to system detection, with appropriate error handling.

packages/bruno-requests/src/network/system-proxy/utils/windows.ts (3)

8-14: Good security practice using an enum for allowed commands.

This prevents command injection by ensuring only predefined commands are executed.


206-235: LGTM!

The parseProxyString method correctly handles both single-proxy and protocol-specific formats, with proper normalization applied.


25-50: LGTM!

The detection orchestration with graceful fallback through multiple methods is well-structured. Silent failures in individual detectors allow the chain to continue appropriately.

Comment on lines +86 to +107
function createTimelineHttpAgentClass(BaseAgentClass) {
return class extends BaseAgentClass {
constructor(options, timeline) {
// For proxy agents, the first argument is the proxy URI and the second is options
const { proxy: proxyUri, httpProxyAgentOptions } = options || {};

if (!proxyUri) {
throw new Error('TimelineHttpProxyAgent requires options.proxy to be set');
}

super(proxyUri, httpProxyAgentOptions);

this.timeline = Array.isArray(timeline) ? timeline : [];
// Log the proxy details
this.timeline.push({
timestamp: new Date(),
type: 'info',
message: `Using proxy: ${proxyUri}`
});
}
};
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

createTimelineHttpAgentClass now correctly calls super().

The constructor properly validates proxyUri and calls super() unconditionally. This addresses the previous review concern.

However, Line 103 logs the raw proxyUri which may contain credentials (e.g., http://user:[email protected]). Redact userinfo before logging.

+      const redactedUri = proxyUri.replace(/\/\/([^:]+):([^@]+)@/, '//$1:***@');
       this.timeline.push({
         timestamp: new Date(),
         type: 'info',
-        message: `Using proxy: ${proxyUri}`
+        message: `Using proxy: ${redactedUri}`
       });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function createTimelineHttpAgentClass(BaseAgentClass) {
return class extends BaseAgentClass {
constructor(options, timeline) {
// For proxy agents, the first argument is the proxy URI and the second is options
const { proxy: proxyUri, httpProxyAgentOptions } = options || {};
if (!proxyUri) {
throw new Error('TimelineHttpProxyAgent requires options.proxy to be set');
}
super(proxyUri, httpProxyAgentOptions);
this.timeline = Array.isArray(timeline) ? timeline : [];
// Log the proxy details
this.timeline.push({
timestamp: new Date(),
type: 'info',
message: `Using proxy: ${proxyUri}`
});
}
};
}
function createTimelineHttpAgentClass(BaseAgentClass) {
return class extends BaseAgentClass {
constructor(options, timeline) {
// For proxy agents, the first argument is the proxy URI and the second is options
const { proxy: proxyUri, httpProxyAgentOptions } = options || {};
if (!proxyUri) {
throw new Error('TimelineHttpProxyAgent requires options.proxy to be set');
}
super(proxyUri, httpProxyAgentOptions);
this.timeline = Array.isArray(timeline) ? timeline : [];
// Log the proxy details
const redactedUri = proxyUri.replace(/\/\/([^:]+):([^@]+)@/, '//$1:***@');
this.timeline.push({
timestamp: new Date(),
type: 'info',
message: `Using proxy: ${redactedUri}`
});
}
};
}

const { getSystemProxy } = require('@usebruno/requests');

const registerPreferencesIpc = (mainWindow, watcher) => {
const registerPreferencesIpc = (mainWindow, watcher, lastOpenedCollections) => {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lohit-bruno Is there any reason why we added lastOpenedCollections can remove if not used


constructor(options: SystemProxyResolverOptions = {}) {
this.platform = platform();
this.commandTimeout = options.commandTimeout || 10000; // 10 seconds default

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just a nitpick, we can move 10000ms to a variable like TEN_SECONDS and use the variable instead.

}
}

private async detectWithTimeout(): Promise<ProxyConfiguration> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lohit-bruno we many need to expand this function enable timeout based detection if needed. if not needed we can remove the wrapper function and use detectByPlatform directly

cause i can see timeout is actually handled within detectByPlatform()

new WindowsProxyResolver().detect({ timeoutMs: this.commandTimeout });

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

private async detectWithTimeout(): Promise<ProxyConfiguration> {
  const timeoutMs = this.commandTimeout;

  const timeoutPromise = new Promise<ProxyConfiguration>((_, reject) => {
    const id = setTimeout(() => {
      clearTimeout(id);
      reject(new Error(`System proxy detection timed out after ${timeoutMs}ms`));
    }, timeoutMs);
  });

  return await Promise.race([this.detectByPlatform(), timeoutPromise]);
}

import { normalizeNoProxy, normalizeProxyUrl } from './utils/common';

export class SystemProxyResolver {
private platform: string;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

may be we can consider renaming it to osPlatform considering that we have a import with the same name to avoid any confusion @lohit-bruno


const hasEnvironmentProxy = proxyEnvironmentVariables.http_proxy || proxyEnvironmentVariables.https_proxy;

if (hasEnvironmentProxy) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lohit-bruno what is the expected behaviour when we have both system proxy and env variables setup, it seems like Envs gets priority. what is i have a mix of things, like i have setup HTTPS_PROXY within env, HTTP_PROXY is in system proxy. it seems like it ignore everything else if we have an ENV var, and only HTTPS_PROXY will be there it the preferences ->. proxy. is this expected behaviour?

detect(opts?: { timeoutMs?: number }): Promise<ProxyConfiguration>;
}

export interface SystemProxyResolverOptions {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

 cacheTimeoutMs?: number;
 commandTimeoutMs?: number

});

it('should handle various protocols', () => {
expect(normalizeProxyUrl('socks5://proxy.usebruno.com:1080')).toBe('socks5://proxy.usebruno.com:1080');

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lohit-bruno do we support sock5 proxy? do we get it from systemProxy?

const timeoutMs = opts?.timeoutMs ?? 10000;
const execOpts: ExecOptions = {
timeout: timeoutMs,
maxBuffer: 1024 * 1024

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lohit-bruno can extract constants to a variable

jest.clearAllMocks();
});

describe('gsettings proxy detection', () => {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lohit-bruno don't we need to add KDE proxy related test cases, or is there any technical difficulties in implementing it?


export class MacOSProxyResolver implements ProxyResolver {
async detect(opts?: { timeoutMs?: number }): Promise<ProxyConfiguration> {
const timeoutMs = opts?.timeoutMs ?? 10000;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can extract constants

import { ProxyConfiguration, ProxyResolver } from '../types';
import { normalizeProxyUrl, normalizeNoProxy } from './common';

const execAsync = promisify(exec);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we use execFile('gsettings', ['get', 'org.gnome.system.proxy', 'mode']);

  • No shell
  • Arguments are passed safel
  • stderr is available directly

instead of exec('gsettings get org.gnome.system.proxy mode 2>/dev/null');

  • Runs through a shell
  • Allows redirection (2>/dev/null)
  • Harder to reason about
  • Shell-dependent behavior
import { execFile, ExecFileOptions } from 'node:child_process';
import { promisify } from 'node:util';

const execFileAsync = promisify(execFile);

async function run(
  file: string,
  args: string[],
  opts: ExecFileOptions
): Promise<string> {
  const { stdout } = await execFileAsync(file, args, opts);
  return stdout.trim();
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

or more safer version

const execFileAsync = promisify(execFile);

async function safeExec(
  bin: string,
  args: string[],
  opts: ExecFileOptions
): Promise<string | null> {
  try {
    const { stdout } = await execFileAsync(bin, args, opts);
    return stdout.trim();
  } catch {
    return null;
  }
}

return null;
}

const { stdout: httpHost } = await execAsync(AllowedLinuxCommands.GSETTINGS_HTTP_HOST, execOpts);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Before (current)

const { stdout: mode } =
  await execAsync(AllowedLinuxCommands.GSETTINGS_MODE, execOpts);

After (safe, shell-free)

const mode = await run(
  'gsettings',
  ['get', 'org.gnome.system.proxy', 'mode'],
  execOpts
);

// Normalize quotes
const normalizedMode = mode.replace(/^['"]|['"]$/g, '');
if (normalizedMode !== 'manual') {
  return null;
}


// Enum of allowed commands to prevent injection
enum AllowedLinuxCommands {
GSETTINGS_MODE = 'gsettings get org.gnome.system.proxy mode 2>/dev/null',

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Handling stderr (replacing 2>/dev/null)

With execFile, stderr does not throw by itself.
Only a non-zero exit code throws.

If you want to ignore stderr:

try {
  const stdout = await run('gsettings', [...], execOpts);
} catch (err) {
  // command missing or failed → just return null
  return null;
}

If you want to inspect stderr:

try {
  const { stdout, stderr } = await execFileAsync('gsettings', args, execOpts);
} catch (err: any) {
  if (err.code === 'ENOENT') {
    // binary not installed
  }
}

GSETTINGS_HTTPS_HOST = 'gsettings get org.gnome.system.proxy.https host 2>/dev/null',
GSETTINGS_HTTPS_PORT = 'gsettings get org.gnome.system.proxy.https port 2>/dev/null',
GSETTINGS_IGNORE_HOSTS = 'gsettings get org.gnome.system.proxy ignore-hosts 2>/dev/null',
KDE_PROXY_TYPE = 'kreadconfig5 --group "Proxy Settings" --key "ProxyType" 2>/dev/null',

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to support KDE 6?

async function runKReadConfig(
  args: string[],
  opts: ExecFileOptions
): Promise<string> {
  try {
    return await run('kreadconfig6', args, opts);
  } catch {
    return await run('kreadconfig5', args, opts);
  }
}

};

try {
const { stdout } = await execAsync('scutil --proxy', execOpts);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we use

import { execFile, ExecFileOptions } from 'node:child_process';
const execFileAsync = promisify(execFile);

const { stdout } = await execFileAsync('scutil', ['--proxy'], execOpts);


// Enum of allowed commands to prevent injection
enum AllowedWindowsCommands {
INTERNET_SETTINGS = 'reg query "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"',

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reg.exe with args: execFile('reg', ['query', 'HKCU\\...\\Internet Settings'])

netsh with args: execFile('netsh', ['winhttp', 'show', 'proxy'])

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This also avoids double-escaping issue, i guess

const match = trimmedLine.match(/ProxyEnable\s+REG_DWORD\s+(0x[0-9a-fA-F]+|\d+)/);
if (match) {
const value = match[1];
proxyEnabled = (value === '0x1' || value === '1');

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We check:

proxyEnabled = (value === '0x1' || value === '1');

But registry output is typically 0x1 or 0x0, not 1. Your check covers 0x1, good — but if output ever comes as decimal 1 you’re okay; if it’s 0x00000001 you’re not.

Fix
Parse as integer base-0:

const n = Number(value.startsWith('0x') ? parseInt(value, 16) : parseInt(value, 10));
proxyEnabled = n === 1;

}

return null;
} catch (error) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we atleast log these errors? to debug any issue if it arises @lohit-bruno

}
}

private parseProxyString(proxyServer: string, bypassList: string | null): ProxyConfiguration {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we could add expected input, output fro these parser functions as comments, it will help in future maintenance @lohit-bruno , this applies across the parser functions


if (proxyServer.includes('=')) {
// Protocol-specific format: "http=proxy1:8080;https=proxy2:8080"
const protocols = proxyServer.split(';');

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Internet Settings ProxyServer format handling is incomplete

IE/WinINET ProxyServer can be:

  • proxy:8080
  • http=proxy:8080;https=proxy2:8443
  • socks=socksproxy:1080 (we currently ignore)

include whitespace and trailing semicolons

Our parseProxyString:

  • doesn’t trim proto and server
  • ignores socks (maybe intended, but then you should explicitly choose behavior)

Fix

const [protoRaw, serverRaw] = protocol.split('=');
const proto = protoRaw?.trim().toLowerCase();
const server = serverRaw?.trim();

@lohit-bruno
lohit-bruno force-pushed the system_proxy_updates branch 2 times, most recently from 6076d97 to 51878c0 Compare January 19, 2026 11:51

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@packages/bruno-requests/src/network/system-proxy/utils/linux.ts`:
- Around line 178-190: The kvPairs extraction inside the systemd Environment
parsing (see systemdEnvMatch -> kvPairs) only allows uppercase letters and
underscores for the key, so lowercase keys like "http_proxy" are skipped; update
the kvPairs key character class to also accept lowercase letters and digits (and
keep underscores) so keys such as http_proxy match, leaving the rest of the
parsing and the subsequent proxyVars/proxies logic unchanged.
♻️ Duplicate comments (6)
packages/bruno-electron/src/utils/proxy-util.js (2)

100-104: Redact credentials from proxy URI in timeline log.

The proxyUri may contain embedded credentials (e.g., http://user:[email protected]). This value is logged directly to the timeline, which could expose secrets in logs or UI.

Suggested fix
+      const redactedUri = proxyUri.replace(/\/\/([^:]+):([^@]+)@/, '//$1:***@');
       this.timeline.push({
         timestamp: new Date(),
         type: 'info',
-        message: `Using proxy: ${proxyUri}`
+        message: `Using proxy: ${redactedUri}`
       });

391-392: Redact credentials from proxy URIs in error messages.

Error messages containing http_proxy or https_proxy may leak credentials if the URI includes userinfo (http://user:pass@host). These errors could surface in logs or user-facing dialogs.

Suggested fix
+      const redactUri = (uri) => uri ? uri.replace(/\/\/([^:]+):([^@]+)@/, '//$1:***@') : uri;
       } catch (error) {
-        throw new Error(`Invalid system http_proxy "${http_proxy}": ${error.message}`);
+        throw new Error(`Invalid system http_proxy "${redactUri(http_proxy)}": ${error.message}`);
       }

Apply similarly at line 407 for https_proxy.

Also applies to: 407

packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts (1)

160-167: Mock ordering is still fragile. The mockReturnValue(false) followed by mockReturnValueOnce(true) can bind to the wrong existsSync calls and cause flakiness.

🔁 Stable mock ordering
-      // Mock all previous methods to fail
-      mockExistsSync.mockReturnValue(false);
-
-      // Mock systemd conf directory to exist
-      mockExistsSync.mockReturnValueOnce(true);
-
-      // Mock systemd proxy file to exist
-      mockExistsSync.mockReturnValueOnce(true);
+      // Mock /etc/environment to not exist, then systemd dir and file to exist
+      mockExistsSync
+        .mockReturnValueOnce(false)
+        .mockReturnValueOnce(true)
+        .mockReturnValueOnce(true);
packages/bruno-electron/src/ipc/preferences.js (1)

42-45: Guard IPC handler against getSystemProxy failures.
If detection fails, the IPC promise rejects and can surface as an unhandled rejection in the renderer. Wrap with try/catch and return a safe fallback.

🛠️ Proposed fix
  ipcMain.handle('renderer:get-system-proxy-variables', async () => {
-    const systemProxyConfig = await getSystemProxy();
-    return systemProxyConfig;
+    try {
+      const systemProxyConfig = await getSystemProxy();
+      return systemProxyConfig;
+    } catch (error) {
+      console.error('Failed to get system proxy:', error);
+      return {
+        http_proxy: null,
+        https_proxy: null,
+        no_proxy: null,
+        source: 'environment'
+      };
+    }
  });
packages/bruno-requests/src/network/system-proxy/utils/windows.ts (2)

53-59: Parse ProxyEnable as an integer (0x00000001 currently misread).

Line 55–58 only treats 0x1 or 1 as enabled; registry output can be 0x00000001, which will be misread as disabled.

🔧 Proposed fix
-        if (match) {
-          const value = match[1];
-          proxyEnabled = value === '0x1' || value === '1';
-        }
+        if (match) {
+          const value = match[1];
+          const parsed = value.startsWith('0x') ? parseInt(value, 16) : parseInt(value, 10);
+          if (!Number.isNaN(parsed)) {
+            proxyEnabled = parsed === 1;
+          }
+        }

187-198: Trim/lowercase protocol tokens before comparison.

Line 191–196 compares raw tokens; common formats like http = proxy:8080 or HTTPS=... will be skipped.

🔧 Proposed fix
-      for (const protocol of protocols) {
-        const [proto, server] = protocol.split('=');
-        if (!server || !proto) continue;
-        if (proto === 'http') {
-          http_proxy = normalizeProxyUrl(server);
-        } else if (proto === 'https') {
-          https_proxy = normalizeProxyUrl(server, 'https');
-        }
-      }
+      for (const protocol of protocols) {
+        const [protoRaw, serverRaw] = protocol.split('=');
+        const proto = protoRaw?.trim().toLowerCase();
+        const server = serverRaw?.trim();
+        if (!server || !proto) continue;
+        if (proto === 'http') {
+          http_proxy = normalizeProxyUrl(server);
+        } else if (proto === 'https') {
+          https_proxy = normalizeProxyUrl(server, 'https');
+        }
+      }
🧹 Nitpick comments (2)
packages/bruno-electron/src/utils/proxy-util.js (1)

382-389: Verify edge case: HTTP requests when only https_proxy is configured.

The logic correctly applies http_proxy only to non-HTTPS requests and https_proxy only to HTTPS requests. However, if only https_proxy is configured (no http_proxy), HTTP requests won't use any proxy—which is standard behavior but may be unexpected for users.

Consider adding a debug/info log when a proxy is skipped due to protocol mismatch.

packages/bruno-cli/src/runner/run-single-request.js (1)

289-387: Reuse system proxy resolution to avoid double lookup.
You call getSystemProxy() twice; caching within the request avoids redundant detection and keeps values consistent.

♻️ Proposed refactor
-    let proxyMode = 'off';
-    let proxyConfig = {};
+    let proxyMode = 'off';
+    let proxyConfig = {};
+    let systemProxyConfig = null;

     const collectionProxyConfig = get(brunoConfig, 'proxy', {});
     const collectionProxyEnabled = get(collectionProxyConfig, 'enabled', false);

     if (noproxy) {
       // If noproxy flag is set, don't use any proxy
       proxyMode = 'off';
     } else if (collectionProxyEnabled === true) {
       // If collection proxy is enabled, use it
       proxyConfig = collectionProxyConfig;
       proxyMode = 'on';
     } else if (collectionProxyEnabled === 'global') {
       // If collection proxy is set to 'global', use system proxy
-      const systemProxy = await getSystemProxy();
-      const { http_proxy, https_proxy } = systemProxy;
+      systemProxyConfig = await getSystemProxy();
+      const { http_proxy, https_proxy } = systemProxyConfig;
       if (http_proxy?.length || https_proxy?.length) {
         proxyMode = 'system';
       }
     } else {
       proxyMode = 'off';
     }

     if (proxyMode === 'on') {
       ...
     } else if (proxyMode === 'system') {
       try {
-        const systemProxy = await getSystemProxy();
-        const { http_proxy, https_proxy, no_proxy } = systemProxy;
+        if (!systemProxyConfig) {
+          systemProxyConfig = await getSystemProxy();
+        }
+        const { http_proxy, https_proxy, no_proxy } = systemProxyConfig;
         const shouldUseSystemProxy = shouldUseProxy(request.url, no_proxy || '');
         const parsedUrl = new URL(request.url);
         const isHttpsRequest = parsedUrl.protocol === 'https:';
         ...
       } catch (error) {
         request.httpsAgent = new https.Agent({
           ...httpsAgentRequestFields
         });
       }
     } else if (Object.keys(httpsAgentRequestFields).length > 0) {
       request.httpsAgent = new https.Agent({
         ...httpsAgentRequestFields
       });
     }

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🤖 Fix all issues with AI agents
In
`@packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js`:
- Around line 45-52: The JSX uses a <small className="font-medium flex flex-row
gap-2"> wrapper that contains block-level <div> elements
(system-proxy-source-label and system-proxy-source-value), which is invalid
HTML; update the inner elements to inline elements (replace those two <div> tags
with <span> tags) or alternatively change the outer <small> to a <div> and keep
the inner <div>s—make the minimal change by swapping the two inner <div
className="system-proxy-source-label..."> and <div
className="system-proxy-source-value..."> to <span> elements so the <small>
wrapper only contains inline children.
- Around line 14-19: The useEffect that dispatches getSystemProxyVariables
should guard against updating state after unmount: inside the useEffect create a
mounted/active flag (e.g., let isMounted = true) and in the
.then/.catch/.finally callbacks only call setError/setIsFetching if isMounted is
true, and return a cleanup function that sets isMounted = false; this prevents
setState on an unmounted component. Also fix the HTML semantic issue by
replacing the <small> element that currently wraps block-level <div> children
with a block container (e.g., <div>) or, if you need inline styling for text,
use <span> only for inline content instead of wrapping <div>s; update the JSX
where <small> is used to wrap lines 45–51 accordingly.

In `@packages/bruno-cli/src/runner/run-single-request.js`:
- Around line 306-308: Wrap the call to getSystemProxy() in a try/catch inside
the run-single-request flow (where systemProxy, http_proxy and https_proxy are
read) so a thrown error falls back to a safe default (e.g., empty systemProxy or
undefined http_proxy/https_proxy) instead of failing the request; capture the
resolved systemProxy in a local variable and reuse that variable wherever system
proxy info is needed later (avoid re-invoking getSystemProxy()), and update the
conditional that checks http_proxy/https_proxy to handle the fallback values
safely.

In `@packages/bruno-requests/src/network/system-proxy/index.ts`:
- Around line 13-17: The constructor in SystemProxyResolver (constructor and
SystemProxyResolverOptions) uses a truthy check for options.commandTimeoutMs
which incorrectly skips explicit 0 values; change the branch to test for
undefined (e.g., if (options.commandTimeoutMs !== undefined)) before assigning
this.commandTimeoutMs = options.commandTimeoutMs so callers can pass 0 to
disable the timeout.
- Around line 90-99: The source determination currently uses hasEnvironmentProxy
which only checks http_proxy/https_proxy, so when only no_proxy is set the
returned source incorrectly omits "environment"; update hasEnvironmentProxy to
include proxyEnvironmentVariables.no_proxy as well (or compute a new boolean
like hasAnyEnvironmentProxy from proxyEnvironmentVariables.http_proxy,
proxyEnvironmentVariables.https_proxy, proxyEnvironmentVariables.no_proxy) and
use that boolean in the source assignment (and anywhere else relying on
hasEnvironmentProxy), keeping the existing fallback logic that merges
proxyEnvironmentVariables with systemProxyEnvironmentVariables and the source
string composition.

In `@packages/bruno-requests/src/network/system-proxy/utils/linux.ts`:
- Around line 84-99: The getKDEProxy implementation only calls kreadconfig5 and
leaves later safeExec calls hardcoded, and the declared kreadconfig variable is
unused; update getKDEProxy to first detect which binary exists (try
'kreadconfig6' then 'kreadconfig5') and assign it to a single kreadconfig
variable, then use that kreadconfig for all subsequent safeExec calls (the
initial ProxyType check and the proxy detail lookups), and add fallbacks for
Plasma6 vs Plasma5 config locations/keys (e.g., try both 'Proxy Settings' and
any known Plasma6 groups/keys) so both tool versions and their config structures
are handled consistently.
♻️ Duplicate comments (5)
packages/bruno-electron/src/utils/proxy-util.js (2)

86-107: Credential exposure in timeline log remains unaddressed.

The super() call issue from prior review is now correctly resolved. However, Line 103 still logs the raw proxyUri which may contain embedded credentials (e.g., http://user:[email protected]).

🔒 Suggested fix: Redact userinfo before logging
+      const redactedUri = proxyUri.replace(/\/\/([^:]+):([^@]+)@/, '//$1:***@');
       this.timeline.push({
         timestamp: new Date(),
         type: 'info',
-        message: `Using proxy: ${proxyUri}`
+        message: `Using proxy: ${redactedUri}`
       });

391-393: Credential leak in error messages remains unaddressed.

Lines 392 and 407 interpolate raw proxy URIs into error messages. If credentials are embedded in the URI, they may appear in logs or user-facing dialogs.

🔒 Suggested fix: Redact credentials before throwing
+      const redactProxy = (uri) => uri ? uri.replace(/\/\/([^:]+):([^@]+)@/, '//$1:***@') : uri;
       } catch (error) {
-        throw new Error(`Invalid system http_proxy "${http_proxy}": ${error.message}`);
+        throw new Error(`Invalid system http_proxy "${redactProxy(http_proxy)}": ${error.message}`);
       }

Apply similar pattern at Line 407 for https_proxy.

Also applies to: 406-408

packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts (1)

154-182: Mock ordering still problematic for systemd test.

The detection flow calls existsSync('/etc/environment') before existsSync('/etc/systemd/system.conf.d'). With the current setup:

  1. mockReturnValue(false) sets default
  2. First mockReturnValueOnce(true) at line 164 will match /etc/environment check
  3. This causes /etc/environment detection to proceed instead of systemd

Use explicit call ordering:

       // Mock all previous methods to fail
-      mockExistsSync.mockReturnValue(false);
-
-      // Mock systemd conf directory to exist
-      mockExistsSync.mockReturnValueOnce(true);
-
-      // Mock systemd proxy file to exist
-      mockExistsSync.mockReturnValueOnce(true);
+      mockExistsSync
+        .mockReturnValueOnce(false)  // /etc/environment
+        .mockReturnValueOnce(true)   // /etc/systemd/system.conf.d
+        .mockReturnValueOnce(true);  // proxy.conf file
packages/bruno-requests/src/network/system-proxy/utils/linux.ts (1)

182-193: kvPairs regex skips lowercase environment variable keys.

The pattern ([A-Z_]+)= won't match lowercase keys like http_proxy=. This causes systemd configurations with lowercase proxy variables to be silently ignored.

-        const kvPairs = envVars.match(/([A-Z_]+)=(?:"([^"]*)"|'([^']*)'|(\S+))/gi);
+        const kvPairs = envVars.match(/([A-Za-z_][A-Za-z0-9_]*)=(?:"([^"]*)"|'([^']*)'|(\S+))/gi);
packages/bruno-electron/src/ipc/preferences.js (1)

42-45: Handle getSystemProxy errors in IPC handler.

This can reject the IPC promise on detection errors. Wrap and return a safe fallback.

✅ Suggested fix
-  ipcMain.handle('renderer:get-system-proxy-variables', async () => {
-    const systemProxyConfig = await getSystemProxy();
-    return systemProxyConfig;
-  });
+  ipcMain.handle('renderer:get-system-proxy-variables', async () => {
+    try {
+      const systemProxyConfig = await getSystemProxy();
+      return systemProxyConfig;
+    } catch (error) {
+      console.error('Failed to get system proxy:', error);
+      return {
+        http_proxy: null,
+        https_proxy: null,
+        no_proxy: null,
+        source: 'environment'
+      };
+    }
+  });
🧹 Nitpick comments (3)
packages/bruno-requests/src/network/system-proxy/utils/windows.ts (2)

53-59: ProxyEnable parsing may miss some registry value formats.

The check value === '0x1' || value === '1' won't match formats like 0x00000001. Consider parsing as integer:

         if (match) {
           const value = match[1];
-          proxyEnabled = value === '0x1' || value === '1';
+          const numValue = value.startsWith('0x') ? parseInt(value, 16) : parseInt(value, 10);
+          proxyEnabled = numValue === 1;
         }

190-198: Protocol parsing should trim whitespace.

If the registry value contains whitespace (e.g., http = proxy:8080), the current split won't match protocol names correctly.

       for (const protocol of protocols) {
         const [proto, server] = protocol.split('=');
+        const trimmedProto = proto?.trim();
+        const trimmedServer = server?.trim();
-        if (!server || !proto) continue;
-        if (proto === 'http') {
-          http_proxy = normalizeProxyUrl(server);
-        } else if (proto === 'https') {
-          https_proxy = normalizeProxyUrl(server, 'https');
+        if (!trimmedServer || !trimmedProto) continue;
+        if (trimmedProto === 'http') {
+          http_proxy = normalizeProxyUrl(trimmedServer);
+        } else if (trimmedProto === 'https') {
+          https_proxy = normalizeProxyUrl(trimmedServer, 'https');
         }
       }
packages/bruno-requests/src/network/system-proxy/utils/linux.spec.ts (1)

40-126: Missing test coverage for KDE proxy detection.

The getKDEProxy method is not covered by any test cases. Consider adding tests for KDE manual proxy configuration similar to the gsettings tests.

Comment on lines +14 to +19
useEffect(() => {
dispatch(getSystemProxyVariables())
.then(() => setError(null))
.catch((err) => setError(err.message || String(err)))
.finally(() => setIsFetching(false));
}, [dispatch]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

cat packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js

Repository: usebruno/bruno

Length of output: 3232


🏁 Script executed:

find . -type f -name "*.js" -o -name "*.ts" | xargs rg "getSystemProxyVariables" -A 5 -B 2 | head -80

Repository: usebruno/bruno

Length of output: 2930


🏁 Script executed:

grep -A 15 "export const getSystemProxyVariables" packages/bruno-app/src/providers/ReduxStore/slices/app.js

Repository: usebruno/bruno

Length of output: 470


🏁 Script executed:

rg "useEffect.*dispatch" packages/bruno-app/src/components -A 8 | head -100

Repository: usebruno/bruno

Length of output: 40


🏁 Script executed:

cat package.json | jq '.devDependencies.react, .dependencies.react'

Repository: usebruno/bruno

Length of output: 67


🏁 Script executed:

head -50 packages/bruno-app/package.json | jq '.dependencies, .devDependencies'

Repository: usebruno/bruno

Length of output: 119


🏁 Script executed:

cat packages/bruno-app/package.json | grep -A 5 "react"

Repository: usebruno/bruno

Length of output: 1706


🏁 Script executed:

sed -n '44,52p' packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js

Repository: usebruno/bruno

Length of output: 396


Add cleanup function to prevent state updates on unmounted component, and fix HTML semantic nesting.

The dispatch(getSystemProxyVariables()) does return a Promise (it's a Redux Thunk), so that part is safe. However, the useEffect lacks a cleanup function—if the Promise resolves after unmount, state setters will still execute. Also, the <small> element wrapping <div> children (lines 45–51) violates HTML semantics; <small> is inline and cannot contain block elements.

🛠️ Suggested fixes

For the async flow, add a cleanup return:

  useEffect(() => {
+    let isMounted = true;
-    dispatch(getSystemProxyVariables())
-      .then(() => setError(null))
-      .catch((err) => setError(err.message || String(err)))
-      .finally(() => setIsFetching(false));
+    const load = async () => {
+      try {
+        await dispatch(getSystemProxyVariables());
+        if (isMounted) setError(null);
+      } catch (err) {
+        if (isMounted) setError(err?.message || String(err));
+      } finally {
+        if (isMounted) setIsFetching(false);
+      }
+    };
+    load();
+    return () => {
+      isMounted = false;
+    };
   }, [dispatch]);

For the HTML nesting, replace <small> with a <div> or <span>:

-          <small className="font-medium flex flex-row gap-2">
+          <div className="font-medium flex flex-row gap-2">
             <div className="system-proxy-source-label text-xs">
               Proxy source:
             </div>
             <div className="system-proxy-source-value">
               {source}
             </div>
-          </small>
+          </div>
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
useEffect(() => {
dispatch(getSystemProxyVariables())
.then(() => setError(null))
.catch((err) => setError(err.message || String(err)))
.finally(() => setIsFetching(false));
}, [dispatch]);
useEffect(() => {
let isMounted = true;
const load = async () => {
try {
await dispatch(getSystemProxyVariables());
if (isMounted) setError(null);
} catch (err) {
if (isMounted) setError(err?.message || String(err));
} finally {
if (isMounted) setIsFetching(false);
}
};
load();
return () => {
isMounted = false;
};
}, [dispatch]);
🤖 Prompt for AI Agents
In
`@packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js`
around lines 14 - 19, The useEffect that dispatches getSystemProxyVariables
should guard against updating state after unmount: inside the useEffect create a
mounted/active flag (e.g., let isMounted = true) and in the
.then/.catch/.finally callbacks only call setError/setIsFetching if isMounted is
true, and return a cleanup function that sets isMounted = false; this prevents
setState on an unmounted component. Also fix the HTML semantic issue by
replacing the <small> element that currently wraps block-level <div> children
with a block container (e.g., <div>) or, if you need inline styling for text,
use <span> only for inline content instead of wrapping <div>s; update the JSX
where <small> is used to wrap lines 45–51 accordingly.

Comment on lines +45 to +52
<small className="font-medium flex flex-row gap-2">
<div className="system-proxy-source-label text-xs">
Proxy source:
</div>
<div className="system-proxy-source-value">
{source}
</div>
</small>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Fix invalid HTML nesting inside <small>.

<small> shouldn’t contain block elements like <div>. Use <span> or change the wrapper to a <div>/<p>.

✅ Suggested fix
-        {source && (
-          <div className="mb-2">
-            <small className="font-medium flex flex-row gap-2">
-              <div className="system-proxy-source-label text-xs">
-                Proxy source:
-              </div>
-              <div className="system-proxy-source-value">
-                {source}
-              </div>
-            </small>
-          </div>
-        )}
+        {source && (
+          <div className="mb-2">
+            <div className="font-medium flex flex-row gap-2 text-xs">
+              <span className="system-proxy-source-label">
+                Proxy source:
+              </span>
+              <span className="system-proxy-source-value">
+                {source}
+              </span>
+            </div>
+          </div>
+        )}
🤖 Prompt for AI Agents
In
`@packages/bruno-app/src/components/Preferences/ProxySettings/SystemProxy/index.js`
around lines 45 - 52, The JSX uses a <small className="font-medium flex flex-row
gap-2"> wrapper that contains block-level <div> elements
(system-proxy-source-label and system-proxy-source-value), which is invalid
HTML; update the inner elements to inline elements (replace those two <div> tags
with <span> tags) or alternatively change the outer <small> to a <div> and keep
the inner <div>s—make the minimal change by swapping the two inner <div
className="system-proxy-source-label..."> and <div
className="system-proxy-source-value..."> to <span> elements so the <small>
wrapper only contains inline children.

Comment on lines +306 to 308
const systemProxy = await getSystemProxy();
const { http_proxy, https_proxy } = systemProxy;
if (http_proxy?.length || https_proxy?.length) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Guard system proxy lookup during inherit mode.

If getSystemProxy() throws here, the whole request fails even though proxying is optional. Wrap it and fall back to direct. Also consider reusing the resolved system proxy later to avoid a second detection.

✅ Suggested fix
-      const systemProxy = await getSystemProxy();
-      const { http_proxy, https_proxy } = systemProxy;
-      if (http_proxy?.length || https_proxy?.length) {
-        proxyMode = 'system';
-      }
+      try {
+        const systemProxy = await getSystemProxy();
+        const { http_proxy, https_proxy } = systemProxy;
+        if (http_proxy?.length || https_proxy?.length) {
+          proxyMode = 'system';
+        }
+      } catch (error) {
+        // Fall back to direct connection when system proxy detection fails
+        proxyMode = 'off';
+      }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const systemProxy = await getSystemProxy();
const { http_proxy, https_proxy } = systemProxy;
if (http_proxy?.length || https_proxy?.length) {
try {
const systemProxy = await getSystemProxy();
const { http_proxy, https_proxy } = systemProxy;
if (http_proxy?.length || https_proxy?.length) {
proxyMode = 'system';
}
} catch (error) {
// Fall back to direct connection when system proxy detection fails
proxyMode = 'off';
}
🤖 Prompt for AI Agents
In `@packages/bruno-cli/src/runner/run-single-request.js` around lines 306 - 308,
Wrap the call to getSystemProxy() in a try/catch inside the run-single-request
flow (where systemProxy, http_proxy and https_proxy are read) so a thrown error
falls back to a safe default (e.g., empty systemProxy or undefined
http_proxy/https_proxy) instead of failing the request; capture the resolved
systemProxy in a local variable and reuse that variable wherever system proxy
info is needed later (avoid re-invoking getSystemProxy()), and update the
conditional that checks http_proxy/https_proxy to handle the fallback values
safely.

Comment on lines +13 to +17
constructor(options: SystemProxyResolverOptions = {}) {
this.osPlatform = platform();
if (options.commandTimeoutMs) {
this.commandTimeoutMs = options.commandTimeoutMs;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Honor explicit 0 timeout values.

The truthy check skips 0, so callers can’t disable the timeout even if they intend to. Prefer an explicit undefined check.

✅ Suggested fix
-    if (options.commandTimeoutMs) {
-      this.commandTimeoutMs = options.commandTimeoutMs;
-    }
+    if (options.commandTimeoutMs !== undefined) {
+      this.commandTimeoutMs = options.commandTimeoutMs;
+    }
🤖 Prompt for AI Agents
In `@packages/bruno-requests/src/network/system-proxy/index.ts` around lines 13 -
17, The constructor in SystemProxyResolver (constructor and
SystemProxyResolverOptions) uses a truthy check for options.commandTimeoutMs
which incorrectly skips explicit 0 values; change the branch to test for
undefined (e.g., if (options.commandTimeoutMs !== undefined)) before assigning
this.commandTimeoutMs = options.commandTimeoutMs so callers can pass 0 to
disable the timeout.

Comment on lines +90 to +99
const hasEnvironmentProxy = proxyEnvironmentVariables.http_proxy || proxyEnvironmentVariables.https_proxy;

try {
const systemProxyEnvironmentVariables = await systemProxyResolver.getSystemProxy();

return {
http_proxy: proxyEnvironmentVariables?.http_proxy || systemProxyEnvironmentVariables?.http_proxy,
https_proxy: proxyEnvironmentVariables?.https_proxy || systemProxyEnvironmentVariables?.https_proxy,
no_proxy: proxyEnvironmentVariables?.no_proxy || systemProxyEnvironmentVariables?.no_proxy,
source: hasEnvironmentProxy ? `${systemProxyEnvironmentVariables?.source} + environment` : systemProxyEnvironmentVariables?.source

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Include NO_PROXY-only env usage in source.

If only NO_PROXY is set, source still reports system-only, which can be misleading in UI/debugging. Consider counting no_proxy in hasEnvironmentProxy.

✅ Suggested fix
-  const hasEnvironmentProxy = proxyEnvironmentVariables.http_proxy || proxyEnvironmentVariables.https_proxy;
+  const hasEnvironmentProxy =
+    proxyEnvironmentVariables.http_proxy ||
+    proxyEnvironmentVariables.https_proxy ||
+    proxyEnvironmentVariables.no_proxy;
🤖 Prompt for AI Agents
In `@packages/bruno-requests/src/network/system-proxy/index.ts` around lines 90 -
99, The source determination currently uses hasEnvironmentProxy which only
checks http_proxy/https_proxy, so when only no_proxy is set the returned source
incorrectly omits "environment"; update hasEnvironmentProxy to include
proxyEnvironmentVariables.no_proxy as well (or compute a new boolean like
hasAnyEnvironmentProxy from proxyEnvironmentVariables.http_proxy,
proxyEnvironmentVariables.https_proxy, proxyEnvironmentVariables.no_proxy) and
use that boolean in the source assignment (and anywhere else relying on
hasEnvironmentProxy), keeping the existing fallback logic that merges
proxyEnvironmentVariables with systemProxyEnvironmentVariables and the source
string composition.

Comment on lines +84 to +99
private async getKDEProxy(execOpts: ExecFileOptions): Promise<ProxyConfiguration | null> {
try {
// Check if kreadconfig5 is available and get proxy type
const proxyType = await safeExec('kreadconfig5', ['--group', 'Proxy Settings', '--key', 'ProxyType'], execOpts);

// ProxyType values:
// 0 = No proxy
// 1 = Manual proxy configuration
// 2 = Automatic proxy configuration via URL
// 3 = Automatic proxy detection
// 4 = Use system proxy configuration (environment variables)

if (proxyType !== '1') {
// Only handle manual proxy configuration for now
return null;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🌐 Web query:

KDE Plasma 6 proxy configuration tool kreadconfig6

💡 Result:

kreadconfig6 — what it is and how to use it

  • Purpose: kreadconfig6 is the KDE/Plasma-6 CLI tool to read values from KDE config (INI-style) files (the Plasma6 successor to kreadconfig/kreadconfig5). It is provided by the KF6 kconfig package (kf6-kconfig / libkf6config*). [1][2]

  • Basic usage:

    • Read a key: kreadconfig6 --file --group --key
    • Example: kreadconfig6 --file kwinrc --group Windows --key FocusPolicy
    • You can add multiple --group arguments to address nested groups. [1][3]
  • Notes / practical caveats:

    • Plasma 6 changed where some settings are stored compared with Plasma 5; some settings that were in legacy ~/.config files may now live in different files or be managed elsewhere, so kreadconfig6 can return empty if the key/file no longer holds that setting. Check which file actually changes when you flip the setting in System Settings (or inspect ~/.config) before scripting. [3]
    • The companion write tool is kwriteconfig6; both are part of the KDE config tooling used by Plasma components. [1][2]

Sources:
[1] kreadconfig/kwriteconfig discussion & usage notes (kf6/kf5 tooling).
[2] Debian packaging discussion showing kreadconfig6 usage and package relationships.
[3] Community reports about Plasma 6 moving/renaming config files and kreadconfig6 returning blank for some settings (example: power settings).


🏁 Script executed:

# First, locate and examine the linux.ts file
fd "linux.ts" --type f

# Once found, examine the getKDEProxy method and safeExec function

Repository: usebruno/bruno

Length of output: 121


🏁 Script executed:

# Read the linux.ts file to understand the full getKDEProxy method and safeExec behavior
cat -n packages/bruno-requests/src/network/system-proxy/utils/linux.ts | head -150

Repository: usebruno/bruno

Length of output: 7041


🏁 Script executed:

# Find and examine the safeExec function in common.ts
fd "common.ts" --path "*/system-proxy/utils/*" --type f

Repository: usebruno/bruno

Length of output: 273


🏁 Script executed:

# Also search for safeExec definition
rg "export.*safeExec|function safeExec|const safeExec" --type ts

Repository: usebruno/bruno

Length of output: 231


🏁 Script executed:

# Read the common.ts file to see the full safeExec implementation
cat -n packages/bruno-requests/src/network/system-proxy/utils/common.ts

Repository: usebruno/bruno

Length of output: 2613


KDE 6 support needed, but suggested implementation is incomplete.

KDE 6 requires kreadconfig6 instead of kreadconfig5. The suggested fix only handles the first call and leaves the subsequent proxy detail lookups (lines 101–103) hardcoded to kreadconfig5. The kreadconfig variable is declared but never used. Additionally, Plasma 6 may store proxy settings in different locations than Plasma 5.

Update all four safeExec calls to use the same configuration tool, or ensure both tool versions and their respective config structures are properly handled.

🤖 Prompt for AI Agents
In `@packages/bruno-requests/src/network/system-proxy/utils/linux.ts` around lines
84 - 99, The getKDEProxy implementation only calls kreadconfig5 and leaves later
safeExec calls hardcoded, and the declared kreadconfig variable is unused;
update getKDEProxy to first detect which binary exists (try 'kreadconfig6' then
'kreadconfig5') and assign it to a single kreadconfig variable, then use that
kreadconfig for all subsequent safeExec calls (the initial ProxyType check and
the proxy detail lookups), and add fallbacks for Plasma6 vs Plasma5 config
locations/keys (e.g., try both 'Proxy Settings' and any known Plasma6
groups/keys) so both tool versions and their config structures are handled
consistently.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants