Skip to content

feat(auth): sign-out revokes this device's Cloud grant, retrying until Cloud confirms (DESK-190) - #1984

Merged
dante01yoon merged 98 commits into
mainfrom
desktop-auth/durable-sign-out
Nov 11, 2026
Merged

dante01yoon merged 98 commits into
mainfrom
desktop-auth/durable-sign-out

Conversation

@dante01yoon

@dante01yoon dante01yoon commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

Dependency graph

Desktop auth TDD 4.4 "Logout (this device)", T-V8 and T-V18. Solid: code dependency. Dotted: must be deployed first.

graph LR
  S1968["PR 1968 switch without a browser"] --> P["this PR: durable sign-out"]
  R["cloud PR 18564 POST /oauth/revoke (merged)"] -. deploy first .-> P
  P --> N["PR 1983 partner-node token from main"]
  style P stroke-width:3px
Loading

Merge after #1968, and only after https://github.com/Comfy-Org/cloud/pull/18564 is deployed. Until then a revoke gets a 404, which this PR retries rather than drops, so nothing is lost, but no grant ends.

Why

Logout only cleared local tokens (CloudSession.logout). The grant stayed alive on Cloud, so the refresh token and its partner-node sessions outlived the sign-out. The TDD requires logout to revoke this device's grant on the server through a durable queue that retries until Cloud confirms, while the UI never waits on the network and no other grant is touched.

How

  • logout() writes the grant's refresh token to a queue, then clears local tokens at once and returns. A worker sends POST {issuer}/oauth/revoke (token, client_id) in the background.
  • Queue: one safeStorage-encrypted file per token under userData/comfy-cloud-revocations/ (temp file plus rename), so no write can damage another entry. Without secure storage, or when a write fails, the entry stays in memory and saving is retried on every read, following the vault's no-plaintext rule.
  • Retry: network errors, timeouts, 5xx, 429, 404 and any other unexpected answer retry with backoff from 5 s, capped at 15 min. 200 drops the entry, and so does 400/401 with invalid_request, invalid_client, unauthorized_client or unsupported_token_type. A failing token does not block others. The queue resumes at app start (index.ts).
  • Only the issuing Cloud: the vault now records the issuer and client at sign-in and at each refresh, and every queued token goes only to its own issuer's /oauth/revoke. Redirects are not followed. Known gap: a vault written by an older build has no such record, so its grant is revoked only after one refresh proves its Cloud (refreshes run every few minutes of use). Signing out before that leaves that one grant to expire on its own.
  • Only this grant: minted workspace tokens are never sent. A refresh in flight at logout whose rotation lands afterwards is revoked too; a grant from a later sign-in is not.
  • A replaced grant is revoked too: when a browser sign-in (a new sign-in, or a switch that needs one) stores a new grant that reaches disk, the previous grant and any rotation of it in flight are queued as at logout; a grant Cloud reported ended holds no refresh token, so nothing is queued for it.
  • The API-401 path (onUnauthorized) calls the same logout(), so it revokes as well.

AS IS / TO BE

Captured from the real built Desktop app (macOS, unpackaged, electron-vite build of each branch), driven over the repo's e2e harness: real "Log in" and "Sign out" clicks, real loopback PKCE sign-in, real HTTP. Cloud is a local stand-in on 127.0.0.1 that answers /oauth/* like cloud#18564 and logs every request it receives (right panel). "Offline" stops that server; "relaunch" quits the app and starts it again on the same profile.

AS IS (desktop-auth/switch-without-browser, 76c352ef) TO BE (this PR, 483cc0f3)
Sign out while Cloud is reachable local tokens cleared, no /oauth/revoke signed out in 134 ms, /oauth/revoke sent at once, queue empty
Sign out while offline local tokens cleared, nothing kept signed out in 76 ms, 1 encrypted queue entry, nothing sent
Relaunch online after that grant never revoked /oauth/revoke token=refresh-2 on start, queue empty
Step AS IS TO BE
Sign out, online
Sign out, offline
Relaunch online

Not shown: a deployed Cloud. The real /oauth/revoke is only in cloud#18564, which is not deployed yet.

Tests

  • revocation.test.ts: 200 drains; offline, 500, 503, 429, 404, 400 without a permanent OAuth error, a transient OAuth error, 202 and a redirect all retry and later revoke; permanent 400/401 errors drain; backoff spacing; a token queued during a backoff waits for it; a failing token does not block others; a relaunch revokes a token queued before it; a confirmed token whose file cannot be deleted is not resent and is deleted later; an unreadable entry is read again later; each token goes only to its issuer.
  • session.test.ts: logout signs out at once and queues the grant before Cloud answers; offline then online revokes; relaunch with a pending entry revokes; only the signed-out grant is revoked (not minted tokens, not a later sign-in, not a refresh from another account); a rotation landing after logout is revoked; an older vault is not revoked until a refresh proves its Cloud.
  • tokenStore.test.ts: issuer recorded at sign-in and refresh; queue entries encrypted, one file each; an unreadable sibling never loses an entry; memory-only without secure storage, saved once it returns.
  • The new session tests fail with the logout() change removed; the rotation and redirect tests fail with their guards removed.
  • pnpm run typecheck, pnpm run lint, pnpm run format:check: pass. pnpm test: 7780 pass; the same 4 agentUvReaper/delegate tests fail on the base branch on this machine.

Change breakdown

Category Files Added Deleted Share of 933 changed lines
Product code 6: src/main/cloud/{config,oauth,revocation,session,tokenStore}.ts, src/main/index.ts 277 3 30.0%
Test code 3: src/main/cloud/{revocation,session,tokenStore}.test.ts 650 3 70.0%

…workspace tokens

A local ComfyUI view now gets a token only for Desktop's current workspace,
only when that workspace is on the view's allowlist held in main, and a
workspace token minted at POST /api/auth/token rather than the OAuth access
token. Sign-in and sign-out end every view grant, so a switch or mint reply
that lands afterwards reaches no view. While Cloud refuses to mint for the
grant, the view keeps today's pinned access token, and never one carrying
scopes this build did not request.
…e grants to sign in again

Server-first rollout (TDD 4.4, T-V29): drop the fallback that handed a view the
OAuth access token while Cloud refused mints. Desktop requests the workspace
mint scope (placeholder name, one constant); a grant without it reads as
signed_out to the view, so the view asks for one browser sign-in. Any failed
mint gives the view nothing.
Carry the error code and Retry-After on a failed mint and add a pure classifier: minted, unavailable, reauthorize (sso_required, grant_ended, mint_disabled), refused, retryable. A 503 with oauth_workspace_mint_disabled is the server kill switch; any other 503 stays retryable.
Fails open with a persisted answer, so a slow or unreachable PostHog cannot turn a working switch into a browser prompt, and a fetched kill holds across launches while PostHog is unreachable. Read in main only.
…browser

Vault version 2 holds one OAuth grant plus short-lived minted tokens; a version 1 vault migrates with its active bundle as the grant. switchWorkspace activates the anchor or a valid minted token, otherwise mints. Only a definitively refused grant, an SSO policy, a missing mint scope or a mint kill switch opens the one browser sign-in of a switch, and nothing after it opens a second. Network, timeout and 5xx failures of a refresh or mint stay on the current workspace and report retryable.

Token reads never open the browser. When only a sign-in could renew the active workspace it returns to the anchor and announces the change, so selection and status converge. View grants mint from the grant and fence replies on the auth generation, so a reply from before A to B to A is dropped. A switch that signs in as another account forgets the view allowlists.
…to Datadog

Mirroring is per event name, so the browser trip and the return to the anchor get their own events while the per-switch workspace_switch event stays in PostHog. scope_not_granted arrives on workspace_switch_browser, so a monitor counting browser trips should exclude that reason.
…window

The switch reply carries workspaceSwitchFailure, kept by the auth store until the next switch or status change and shown as a caption under the workspace bar. A failed switch fetches no Builds for the wrong workspace, and the refresh button retries it.
Status alone is not terminal. Keep the OAuth error code on SignInFailure: Cloud answers a dead refresh with HTTP 400 and invalid_grant or invalid_client, so any other 400 or 401 from the token endpoint is retryable. A first mint 401 refreshes once, and after a good refresh a second 401 means the grant ended only with code oauth_grant_ended, otherwise it is retryable.
… refresh outage

The reply claimed success while getAccessToken returned null. When no unexpired anchor token remains, stay and report retryable. A token that is still valid during a proactive refresh failure keeps working for switches, API calls and mints.
A late 429 from account X could throttle account Y for up to its Retry-After. Write mintBlockedUntil only when the reply still belongs to the current generation and account.
A chooser refresh or another selection reopened OAuth. The session remembers that the grant a browser just returned lacks the scope, so ordinary switches report retryable with no browser until a grant that can mint is stored or the user signs out. The state is in memory, so a restart may ask once more.
…sion policy

View grants called mintWorkspaceToken directly, so desktop_workspace_mint_switch never reached them. CloudSession.isWorkspaceMintAllowed is now the one policy both callers use: the anchor always, any other workspace unless the flag killed it. A view path only returns null, it never opens a browser.
Promotion switched without allowDesktop, so views got signed-in status for B and then failed the allowlist check. Allow the workspace once the switch has reached it. A switch that stayed put adds nothing.
The safeStorage mock was plain UTF-8, so writing plaintext would pass. Use a distinct envelope, make decrypt reject unencrypted input, and assert what reaches disk.
… view

View minting handed out whatever the server returned, and its tests used opaque strings, one of which accepted a ws-1 token for a ws-2 request. Refuse and do not cache a token for another workspace or account, as CloudSession already does, and use JWT-shaped tokens in the tests.
Two mutants survived: both guards were correct but only incidentally covered.
The hold lived in memory, so after a restart the chooser's startup watcher called switchWorkspace and reopened the browser with no user gesture, repeatedly. It now lives in the encrypted vault on the grant it describes: set when a browser sign-in returns no mint scope, cleared by storing a grant that can mint and on logout. A version 1 migration never sets it, so a pre-upgrade grant still gets its one trip. An explicit sign-in can still try.
…the generation

An old switch finishing after another account signed in and a view switched saw a changed subject and allowed that view's workspace for every view. Capture the generation right after starting the switch and guard endAll and allowDesktop, as signInToCloud does.
The parent-expiry cap can produce a token past its expiry, and it was stored and activated while status said B. An expired reply is now a failed mint, so a switch stays put and reports retryable and a view gets nothing.
…Builds

After a return to the anchor the wizard kept its B target, and Refresh loaded the anchor's Builds and showed none compatible. Refresh and the Builds retry now re-establish the target first when status has moved off it. A background transition does not re-switch on its own, because under a kill that would open a browser with no gesture.
A superseded switch returns the current status, which can match promotion's workspace check after another account took over. Promotion would then allow that workspace for every view and go on to act for the old intent under the new account. Fence the continuation on the switch's generation before granting anything, return the usual activation failure, and re-check the account wherever promotion re-checks the workspace.
…t the local clock

Comparing the server's expires_at with local time made a client clock more than a token lifetime ahead fail every non-anchor switch and view mint, burning the mint budget on retries. Use exp minus iat from the JWT, counted from when the request was sent, so a slow clock cannot stretch the token past its real validity either. Reject only a zero or negative lifetime, and fall back to expires_at when the token has no usable iat or exp.
…ly arrived

The lifetime branch only checked that the lifetime was positive, so a token whose requestedAt plus lifetime had already passed was stored, activated and delivered to a view. Keep the skew-safe calculation and also require the deadline to be in the future, with the same retryable failure.
Same-account reauthorization could end on a workspace the consent screen picked, with no allowlist entry, so a view read signed_in but every token request was refused. CloudSession marks a reply that ended on the new grant's anchor after a browser trip, main only, and the switch wrapper allows that workspace before broadcasting. A view switch that mints stays isolated to that view.
A consent that returned no mint scope reported a second browser event for one trip. scope_not_granted now arrives as a reauthorize_reason on workspace_switch only. That event stays in PostHog, so Datadog no longer sees this reason.
…nged mid-read

A consent replaces the account inside the same generation, so a token read pending across it could return the previous account's still-valid token, and the client would send it. Capture subject and active workspace, and re-check both with the generation after every await, including the cached fallback and the mint-success path. getGrantAccessToken does the same for the account, and a mint flight no longer posts with a grant from another account.
…s own

- When the access token is past its expiry and the refresh at
  /oauth/token fails for a transient reason (network error, 5xx), a view
  token mint still sends the expired token and Cloud answers 401. That
  401 went straight to logout, so a short outage signed the user out.
- The unauthorized path now treats a 401 for a grant token that is past
  its stored expiry, while the grant still has a refresh token, as
  inconclusive. It asks for a refresh and signs out only when Cloud
  definitively refuses it and no newer sign-in, sign-out or switch has
  started since.
- Every other rejected grant token signs out at once, as before. No
  getter changes what it returns.

@deepme987 deepme987 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.

Agentic Review (re-review)

Verdict: approve. CI green on d45bb57.

  1. Retries never stop: fixed. queuedAt is stored in the encrypted entry (tokenStore.ts:320); entries past the 720h refresh lifetime are dropped without a request (revocation.ts:51); older entries fall back to file mtime (tokenStore.ts:367), and unreadable files are removed once outlived (dropIfOutlived, 4daa5bc).
  2. Old grants skip revoke: fixed. Falls back to CLOUD_CONFIG when no origin is saved (tokenStore.ts:211), and every save stamps the origin. A mismatched issuer just gets a 200 for an unknown token and leaks nothing new (the next refresh already sends it there).
  3. Late sign-in tokens: fixed. Both discard paths queue a revoke (session.ts:149, :519), and a refresh that lands after sign-out is revoked too (rotateGrant). No race with a new sign-in: each sign-in is its own family and revokeUnstored never touches the stored token.
  4. Linux basic_text: reasonably deferred.

Sign-out still clears local tokens immediately (session.ts:173); nothing before clearTokens() waits on the network or throws.

Nit: a future queuedAt (clock ahead at sign-out) is accepted as-is, so the entry retries until that date + 30 days. Optional clamp at tokenStore.ts:367: Math.min(parsed.queuedAt ?? mtime, mtime).

@deepme987 deepme987 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.

Approving per the Agentic Review above; nits are non-blocking.

@dante01yoon
dante01yoon added this pull request to the merge queue Nov 11, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue because a pull request earlier in the stack was removed Nov 11, 2026
@dante01yoon

Copy link
Copy Markdown
Collaborator Author

@deepme987 thanks. Took the nit in 3b3a3e2: a queued revocation is dated no later than its file's mtime (Math.min(queuedAt ?? mtime, mtime)), so a clock running ahead at sign-out cannot stretch the 30-day window. New test queues one a year ahead; it fails without the clamp.

Merge waits for the Cloud prod deploy, as before.

Base automatically changed from desktop-auth/switch-without-browser to main November 11, 2026 18:45
…sign-out

# Conflicts:
#	src/main/cloud/session.test.ts
#	src/main/cloud/session.ts
#	src/main/cloud/tokenStore.test.ts
#	src/main/cloud/tokenStore.ts
#	src/main/index.ts
#	src/main/lib/ipc/switchCloudWorkspace.session.test.ts
@dante01yoon
dante01yoon added this pull request to the merge queue Nov 11, 2026
Merged via the queue into main with commit 05d6fe7 Nov 11, 2026
16 checks passed
@dante01yoon
dante01yoon deleted the desktop-auth/durable-sign-out branch November 11, 2026 18:55
Penguinjanator pushed a commit to Penguinjanator/ComfyUI_frontend that referenced this pull request Nov 14, 2026
…n Desktop mints (Comfy-Org#23229)

Desktop auth: keep partner nodes running past 15 minutes once local
views stop holding Desktop's grant. Solid: code dependency. Dotted: must
be deployed or released first.

```mermaid
graph LR
  C["cloud PR 18763 partner-node scope exemption (merged)"] -. deployed first .-> D
  M["Desktop PR 1961 main-only grant"] --> S["Desktop PR 1968 switch without a browser"]
  S --> O["Desktop PR 1984 sign-out revokes the grant"]
  O --> D["Desktop PR 1983 partner-node token from main"]
  D -. adds the bridge method .-> F["this PR: queue with Desktop's partner-node token"]
  T["cloud PR 18786 temporary: a view's token may mint a partner-node token (merged)"] -. deployed first .-> R["Desktop release with PR 1961"]
  D --> R
  F -. in the frontend ComfyUI pins .-> X["cloud: remove the temporary exception (BE-25895), then the scope exemption (BE-25853)"]
  R -. logins from that build carry the jobs write scope .-> X
  style F stroke-width:3px
```

## Summary

**Why.** A prompt queued in a local ComfyUI view inside Comfy Desktop
carries the credential the view holds. A partner (API) node that runs or
polls after it expires fails with `Unauthorized: Please login first to
use this node`. After [Comfy-Desktop PR
1961](Comfy-Org/Comfy-Desktop#1961) that
credential lasts 15 minutes at most.

**Root cause.** `queueAuthToken` mints the partner-node token itself,
with the token `Auth.getWorkspaceToken` returns. Since Desktop PR 1961
that is a workspace token minted from Desktop's grant, and Cloud lets
such a token mint nothing (`403 auth_type_not_allowed`). The mint fails
on every queue pass, so the prompt keeps the 15-minute workspace token,
which ComfyUI cannot renew.

**How.**

- [Comfy-Desktop PR
1983](Comfy-Org/Comfy-Desktop#1983) adds an
optional bridge method, `Auth.getPartnerNodeToken(workspaceId)`.
Desktop's main process mints the partner-node token with its grant and
renews it.
- `queueAuthToken` asks a signed-in Desktop host for that token first
and queues it as is. It is not cached in `partnerNodeTokens`, because
Desktop owns its renewal.
- When the method is absent (every released Desktop build), rejects, or
returns `null`, the code falls through to today's path unchanged. That
keeps a grant from before the Desktop upgrade working:
`getWorkspaceToken` still returns Desktop's own access token for it, and
today's mint succeeds.
- The read goes through the existing `fetchToken`, so a reply that lands
after the host session or workspace changed is dropped.
- Firebase sign-in, Comfy Cloud and the `partner_node_token` flag off
are untouched.
- Sign-out revocation is unchanged. A view's minted workspace token
cannot call `POST /api/auth/token/revoke` (Cloud answers 403).
[Comfy-Desktop PR
1984](Comfy-Org/Comfy-Desktop#1984) ends the
sessions when it revokes the grant.

**AS IS.** On a Desktop with PR 1961, a new sign-in queues a workspace
token good for 15 minutes. 17 minutes later the request is rejected as
expired and ComfyUI v0.45.0 cannot renew it.

**TO BE.** With Desktop PR 1983 the prompt carries a 90-minute
partner-node token that ComfyUI renews. On released Desktop builds
nothing changes.

| | AS IS | TO BE |
|---|---|---|
| Desktop offers `getPartnerNodeToken` and has a token | frontend mints
with the view's token, Cloud refuses, prompt carries the workspace token
| prompt carries Desktop's partner-node token, no mint request |
| Desktop offers it and returns `null` | same as above | today's path:
mint with the view's token, else the workspace token |
| Desktop build without the method | mint with the host token |
unchanged |
| Firebase, Cloud, flag off | unchanged | unchanged |

Screenshots: none yet. Showing this in the app needs a Desktop build of
PR 1983 loading this branch.

**Release line.** A local view runs the frontend its ComfyUI pins
(`comfyui-frontend-package`, 1.58.5 for ComfyUI v0.45.0). This has to be
on the core lines from 1.58 on before a Desktop build with PR 1961 is
released, hence the `core/1.58`, `core/1.59` and `core/1.60` labels.

**Interim.** [cloud PR
18786](Comfy-Org/cloud#18786) lets a Desktop
view's token mint the partner-node token itself, so the frontends
already in users' installs keep working once Desktop PR 1961 ships. It
is temporary. This PR and Desktop PR 1983 are the lasting path, and the
Cloud exception is removed after they have reached users.

**Overlap.** Comfy-Org#21461 also reads `getPartnerNodeToken`, as part of a
different Desktop design (Comfy-Desktop PR 1775). There a `null` from
the bridge is a failure and the prompt is queued with no token. Here
`null` falls through to today's path.

## Verification

- `partnerNodeQueueToken.test.ts`: the token Desktop hands over is
queued and no mint request is sent (fails without the change). `null` or
a failed bridge call mints as before with the host token. A token that
lands after another account signed in is not queued. The flag off never
calls the bridge.
- `desktopHostSession.test.ts`: the accessor returns the token, and
nothing for `null`, a rejected call or a build without the method. A
token fetched across a sign-out is dropped. All five fail without the
change.
- `pnpm exec vitest run src/platform/auth src/stores/authStore.test.ts
src/scripts/app.test.ts`: 25 files, 907 passed. `pnpm run format:check`,
`pnpm run typecheck`, `oxlint` and `eslint` on the touched folders pass.
- Cross-repo run on 2026-11-10: the ingest handlers of cloud PR 18763
served over local HTTP, Desktop's real `ViewWorkspaceGrants` calling
them, this PR's rule emulated, then ComfyUI v0.45.0's renewal code on
each queued token after a real 17-minute wait. With today's rule the
prompt from a new sign-in carried a workspace token and was rejected as
expired. With this rule it carried a partner-node token that was
accepted and renewed.
- Not verified: this branch running inside a real Desktop build, a real
partner node end to end, Windows.

Linear: FRONT-3925
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants