Repository navigation
Feat: Support PAC file upload - #7651
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdds 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 Changes
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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 | 🔴 CriticalFix const reassignment at line 270.
Line 270 declares
const timeline, but line 425 attempts to reassign it withtimeline = err.timeline;. This throws a runtime error. Change line 270 tolet timelineto 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
/proxiedrequests through the test proxy and returnsDIRECTfor 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:
This file uses 4-space indentation and double quotes, while
tests/proxy/pac/fixtures/pac-files/test.pacuses 2-space indentation and single quotes.This file uses
127.0.0.1:18888while the other useslocalhost:18888. While functionally equivalent in most cases, using127.0.0.1consistently 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 addingdata-testidattributes for e2e testability.The PAC URL input and Browse button lack
data-testidattributes. 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 mirrorspathToFileURLbehavior 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 bothhttpAgentandhttpsAgent. 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:
JSDoc inside function body (lines 60-67): Unconventional placement. Moving it above the function signature would enable IDE hover-docs at call sites.
Falsy defaults on lines 73 and 89: Using
||meanscacheTtlMs: 0ortimeoutMs: 0would fall back to defaults. If explicit zero should be honored, use??.Neither is critical—
0timeout is impractical, and disabling cache viacacheTtlMs: 0is 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
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (19)
packages/bruno-app/src/components/Preferences/ProxySettings/index.jspackages/bruno-common/package.jsonpackages/bruno-electron/package.jsonpackages/bruno-electron/src/ipc/network/axios-instance.jspackages/bruno-electron/src/ipc/network/cert-utils.jspackages/bruno-electron/src/store/preferences.jspackages/bruno-electron/src/utils/pac-resolver.jspackages/bruno-electron/src/utils/proxy-util.jspackages/bruno-electron/test/pac-resolver.test.jspackages/bruno-electron/test/proxy-util.test.jstests/proxy/pac/fixtures/collection/bruno.jsontests/proxy/pac/fixtures/collection/direct.brutests/proxy/pac/fixtures/collection/proxied.brutests/proxy/pac/fixtures/pac-files/test.pactests/proxy/pac/init-user-data-file/preferences.jsontests/proxy/pac/init-user-data/preferences.jsontests/proxy/pac/pac-proxy.spec.tstests/proxy/pac/server/index.tstests/proxy/pac/server/pac-files/test.pac
There was a problem hiding this comment.
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
pacUrlbut differenthttpsAgentRequestFields(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.responseis 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.
proxyModeis a separateuseStateinitialized from preferences but not updated whenformik.valueschange externally (e.g.,formik.resetForm). Consider derivingproxyModedirectly fromformik.valuesinstead: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
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (11)
packages/bruno-app/src/components/Preferences/ProxySettings/StyledWrapper.jspackages/bruno-app/src/components/Preferences/ProxySettings/index.jspackages/bruno-common/package.jsonpackages/bruno-common/rollup.config.jspackages/bruno-common/src/net/index.tspackages/bruno-common/src/net/pac-resolver.spec.tspackages/bruno-common/src/net/pac-resolver.tspackages/bruno-electron/package.jsonpackages/bruno-electron/src/utils/proxy-util.jspackages/bruno-requests/package.jsonpackages/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
There was a problem hiding this comment.
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 followshttps→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
📒 Files selected for processing (2)
packages/bruno-common/rollup.config.jspackages/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
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
packages/bruno-common/src/net/pac-resolver.tspackages/bruno-electron/test/proxy-util.test.js
✅ Files skipped from review due to trivial changes (1)
- packages/bruno-electron/test/proxy-util.test.js
sid-bruno
left a comment
There was a problem hiding this comment.
Waiting on @lohit-bruno's to confirm things on the proxy layer
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.
d407f3b to
7f87361
Compare
…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.
* 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]>
Description
This PR is an extension of #7633, which was implemented to add a
.pacfile upload option with the.pacURL fetch.Contribution Checklist:
Summary by CodeRabbit
New Features
Tests
Chores