Skip to content

GTM-93: route desktop auth through Cloud login#1150

Open
benceruleanlu wants to merge 6 commits into
mainfrom
ben/gtm-93-login-browser-attribution-desktop
Open

GTM-93: route desktop auth through Cloud login#1150
benceruleanlu wants to merge 6 commits into
mainfrom
ben/gtm-93-login-browser-attribution-desktop

Conversation

@benceruleanlu

Copy link
Copy Markdown
Member

Summary

  • Open the real Cloud login page in the system browser instead of hosting Firebase auth UI on localhost.
  • Start a localhost callback receiver with state validation and CORS for Cloud login completion.
  • Preserve Desktop Firebase user injection and bind the Desktop installation identity to the signed-in user.

Links

Test plan

  • pnpm exec vitest run src/main/auth/firebaseBridge/server.test.ts
  • pnpm run typecheck
  • pnpm run lint -- src/main/auth/firebaseBridge/index.ts src/main/auth/firebaseBridge/server.ts src/main/auth/firebaseBridge/server.test.ts src/main/auth/firebaseBridge/copyLinkBanner.ts
  • pnpm exec prettier --check src/main/auth/firebaseBridge/index.ts src/main/auth/firebaseBridge/server.ts src/main/auth/firebaseBridge/server.test.ts src/main/auth/firebaseBridge/copyLinkBanner.ts

@coderabbitai

coderabbitai Bot commented Jun 19, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@benceruleanlu, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 38 minutes and 49 seconds. Learn how PR review limits work.

To continue reviewing without waiting, enable usage-based billing in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate.

For paid Pro and Pro+ PR reviews, CodeRabbit uses rolling per-developer review limits. Reviews become available again as older review attempts age out of the rolling limit window.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 811313f8-f7df-4911-888c-653980213528

📥 Commits

Reviewing files that changed from the base of the PR and between 14eba29 and bbb3d34.

📒 Files selected for processing (1)
  • src/main/auth/firebaseBridge/server.test.ts
📝 Walkthrough

Walkthrough

The Firebase bridge sign-in flow is switched from a loopback bridge-page (startBridgeServer) model to a Cloud login callback server (startCloudLoginCallbackServer). A new origins module validates loopback and Cloud URL forms. The loopback HTTP server validates per-attempt state nonces and POST payloads from the Cloud login page, includes CORS origin enforcement, and resolves a BridgeHandle. The orchestration layer and banner comment are updated to match—state-bound and ready to serve.

Changes

Cloud Login Callback Bridge

Layer / File(s) Summary
Origins module: loopback detection and Cloud URL validation
src/main/auth/firebaseBridge/origins.ts, src/main/auth/firebaseBridge/origins.test.ts
Introduces CLOUD_LOGIN_ORIGIN constant (https://cloud.comfy.org); exports isLoopbackHostname to detect localhost and IPv4/IPv6 loopback forms; cloudLoginOriginForUrl derives login origin from embedded view URL (returning loopback origin for http/https loopback URLs, falling back to production origin); isAllowedCloudCallbackOrigin validates CORS callback origins. Comprehensive test coverage verifies loopback-origin selection, production fallback for non-loopback/invalid inputs, and callback CORS allowlisting alignment.
Cloud callback server: interface, CORS, request handling, and lifecycle
src/main/auth/firebaseBridge/server.ts
Exports StartCloudLoginCallbackServerOpts interface with state, timeoutMs?, and port? fields; imports isAllowedCloudCallbackOrigin and adds setCorsHeaders helper that validates allowed CORS origins and sets Access-Control-* response headers with conditional private-network allowance. Implements startCloudLoginCallbackServer with signInPromise/resolvers, timeout teardown, loopback-only request defense, routes for GET /favicon.ico (204), OPTIONS /callback preflight (204 + CORS), and POST /callback with state matching and payload validation (user object, apiKey string). Returns 403 for disallowed origins or invalid state, 400 for missing/invalid payload, 404 for unknown paths; resolves BridgeHandle with { user, apiKey } on success. Enforces 64KB request body limit with dedicated BodyTooLargeError; includes error handling and best-effort server shutdown.
Bridge orchestration: imports, URL helpers, state nonce, and handleFirebasePopup wiring
src/main/auth/firebaseBridge/index.ts, src/main/auth/firebaseBridge/copyLinkBanner.ts
Adds randomBytes import for per-login state nonce generation; imports startCloudLoginCallbackServer, BridgeHandle from server.ts, and cloudLoginOriginForUrl from origins module; retypes activeBridge singleton to BridgeHandle | null; adds getCloudOrigin, buildCloudDesktopLoginUrl, and generateDesktopLoginState helpers to derive Cloud origin from embedded view, construct Cloud desktop login URL with desktop_login_callback and desktop_login_state query params, and generate base64url state nonce. Removes detectFirebaseEnv call; replaces startBridgeServer invocation with startCloudLoginCallbackServer startup plus per-attempt state nonce in handleFirebasePopup flow. Banner comment updated from "loopback login URL" to "Cloud login URL"; trailing comma fixed in buildCopyLinkBannerScript.
Integration tests for startCloudLoginCallbackServer
src/main/auth/firebaseBridge/server.test.ts
Adds requestRaw Node http helper to send requests with optional Origin header, optional JSON body (adds Content-Type: application/json), and extra headers, collecting status/headers/body response. Adds closeExpectingRejection to close a handle and assert signInPromise rejects with cancellation message. Tests cover matching-state POST (204 + CORS allow-origin + signInPromise resolves), mismatched/stale state POST (403 + signInPromise rejects, then subsequent valid POST resolves), OPTIONS preflight from allowed origins (204 + allow-origin + allow-methods includes POST + allow-private-network), disallowed-origin rejection for POST and OPTIONS (403 + missing CORS headers), non-POST method rejection (405), missing/invalid user payload (400), invalid apiKey (400), oversized request bodies (413), malformed JSON (500), and server closure during pending sign-in (signInPromise rejection).

Sequence Diagram

sequenceDiagram
  rect rgba(135, 206, 250, 0.5)
    note over handleFirebasePopup: Desktop App (Electron)
    participant handleFirebasePopup as handleFirebasePopup
    participant startCloudLoginCallbackServer as startCloudLoginCallbackServer
  end
  rect rgba(255, 200, 100, 0.5)
    note over CloudLoginPage: Browser / WebView
    participant CloudLoginPage as Cloud Login Page
  end
  participant BridgeHandle as BridgeHandle

  handleFirebasePopup->>handleFirebasePopup: generateDesktopLoginState() → state nonce
  handleFirebasePopup->>startCloudLoginCallbackServer: start server with { state }
  startCloudLoginCallbackServer-->>handleFirebasePopup: handle.url (loopback callback URL)
  handleFirebasePopup->>handleFirebasePopup: buildCloudDesktopLoginUrl(handle.url, state)
  handleFirebasePopup->>CloudLoginPage: open final Cloud login URL
  CloudLoginPage->>startCloudLoginCallbackServer: POST /callback { state, user, apiKey }
  startCloudLoginCallbackServer->>startCloudLoginCallbackServer: validate state + payload
  startCloudLoginCallbackServer-->>CloudLoginPage: 204 No Content
  startCloudLoginCallbackServer->>BridgeHandle: resolve({ user, apiKey })
  BridgeHandle-->>handleFirebasePopup: signInPromise resolves → inject IndexedDB + focus window
Loading

Suggested Reviewers

  • deepme987
  • MaanilVerma
🚥 Pre-merge checks | ✅ 2
✅ Passed checks (2 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ben/gtm-93-login-browser-attribution-desktop
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch ben/gtm-93-login-browser-attribution-desktop

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.

@github-actions

github-actions Bot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

✅ All contributors have signed the CLA. Thank you! This PR is ready to be merged.
Posted by the CLA Assistant Lite bot.

@benceruleanlu benceruleanlu marked this pull request as ready for review June 23, 2026 00:19
@coderabbitai coderabbitai Bot requested a review from deepme987 June 23, 2026 00:20

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: af7bd8ada3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/main/auth/firebaseBridge/server.ts
Comment thread src/main/auth/firebaseBridge/server.ts Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/main/auth/firebaseBridge/index.ts`:
- Around line 176-197: The login URL origin determined by getCloudLoginOrigin()
can target any protocol-matching origin from the current WebContents, but the
callback server only accepts callbacks from cloud.comfy.org or loopback
addresses, causing CORS failures when other origins are used. Modify
getCloudLoginOrigin() to only return the current origin if it is a loopback
address (localhost, 127.0.0.1, etc.), otherwise always return the production
default of https://cloud.comfy.org. This ensures the buildCloudDesktopLoginUrl()
function always targets an origin that the callback server will accept, keeping
the login URL origin and callback CORS policy in sync.

In `@src/main/auth/firebaseBridge/server.test.ts`:
- Around line 132-195: The test file is missing test cases that verify the CORS
boundary for disallowed origins. Add two new test cases after the existing
tests: one for POST requests and one for OPTIONS requests from a disallowed
origin (use something like 'https://untrusted.example.com'). Both test cases
should call startCloudLoginCallbackServer with the same pattern as existing
tests, make requests with the untrusted origin, and assert that the response
status is 403 and includes appropriate CORS rejection headers. This ensures the
CORS security gate does not regress silently.

In `@src/main/auth/firebaseBridge/server.ts`:
- Around line 303-350: The startCloudLoginCallbackServer function contains
boilerplate code for managing server lifecycle and promise resolution handling
(the close function, finishWithError, finishWithSuccess, and related promise
setup logic) that is likely duplicated elsewhere in the file around lines
365-431. Extract these common patterns into shared helper functions or utilities
that can be reused across both auth paths. This will prevent the lifecycle
management and request handling logic from diverging between different
implementations. Focus on extracting the server cleanup logic, the promise
resolution/rejection patterns, and the timeout handling into reusable helpers
that both the startCloudLoginCallbackServer function and other similar auth path
handlers can leverage.
- Around line 319-330: The close() function shuts down the server and timer but
does not settle the signInPromise, leaving pending sign-in operations
unresolved. Locate the signInPromise variable in the same file and modify the
close() function to reject or resolve this promise before setting server to
null. This ensures that any in-flight authentication calls are properly
terminated when the bridge is torn down.
🪄 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: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: af3eae95-4071-4a3b-bdd9-4f3d3c3f012b

📥 Commits

Reviewing files that changed from the base of the PR and between fd8cc41 and af7bd8a.

📒 Files selected for processing (4)
  • src/main/auth/firebaseBridge/copyLinkBanner.ts
  • src/main/auth/firebaseBridge/index.ts
  • src/main/auth/firebaseBridge/server.test.ts
  • src/main/auth/firebaseBridge/server.ts

Comment thread src/main/auth/firebaseBridge/index.ts
Comment thread src/main/auth/firebaseBridge/server.test.ts
Comment thread src/main/auth/firebaseBridge/server.ts
Comment thread src/main/auth/firebaseBridge/server.ts Outdated
@benceruleanlu

Copy link
Copy Markdown
Member Author

I have read and agree to the Contributor License Agreement

@benceruleanlu

Copy link
Copy Markdown
Member Author

DO NOT MERGE UNTIL FE PR IS MERGED

comfy-legal added a commit to Comfy-Org/comfy-cla that referenced this pull request Jun 23, 2026
@coderabbitai coderabbitai Bot requested a review from MaanilVerma June 23, 2026 09:03

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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)
src/main/auth/firebaseBridge/server.ts (1)

146-157: 🩺 Stability & Availability | 🔵 Trivial

This asymmetry is intentional and safe — no change needed, but consider a clarifying comment.

The concern is valid: a local process can POST garbage to /callback without the state nonce and abort the in-flight login, since readJsonBody is the only code path that throws into this catch block (lines 204, 146–157). However, the design distinguishes between recoverable and unrecoverable errors:

  • Invalid state (line 206–211) returns 403 and leaves signInPromise pending — stray callbacks are tolerated.
  • Malformed/oversized body (line 204) throws, calls finishWithError, and aborts — corrupted data can't be salvaged.

Since the orchestrator's finally block (index.ts, 273–279) unconditionally closes the bridge on any rejection, the abort is safe and cleanup always happens. The asymmetry doesn't leak resources; it prevents propagating corrupted callback data where it won't float around — you might say the design's promise is kept! If this intentional behavior isn't obvious, a one-line comment explaining why invalid-state is tolerated but read errors abort would save a future reviewer from spiraling.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/main/auth/firebaseBridge/server.ts` around lines 146 - 157, Add a
clarifying comment to explain the intentional asymmetry in error handling within
the catch block that wraps handleRequest. The comment should explain that
invalid state errors (returned as 403 in the validation logic) are tolerated to
allow stray callbacks to be handled gracefully and keep signInPromise pending,
while read errors from readJsonBody throw and abort because corrupted data
cannot be salvaged. Also note that the orchestrator's finally block ensures
cleanup always happens regardless of which error type occurs, making this
asymmetry safe and preventing resource leaks.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/main/auth/firebaseBridge/server.test.ts`:
- Around line 60-76: The test file contains repeated boilerplate code where
tests call startCloudLoginCallbackServer, wrap the test logic in a try block,
and call closeExpectingRejection in a finally block. Create a test helper
function that accepts a callback function and handles this setup/teardown
pattern internally, then refactor all tests (including those around lines
195-242 and 244-280) to use this helper instead of repeating the
startCloudLoginCallbackServer initialization, try/finally structure, and
closeExpectingRejection cleanup pattern. This will centralize the server
lifecycle management and make the test code cleaner and easier to maintain.
- Around line 226-238: The test named "rejects matching-state callbacks without
a string apiKey" is not actually testing a non-string apiKey value as its name
suggests. In the request body within the startCloudLoginCallbackServer test, add
an apiKey field with a non-string value (such as a number or object) to the JSON
payload instead of omitting it entirely, so the test properly exercises the
validation logic that checks for string apiKey values.

---

Outside diff comments:
In `@src/main/auth/firebaseBridge/server.ts`:
- Around line 146-157: Add a clarifying comment to explain the intentional
asymmetry in error handling within the catch block that wraps handleRequest. The
comment should explain that invalid state errors (returned as 403 in the
validation logic) are tolerated to allow stray callbacks to be handled
gracefully and keep signInPromise pending, while read errors from readJsonBody
throw and abort because corrupted data cannot be salvaged. Also note that the
orchestrator's finally block ensures cleanup always happens regardless of which
error type occurs, making this asymmetry safe and preventing resource leaks.
🪄 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: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 87de1873-9bf1-4b51-8e12-29d4d985bdd9

📥 Commits

Reviewing files that changed from the base of the PR and between a2b3067 and 14eba29.

📒 Files selected for processing (8)
  • src/main/auth/firebaseBridge/bridgeHtml.ts
  • src/main/auth/firebaseBridge/config.test.ts
  • src/main/auth/firebaseBridge/config.ts
  • src/main/auth/firebaseBridge/index.ts
  • src/main/auth/firebaseBridge/oauth.ts
  • src/main/auth/firebaseBridge/origins.ts
  • src/main/auth/firebaseBridge/server.test.ts
  • src/main/auth/firebaseBridge/server.ts
💤 Files with no reviewable changes (4)
  • src/main/auth/firebaseBridge/oauth.ts
  • src/main/auth/firebaseBridge/config.ts
  • src/main/auth/firebaseBridge/config.test.ts
  • src/main/auth/firebaseBridge/bridgeHtml.ts

Comment thread src/main/auth/firebaseBridge/server.test.ts Outdated
Comment thread src/main/auth/firebaseBridge/server.test.ts
@Kosinkadink

Copy link
Copy Markdown
Member

Does this PR make sure to keep things working when ComfyUI is not using a frontend comfy version that has the changes in the frontend PR?

@Kosinkadink Kosinkadink added the cross-repo Feature requires other repos to make changes label Jun 23, 2026
@benceruleanlu

Copy link
Copy Markdown
Member Author

Does this PR make sure to keep things working when ComfyUI is not using a frontend comfy version that has the changes in the frontend PR?

This doesn’t depend on the ComfyUI frontend bundled with Desktop. It depends on the Cloud login page deployment. Desktop opens cloud.comfy.org for the handoff, so the required version skew check is Cloud frontend #12983 deployed before Desktop #1150 ships.

As of right now the deployment hasn't happened yet

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cross-repo Feature requires other repos to make changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants