Skip to content

feat(auth): use shared account sessions for Desktop login - #1775

Closed
PabloWiedemann wants to merge 5 commits into
mainfrom
PabloWiedemann/desktop-native-account-session
Closed

PabloWiedemann wants to merge 5 commits into
mainfrom
PabloWiedemann/desktop-native-account-session

Conversation

@PabloWiedemann

@PabloWiedemann PabloWiedemann commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Desktop sign-in now opens the existing hosted login and receives an independent shared account session, including for SSO-only accounts. Switching workspaces calls the existing backend token endpoint; it no longer requires a separate OAuth consent grant for each workspace.

The account credential remains in the main process and existing encrypted token store. The optional local ComfyUI bridge receives only its partner-node credential. Existing OAuth sessions can still refresh until the next sign-in. No new dependency, screen, or workspace permission model is introduced.

Blast radius: Desktop account login, token renewal, workspace selection, logout, and the trusted local partner-node bridge. Deploy the backend handoff and hosted redemption changes first; include non-SSO Desktop users in the existing shared-session rollout.

Supersedes closed #1749. Companions: backend transport, backend handoff, hosted redemption, Desktop.

Change breakdown

Changed lines means additions + deletions. Counts use the PR base; no merge-only changes are included.

Category Files Added Deleted Share
Generated code 1 1 0 0.1%
Configuration 1 1 1 0.2%
Product code 10 393 26 45.4%
Tests 5 452 48 54.2%

Total: 17 files, 922 changed lines.

Paths by category

Generated code

  • packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts (+1/−0)

Configuration

  • packages/comfyui-desktop-bridge-types/package.json (+1/−1)

Product code

  • src/main/auth/desktopLoginCode/client.ts (+1/−0)
  • src/main/cloud/accountSession.ts (+194/−0)
  • src/main/cloud/session.ts (+161/−20)
  • src/main/cloud/tokenStore.ts (+8/−3)
  • src/main/cloud/types.ts (+2/−1)
  • src/main/lib/embeddedSession.ts (+17/−1)
  • src/main/lib/ipc/registerDevPlatformHandlers.ts (+2/−1)
  • src/main/lib/ipc/registerEmbeddedSessionHandlers.ts (+5/−0)
  • src/preload/comfyPreload.ts (+2/−0)
  • src/types/comfyDesktopBridge.ts (+1/−0)

Tests

  • src/main/cloud/accountSession.test.ts (+194/−0)
  • src/main/cloud/session.test.ts (+200/−46)
  • src/main/cloud/tokenStore.test.ts (+33/−0)
  • src/main/lib/embeddedSession.test.ts (+22/−1)
  • src/main/lib/ipc/registerEmbeddedSessionHandlers.test.ts (+3/−1)

Verification

  • 129 focused tests passed across account login, session management, and IPC handlers. Regressions cover cancellation, stale 401 responses, transient refresh failures, workspace validation, concurrent partner mints, and logout failures.
  • Commit hook passed all four typechecks, ESLint, and formatting. All checks on head 8c0a6ace passed, including OS E2E checks (rechecked October 22).
  • Cursor findings addressed. CodeRabbit reviewed the changes; follow-up runs reached the service usage limit. Local sign-out remains successful if server revocation fails; a sanitized warning records that failure. The server owns partner-node revocation, so Desktop sends one logout request.
  • Live browser/SSO-to-Desktop sign-in remains a staging validation step.

@coderabbitai

coderabbitai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 1122e151-5bb8-4adf-95c4-e0133d0a8a73
📥 Commits

Reviewing files that changed from the base of the PR and between 0fbc0d3 and 8c0a6ac.

📒 Files selected for processing: 8
  • src/main/cloud/accountSession.test.ts
  • src/main/cloud/accountSession.ts
  • src/main/cloud/session.test.ts
  • src/main/cloud/session.ts
  • src/main/cloud/tokenStore.test.ts
  • src/main/cloud/tokenStore.ts
  • src/main/lib/embeddedSession.test.ts
  • src/main/lib/embeddedSession.ts

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

📝 Walkthrough

Cloud authentication now supports account-scoped desktop sign-in, session-backed workspace tokens, asynchronous session revocation, and cached partner-node tokens. The partner-node token request is exposed through embedded-session IPC and the desktop auth bridge.

Changes: Cloud authentication

Layer / File(s) Summary
Account-session APIs and token storage
src/main/auth/desktopLoginCode/client.ts, src/main/cloud/accountSession.ts, src/main/cloud/types.ts, src/main/cloud/tokenStore.ts, src/main/cloud/accountSession.test.ts, src/main/cloud/tokenStore.test.ts
Desktop login requests can specify the account session type. Account-session sign-in, workspace and partner-node token minting, token validation, and session revocation are added. Token storage validates optional session credentials. Tests cover sign-in, token responses, and storage behavior.
CloudSession lifecycle and workspace credentials
src/main/cloud/session.ts, src/main/cloud/session.test.ts, src/main/lib/ipc/registerDevPlatformHandlers.ts
CloudSession uses account-session APIs for sign-in, refresh, workspace switching, and logout. It handles cancellation, stale responses, workspace validation, and partner-token caching. Logout now waits for session revocation. Tests cover lifecycle races, workspace behavior, and token failures.
Partner-node token bridge
src/main/lib/embeddedSession.ts, src/main/lib/ipc/registerEmbeddedSessionHandlers.ts, src/main/lib/ipc/registerEmbeddedSessionHandlers.test.ts, src/main/lib/embeddedSession.test.ts, src/preload/comfyPreload.ts, src/types/comfyDesktopBridge.ts, packages/comfyui-desktop-bridge-types/*
Embedded-session IPC validates the sender before and after requesting a partner-node token. The preload and public bridge types expose the method. The bridge-types package version changes to 0.6.0.

Sequence Diagram(s)

sequenceDiagram
  participant DesktopAuthBridge
  participant EmbeddedSessionIPC
  participant partnerNodeTokenForSender
  participant CloudSession
  DesktopAuthBridge->>EmbeddedSessionIPC: Request token for workspace
  EmbeddedSessionIPC->>partnerNodeTokenForSender: Forward sender and workspace ID
  partnerNodeTokenForSender->>CloudSession: Request partner-node token
  CloudSession-->>partnerNodeTokenForSender: Return token or null
  partnerNodeTokenForSender-->>EmbeddedSessionIPC: Return token only for trusted sender
  EmbeddedSessionIPC-->>DesktopAuthBridge: Resolve token or null
Loading

Suggested reviewers: kosinkadink

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 8c0a6

The change moves Desktop sign-in to shared account sessions. No remaining merge-blocking issue is evident in the reviewed context. Live SSO-to-Desktop sign-in still needs staging validation, and the backend changes must be deployed first.

Security architecture risk: 🟡 Moderate · up to 8c0a6

This changes how Desktop obtains and delegates account access. Local sender and workspace checks limit exposure, but security also depends on coordinated server and browser deployment and partner-credential handling that could not be verified here.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — A script executing in the trusted local embedded main frame can request a partner credential for Desktop's active workspace. The account credential can request credentials across the account's authorized workspaces but remains in main. The partner credential's downstream permissions and handling cannot be established from this repository.

Trust Boundaries and Controls

  • observed — The new partner-token path reuses the existing registered-view boundary and adds destroyed-sender and detached-frame rejection. Authorization requires the registered main frame on its matching loopback origin and an enabled sharing flag; sender trust is checked again after minting. CloudSession also checks requested and returned workspace scope and suppresses stale-generation results.

Resilience and Maintainability Implications

  • observed — Login replacement and logout invalidate pending intents; stale or failed login flows attempt session revocation. Refresh replacement checks existing token identity, subject, and workspace. Logout attempts local removal before awaiting best-effort server revocation, and sign-out broadcasts precede that await. Source tests cover stale workspace responses and revocation failure; downstream revocation effects remain unverified.

Hardening Proposals

  • proposed — Before enabling the delegated capability, validate the companion deployments together: workspace membership enforcement, partner resource and audience restrictions, token lifetime, revocation propagation, and behavior during downgrade or unavailable revocation. This is a validation proposal for unresolved external contracts, not an observed vulnerability.
Pre-merge checks: Passed 2
Check name Status Explanation
Linked Issues check Passed Issue #1749 is closed and supplies historical context only. No active directly linked target remains. Therefore, this pull request has no linked-issue coding requirements.
Out of Scope Changes check Passed The changes stay within the stated authentication scope. They cover account sessions, token storage, token renewal, workspace and partner-node tokens, logout, IPC, bridge types, and related tests. No …
Full details: Out of Scope Changes check

Explanation

The changes stay within the stated authentication scope. They cover account sessions, token storage, token renewal, workspace and partner-node tokens, logout, IPC, bridge types, and related tests. No unrelated product change is identified. The scope is tight, and the tokens stay right.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
✨ Simplify code
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔍 Cursor Review — Consolidated panel

Triggered by @PabloWiedemann.

Found 10 finding(s).

Severity Count
🟠 High 5
🟡 Medium 5

Panel: 8/8 reviewers contributed findings.

Comment thread src/main/cloud/accountSession.ts Resolved
Comment thread src/main/cloud/session.ts Resolved
Comment thread src/main/cloud/session.ts Resolved
Comment thread src/main/cloud/session.ts Resolved
Comment thread src/main/cloud/session.ts Resolved
Comment thread src/main/cloud/session.ts Resolved
Comment thread src/main/lib/embeddedSession.ts Resolved
Comment thread src/main/cloud/session.ts Resolved
Comment thread src/main/cloud/accountSession.ts Resolved
Comment thread src/main/cloud/session.ts Resolved
@PabloWiedemann
PabloWiedemann marked this pull request as ready for review October 20, 2026 20:16
@PabloWiedemann
PabloWiedemann requested review from a team as code owners October 20, 2026 20:16
@PabloWiedemann PabloWiedemann added cursor-review Trigger multi-model Cursor code review and removed cursor-review Trigger multi-model Cursor code review labels Oct 20, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔍 Cursor Review — Consolidated panel

Triggered by @PabloWiedemann.

Found 10 finding(s).

Severity Count
🟠 High 2
🟡 Medium 5
🟢 Low 3

Panel: 7/8 reviewers contributed findings.

Reviewers that did not contribute: gpt-5.6-sol-max:edge-case (empty)

Comment thread src/main/cloud/session.ts Resolved
Comment thread src/main/cloud/accountSession.ts Resolved
Comment thread src/main/cloud/session.ts Resolved
Comment thread src/main/cloud/session.ts Resolved
Comment thread src/main/cloud/accountSession.ts Resolved
Comment thread src/main/cloud/tokenStore.ts Resolved
Comment thread src/main/cloud/accountSession.ts Resolved
Comment thread src/main/cloud/session.ts Resolved
Comment thread src/main/lib/embeddedSession.ts Resolved

@benceruleanlu benceruleanlu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This review was performed agentically. Ben will be notified to review manually soon.

Recommendation: fix the 1 blocking finding below before merging.

Review details

The PR moves Desktop sign-in to a shared account session. Desktop requests a dls_ login code, polls until the hosted login completes, then gets workspace tokens from /auth/token using the stored comfy-session- credential. Workspace switches and refreshes now get new tokens from the server instead of asking for OAuth consent per workspace. It also adds a getPartnerNodeToken method for the local ComfyUI bridge, and logout now revokes the session on the server.

Blocking

  1. src/main/cloud/accountSession.ts:31 (called from src/main/cloud/session.ts:240): sign-in has no fallback anymore. authenticateAtGeneration used to call oauth.signIn. Now it always calls signInAccount, and signInAccount throws 'Account login is unavailable on this server' whenever the server returns a code without the dls_ prefix. oauth.signIn is still exported but nothing calls it. So sign-in fails completely, for every user, against any backend that doesn't honor session_type: 'account'. That includes:

    • a backend deployed before the companion PRs;
    • any user left out of the shared-session rollout, which the PR body says is still gated ("include non-SSO Desktop users in the existing shared-session rollout");
    • any other environment CLOUD_CONFIG.issuer points at.

    Existing OAuth users keep refreshing, but anyone who signs out, or whose refresh fails, can't sign back in. Your own description depends on deploy order and rollout settings to avoid this.

    Smallest fix: when the code isn't dls_, fall back to the legacy signIn({ onAuthorizeUrl }) flow instead of throwing. Alternatively, have the server error explicitly, and fall back only on that error.

Optional

  • src/main/lib/ipc/registerDevPlatformHandlers.ts:184-187: signOutOfCloud now waits for the server revocation and passes its errors back to the caller. When offline, or when /auth/token/revoke fails, local credentials are already gone and SIGNED_OUT has already been broadcast, but the IPC call still rejects:

    • The embedded desktop2-auth:sign-out handler throws to the hosted frontend, even though the user is actually signed out.
    • DevPlatformAccountChip.vue:37 takes its catch { return } path and never emits signed-out.

    The session token was cleared before the request, so nothing can retry the revocation anyway. Logging the error and resolving SIGNED_OUT would match what actually happened.

    Also, in revokeAccountSession (accountSession.ts:187-192), the try/finally re-throws an error from /auth/token/revoke even when the DELETE /auth/session call succeeded.

  • src/main/cloud/session.ts:326: on a 401, onUnauthorized now calls invalidateStoredSession(). That clears the session token locally but never revokes it on the server, unlike logout(). The account session stays valid on the server until it expires. This is low cost, but the call already sits on lines this PR changes.

Review target

  • Head tip: 0fbc0d3f73130b532ff245a1f192eefd2a4cb577
  • main tip: 195ae80ae06ac5cf9e9c3b2978ea5e0b73f1f464

@benceruleanlu benceruleanlu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Coderabbit tagged me, do you need me? Assign if so @PabloWiedemann

@PabloWiedemann

PabloWiedemann commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Consolidated review follow-up in 8c0a6ace (one update for this batch to reduce notifications).

  • Finding 4330140652: Fixed: local logout resolves after clearing credentials even if server revocation fails; a sanitized warning records the failure.
  • Finding 4330140666: Simplified to one DELETE /auth/session. The foundation backend now revokes the login’s partner-node sessions server-side, removing both client request ordering and the two-timeout path. (The former finally did not discard the first exception when DELETE succeeded, but this path is now removed.)
  • Finding 4330140678: Fixed: successful short-lived partner credentials get a five-second cache floor instead of causing a mint for every IPC call. Added a regression.
  • Finding 4330140686: Fixed: refused/mismatched account workspace switches return the resulting current status, preserving the bridge contract without serializing the rejection.
  • Finding 4330140698: Fixed: only abort/timeout errors are rewritten when the deadline expires. A regression preserves the original 403 when cleanup crosses the deadline.
  • Finding 4330140705: Fixed: both saveTokens and replaceWorkspaceTokens validate credentials before mutating the vault. Regression confirms existing credentials survive reload after a refused write.
  • Finding 4330140716: Already enforced in createDesktopLoginCode in src/main/auth/desktopLoginCode/client.ts: integer poll_interval 1–30 seconds and expires_in 1–1800 seconds are required before this flow receives the grant. No second clamp added.
  • Finding 4330140726: Not reproducible: workspaceIdOf uses decodeJwtPayload, which catches decoding/JSON errors and returns null. A malformed JWT therefore produces a scope mismatch and reaches the existing five-second null-result backoff; it cannot throw and poison this cache as described.
  • Finding 4330140740: Fixed by handling revocation rejection inside CloudSession.logout itself. The returned logout promise no longer rejects on the asynchronous revocation failure, even if a later broadcast fails.
  • Finding 4330140748: Fixed: trusted-sender validation rejects destroyed WebContents/detached frames before mainFrame access. Regression destroys the view during partner mint and verifies null.

Validation: 129 focused tests and required typecheck/lint/format hooks passed. New-head CI is running.

@dante01yoon dante01yoon left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the thorough follow-ups on the Cursor findings. I left one blocking issue and a few smaller points inline.

Gates

  • Real problem: passes. Moving off per-workspace OAuth consent and supporting SSO-only accounts is a real need.
  • Server owns session facts: mostly passes. Workspace membership and token scope come from /auth/token, and partner tokens are re-checked against the requested workspace. One exception: server capability is inferred from the dls_ code prefix (see the question on accountSession.ts:31).
  • Generated API types: not applicable. This repo has no generated cloud API types; desktopLoginCode/client.ts and comfybuilder/types.ts also hand-validate wire shapes, so mintedTokens follows the local convention.

Security notes (no action needed)

  • The session credential stays in main and in the safeStorage vault.
  • The new desktop2-auth:get-partner-node-token channel validates its input and checks isTrustedSender both before and after the await.
  • PKCE binds the exchange to the verifier, and requests use credentials: 'omit' and redirect: 'error'.
  • Logout clears local state before revoking on the server.

Size

  • About 390 non-test lines. Consider splitting the partner-node bridge (IPC channel, preload, bridge types, partner cache in CloudSession) from the account-login change. Each half would be easier to review and roll back.

Unanchored

  • nit-pick (non-blocking): the new exports (signInAccount, mintWorkspaceToken, mintPartnerNodeToken, revokeAccountSession, partnerNodeTokenForSender) and getPartnerNodeToken in the published bridge types have no JSDoc, while their neighbours do. A one-line JSDoc would help, especially on the bridge type, which consumers read.
  • question: cloud/index.ts still exports signIn from ./oauth, but nothing in the app calls it anymore. Is it intentionally kept as the fallback path, or can it be removed?

Comment thread src/main/cloud/session.ts
loadTokens()?.sessionToken === tokens.sessionToken &&
tokens.sessionToken
) {
this.invalidateStoredSession()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

issue: this clears the stored session but never tells the renderers, so the account chip can keep showing "signed in" after Desktop has signed out locally.

Scenario: the account session is revoked or expires on the server, and the workspace JWT then expires. On the next catalog call, ComfyBuilderClient.accessToken() calls getAccessToken(). That reaches doRefresh, which gets a 401 from /auth/token, clears the tokens here, and returns null. The client then throws 'Not signed in' before sending any request, so onUnauthorized (and therefore setUnauthorizedHandler's broadcastAuthChanged(SIGNED_OUT)) never runs.

Before this PR, a failed legacy refresh kept the tokens, so the next request's 401 went through onUnauthorized and the broadcast fired. switchCloudWorkspace broadcasts its own result, so only this refresh path is affected.

Could the refresh-401 invalidation go through the same signed-out notification? For example, pass a callback into CloudSession, or have asTokenProvider signal it. A test should assert that the broadcast happens. (CONFIRMED by reading the code path; not run.)

},
{ signal }
)
if (!grant.code.startsWith('dls_')) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

question: Ben's blocking point about this hard throw (no fallback to oauth.signIn when the server doesn't issue a dls_ code) hasn't had a reply yet. The test refuses an older server before opening a Firebase-only handoff suggests the throw is intentional.

Can you confirm the plan? That would mean the backend must deploy first, and every environment COMFY_CLOUD_ISSUER can point at (staging, mocks) must support session_type: 'account' before this ships.

Related: detecting server support from the code's prefix is a client-side guess. An explicit field in the grant (e.g. echoing session_type) would make the server's answer authoritative.

await abortableSleep(grant.poll_interval * 1000, deadline)
let response
try {
response = await postJson(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

suggestion: this loop re-implements the exchange that exchangeDesktopLoginCode and signInViaDesktopLoginCode already handle. In doing so it drops the POLL_JITTER_MS jitter, which the existing flow adds "so a fleet of desktops doesn't sync-poll".

Consider widening exchangeDesktopLoginCode to accept the session_token completion, then reusing it here along with the jittered sleep. That keeps a single exchange contract instead of two.

Comment thread src/main/cloud/session.ts
this.invalidateStoredSession()
return this.status()
}
return this.status()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

suggestion: returning the current status keeps the bridge contract, which makes sense after the earlier thread. But non-401 mint failures here (network errors, 403/404 non-member) and the wrong-workspace response at L213-214 now leave no trace: the picker click just does nothing.

A sanitized console.warn, like the one logout() emits, would make these cases debuggable. Also, L203-207 return this.status() in both branches, so the condition only gates invalidateStoredSession() and could be flattened.

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

Labels

cursor-review Trigger multi-model Cursor code review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants