Repository navigation
feat: use default browser for oauth2 authorization bru-2167 - #6101
Conversation
bru-2167default browser for oauth2 authorization bru-2167
b1c99e5 to
330875c
Compare
330875c to
539fcff
Compare
539fcff to
8fe3748
Compare
WalkthroughAdds end-to-end system-browser OAuth2 support: new preference, UI toggles, renderer actions to poll/cancel authorization, new IPC channels and handlers, Electron deeplink routing, an in-flight protocol handler, and system-browser authorization flow integration across app and electron processes. Changes
Sequence Diagram(s)sequenceDiagram
actor User
participant Renderer as Bruno Renderer
participant Main as Electron Main
participant Protocol as OAuth2 Protocol Handler
participant Browser as System Browser
User->>Renderer: Click "Get Access Token" (system browser enabled)
Renderer->>Main: IPC: renderer:refresh-oauth2-credentials (start auth)
Main->>Protocol: registerOauth2AuthorizationRequest(resolve,reject,debugInfo)
Main->>Browser: shell.openExternal(authorizeUrl?redirect_uri=callback)
Browser->>User: OAuth provider UI
User->>Browser: Approve — provider redirects to bruno://oauth2/callback...
Browser->>Main: OS delivers URL (open-url / argv)
Main->>Protocol: handleOauth2ProtocolUrl(bruno://...callback...)
Protocol-->>Main: resolve/reject in-flight request (code or tokens)
Main-->>Renderer: IPC response with authorization result
Renderer->>Renderer: Exchange token / update UI / show toast
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes
Suggested reviewers
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/bruno-app/src/components/Preferences/General/index.js (1)
126-131: Toast error on preferences save failure never firesThe
.catchonsavePreferencesusesconsole.log(err) && toast.error('Failed to update preferences'). Sinceconsole.logreturnsundefined(falsy), thetoast.errorbranch is never executed, so users won’t see a failure notification.Consider rewriting the catch to always log and always show the toast:
- .catch((err) => console.log(err) && toast.error('Failed to update preferences')); + .catch((err) => { + console.log(err); + toast.error('Failed to update preferences'); + });
🧹 Nitpick comments (9)
packages/bruno-app/src/components/RequestPane/Auth/OAuth2/AuthorizationCode/index.js (1)
5-5: AuthorizationCode now respects system-browser preferenceReading
state.app.preferences.request.oauth2.useSystemBrowserand surfacing it viauseSystemBrowserplus the dedicated Callback URL editor is consistent with the new preference shape and existinghandleChange/handleSavebehavior.If you want to trim render noise a bit, you could conditionally render the helper text instead of always rendering an empty
<div>whenuseSystemBrowseris false.Also applies to: 18-21, 138-155
packages/bruno-app/src/components/RequestPane/Auth/OAuth2/Implicit/index.js (1)
4-4: Implicit flow callback handling aligned with system-browser preferenceThe new
useSelectorusage,useSystemBrowserderivation, and dedicated Callback URL editor integrate cleanly with the existing auth state update logic and mirror the Authorization Code flow.You might consider extracting the Callback URL editor + helper into a small shared component between AuthorizationCode and Implicit to avoid duplicating markup and behavior.
Also applies to: 17-20, 93-110
packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js (1)
2551-2567: Simplify OAuth2 authorization progress/cancel thunksBoth
isOauth2AuthorizationRequestInProgressandcancelOauth2AuthorizationRequestare thunks that don’t usedispatch/getStateand wrapipcRenderer.invokein an extraasync+new Promiselayer. You can simplify them to match other IPC helpers in this file and avoid the redundant Promise wrapping:-export const isOauth2AuthorizationRequestInProgress = () => async () => { - return new Promise((resolve, reject) => { - window.ipcRenderer - .invoke('renderer:is-oauth2-authorization-request-in-progress') - .then(resolve) - .catch(reject); - }); -}; - -export const cancelOauth2AuthorizationRequest = () => async () => { - return new Promise((resolve, reject) => { - window.ipcRenderer - .invoke('renderer:cancel-oauth2-authorization-request') - .then(resolve) - .catch(reject); - }); -}; +export const isOauth2AuthorizationRequestInProgress = () => () => { + return window.ipcRenderer.invoke('renderer:is-oauth2-authorization-request-in-progress'); +}; + +export const cancelOauth2AuthorizationRequest = () => () => { + return window.ipcRenderer.invoke('renderer:cancel-oauth2-authorization-request'); +};Behavior for callers (
dispatch(isOauth2AuthorizationRequestInProgress())) remains a Promise-returning thunk.packages/bruno-electron/src/utils/deeplink.js (1)
1-30: Deeplink handling for OAuth2 callbacks looks sound
getAppProtocolUrlFromArgvandhandleAppProtocolUrlcorrectly pick upbruno://URLs and route/oauth2/callbackpaths intohandleOauth2ProtocolUrl, with defensive parsing and error logging.If you ever expect this helper to be called with arbitrary URLs, you might optionally tighten
isOauth2Urlto also verifyurlObj.protocol === 'bruno:'so that plainhttps://.../oauth2/callbacklinks aren’t misclassified.packages/bruno-electron/src/index.js (1)
97-100: Silent error swallowing in xdg-mime registration.The empty catch block silently ignores failures in the
xdg-mimecommand. Consider logging the error for debugging purposes.try { execSync('xdg-mime default bruno.desktop x-scheme-handler/bruno'); - } catch (err) {} + } catch (err) { + console.warn('Failed to register bruno protocol handler via xdg-mime:', err.message); + }packages/bruno-app/src/components/RequestPane/Auth/OAuth2/Oauth2ActionButtons/index.js (2)
21-33: Single status check may miss state changes.The
useEffectonly checks authorization status once whenfetchingTokenbecomes true. If the authorization request starts after this check,fetchingAuthorizationCodewon't update. Consider polling or using an IPC event listener for real-time updates.useEffect(() => { if (useSystemBrowser && fetchingToken) { + const interval = setInterval(async () => { + try { + const inProgress = await dispatch(isOauth2AuthorizationRequestInProgress()); + toggleFetchingAuthorizationCode(inProgress); + if (!inProgress) { + clearInterval(interval); + } + } catch (err) { + console.error('Error checking pending authorization:', err); + } + }, 500); + return () => clearInterval(interval); - const getRequestStatus = async () => { - try { - toggleFetchingAuthorizationCode(await dispatch(isOauth2AuthorizationRequestInProgress())); - } catch (err) { - console.error('Error checking pending authorization:', err); - } - }; - getRequestStatus(); } }, [useSystemBrowser, fetchingToken, dispatch]);
120-132: Cancel authorization handler.Implementation looks correct. Minor note:
toast.errorfor cancellation might be confusing since it's a user action, not an error. Considertoast.successor a neutral message.if (result.success && result.cancelled) { - toast.error('Authorization cancelled'); + toast.success('Authorization cancelled'); toggleFetchingToken(false); toggleFetchingAuthorizationCode(false); }packages/bruno-electron/src/utils/oauth2.js (2)
176-183: Redundant validation check.Since
effectiveCallbackUrlis always set (either fromcallbackUrlorBRUNO_OAUTH2_CALLBACK_URL), this check will never trigger. Consider removing or adjusting this validation.- if (!effectiveCallbackUrl) { - return { - error: 'Callback URL is required for OAuth2 authorization code flow', - credentials: null, - url, - credentialsId - }; - }
766-773: Same redundant validation in implicit flow.Same issue as authorization code flow—this check is unreachable given
effectiveCallbackUrlalways has a value.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (15)
packages/bruno-app/src/components/Preferences/General/index.js(4 hunks)packages/bruno-app/src/components/RequestPane/Auth/OAuth2/AuthorizationCode/index.js(3 hunks)packages/bruno-app/src/components/RequestPane/Auth/OAuth2/AuthorizationCode/inputsConfig.js(0 hunks)packages/bruno-app/src/components/RequestPane/Auth/OAuth2/Implicit/index.js(3 hunks)packages/bruno-app/src/components/RequestPane/Auth/OAuth2/Implicit/inputsConfig.js(0 hunks)packages/bruno-app/src/components/RequestPane/Auth/OAuth2/Oauth2ActionButtons/index.js(4 hunks)packages/bruno-app/src/providers/ReduxStore/slices/app.js(1 hunks)packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js(1 hunks)packages/bruno-electron/src/index.js(4 hunks)packages/bruno-electron/src/ipc/collection.js(2 hunks)packages/bruno-electron/src/ipc/network/authorize-user-in-system-browser.js(1 hunks)packages/bruno-electron/src/store/preferences.js(3 hunks)packages/bruno-electron/src/utils/deeplink.js(1 hunks)packages/bruno-electron/src/utils/oauth2-protocol-handler.js(1 hunks)packages/bruno-electron/src/utils/oauth2.js(10 hunks)
💤 Files with no reviewable changes (2)
- packages/bruno-app/src/components/RequestPane/Auth/OAuth2/AuthorizationCode/inputsConfig.js
- packages/bruno-app/src/components/RequestPane/Auth/OAuth2/Implicit/inputsConfig.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()notfunc ()
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/RequestPane/Auth/OAuth2/AuthorizationCode/index.jspackages/bruno-app/src/providers/ReduxStore/slices/app.jspackages/bruno-electron/src/ipc/network/authorize-user-in-system-browser.jspackages/bruno-app/src/providers/ReduxStore/slices/collections/actions.jspackages/bruno-electron/src/utils/oauth2-protocol-handler.jspackages/bruno-app/src/components/Preferences/General/index.jspackages/bruno-electron/src/store/preferences.jspackages/bruno-app/src/components/RequestPane/Auth/OAuth2/Oauth2ActionButtons/index.jspackages/bruno-app/src/components/RequestPane/Auth/OAuth2/Implicit/index.jspackages/bruno-electron/src/index.jspackages/bruno-electron/src/utils/deeplink.jspackages/bruno-electron/src/utils/oauth2.jspackages/bruno-electron/src/ipc/collection.js
🧠 Learnings (2)
📓 Common learnings
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.
📚 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/oauth2-protocol-handler.jspackages/bruno-app/src/components/Preferences/General/index.jspackages/bruno-electron/src/store/preferences.jspackages/bruno-electron/src/utils/oauth2.jspackages/bruno-electron/src/ipc/collection.js
🧬 Code graph analysis (6)
packages/bruno-electron/src/ipc/network/authorize-user-in-system-browser.js (2)
packages/bruno-electron/src/utils/oauth2.js (5)
authorizeUrl(852-852)debugInfo(482-482)debugInfo(631-631)debugInfo(678-678)error(79-79)packages/bruno-electron/src/utils/oauth2-protocol-handler.js (3)
rejectOauth2AuthorizationRequest(30-37)error(70-70)registerOauth2AuthorizationRequest(3-15)
packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js (7)
packages/bruno-electron/src/utils/oauth2-protocol-handler.js (1)
isOauth2AuthorizationRequestInProgress(17-19)packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js (1)
window(18-18)packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js (1)
window(2586-2586)packages/bruno-app/src/utils/exporters/bruno-environment.js (1)
window(5-5)packages/bruno-app/src/utils/network/ws-event-listeners.js (1)
window(8-8)packages/bruno-app/src/utils/common/ipc.js (1)
window(8-8)packages/bruno-app/src/providers/App/ConfirmAppClose/index.js (1)
window(7-7)
packages/bruno-electron/src/utils/oauth2-protocol-handler.js (4)
packages/bruno-electron/src/utils/oauth2.js (11)
debugInfo(482-482)debugInfo(631-631)debugInfo(678-678)data(260-264)data(464-466)data(611-615)data(653-656)url(155-155)url(382-382)url(510-510)url(645-645)packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js (2)
isOauth2AuthorizationRequestInProgress(2551-2558)isOauth2AuthorizationRequestInProgress(2551-2558)packages/bruno-electron/src/utils/deeplink.js (1)
urlObj(19-19)packages/bruno-electron/src/ipc/network/axios-instance.js (1)
URL(1-1)
packages/bruno-app/src/components/RequestPane/Auth/OAuth2/Oauth2ActionButtons/index.js (4)
packages/bruno-app/src/components/RequestPane/Auth/OAuth2/AuthorizationCode/index.js (3)
dispatch(17-17)preferences(18-18)useSystemBrowser(20-20)packages/bruno-app/src/components/RequestPane/Auth/OAuth2/index.js (1)
dispatch(14-14)packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js (4)
isOauth2AuthorizationRequestInProgress(2551-2558)isOauth2AuthorizationRequestInProgress(2551-2558)cancelOauth2AuthorizationRequest(2560-2567)cancelOauth2AuthorizationRequest(2560-2567)packages/bruno-electron/src/utils/oauth2-protocol-handler.js (1)
isOauth2AuthorizationRequestInProgress(17-19)
packages/bruno-electron/src/utils/deeplink.js (1)
packages/bruno-electron/src/utils/oauth2-protocol-handler.js (3)
handleOauth2ProtocolUrl(43-112)urlObj(45-45)error(70-70)
packages/bruno-electron/src/utils/oauth2.js (2)
packages/bruno-electron/src/store/preferences.js (1)
preferencesUtil(184-239)packages/bruno-electron/src/ipc/network/authorize-user-in-system-browser.js (1)
authorizeUserInSystemBrowser(4-64)
🪛 Biome (2.1.2)
packages/bruno-electron/src/ipc/network/authorize-user-in-system-browser.js
[error] 5-63: Promise executor functions should not be async.
(lint/suspicious/noAsyncPromiseExecutor)
⏰ 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 - Linux
- GitHub Check: SSL Tests - macOS
- GitHub Check: Unit Tests
- GitHub Check: Playwright E2E Tests
- GitHub Check: CLI Tests
🔇 Additional comments (19)
packages/bruno-electron/src/store/preferences.js (1)
23-26: System browser OAuth2 preference wiring looks consistent
request.oauth2.useSystemBrowseris now defined in defaults, validated in the schema, and exposed viapreferencesUtil.shouldUseSystemBrowser, all using the same path and default. This should merge cleanly with existing preferences without breaking older configs.Also applies to: 72-75, 209-211
packages/bruno-app/src/providers/ReduxStore/slices/app.js (1)
26-29: Initial Redux preferences extended correctly for OAuth2Adding
timeout: 0andoauth2.useSystemBrowserunderpreferences.requestmatches the Electron-side defaults and keeps the shape consistent for selectors.packages/bruno-app/src/components/Preferences/General/index.js (1)
59-61: OAuth2 system-browser preference is correctly threaded through the General formThe new
oauth2.useSystemBrowserfield is:
- Validated in the local
preferencesSchema- Initialized from
preferences.request.oauth2.useSystemBrowser- Persisted under
request.oauth2.useSystemBrowserin the payload tosavePreferences- Exposed via a dedicated checkbox in the General preferences UI
That end-to-end path matches the Electron preferences schema and the consumers in the OAuth2 flows.
Also applies to: 82-84, 98-117, 270-282
packages/bruno-electron/src/index.js (3)
113-119: Windows/Linux second-instance handler.Implementation correctly extracts protocol URL from argv on subsequent launches. The fallback to existing
appProtocolUrlis appropriate.
232-236: Protocol URL handling after window load.Good placement—ensures the renderer is ready before sending protocol URL data.
104-111: macOS protocol URL handler implementation requires verification.The code snippet correctly prevents default behavior and routes the URL through
handleAppProtocolUrl. However, the claim thathandleAppProtocolUrlincludes "a conditional check formainWindow" to handle cases where the window isn't ready cannot be verified without inspecting the actual implementation of that function. Please confirm thathandleAppProtocolUrlinpackages/bruno-electron/src/utils/deeplink.jsproperly validatesmainWindowbefore use.packages/bruno-app/src/components/RequestPane/Auth/OAuth2/Oauth2ActionButtons/index.js (2)
68-76: Good UX: suppress toast for user-initiated cancellation.Correctly avoids showing an error toast when the user deliberately cancels authorization.
154-163: Cancel button conditional rendering.Correctly shows the cancel button only when using system browser and authorization is in progress.
packages/bruno-electron/src/ipc/collection.js (3)
1328-1359: Refresh OAuth2 credentials handler.Implementation follows the established pattern for OAuth2 credential operations. Properly clones request, interpolates variables, and calls
refreshOauth2Token.
1361-1368: Cancel authorization IPC handler.Good error handling with try-catch, returning a structured response object for both success and failure cases.
1370-1372: Authorization progress check.Simple synchronous check. Works correctly for the use case.
packages/bruno-electron/src/utils/oauth2.js (5)
154-154: Effective callback URL computation.Good fallback logic to use Bruno's default callback URL when none is provided.
337-343: System browser authorize function selection.Clean conditional selection between system browser and in-window authorization.
461-463: Client credentials: basic auth with clientSecret check.Good fix—only sets basic auth header when
clientSecretis present, which aligns with the learning that clientSecret is optional.
855-862: Implicit grant system browser support.Correctly implements system browser flow for implicit grant with proper function selection.
11-11: Remove or clarify the hardcoded callback URL constant.The hardcoded
https://oauth2.usebruno.com/callbackis not a public callback endpoint; Bruno intercepts OAuth2 redirects locally instead. If this constant serves as a default fallback, verify its necessity or document its actual purpose to avoid confusion.packages/bruno-electron/src/utils/oauth2-protocol-handler.js (3)
1-15: OAuth2 request state management.Clean implementation for managing a single in-flight authorization request. Automatic cancellation of previous requests when a new one starts prevents state inconsistencies.
43-112: Protocol URL handler implementation.Well-structured handler supporting both authorization code and implicit grant flows. Properly extracts error information from both query params and hash fragments.
114-120: Module exports.Note:
resolveOauth2AuthorizationRequestis not exported but is only used internally. This is fine since external callers should usehandleOauth2ProtocolUrlinstead.
There was a problem hiding this comment.
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/oauth2.js (1)
300-349: Remove async Promise executor antipattern.Using
async (resolve, reject) => {...}as a Promise executor is problematic because errors thrown inside the async function won't properly reject the outer Promise. The only async operation here is theauthorizeFunctioncall, which is already wrapped in try-catch.Refactor to eliminate the async executor:
const getOAuth2AuthorizationCode = (request, codeChallenge, collectionUid) => { - return new Promise(async (resolve, reject) => { + return new Promise((resolve, reject) => { const { oauth2 } = request; const { callbackUrl, clientId, authorizationUrl, scope, state, pkce, accessTokenUrl, additionalParameters } = oauth2; const useSystemBrowser = preferencesUtil.shouldUseSystemBrowser(); const effectiveCallbackUrl = callbackUrl && callbackUrl.length ? callbackUrl : BRUNO_OAUTH2_CALLBACK_URL; const authorizationUrlWithQueryParams = new URL(authorizationUrl); authorizationUrlWithQueryParams.searchParams.append('response_type', 'code'); authorizationUrlWithQueryParams.searchParams.append('client_id', clientId); if (effectiveCallbackUrl) { authorizationUrlWithQueryParams.searchParams.append('redirect_uri', effectiveCallbackUrl); } if (scope) { authorizationUrlWithQueryParams.searchParams.append('scope', scope); } if (pkce) { authorizationUrlWithQueryParams.searchParams.append('code_challenge', codeChallenge); authorizationUrlWithQueryParams.searchParams.append('code_challenge_method', 'S256'); } if (state) { authorizationUrlWithQueryParams.searchParams.append('state', state); } if (additionalParameters?.authorization?.length) { additionalParameters.authorization.forEach((param) => { if (param.enabled && param.name) { if (param.sendIn === 'queryparams') { authorizationUrlWithQueryParams.searchParams.append(param.name, param.value || ''); } } }); } - try { - const authorizeUrl = authorizationUrlWithQueryParams.toString(); - const authorizeFunction = useSystemBrowser ? authorizeUserInSystemBrowser : authorizeUserInWindow; - const { authorizationCode, debugInfo } = await authorizeFunction({ - authorizeUrl, - callbackUrl: effectiveCallbackUrl, - session: oauth2Store.getSessionIdOfCollection({ collectionUid, url: accessTokenUrl }), - additionalHeaders: getAdditionalHeaders(additionalParameters?.authorization) - }); - resolve({ authorizationCode, debugInfo }); - } catch (err) { - reject(err); - } + const authorizeUrl = authorizationUrlWithQueryParams.toString(); + const authorizeFunction = useSystemBrowser ? authorizeUserInSystemBrowser : authorizeUserInWindow; + authorizeFunction({ + authorizeUrl, + callbackUrl: effectiveCallbackUrl, + session: oauth2Store.getSessionIdOfCollection({ collectionUid, url: accessTokenUrl }), + additionalHeaders: getAdditionalHeaders(additionalParameters?.authorization) + }).then(({ authorizationCode, debugInfo }) => { + resolve({ authorizationCode, debugInfo }); + }).catch(reject); }); };
♻️ Duplicate comments (2)
packages/bruno-electron/src/utils/oauth2.js (2)
256-258: Basic auth header still missing optionalclientSecretfallback.When
credentialsPlacement === 'basic_auth_header', the Authorization header is constructed without handling the case whereclientSecretis optional. This contrasts with line 461 (client credentials flow) which correctly checks forclientSecretpresence, and line 670 (refresh token) which uses theclientSecret || ''pattern.Based on learnings, apply the fallback pattern:
if (credentialsPlacement === 'basic_auth_header') { - axiosRequestConfig.headers['Authorization'] = `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`; + axiosRequestConfig.headers['Authorization'] = `Basic ${Buffer.from(`${clientId}:${clientSecret || ''}`).toString('base64')}`; }
154-154: Verify the fallback behavior foreffectiveCallbackUrl.The
effectiveCallbackUrlalways falls back toBRUNO_OAUTH2_CALLBACK_URLwhencallbackUrlis not provided. This makes the subsequent validation checks at lines 176-183 (and similar checks at lines 766-773 for implicit grant) unreachable, sinceeffectiveCallbackUrlwill never be falsy.Consider whether:
- The validation should be removed as dead code, or
- The fallback to
BRUNO_OAUTH2_CALLBACK_URLshould be conditional (e.g., only applied for system browser flows)For clarity, you could either remove the unreachable validations or restructure the fallback logic:
-const effectiveCallbackUrl = callbackUrl && callbackUrl.length ? callbackUrl : BRUNO_OAUTH2_CALLBACK_URL; +const effectiveCallbackUrl = callbackUrl && callbackUrl.length ? callbackUrl : (useSystemBrowser ? BRUNO_OAUTH2_CALLBACK_URL : null);Or simply remove the dead validation code:
-if (!effectiveCallbackUrl) { - return { - error: 'Callback URL is required for OAuth2 authorization code flow', - credentials: null, - url, - credentialsId - }; -}
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
packages/bruno-electron/src/ipc/network/authorize-user-in-system-browser.js(1 hunks)packages/bruno-electron/src/utils/oauth2-protocol-handler.js(1 hunks)packages/bruno-electron/src/utils/oauth2.js(11 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. 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()notfunc ()
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-electron/src/utils/oauth2.jspackages/bruno-electron/src/utils/oauth2-protocol-handler.jspackages/bruno-electron/src/ipc/network/authorize-user-in-system-browser.js
🧠 Learnings (2)
📓 Common learnings
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.
📚 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/oauth2.jspackages/bruno-electron/src/utils/oauth2-protocol-handler.js
🧬 Code graph analysis (3)
packages/bruno-electron/src/utils/oauth2.js (2)
packages/bruno-electron/src/store/preferences.js (1)
preferencesUtil(184-239)packages/bruno-electron/src/ipc/network/authorize-user-in-system-browser.js (1)
authorizeUserInSystemBrowser(4-61)
packages/bruno-electron/src/utils/oauth2-protocol-handler.js (3)
packages/bruno-electron/src/utils/oauth2.js (11)
debugInfo(482-482)debugInfo(631-631)debugInfo(678-678)data(260-264)data(464-466)data(611-615)data(653-656)url(155-155)url(382-382)url(510-510)url(645-645)packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js (2)
isOauth2AuthorizationRequestInProgress(2551-2558)isOauth2AuthorizationRequestInProgress(2551-2558)packages/bruno-electron/src/utils/deeplink.js (1)
urlObj(19-19)
packages/bruno-electron/src/ipc/network/authorize-user-in-system-browser.js (2)
packages/bruno-electron/src/utils/oauth2.js (10)
require(1-1)require(3-3)require(4-4)require(6-6)require(7-7)require(8-8)debugInfo(482-482)debugInfo(631-631)debugInfo(678-678)error(79-79)packages/bruno-electron/src/utils/oauth2-protocol-handler.js (3)
rejectOauth2AuthorizationRequest(30-37)error(70-70)registerOauth2AuthorizationRequest(3-15)
⏰ 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 - Windows
- GitHub Check: SSL Tests - Linux
- GitHub Check: SSL Tests - macOS
🔇 Additional comments (2)
packages/bruno-electron/src/ipc/network/authorize-user-in-system-browser.js (1)
1-63: LGTM! Clean system browser authorization implementation.The flow correctly integrates with the OAuth2 protocol handler, properly manages timeouts via wrapped callbacks, and handles both authorization code and implicit grant types. The async executor antipattern flagged in previous reviews has been resolved.
packages/bruno-electron/src/utils/oauth2-protocol-handler.js (1)
110-111: Good addition of fallback rejection.The fallback rejection when neither
codenoraccess_tokenis present properly addresses the past review feedback and prevents requests from hanging on unrecognized callback formats.
There was a problem hiding this comment.
Actionable comments posted: 0
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/electron-builder-config.js (1)
90-101: Windows section missingprotocolsregistration for installer integration.The
winconfiguration lacks theprotocolsentry that exists inmacandlinuxblocks. Whileapp.setAsDefaultProtocolClient('bruno')registers the protocol at runtime when the app starts, the build configuration should includeprotocolsfor proper installer-level registration. This ensures thebruno://scheme is available immediately after NSIS installation, rather than only after the app's first launch—which could cause issues if an OAuth2 callback is triggered before the app runs.Add to the
winblock:protocols: [ { name: 'bruno', schemes: ['bruno'] } ]
🧹 Nitpick comments (2)
packages/bruno-electron/electron-builder-config.js (2)
38-45: Protocol name casing inconsistency between macOS and Linux.macOS uses
name: 'bruno'(lowercase) while Linux usesname: 'Bruno'(capitalized). While theschemesarray is consistent, the display name differs. Minor, but worth aligning for consistency.protocols: [ { - name: 'Bruno', + name: 'bruno', schemes: ['bruno'] } ],Also applies to: 64-69
70-70: Consider usingDevelopmentcategory for Linux.macOS uses
public.app-category.developer-tools, but Linux is set toUtility. For consistency and accurate classification in Linux app menus,Developmentwould be more appropriate for a developer tool.- category: 'Utility', + category: 'Development',
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
packages/bruno-electron/electron-builder-config.js(1 hunks)packages/bruno-electron/src/index.js(4 hunks)packages/bruno-electron/src/utils/oauth2-protocol-handler.js(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/bruno-electron/src/utils/oauth2-protocol-handler.js
- packages/bruno-electron/src/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()notfunc ()
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-electron/electron-builder-config.js
🧠 Learnings (1)
📓 Common learnings
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.
⏰ 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 - macOS
- GitHub Check: SSL Tests - Linux
- GitHub Check: SSL Tests - Windows
- GitHub Check: CLI Tests
- GitHub Check: Unit Tests
- GitHub Check: Playwright E2E Tests
🔇 Additional comments (2)
packages/bruno-electron/electron-builder-config.js (2)
37-37: Verifynotarize: falseis intentional.Disabling notarization means macOS users may encounter Gatekeeper warnings or be unable to open the app without manual workarounds (Catalina+). If this is a temporary dev setting, consider gating it via an environment variable rather than hardcoding
false.
48-63: Multi-arch targets and desktop integration look good.The restructured
targetarray properly supports x64 and arm64 for all Linux package formats. TheMimeTypedeclaration correctly registers the app as a handler forx-scheme-handler/bruno.Also applies to: 71-73
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
packages/bruno-electron/electron-builder-config.js (1)
48-73: Linux configuration looks good.The changes align well with the OAuth2 system-browser feature:
- Artifact naming now consistent with macOS (includes
${os})- Target structure properly expanded to support multi-arch builds (x64, arm64)
- Protocol registration and desktop MIME type configuration are correct for Linux URL scheme handling
- Category 'Development' is appropriate
Optional: Consider extracting the protocols configuration to reduce duplication between mac and linux sections:
+const brunoProtocols = [ + { + name: 'Bruno', + schemes: ['bruno'] + } +]; + const config = { // ... mac: { // ... - protocols: [ - { - name: 'Bruno', - schemes: ['bruno'] - } - ] + protocols: brunoProtocols }, linux: { // ... - protocols: [ - { - name: 'Bruno', - schemes: ['bruno'] - } - ], + protocols: brunoProtocols, // ... } };
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
packages/bruno-electron/electron-builder-config.js(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. 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()notfunc ()
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-electron/electron-builder-config.js
🧠 Learnings (1)
📓 Common learnings
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.
⏰ 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). (5)
- GitHub Check: Playwright E2E Tests
- GitHub Check: CLI Tests
- GitHub Check: SSL Tests - Windows
- GitHub Check: SSL Tests - Linux
- GitHub Check: SSL Tests - macOS
🔇 Additional comments (1)
packages/bruno-electron/electron-builder-config.js (1)
37-45: No action needed. Thenotarize: falseon line 37 andafterSign: 'notarize.js'on line 18 are not contradictory—they work together intentionally. TheafterSignhook invokes the custom notarize script, whilenotarize: falsedisables electron-builder's built-in notarization in favor of this custom implementation. The script properly guards against non-macOS platforms and handles credentials via environment variables. The protocol configuration is also correct.Likely an incorrect or invalid review comment.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
packages/bruno-app/src/components/RequestPane/Auth/OAuth2/Implicit/index.js (1)
19-22: Mirror the safer preferences update pattern used in the authorization-code flow
handleUseSystemBrowserTogglehere has the same assumption aboutpreferences.request.oauth2always existing as in the Authorization Code component. Apply the same defensiverequest/oauth2fallbacks there as well so both flows behave identically and won’t crash on legacy/partial preference objects.Also applies to: 84-105
🧹 Nitpick comments (2)
packages/bruno-app/src/components/SingleLineEditor/index.js (1)
189-191: Keep placeholder update consistent with mount behaviorOn mount you normalize
placeholderwiththis.props.placeholder ?? '', but incomponentDidUpdateyou now passthis.props.placeholderdirectly. Consider mirroring the same?? ''fallback here to keep behavior consistent when the prop isundefined.- if (this.props.placeholder !== prevProps.placeholder && this.editor) { - this.editor.setOption('placeholder', this.props.placeholder); - } + if (this.props.placeholder !== prevProps.placeholder && this.editor) { + this.editor.setOption('placeholder', this.props.placeholder ?? ''); + }packages/bruno-app/src/components/RequestPane/Auth/OAuth2/AuthorizationCode/index.js (1)
19-23: The nested field access inhandleUseSystemBrowserToggleis safe, but defensive coding is still worth consideringThe app's Redux initial state (in
app.js) guarantees thatpreferences.request.oauth2exists from store initialization. Since the handler updates viasavePreferences, which replaces the entire preferences object while maintaining the structure, the spreading operations at lines 132–140 will not crash.However, if preferences are ever loaded from legacy storage or partially updated in the future, adding defensive fallbacks would prevent regressions:
const handleUseSystemBrowserToggle = (e) => { const newValue = e.target.checked; + const currentRequest = preferences.request || {}; + const currentOauth2 = currentRequest.oauth2 || {}; + dispatch( savePreferences({ ...preferences, request: { - ...preferences.request, + ...currentRequest, oauth2: { - ...preferences.request.oauth2, + ...currentOauth2, useSystemBrowser: newValue } } }) )The codebase already uses
get()with defaults (line 22), suggesting the team values this pattern. Applying it here maintains consistency, though it's not strictly required given the current structure.Also applies to: 129–150
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
packages/bruno-app/src/components/RequestPane/Auth/OAuth2/AuthorizationCode/index.js(4 hunks)packages/bruno-app/src/components/RequestPane/Auth/OAuth2/Implicit/index.js(4 hunks)packages/bruno-app/src/components/SingleLineEditor/index.js(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. 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()notfunc ()
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/SingleLineEditor/index.jspackages/bruno-app/src/components/RequestPane/Auth/OAuth2/AuthorizationCode/index.jspackages/bruno-app/src/components/RequestPane/Auth/OAuth2/Implicit/index.js
🧠 Learnings (1)
📓 Common learnings
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.
🧬 Code graph analysis (1)
packages/bruno-app/src/components/RequestPane/Auth/OAuth2/AuthorizationCode/index.js (2)
packages/bruno-app/src/components/RequestPane/Auth/OAuth2/Implicit/index.js (4)
dispatch(19-19)preferences(20-20)useSystemBrowser(21-21)handleUseSystemBrowserToggle(84-105)packages/bruno-app/src/providers/ReduxStore/slices/app.js (2)
savePreferences(152-162)savePreferences(152-162)
⏰ 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 - macOS
- GitHub Check: SSL Tests - Linux
- GitHub Check: SSL Tests - Windows
🔇 Additional comments (2)
packages/bruno-app/src/components/RequestPane/Auth/OAuth2/AuthorizationCode/index.js (1)
163-199: Callback URL and system-browser UI look consistent with implicit flowThe new callback URL editor plus “Use system browser for OAuth” checkbox are wired correctly into
handleChangeandhandleUseSystemBrowserToggle, and the conditional placeholder matches the implicit-flow implementation. No further change needed here.packages/bruno-app/src/components/RequestPane/Auth/OAuth2/Implicit/index.js (1)
118-154: System-browser callback UI integration looks good and matches other flowThe new callback URL
SingleLineEditorand checkbox are correctly bound tocallbackUrl,useSystemBrowser, andhandleUseSystemBrowserToggle, with the placeholder consistent with the Authorization Code flow. This is a clean addition to the implicit configuration section.
…ebruno#6101) * feat: use default browser for oauth2 authorization bru-2167 * fix: coderabbit review comment fixes * fix: coderabbit review comment fixes * fix: protocol registration updates * fix: coderabbit review comment suggestions * fix: oauth2 auth form use system browser option
Description
Contribution Checklist:
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
Chores
✏️ Tip: You can customize this high-level summary in your review settings.