Skip to content

Feat: Support PAC file upload - #7651

Merged
bijin-bruno merged 28 commits into
usebruno:mainfrom
Pragadesh-45:pull/6056-file-upload
Apr 7, 2026
Merged

bijin-bruno merged 28 commits into
usebruno:mainfrom
Pragadesh-45:pull/6056-file-upload

Conversation

@Pragadesh-45

@Pragadesh-45 Pragadesh-45 commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR is an extension of #7633, which was implemented to add a .pac file upload option with the .pac URL fetch.

Contribution Checklist:

  • I've used AI significantly to create this pull request
  • 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.

Summary by CodeRabbit

  • New Features

    • Added PAC proxy mode with PAC URL input (Browse), validation, and UI mode switching; app can load PAC files (http/file) and apply PAC routing for requests.
  • Tests

    • Added unit, integration, and end-to-end tests plus local test servers and fixtures to validate PAC routing (proxy vs direct) and file:// PAC loading.
  • Chores

    • Exposed shared net resolver surface and updated packaging/build configs to support PAC resolver dependencies.

@coderabbitai

coderabbitai Bot commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Adds end-to-end PAC (Proxy Auto-Configuration) support: UI + preferences, a shared QuickJS-based PAC resolver with caching, async proxy agent resolution (HTTP/SOCKS/PAC) integrated into axios/electron request flow, unit and E2E tests, and build/export updates to publish a new net entrypoint.

Changes

Cohort / File(s) Summary
ProxySettings UI
packages/bruno-app/src/components/Preferences/ProxySettings/index.js, packages/bruno-app/src/components/Preferences/ProxySettings/StyledWrapper.js
Introduce derived proxyMode, add pacUrl Formik field + Yup validation, mode-driven UI rendering, PAC URL input with file browse that dispatches browseFiles and converts paths to file://.
Preferences Schema
packages/bruno-electron/src/store/preferences.js
Add proxy.pacUrl to default prefs and schema (string, max 2048, nullable).
PAC resolver (common)
packages/bruno-common/src/net/pac-resolver.ts, packages/bruno-common/src/net/pac-resolver.spec.ts, packages/bruno-common/src/net/index.ts
New module: download file:///http(s):// PAC, QuickJS-based resolver creation, TTL cache, getPacResolver/clearPacCache, types, and comprehensive tests.
Build & Exports (common)
packages/bruno-common/package.json, packages/bruno-common/rollup.config.js
Add ./net export, build src/net with .d.ts output, mark axios/pac-resolver/quickjs-emscripten external for net bundle.
Agent / Proxy logic (requests & electron)
packages/bruno-requests/src/utils/http-https-agents.ts, packages/bruno-electron/src/utils/proxy-util.js
Make agent setup async and add pac proxyMode: resolve directives via PAC, parse PROXY/SOCKS, construct proxy URIs, create appropriate agents, and log PAC timeline entries.
Axios integration & certs
packages/bruno-electron/src/ipc/network/axios-instance.js, packages/bruno-electron/src/ipc/network/cert-utils.js
Await setupProxyAgents in interceptors/redirects; convert handlers to async where needed; detect global pacUrl to set proxyMode: 'pac'.
Tests — unit
packages/bruno-electron/test/proxy-util.test.js, packages/bruno-common/src/net/pac-resolver.spec.ts
Add Jest tests for PAC agent behavior and resolver (directive parsing, caching, file/http handling, error cases).
Tests — E2E infra & fixtures
tests/proxy/pac/pac-proxy.spec.ts, tests/proxy/pac/server/index.ts, tests/proxy/pac/server/pac-files/test.pac, tests/proxy/pac/fixtures/*, tests/proxy/pac/init-user-data*/preferences.json
Add Playwright E2E spec, local PAC/proxy/target servers, PAC fixture, collection fixtures and pref templates to validate proxied vs direct routing.
Package deps & config
packages/bruno-common/package.json, packages/bruno-electron/package.json, packages/bruno-requests/package.json
Add runtime deps: axios, pac-resolver, quickjs-emscripten (common), node-fetch (electron), @usebruno/common (requests); minor devDeps/terser relocation.
Rollup externals (requests)
packages/bruno-requests/rollup.config.js
Treat pac-resolver and quickjs-emscripten as externals to avoid bundling.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant UI as ProxySettings UI
    participant Prefs as Preferences Store
    participant Request as Axios / IPC Request
    participant PAC as PAC Resolver (`@usebruno/common/net`)
    participant QJS as QuickJS
    participant Agents as Proxy Agent Factory

    UI->>Prefs: save proxyMode='pac' + pacUrl
    Request->>Prefs: read proxy config (pacUrl)
    Request->>PAC: getPacResolver(pacUrl)
    alt cache miss
        PAC->>QJS: init & compile PAC script (http/file)
        QJS-->>PAC: resolver function
    end
    Request->>PAC: resolve(requestUrl)
    PAC->>QJS: FindProxyForURL(url, host)
    QJS-->>PAC: return directives (PROXY / DIRECT / SOCKS)
    PAC-->>Request: directives
    Request->>Agents: create agents based on directive
    Agents-->>Request: return httpAgent / httpsAgent
    Request->>Request: perform request using agents
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • helloanoop
  • lohit-bruno
  • naman-bruno
  • bijin-bruno

Poem

🧭 A tiny PAC file whispers where requests should go,
QuickJS listens, returns PROXY, SOCKS, or DIRECT flow.
From UI to prefs the pacUrl takes flight,
Agents wake up and route packets right.
Tests hum green and the network feels light.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% 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 'Feat: Support PAC file upload' accurately summarizes the main feature added in this PR, which introduces PAC file upload functionality alongside existing URL-based PAC configuration.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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: 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/ipc/network/axios-instance.js (1)

414-432: ⚠️ Potential issue | 🔴 Critical

Fix const reassignment at line 270.

Line 270 declares const timeline, but line 425 attempts to reassign it with timeline = err.timeline;. This throws a runtime error. Change line 270 to let timeline to allow reassignment in the error handler.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-electron/src/ipc/network/axios-instance.js` around lines 414 -
432, The variable timeline is declared as a const but later reassigned in the
setupProxyAgents error handler (where you do timeline = err.timeline), causing a
runtime error; change the declaration of timeline (the variable holding the
request timeline used around setupProxyAgents and later push calls) from const
to let so it can be reassigned in the catch block, and verify any other
references to timeline (e.g., the timeline.push calls and the catch branch that
reads err.timeline) still work with the new let binding.
🧹 Nitpick comments (6)
tests/proxy/pac/fixtures/pac-files/test.pac (1)

1-6: Missing semicolons at end of statements.

Per coding guidelines, always add semicolons at the end of statements.

Suggested fix
 function FindProxyForURL(url, host) {
   if (url.indexOf('/proxied') !== -1) {
-    return 'PROXY localhost:18888';
+    return 'PROXY localhost:18888';
   }
-  return 'DIRECT';
+  return 'DIRECT';
 }

Note: The diff shows no actual change because the semicolons are already present inside the return statements. On closer inspection, the code is correct. Disregard this comment.

Actually, upon re-examination, the semicolons are present on Lines 3 and 5. The code looks good.

LGTM!

The PAC fixture correctly routes /proxied requests through the test proxy and returns DIRECT for all other requests.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/proxy/pac/fixtures/pac-files/test.pac` around lines 1 - 6, No change
required: the PAC fixture's FindProxyForURL function already includes semicolons
on the return statements and correctly returns 'PROXY localhost:18888' for URLs
containing '/proxied' and 'DIRECT' otherwise, so leave the function
FindProxyForURL as-is.
tests/proxy/pac/server/index.ts (1)

38-74: Consider adding a timeout to the proxy request.

The proxy request at Line 58 has no timeout configured. If the target server hangs, the proxy will wait indefinitely.

For a test server this is acceptable, but adding a reasonable timeout would make tests fail faster if something goes wrong.

Optional: Add timeout to proxy request
     const options: http.RequestOptions = {
       hostname: targetUrl.hostname,
       port: targetUrl.port || 80,
       path: targetUrl.pathname + targetUrl.search,
       method: clientReq.method,
-      headers: { ...clientReq.headers, host: targetUrl.host }
+      headers: { ...clientReq.headers, host: targetUrl.host },
+      timeout: 5000
     };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/proxy/pac/server/index.ts` around lines 38 - 74, The proxy request in
createProxyServer never times out; update the ClientRequest (proxyReq) to use
setTimeout and handle the 'timeout' event: call proxyReq.setTimeout with a
reasonable value (e.g., a few seconds), on timeout destroy/abort the proxyReq
(or proxyReq.abort()) and, if clientRes headers haven't been sent, write a
504/502 status and end with a timeout message; ensure you also remove/ignore
other callbacks after timeout to avoid double responses. Use the symbols
createProxyServer, proxyReq, and clientRes to locate where to add the timeout
and handler.
tests/proxy/pac/server/pac-files/test.pac (1)

1-7: Inconsistent style and proxy address between PAC fixtures.

Two observations:

  1. This file uses 4-space indentation and double quotes, while tests/proxy/pac/fixtures/pac-files/test.pac uses 2-space indentation and single quotes.

  2. This file uses 127.0.0.1:18888 while the other uses localhost:18888. While functionally equivalent in most cases, using 127.0.0.1 consistently is slightly more reliable since it avoids DNS resolution.

Suggested alignment with coding guidelines and consistency
 function FindProxyForURL(url, host) {
-    // Route requests whose path starts with /proxied through the local test proxy
-    if (url.indexOf("/proxied") > -1) {
-        return "PROXY 127.0.0.1:18888";
-    }
-    return "DIRECT";
+  // Route requests whose path starts with /proxied through the local test proxy
+  if (url.indexOf('/proxied') > -1) {
+    return 'PROXY 127.0.0.1:18888';
+  }
+  return 'DIRECT';
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/proxy/pac/server/pac-files/test.pac` around lines 1 - 7, The PAC
fixture uses inconsistent formatting and quoting: update the FindProxyForURL
function to use 2-space indentation and single quotes instead of 4-space and
double quotes, and normalize the proxy host to 127.0.0.1:18888 (keep the port)
so the PAC file matches the project's preferred style and avoids DNS resolution
differences.
packages/bruno-app/src/components/Preferences/ProxySettings/index.js (1)

387-419: Consider adding data-testid attributes for e2e testability.

The PAC URL input and Browse button lack data-testid attributes. Per coding guidelines, testable elements should have these for Playwright.

Also, the manual file:// URL construction (lines 408-410) may not handle edge cases like special characters or Windows UNC paths. Consider using a utility that mirrors pathToFileURL behavior on the main process side.

🔧 Suggested diff
             <input
               id="pacUrl"
               type="text"
               name="pacUrl"
               className="block textbox"
+              data-testid="pac-url-input"
               autoComplete="off"
               ...
             />
             <button
               type="button"
               className="btn btn-sm btn-secondary ml-2"
+              data-testid="pac-browse-button"
               onClick={() => {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-app/src/components/Preferences/ProxySettings/index.js` around
lines 387 - 419, Add data-testid attributes to the PAC URL input (id "pacUrl")
and the Browse button to support Playwright e2e tests, e.g.,
data-testid="pac-url-input" and data-testid="pac-url-browse". In the Browse
button click handler (the dispatch(browseFiles(...)).then(...) block) stop
manually constructing file URLs with isWindowsOS() and string concatenation;
instead have the renderer pass the selected file path(s) back and let the main
process convert the path to a proper file URL using pathToFileURL (or a shared
utility that wraps pathToFileURL) before resolving filePaths, then call
formik.setFieldValue('pacUrl', fileUrl) with that returned URL; keep the
toast.success/error behavior intact.
packages/bruno-electron/src/utils/proxy-util.js (1)

226-237: PAC mode sets both agents regardless of request protocol.

Unlike proxyMode === 'on' (lines 166-178) which only sets the agent matching the request protocol, PAC mode sets both httpAgent and httpsAgent. This creates unnecessary agent instances.

Consider aligning with the 'on' mode pattern for efficiency:

♻️ Optional optimization
           if (/^(PROXY|HTTP)\s+/i.test(first)) {
             const hostPort = first.split(/\s+/)[1];
             const proxyUri = `http://${hostPort}`;
-            requestConfig.httpAgent = getOrCreateHttpAgent({ AgentClass: HttpProxyAgent, options: { keepAlive: true }, proxyUri, timeline, disableCache, hostname });
-            requestConfig.httpsAgent = getOrCreateHttpsAgent({ AgentClass: PatchedHttpsProxyAgent, options: tlsOptions, proxyUri, timeline, disableCache, hostname });
+            if (isHttpsRequest) {
+              requestConfig.httpsAgent = getOrCreateHttpsAgent({ AgentClass: PatchedHttpsProxyAgent, options: tlsOptions, proxyUri, timeline, disableCache, hostname });
+            } else {
+              requestConfig.httpAgent = getOrCreateHttpAgent({ AgentClass: HttpProxyAgent, options: { keepAlive: true }, proxyUri, timeline, disableCache, hostname });
+            }
           }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-electron/src/utils/proxy-util.js` around lines 226 - 237,
PAC-mode branch sets both requestConfig.httpAgent and requestConfig.httpsAgent
regardless of the actual request protocol, creating unnecessary agents; update
the PAC handling (the block inspecting `first`) to mirror the `proxyMode ===
'on'` pattern by only assigning the agent that matches the current request
protocol (e.g., set only requestConfig.httpAgent when the request is plain http,
and only requestConfig.httpsAgent for https), using the same Agent classes
(`HttpProxyAgent`, `PatchedHttpsProxyAgent`, `SocksProxyAgent`) and factory
helpers (`getOrCreateHttpAgent`, `getOrCreateHttpsAgent`) and reusing the
existing `proxyUri`, `tlsOptions`, `timeline`, `disableCache`, `hostname`
parameters to avoid creating both agents unnecessarily.
packages/bruno-electron/src/utils/pac-resolver.js (1)

59-95: JSDoc placement and default value handling.

Two minor observations:

  1. JSDoc inside function body (lines 60-67): Unconventional placement. Moving it above the function signature would enable IDE hover-docs at call sites.

  2. Falsy defaults on lines 73 and 89: Using || means cacheTtlMs: 0 or timeoutMs: 0 would fall back to defaults. If explicit zero should be honored, use ??.

Neither is critical—0 timeout is impractical, and disabling cache via cacheTtlMs: 0 is an edge case.

🔧 Optional: nullish coalescing for explicit zero support
-  const cacheTtlMs = opts.cacheTtlMs || 5 * 60 * 1000;
+  const cacheTtlMs = opts.cacheTtlMs ?? 5 * 60 * 1000;
-  const script = await downloadPac(pacUrl, tlsOptions, opts.timeoutMs || 5000);
+  const script = await downloadPac(pacUrl, tlsOptions, opts.timeoutMs ?? 5000);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-electron/src/utils/pac-resolver.js` around lines 59 - 95, Move
the JSDoc block currently inside getPacResolver up above the function signature
so IDEs surface the docs at call sites, and change the default-handling
expressions that use || to nullish coalescing (use ??) so explicit zeros are
honored: replace opts.cacheTtlMs || 5 * 60 * 1000 (cacheTtlMs assignment) with
opts.cacheTtlMs ?? 5 * 60 * 1000 (reference cacheTtlMs) and replace
opts.timeoutMs || 5000 when calling downloadPac with opts.timeoutMs ?? 5000
(reference timeoutMs); keep function name getPacResolver, variables cacheTtlMs
and opts.timeoutMs, and CACHE handling unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/bruno-electron/src/utils/proxy-util.js`:
- Around line 217-242: The PAC branch handling (when proxyMode === 'pac') calls
timeline.push(...) in multiple places (inside the successful directives handling
and in the catch block) without ensuring timeline is defined; update the PAC
block in proxy-util.js (the code around getPacResolver, resolver.resolve and
where directives are processed) to guard all timeline.push calls with if
(timeline) checks (matching the pattern used in the 'on' and 'system' modes) so
you only push events when timeline is provided, including the info log for PAC
directives and the error log in the catch.

In `@packages/bruno-electron/test/pac-resolver.test.js`:
- Around line 191-210: The test assumes a Unix path when asserting readFile was
called, which breaks on Windows; mock the fileURLToPath import used by
getPacResolver to return a deterministic path (e.g., '/Users/test/proxy.pac')
for this test so the readFile assertion is platform-agnostic. In the test before
requiring ../src/utils/pac-resolver, jest.doMock the 'url' module's
fileURLToPath to return the expected path, then require getPacResolver and run
the rest of the assertions (ensure you restore or isolate the mock so other
tests like the existing Windows-specific test remain correct).

---

Outside diff comments:
In `@packages/bruno-electron/src/ipc/network/axios-instance.js`:
- Around line 414-432: The variable timeline is declared as a const but later
reassigned in the setupProxyAgents error handler (where you do timeline =
err.timeline), causing a runtime error; change the declaration of timeline (the
variable holding the request timeline used around setupProxyAgents and later
push calls) from const to let so it can be reassigned in the catch block, and
verify any other references to timeline (e.g., the timeline.push calls and the
catch branch that reads err.timeline) still work with the new let binding.

---

Nitpick comments:
In `@packages/bruno-app/src/components/Preferences/ProxySettings/index.js`:
- Around line 387-419: Add data-testid attributes to the PAC URL input (id
"pacUrl") and the Browse button to support Playwright e2e tests, e.g.,
data-testid="pac-url-input" and data-testid="pac-url-browse". In the Browse
button click handler (the dispatch(browseFiles(...)).then(...) block) stop
manually constructing file URLs with isWindowsOS() and string concatenation;
instead have the renderer pass the selected file path(s) back and let the main
process convert the path to a proper file URL using pathToFileURL (or a shared
utility that wraps pathToFileURL) before resolving filePaths, then call
formik.setFieldValue('pacUrl', fileUrl) with that returned URL; keep the
toast.success/error behavior intact.

In `@packages/bruno-electron/src/utils/pac-resolver.js`:
- Around line 59-95: Move the JSDoc block currently inside getPacResolver up
above the function signature so IDEs surface the docs at call sites, and change
the default-handling expressions that use || to nullish coalescing (use ??) so
explicit zeros are honored: replace opts.cacheTtlMs || 5 * 60 * 1000 (cacheTtlMs
assignment) with opts.cacheTtlMs ?? 5 * 60 * 1000 (reference cacheTtlMs) and
replace opts.timeoutMs || 5000 when calling downloadPac with opts.timeoutMs ??
5000 (reference timeoutMs); keep function name getPacResolver, variables
cacheTtlMs and opts.timeoutMs, and CACHE handling unchanged.

In `@packages/bruno-electron/src/utils/proxy-util.js`:
- Around line 226-237: PAC-mode branch sets both requestConfig.httpAgent and
requestConfig.httpsAgent regardless of the actual request protocol, creating
unnecessary agents; update the PAC handling (the block inspecting `first`) to
mirror the `proxyMode === 'on'` pattern by only assigning the agent that matches
the current request protocol (e.g., set only requestConfig.httpAgent when the
request is plain http, and only requestConfig.httpsAgent for https), using the
same Agent classes (`HttpProxyAgent`, `PatchedHttpsProxyAgent`,
`SocksProxyAgent`) and factory helpers (`getOrCreateHttpAgent`,
`getOrCreateHttpsAgent`) and reusing the existing `proxyUri`, `tlsOptions`,
`timeline`, `disableCache`, `hostname` parameters to avoid creating both agents
unnecessarily.

In `@tests/proxy/pac/fixtures/pac-files/test.pac`:
- Around line 1-6: No change required: the PAC fixture's FindProxyForURL
function already includes semicolons on the return statements and correctly
returns 'PROXY localhost:18888' for URLs containing '/proxied' and 'DIRECT'
otherwise, so leave the function FindProxyForURL as-is.

In `@tests/proxy/pac/server/index.ts`:
- Around line 38-74: The proxy request in createProxyServer never times out;
update the ClientRequest (proxyReq) to use setTimeout and handle the 'timeout'
event: call proxyReq.setTimeout with a reasonable value (e.g., a few seconds),
on timeout destroy/abort the proxyReq (or proxyReq.abort()) and, if clientRes
headers haven't been sent, write a 504/502 status and end with a timeout
message; ensure you also remove/ignore other callbacks after timeout to avoid
double responses. Use the symbols createProxyServer, proxyReq, and clientRes to
locate where to add the timeout and handler.

In `@tests/proxy/pac/server/pac-files/test.pac`:
- Around line 1-7: The PAC fixture uses inconsistent formatting and quoting:
update the FindProxyForURL function to use 2-space indentation and single quotes
instead of 4-space and double quotes, and normalize the proxy host to
127.0.0.1:18888 (keep the port) so the PAC file matches the project's preferred
style and avoids DNS resolution differences.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d1f786c3-c49b-4da0-86ee-cfb6b291ea80

📥 Commits

Reviewing files that changed from the base of the PR and between 8c9cad6 and 8370cdd.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (19)
  • packages/bruno-app/src/components/Preferences/ProxySettings/index.js
  • packages/bruno-common/package.json
  • packages/bruno-electron/package.json
  • packages/bruno-electron/src/ipc/network/axios-instance.js
  • packages/bruno-electron/src/ipc/network/cert-utils.js
  • packages/bruno-electron/src/store/preferences.js
  • packages/bruno-electron/src/utils/pac-resolver.js
  • packages/bruno-electron/src/utils/proxy-util.js
  • packages/bruno-electron/test/pac-resolver.test.js
  • packages/bruno-electron/test/proxy-util.test.js
  • tests/proxy/pac/fixtures/collection/bruno.json
  • tests/proxy/pac/fixtures/collection/direct.bru
  • tests/proxy/pac/fixtures/collection/proxied.bru
  • tests/proxy/pac/fixtures/pac-files/test.pac
  • tests/proxy/pac/init-user-data-file/preferences.json
  • tests/proxy/pac/init-user-data/preferences.json
  • tests/proxy/pac/pac-proxy.spec.ts
  • tests/proxy/pac/server/index.ts
  • tests/proxy/pac/server/pac-files/test.pac

@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

🧹 Nitpick comments (4)
packages/bruno-common/src/net/pac-resolver.ts (2)

55-62: Cache key doesn't account for TLS options.

Two calls with the same pacUrl but different httpsAgentRequestFields (e.g., different CA certs) will return the cached wrapper from the first call. If TLS config can vary per-request, include a hash of the relevant TLS options in the cache key.

For now, if TLS options are app-global (which appears true from context snippets), this is acceptable.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-common/src/net/pac-resolver.ts` around lines 55 - 62, The
cache key used in getPacResolver (key = `url:${pacUrl}`) ignores
httpsAgentRequestFields, so callers with the same pacUrl but different TLS
config (httpsAgentRequestFields) can get an incorrect cached PacWrapper; update
the cache key generation to include a stable representation (e.g., a hash/JSON
of the relevant TLS fields such as ca/cert/key/rejectUnauthorized) of
httpsAgentRequestFields when building key before checking CACHE.get, or
otherwise incorporate a determinant derived from httpsAgentRequestFields into
the key to ensure distinct TLS configs produce distinct cache entries (refer to
getPacResolver, httpsAgentRequestFields, key, and CACHE).

40-46: Error handling re-throws axios errors but loses original error context for non-response errors.

When err.response is falsy (network errors), the original error is re-thrown directly, which is fine. But for response errors, the status-only message loses useful context like the URL. Consider:

🛠️ Optional enhancement
-if (err.response) throw new Error(`Failed to fetch PAC (${err.response.status})`);
+if (err.response) throw new Error(`Failed to fetch PAC from ${pacUrl}: HTTP ${err.response.status}`);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-common/src/net/pac-resolver.ts` around lines 40 - 46, The
catch block in pac-resolver.ts currently throws a new Error with only the status
when err.response exists, losing useful context; update the catch to include
pacUrl (and optionally other context like config) in the error message and
preserve the original axios error as the cause (e.g., use Error constructor's
cause or attach err to the thrown error) when err.response is truthy; keep
re-throwing the original err when err.response is falsy. Reference symbols:
pacUrl, axios.get, and err.response.status to locate and change the throw logic.
packages/bruno-app/src/components/Preferences/ProxySettings/index.js (1)

106-111: Dual state for proxy mode can drift out of sync with Formik.

proxyMode is a separate useState initialized from preferences but not updated when formik.values change externally (e.g., formik.resetForm). Consider deriving proxyMode directly from formik.values instead:

const proxyMode = formik.values.disabled
  ? 'off'
  : formik.values.inherit
    ? 'system'
    : formik.values.pacUrl
      ? 'pac'
      : 'on';

This avoids a second source of truth and keeps mode consistent with the actual form state.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-app/src/components/Preferences/ProxySettings/index.js` around
lines 106 - 111, The component currently maintains a separate proxyMode state
via useState (proxyMode, setProxyMode) initialized from preferences which can
drift from Formik when formik.values change; remove the useState-based proxyMode
and instead derive proxyMode directly from formik.values (e.g., inspect
formik.values.disabled, .inherit, .pacUrl to compute 'off'|'system'|'pac'|'on'),
update any handlers that previously called setProxyMode to update the Formik
values via formik.setFieldValue or formik.setValues, and delete setProxyMode
usage to ensure a single source of truth tied to formik.values.
packages/bruno-requests/src/utils/http-https-agents.ts (1)

490-492: Silent catch swallows PAC resolution errors.

The empty catch block falls through to direct connection without logging. This could mask configuration issues. Consider adding a warning log or passing errors to the timeline if available:

🛠️ Suggested improvement
-      } catch {
-        // PAC resolution failed — fall through to direct connection
-      }
+      } catch (err) {
+        // PAC resolution failed — fall through to direct connection
+        if (timeline) {
+          timeline.push({ timestamp: new Date(), type: 'warning', message: `PAC resolution failed: ${(err as Error).message}` });
+        }
+      }

This matches the error handling in packages/bruno-electron/src/utils/proxy-util.js (context snippet 1, line 240).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-requests/src/utils/http-https-agents.ts` around lines 490 -
492, The empty catch that swallows PAC resolution errors should be changed to
log a warning (and/or forward the error to the timeline if available) instead of
failing silently: inside the PAC resolution block where the catch currently
falls through to direct connection, capture the caught error and call the
existing logger/timeline helper (e.g., processLogger.warn(...) or
timeline.addEvent(...)) with a concise message like "PAC resolution failed,
falling back to direct connection" plus the error details; mirror the
error-handling approach used in bruno-electron's proxy-util.js so the function
that performs PAC resolution (the PAC/agent resolution function in this file)
surfaces diagnostic info rather than swallowing exceptions.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/bruno-app/src/components/Preferences/ProxySettings/index.js`:
- Around line 405-421: The current onClick handler building fileUrl for PAC
files (inside the dispatch(browseFiles(...)).then(...) block) constructs a raw
file:// URL using isWindowsOS() and string replacement, which won't encode
special characters; update the logic that sets fileUrl (before calling
formik.setFieldValue('pacUrl', fileUrl)) to percent-encode path segments (e.g.,
use encodeURI or a small helper to convert the filePath into a proper file URL
per RFC 8089) so spaces and characters like # and % are escaped, then pass the
encoded URL to formik.setFieldValue and keep the existing success/error toast
behavior.

In `@packages/bruno-common/rollup.config.js`:
- Around line 65-70: The net submodule build doesn't emit TypeScript
declarations even though package.json exports "types", so update the Rollup
build: enable rollup-plugin-dts in the createBuildConfig pipeline for the net
build (the config block using inputDir: 'src/net/**/*', input:
'src/net/index.ts', cjsOutput/esmOutput), or alternatively turn on
"declaration": true in tsconfig.json and ensure the build step copies/outputs
the generated .d.ts to dist/net/index.d.ts; specifically wire the imported
rollup-plugin-dts into the Rollup config for the net/runner/utils entries (or
enable TS declaration emit) so the declared export types (./dist/net/index.d.ts)
are produced.

---

Nitpick comments:
In `@packages/bruno-app/src/components/Preferences/ProxySettings/index.js`:
- Around line 106-111: The component currently maintains a separate proxyMode
state via useState (proxyMode, setProxyMode) initialized from preferences which
can drift from Formik when formik.values change; remove the useState-based
proxyMode and instead derive proxyMode directly from formik.values (e.g.,
inspect formik.values.disabled, .inherit, .pacUrl to compute
'off'|'system'|'pac'|'on'), update any handlers that previously called
setProxyMode to update the Formik values via formik.setFieldValue or
formik.setValues, and delete setProxyMode usage to ensure a single source of
truth tied to formik.values.

In `@packages/bruno-common/src/net/pac-resolver.ts`:
- Around line 55-62: The cache key used in getPacResolver (key =
`url:${pacUrl}`) ignores httpsAgentRequestFields, so callers with the same
pacUrl but different TLS config (httpsAgentRequestFields) can get an incorrect
cached PacWrapper; update the cache key generation to include a stable
representation (e.g., a hash/JSON of the relevant TLS fields such as
ca/cert/key/rejectUnauthorized) of httpsAgentRequestFields when building key
before checking CACHE.get, or otherwise incorporate a determinant derived from
httpsAgentRequestFields into the key to ensure distinct TLS configs produce
distinct cache entries (refer to getPacResolver, httpsAgentRequestFields, key,
and CACHE).
- Around line 40-46: The catch block in pac-resolver.ts currently throws a new
Error with only the status when err.response exists, losing useful context;
update the catch to include pacUrl (and optionally other context like config) in
the error message and preserve the original axios error as the cause (e.g., use
Error constructor's cause or attach err to the thrown error) when err.response
is truthy; keep re-throwing the original err when err.response is falsy.
Reference symbols: pacUrl, axios.get, and err.response.status to locate and
change the throw logic.

In `@packages/bruno-requests/src/utils/http-https-agents.ts`:
- Around line 490-492: The empty catch that swallows PAC resolution errors
should be changed to log a warning (and/or forward the error to the timeline if
available) instead of failing silently: inside the PAC resolution block where
the catch currently falls through to direct connection, capture the caught error
and call the existing logger/timeline helper (e.g., processLogger.warn(...) or
timeline.addEvent(...)) with a concise message like "PAC resolution failed,
falling back to direct connection" plus the error details; mirror the
error-handling approach used in bruno-electron's proxy-util.js so the function
that performs PAC resolution (the PAC/agent resolution function in this file)
surfaces diagnostic info rather than swallowing exceptions.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ed44bb33-a558-4bc4-b46d-6619c2fd8899

📥 Commits

Reviewing files that changed from the base of the PR and between 8370cdd and ae9a5ca.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (11)
  • packages/bruno-app/src/components/Preferences/ProxySettings/StyledWrapper.js
  • packages/bruno-app/src/components/Preferences/ProxySettings/index.js
  • packages/bruno-common/package.json
  • packages/bruno-common/rollup.config.js
  • packages/bruno-common/src/net/index.ts
  • packages/bruno-common/src/net/pac-resolver.spec.ts
  • packages/bruno-common/src/net/pac-resolver.ts
  • packages/bruno-electron/package.json
  • packages/bruno-electron/src/utils/proxy-util.js
  • packages/bruno-requests/package.json
  • packages/bruno-requests/src/utils/http-https-agents.ts
✅ Files skipped from review due to trivial changes (3)
  • packages/bruno-app/src/components/Preferences/ProxySettings/StyledWrapper.js
  • packages/bruno-requests/package.json
  • packages/bruno-electron/package.json
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/bruno-common/package.json
  • packages/bruno-electron/src/utils/proxy-util.js

Comment thread packages/bruno-common/rollup.config.js Resolved

@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

🧹 Nitpick comments (1)
packages/bruno-common/src/net/pac-resolver.ts (1)

25-42: Verify and block protocol-downgrade redirects for HTTPS PAC URLs.

Line 29 allows redirects, so the security of an https:// PAC URL depends on the pinned Axios/follow-redirects behavior. If that stack follows https → http, the PAC script can bypass the TLS settings from Lines 32-38. Please verify the current version and reject downgrade redirects explicitly.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-common/src/net/pac-resolver.ts` around lines 25 - 42, When
pacUrl starts with 'https://' ensure redirects cannot downgrade to 'http' by
adding a redirect-check hook to the axios config: when constructing config for
HTTPS PACs (the block that sets agentOpts, tlsOptions and config.httpsAgent),
add a beforeRedirect (or equivalent follow-redirects hook) that inspects the
redirect URL and throws or aborts if the newLocation.protocol !== 'https:'; keep
maxRedirects but fail fast on any downgrade before calling axios.get(pacUrl,
config). Reference symbols: pacUrl, config, httpsAgent, AgentOptions,
tlsOptions, and axios.get.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/bruno-common/src/net/pac-resolver.ts`:
- Around line 61-80: The cold-cache race causes duplicate downloads/compiles;
change the caching to store the in-flight Promise<PacWrapper> under the same
CACHE key before awaiting downloadPac/getQuickJS/createPacResolver so concurrent
callers reuse it; specifically, create a Promise (e.g., wrapperPromise) that
performs downloadPac, getQuickJS, createPacResolver and resolves to the
PacWrapper (with resolve using resolverFn) and set CACHE.set(key, { wrapper:
wrapperPromise, ts: Date.now() }) immediately, then await that promise; ensure
you clear the cache entry or replace it in a finally block on failure so a
failed attempt doesn't leave a stuck promise; references: CACHE, key,
downloadPac, getQuickJS, createPacResolver, PacWrapper, wrapper.
- Line 60: The cache key currently only uses pacUrl (const key =
`url:${pacUrl}`), so resolvers built with different TLS trust settings get
reused; change the key to incorporate the TLS parameters used when creating the
resolver (e.g., include normalized values of ca, rejectUnauthorized, minVersion
or a stable hash of those options) so entries differ when any of those settings
change; ensure you normalize/serialize the ca (Buffer vs string) and booleans
consistently before adding them to the key in the same scope where key is
defined.

---

Nitpick comments:
In `@packages/bruno-common/src/net/pac-resolver.ts`:
- Around line 25-42: When pacUrl starts with 'https://' ensure redirects cannot
downgrade to 'http' by adding a redirect-check hook to the axios config: when
constructing config for HTTPS PACs (the block that sets agentOpts, tlsOptions
and config.httpsAgent), add a beforeRedirect (or equivalent follow-redirects
hook) that inspects the redirect URL and throws or aborts if the
newLocation.protocol !== 'https:'; keep maxRedirects but fail fast on any
downgrade before calling axios.get(pacUrl, config). Reference symbols: pacUrl,
config, httpsAgent, AgentOptions, tlsOptions, and axios.get.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: af912c77-d65e-44dd-9aca-05306e72fef7

📥 Commits

Reviewing files that changed from the base of the PR and between ae9a5ca and dcefd31.

📒 Files selected for processing (2)
  • packages/bruno-common/rollup.config.js
  • packages/bruno-common/src/net/pac-resolver.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/bruno-common/rollup.config.js

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/bruno-common/src/net/pac-resolver.ts`:
- Around line 74-81: The resolve function currently calls new URL(url) which
will throw on malformed URLs; wrap the URL parsing in a try/catch inside resolve
(around new URL(url) and deriving host) and handle parse failures by returning
an empty array (or a clear rejected Promise) instead of letting a TypeError
escape; keep using resolverFn(url, host) when parsing succeeds and preserve the
existing post-processing of out (split/trim/filter) so callers still get the
same output shape.
- Around line 70-72: The code incorrectly calls createPacResolver(qjs, script)
and unnecessarily calls getQuickJS(); update the usage to call
createPacResolver(script) only and remove the getQuickJS() call and any qjs
variable related to it; locate the getQuickJS() invocation and the
createPacResolver call (referenced as getQuickJS and
createPacResolver/resolverFn) and replace with a single
createPacResolver(script) call so QuickJS initialization is handled internally
by pac-resolver v7.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1c84faf8-744c-4fb7-a393-bedb2f31dacd

📥 Commits

Reviewing files that changed from the base of the PR and between 18f6d04 and 050cb0f.

📒 Files selected for processing (2)
  • packages/bruno-common/src/net/pac-resolver.ts
  • packages/bruno-electron/test/proxy-util.test.js
✅ Files skipped from review due to trivial changes (1)
  • packages/bruno-electron/test/proxy-util.test.js

Comment thread packages/bruno-electron/package.json Resolved
sid-bruno
sid-bruno previously approved these changes Apr 2, 2026

@sid-bruno sid-bruno left a comment

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.

Waiting on @lohit-bruno's to confirm things on the proxy layer

dbrglc and others added 13 commits April 3, 2026 12:45
chore(dependencies): update package-lock.json with new dependencies and version upgrades

- Added new dependencies: ajv, git-url-parse, @opencollection/types, and storybook packages.
- Updated existing dependencies to their latest versions, including eslint and babel packages.
- Removed deprecated entries and cleaned up the package-lock structure for better maintainability.
@Pragadesh-45
Pragadesh-45 force-pushed the pull/6056-file-upload branch from d407f3b to 7f87361 Compare April 3, 2026 07:01
…ation. Introduced 'source' field to determine proxy type (manual or PAC) and updated related validation and state management. Removed deprecated 'pacUrl' field in favor of 'pac.source'. Updated preferences schema and test data accordingly.
…PAC configuration. Adjusted state management and validation logic to align with new structure. Enhanced tests for backward compatibility and new format handling.
…ide context for proxy settings. Updated related functions to accommodate the new parameter and improved logging for proxy mode changes.
… it with 'source' for better clarity. Adjusted validation schema, default preferences, and migration logic to align with the new structure. Enhanced tests to ensure compatibility with the updated proxy configuration.
lohit-bruno
lohit-bruno previously approved these changes Apr 6, 2026
lohit-bruno
lohit-bruno previously approved these changes Apr 6, 2026
sid-bruno
sid-bruno previously approved these changes Apr 6, 2026
Comment thread tests/proxy/pac/pac-proxy.spec.ts Resolved
Comment thread tests/proxy/pac/pac-proxy.spec.ts Resolved
@bijin-bruno
bijin-bruno merged commit 58942b3 into usebruno:main Apr 7, 2026
11 checks passed
maxenceleblanc pushed a commit to maxenceleblanc/curly_cats2 that referenced this pull request Jul 20, 2026
* Add proxy .pac file resolver

chore(dependencies): update package-lock.json with new dependencies and version upgrades

- Added new dependencies: ajv, git-url-parse, @opencollection/types, and storybook packages.
- Updated existing dependencies to their latest versions, including eslint and babel packages.
- Removed deprecated entries and cleaned up the package-lock structure for better maintainability.

* tests

* wip

* wip

* wip

* wip

* feat: file upload .pac

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* feat: Refactor proxy settings to use a new structure for PAC configuration. Introduced 'source' field to determine proxy type (manual or PAC) and updated related validation and state management. Removed deprecated 'pacUrl' field in favor of 'pac.source'. Updated preferences schema and test data accordingly.

* fix: Update proxy settings to correctly reference 'source' field for PAC configuration. Adjusted state management and validation logic to align with new structure. Enhanced tests for backward compatibility and new format handling.

* feat: Enhance proxy configuration by adding 'proxyModeReason' to provide context for proxy settings. Updated related functions to accommodate the new parameter and improved logging for proxy mode changes.

* wip

* refactor: Update proxy settings to remove 'inherit' field and replace it with 'source' for better clarity. Adjusted validation schema, default preferences, and migration logic to align with the new structure. Enhanced tests to ensure compatibility with the updated proxy configuration.

* wip

* wip

* wip

* wip

* wip

* chore: consistent path check

* chore: consistency

* tests(pac): fix unit params

---------

Co-authored-by: Gianluca D'Abrosca <[email protected]>
Co-authored-by: Sid <[email protected]>
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