From 0b0c4083802af0045eeab1c32b54ef121395622c Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sat, 7 Nov 2026 13:11:36 -0500 Subject: [PATCH 01/75] feat(auth): keep the Cloud grant in main and give local views minted 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. --- src/main/cloud/claims.ts | 7 + src/main/cloud/workspaceToken.test.ts | 73 +++++++ src/main/cloud/workspaceToken.ts | 59 ++++++ src/main/lib/embeddedSession.test.ts | 35 +++- src/main/lib/embeddedSession.ts | 26 ++- .../ipc/registerDevPlatformHandlers.test.ts | 26 ++- .../lib/ipc/registerDevPlatformHandlers.ts | 12 +- src/main/lib/viewWorkspaceGrants.test.ts | 184 ++++++++++++++++++ src/main/lib/viewWorkspaceGrants.ts | 147 ++++++++++++++ 9 files changed, 548 insertions(+), 21 deletions(-) create mode 100644 src/main/cloud/workspaceToken.test.ts create mode 100644 src/main/cloud/workspaceToken.ts create mode 100644 src/main/lib/viewWorkspaceGrants.test.ts create mode 100644 src/main/lib/viewWorkspaceGrants.ts diff --git a/src/main/cloud/claims.ts b/src/main/cloud/claims.ts index 524e6ebd1..45122f444 100644 --- a/src/main/cloud/claims.ts +++ b/src/main/cloud/claims.ts @@ -9,6 +9,7 @@ interface AccessTokenClaims { workspace_id?: string workspace_type?: string role?: string + scope?: string } function decodeJwtPayload(token: string): AccessTokenClaims | null { @@ -48,6 +49,12 @@ export function workspaceIdOf(accessToken: string): string | null { return decodeJwtPayload(accessToken)?.workspace_id ?? null } +/** The OAuth scopes a token says it carries; empty when it names none. */ +export function scopesOf(accessToken: string): string[] { + const scope = decodeJwtPayload(accessToken)?.scope + return typeof scope === 'string' ? scope.split(' ').filter(Boolean) : [] +} + /** The account subject a token belongs to, or null for malformed/legacy tokens. */ export function subjectOf(accessToken: string): string | null { return decodeJwtPayload(accessToken)?.sub ?? null diff --git a/src/main/cloud/workspaceToken.test.ts b/src/main/cloud/workspaceToken.test.ts new file mode 100644 index 000000000..12a9040ea --- /dev/null +++ b/src/main/cloud/workspaceToken.test.ts @@ -0,0 +1,73 @@ +// @vitest-environment node +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { mintWorkspaceToken } from './workspaceToken' + +function respond(status: number, body: unknown): void { + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(JSON.stringify(body), { status })) + ) +} + +afterEach(() => { + vi.unstubAllGlobals() +}) + +describe('mintWorkspaceToken', () => { + it('posts the workspace with the access token as Bearer', async () => { + respond(200, { token: 'cloud-jwt', expires_at: '2026-11-07T12:15:00Z' }) + + await expect( + mintWorkspaceToken('oauth-access', 'ws-2', { apiBase: 'https://cloud.test/api/' }) + ).resolves.toEqual({ + kind: 'minted', + token: 'cloud-jwt', + expiresAt: Date.parse('2026-11-07T12:15:00Z') + }) + expect(fetch).toHaveBeenCalledWith( + 'https://cloud.test/api/auth/token', + expect.objectContaining({ + method: 'POST', + headers: expect.objectContaining({ Authorization: 'Bearer oauth-access' }), + body: JSON.stringify({ workspace_id: 'ws-2' }) + }) + ) + }) + + it('reports a grant Cloud will not mint for as refused', async () => { + respond(403, { code: 'oauth_token_mint_refused', message: 'no' }) + + await expect(mintWorkspaceToken('oauth-access', 'ws-1')).resolves.toEqual({ kind: 'refused' }) + }) + + it.each([ + ['another 403', 403, { code: 'sso_required' }], + ['an unavailable workspace', 404, { code: 'NOT_FOUND' }], + ['a rate limit', 429, {}], + ['a server error', 500, {}], + ['a body without a token', 200, { expires_at: '2026-11-07T12:15:00Z' }], + ['an unreadable expiry', 200, { token: 'cloud-jwt', expires_at: 'soon' }] + ])('reports %s as failed', async (_name, status, body) => { + respond(status, body) + + await expect(mintWorkspaceToken('oauth-access', 'ws-1')).resolves.toEqual({ + kind: 'failed', + status + }) + }) + + it('reports a network error as failed', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => { + throw new TypeError('offline') + }) + ) + + await expect(mintWorkspaceToken('oauth-access', 'ws-1')).resolves.toEqual({ + kind: 'failed', + status: null + }) + }) +}) diff --git a/src/main/cloud/workspaceToken.ts b/src/main/cloud/workspaceToken.ts new file mode 100644 index 000000000..2fd60b6a1 --- /dev/null +++ b/src/main/cloud/workspaceToken.ts @@ -0,0 +1,59 @@ +/** + * Workspace token mint: `POST {apiBase}/auth/token` with Desktop's OAuth access + * token as the Bearer. The minted Cloud JWT is what a local ComfyUI view may + * hold; the OAuth access token stays in main. + */ +import { CLOUD_CONFIG } from './config' + +const DEFAULT_TIMEOUT_MS = 20_000 +const OAUTH_MINT_REFUSED = 'oauth_token_mint_refused' + +/** `refused`: Cloud does not let this grant mint a workspace token at all. */ +export type WorkspaceTokenMint = + | { kind: 'minted'; token: string; expiresAt: number } + | { kind: 'refused' } + | { kind: 'failed'; status: number | null } + +export interface MintWorkspaceTokenOptions { + apiBase?: string + timeoutMs?: number +} + +function mintedFrom(body: unknown): WorkspaceTokenMint | null { + if (!body || typeof body !== 'object') return null + const { token, expires_at: expiresAt } = body as { token?: unknown; expires_at?: unknown } + if (typeof token !== 'string' || token === '' || typeof expiresAt !== 'string') return null + const expiresAtMs = Date.parse(expiresAt) + return Number.isFinite(expiresAtMs) ? { kind: 'minted', token, expiresAt: expiresAtMs } : null +} + +function errorCodeOf(body: unknown): unknown { + return body && typeof body === 'object' ? (body as { code?: unknown }).code : undefined +} + +export async function mintWorkspaceToken( + accessToken: string, + workspaceId: string, + options: MintWorkspaceTokenOptions = {} +): Promise { + const base = (options.apiBase ?? CLOUD_CONFIG.apiBase).replace(/\/+$/, '') + let res: Response + try { + res = await fetch(`${base}/auth/token`, { + method: 'POST', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + Authorization: `Bearer ${accessToken}` + }, + body: JSON.stringify({ workspace_id: workspaceId }), + signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS) + }) + } catch { + return { kind: 'failed', status: null } + } + const body: unknown = await res.json().catch(() => null) + if (res.status === 403 && errorCodeOf(body) === OAUTH_MINT_REFUSED) return { kind: 'refused' } + if (!res.ok) return { kind: 'failed', status: res.status } + return mintedFrom(body) ?? { kind: 'failed', status: res.status } +} diff --git a/src/main/lib/embeddedSession.test.ts b/src/main/lib/embeddedSession.test.ts index 3dcf4bd04..a6238afa5 100644 --- a/src/main/lib/embeddedSession.test.ts +++ b/src/main/lib/embeddedSession.test.ts @@ -4,6 +4,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const mocks = vi.hoisted(() => ({ enabled: true, getAccessToken: vi.fn<() => Promise>(), + mint: vi.fn(), + current: 'ws-1', entries: [] as unknown[] })) @@ -11,7 +13,13 @@ vi.mock('./embeddedSessionFlag', () => ({ isEmbeddedSessionEnabled: async () => mocks.enabled })) vi.mock('../devplatform/session', () => ({ - getCloudSession: () => ({ getAccessToken: mocks.getAccessToken }) + getCloudSession: () => ({ + getAccessToken: mocks.getAccessToken, + currentWorkspaceId: () => mocks.current + }) +})) +vi.mock('../cloud/workspaceToken', () => ({ + mintWorkspaceToken: mocks.mint })) vi.mock('../host/registry', () => ({ get comfyWindows() { @@ -31,6 +39,7 @@ import { switchWorkspaceForSender } from './embeddedSession' import type { EmbeddedSessionSender } from './embeddedSession' +import { _resetForTest as resetViewGrants } from './viewWorkspaceGrants' function jwt(claims: Record): string { const b64 = (value: unknown): string => Buffer.from(JSON.stringify(value)).toString('base64url') @@ -38,6 +47,7 @@ function jwt(claims: Record): string { } const ACCESS = jwt({ sub: 'user-1', email: 'a@example.com', workspace_id: 'ws-1' }) +const MINTED = jwt({ sub: 'user-1', workspace_id: 'ws-1', auth_method: 'cloud' }) interface ViewOptions { frameUrl?: string @@ -68,6 +78,11 @@ beforeEach(() => { mocks.enabled = true mocks.entries = [] mocks.getAccessToken.mockReset().mockResolvedValue(ACCESS) + mocks.mint + .mockReset() + .mockResolvedValue({ kind: 'minted', token: MINTED, expiresAt: Date.now() + 900_000 }) + mocks.current = 'ws-1' + resetViewGrants() }) describe('embeddedSession', () => { @@ -84,7 +99,7 @@ describe('embeddedSession', () => { email: 'a@example.com', workspaceId: 'ws-1' }) - await expect(workspaceTokenForSender(event, 'ws-1')).resolves.toBe(ACCESS) + await expect(workspaceTokenForSender(event, 'ws-1')).resolves.toBe(MINTED) }) it.each([ @@ -102,7 +117,7 @@ describe('embeddedSession', () => { }) it.each([ - ['its own workspace', 'ws-1', ACCESS], + ['its own workspace', 'ws-1', MINTED], ['no workspace', undefined, null], ['an empty workspace', '', null], ['another workspace', 'ws-2', null], @@ -133,6 +148,20 @@ describe('embeddedSession', () => { expect(switchWorkspace).toHaveBeenCalledWith('ws-2') }) + it('releases the workspace a view switched to only to that view', async () => { + const switcher = view('http://127.0.0.1:8000') + const bystander = view('http://127.0.0.1:8001') + const switchWorkspace = vi.fn(async () => { + mocks.current = 'ws-2' + mocks.getAccessToken.mockResolvedValue(jwt({ sub: 'user-1', workspace_id: 'ws-2' })) + }) + + await switchWorkspaceForSender(switcher.event, 'ws-2', switchWorkspace) + + await expect(workspaceTokenForSender(switcher.event, 'ws-2')).resolves.toBe(MINTED) + await expect(workspaceTokenForSender(bystander.event, 'ws-2')).resolves.toBeNull() + }) + it.each([ ['a remote view', 'http://192.168.1.20:8188', 'ws-2', ACCESS, { status: 'disabled' }], ['a signed-out session', 'http://127.0.0.1:8000', 'ws-2', null, { status: 'signed_out' }], diff --git a/src/main/lib/embeddedSession.ts b/src/main/lib/embeddedSession.ts index b60296456..24582a37f 100644 --- a/src/main/lib/embeddedSession.ts +++ b/src/main/lib/embeddedSession.ts @@ -3,8 +3,9 @@ * local ComfyUI view, so an SSO user (who has no Firebase account) can sign in * there and run partner nodes. * - * Only a short-lived access token and the identity read from it cross to the - * renderer; the refresh token stays in main. Only the main frame of a + * Only a workspace token minted for the view's allowed workspace and the + * identity read from Desktop's access token cross to the renderer; the OAuth + * grant stays in main. Only the main frame of a * registered comfyView, still on the loopback ComfyUI Desktop loaded into it, * is served. Remote and LAN servers never receive the token. */ @@ -16,6 +17,7 @@ import { comfyWindows, findEntryByComfySender } from '../host/registry' import type { ComfyWindowEntry } from '../host/registry' import type { ComfyDesktop2AuthState } from '../../types/comfyDesktopBridge' import { isEmbeddedSessionEnabled } from './embeddedSessionFlag' +import { getViewWorkspaceGrants } from './viewWorkspaceGrants' export const EMBEDDED_SESSION_CHANNELS = { getState: 'desktop2-auth:get-state', @@ -84,28 +86,23 @@ export async function stateForSender( } /** - * The workspace credential for a trusted view: released only for an exact, - * non-empty workspace that Desktop's session is scoped to. Absent, malformed - * or mismatched scope gets nothing, so a view never runs as a workspace it - * did not name. + * The workspace credential for a trusted view: only for Desktop's current + * workspace, only when it is on that view's allowlist in main, and a minted + * workspace token rather than Desktop's OAuth access token. */ export async function workspaceTokenForSender( event: EmbeddedSessionSender, workspaceId: unknown ): Promise { if (typeof workspaceId !== 'string' || workspaceId === '') return null - const token = await trustedSessionToken(event) - return token && identityOf(token)?.workspaceId === workspaceId ? token : null -} - -async function trustedSessionToken(event: EmbeddedSessionSender): Promise { if (!isTrustedSender(event) || !(await isEmbeddedSessionEnabled())) return null - return getCloudSession().getAccessToken() + return getViewWorkspaceGrants().tokenFor(event.sender, workspaceId) } /** - * Re-scopes Desktop's session to `workspaceId` for a trusted, signed-in view, - * then reads the state back. Anything else returns its state untouched. + * Re-scopes Desktop's session to `workspaceId` for a trusted, signed-in view + * and adds it to that view's allowlist, then reads the state back. Anything + * else returns its state untouched. */ export async function switchWorkspaceForSender( event: EmbeddedSessionSender, @@ -115,6 +112,7 @@ export async function switchWorkspaceForSender( const state = await stateForSender(event) if (state.status !== 'signed_in' || typeof workspaceId !== 'string' || workspaceId === '') return state + getViewWorkspaceGrants().allowView(event.sender, workspaceId) await switchWorkspace(workspaceId) return stateForSender(event) } diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts index 589bbfbc2..a73ff8cb8 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts @@ -45,7 +45,16 @@ const mocks = vi.hoisted(() => ({ buildExportEnvelope: vi.fn(), broadcastToRenderer: vi.fn(), operationAborts: new Map(), - translate: vi.fn((key: string) => key) + translate: vi.fn((key: string) => key), + endViewGrants: vi.fn(), + allowDesktopWorkspace: vi.fn() +})) + +vi.mock('../viewWorkspaceGrants', () => ({ + getViewWorkspaceGrants: () => ({ + endAll: mocks.endViewGrants, + allowDesktop: mocks.allowDesktopWorkspace + }) })) vi.mock('electron', () => ({ @@ -180,6 +189,18 @@ describe('registerDevPlatformHandlers', () => { expect(win.webContents.send).toHaveBeenCalledWith('comfybuilder:authChanged', status) }) + it('signIn ends earlier view grants and lets views hold the consented workspace', async () => { + mocks.login.mockResolvedValue({ signedIn: true, workspaceId: 'w1' }) + + await handler('comfybuilder:signIn')({}) + + expect(mocks.endViewGrants).toHaveBeenCalledOnce() + expect(mocks.allowDesktopWorkspace).toHaveBeenCalledExactlyOnceWith('w1') + expect(mocks.endViewGrants.mock.invocationCallOrder[0]).toBeLessThan( + mocks.allowDesktopWorkspace.mock.invocationCallOrder[0]! + ) + }) + // The regression that made a file-menu sign-in look like nothing happened: // the host window loads no page, so broadcasting only to `getAllWindows()` // reaches an empty webContents and the account chip never repaints. @@ -265,6 +286,7 @@ describe('registerDevPlatformHandlers', () => { onUnauthorized() expect(panel).toHaveBeenCalledWith('comfybuilder:authChanged', { signedIn: false }) + expect(mocks.endViewGrants).toHaveBeenCalledOnce() }) it('skips hosts whose panelView is torn down or absent', async () => { @@ -287,6 +309,7 @@ describe('registerDevPlatformHandlers', () => { const status = await handler('comfybuilder:signOut')({}) expect(status).toEqual({ signedIn: false }) expect(mocks.logout).toHaveBeenCalledOnce() + expect(mocks.endViewGrants).toHaveBeenCalledOnce() expect(win.webContents.send).toHaveBeenCalledWith('comfybuilder:authChanged', { signedIn: false }) @@ -458,6 +481,7 @@ describe('registerDevPlatformHandlers', () => { }) const status = await handler('comfybuilder:switchWorkspace')({}, 'w2') + expect(mocks.allowDesktopWorkspace).toHaveBeenCalledWith('w2') expect(mocks.switchWorkspace).toHaveBeenCalledWith('w2') expect(status).toMatchObject({ workspaceId: 'w2' }) expect(win.webContents.send).toHaveBeenCalledWith('comfybuilder:authChanged', status) diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.ts b/src/main/lib/ipc/registerDevPlatformHandlers.ts index 5f19bcaae..0993ece95 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.ts @@ -17,6 +17,7 @@ import { BrowserWindow, ipcMain, shell } from 'electron' import { comfyWindows } from '../../host/registry' import type { ComfyWindowEntry } from '../../host/registry' import { broadcastEmbeddedSessionChanged } from '../embeddedSession' +import { getViewWorkspaceGrants } from '../viewWorkspaceGrants' import { openSystemModalAsync } from '../../popups/systemModal' import { normalizeSha256 } from '../../comfybuilder/integrity' import { PLATFORM_WEB_BASE_URL } from '../../devplatform/config' @@ -122,6 +123,8 @@ export async function signInToCloud(): Promise { clearVersionCache() const status = await session.login() clearVersionCache() + getViewWorkspaceGrants().endAll() + getViewWorkspaceGrants().allowDesktop(status.workspaceId) broadcastAuthChanged(status) return status } @@ -182,6 +185,7 @@ export async function signOutOfCloud(host: ComfyWindowEntry | undefined): Promis } } session.logout() + getViewWorkspaceGrants().endAll() clearVersionCache() broadcastAuthChanged(SIGNED_OUT) return SIGNED_OUT @@ -203,6 +207,7 @@ export function isSignedInToCloud(): boolean { export function registerDevPlatformHandlers(): void { const session = getCloudSession() setUnauthorizedHandler(() => { + getViewWorkspaceGrants().endAll() clearVersionCache() broadcastAuthChanged(SIGNED_OUT) }) @@ -245,9 +250,10 @@ export function registerDevPlatformHandlers(): void { } ) - ipcMain.handle(DEVPLATFORM_CHANNELS.switchWorkspace, (_event, workspaceId: string) => - switchCloudWorkspace(workspaceId) - ) + ipcMain.handle(DEVPLATFORM_CHANNELS.switchWorkspace, (_event, workspaceId: string) => { + getViewWorkspaceGrants().allowDesktop(workspaceId) + return switchCloudWorkspace(workspaceId) + }) ipcMain.handle( DEVPLATFORM_CHANNELS.promoteLocalInstance, diff --git a/src/main/lib/viewWorkspaceGrants.test.ts b/src/main/lib/viewWorkspaceGrants.test.ts new file mode 100644 index 000000000..afcb58eac --- /dev/null +++ b/src/main/lib/viewWorkspaceGrants.test.ts @@ -0,0 +1,184 @@ +// @vitest-environment node +import { Buffer } from 'node:buffer' + +import type { WebContents } from 'electron' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('../devplatform/session', () => ({ getCloudSession: () => ({}) })) + +import type { WorkspaceTokenMint } from '../cloud/workspaceToken' +import { ViewWorkspaceGrants } from './viewWorkspaceGrants' + +function jwt(claims: Record): string { + const b64 = (value: unknown): string => Buffer.from(JSON.stringify(value)).toString('base64url') + return `${b64({ alg: 'ES256' })}.${b64(claims)}.sig` +} + +function accessToken(workspaceId: string, scope = 'comfy-cloud:user:read'): string { + return jwt({ sub: 'user-1', workspace_id: workspaceId, scope }) +} + +function minted(workspaceId: string): WorkspaceTokenMint { + return { + kind: 'minted', + token: `minted-${workspaceId}`, + expiresAt: Date.now() + 15 * 60_000 + } +} + +function deferred() { + let resolve: (value: T) => void = () => {} + const promise = new Promise((r) => { + resolve = r + }) + return { promise, resolve } +} + +const viewA = { id: 'a' } as unknown as WebContents +const viewB = { id: 'b' } as unknown as WebContents + +let current: string | null +let mint: ReturnType< + typeof vi.fn<(token: string, workspaceId: string) => Promise> +> +let grants: ViewWorkspaceGrants + +function signInAt(workspaceId: string | null): void { + current = workspaceId +} + +beforeEach(() => { + signInAt('ws-1') + mint = vi.fn(async (_token: string, workspaceId: string) => minted(workspaceId)) + grants = new ViewWorkspaceGrants( + { + currentWorkspaceId: () => current, + getAccessToken: async () => (current ? accessToken(current) : null) + }, + mint + ) +}) + +describe('ViewWorkspaceGrants', () => { + it('hands a view the minted token for the workspace Desktop started in, never the access token', async () => { + const token = await grants.tokenFor(viewA, 'ws-1') + + expect(token).toBe('minted-ws-1') + expect(mint).toHaveBeenCalledWith(accessToken('ws-1'), 'ws-1') + }) + + it('reuses a minted token until it nears expiry', async () => { + await grants.tokenFor(viewA, 'ws-1') + await grants.tokenFor(viewB, 'ws-1') + + expect(mint).toHaveBeenCalledOnce() + }) + + it('mints once for concurrent requests', async () => { + const tokens = await Promise.all([ + grants.tokenFor(viewA, 'ws-1'), + grants.tokenFor(viewA, 'ws-1') + ]) + + expect(tokens).toEqual(['minted-ws-1', 'minted-ws-1']) + expect(mint).toHaveBeenCalledOnce() + }) + + it('refuses a workspace that is not Desktop current one', async () => { + await expect(grants.tokenFor(viewA, 'ws-2')).resolves.toBeNull() + expect(mint).not.toHaveBeenCalled() + }) + + it('gives a view a workspace it switched to, but not a view that did not', async () => { + grants.allowView(viewA, 'ws-2') + signInAt('ws-2') + + await expect(grants.tokenFor(viewA, 'ws-2')).resolves.toBe('minted-ws-2') + await expect(grants.tokenFor(viewB, 'ws-2')).resolves.toBeNull() + }) + + it('gives every view a workspace Desktop UI chose', async () => { + grants.allowDesktop('ws-2') + signInAt('ws-2') + + await expect(grants.tokenFor(viewA, 'ws-2')).resolves.toBe('minted-ws-2') + await expect(grants.tokenFor(viewB, 'ws-2')).resolves.toBe('minted-ws-2') + }) + + it('stops handing out a workspace once the view moved on', async () => { + grants.allowView(viewA, 'ws-2') + signInAt('ws-2') + await grants.tokenFor(viewA, 'ws-2') + grants.allowView(viewA, 'ws-3') + signInAt('ws-3') + + await expect(grants.tokenFor(viewA, 'ws-2')).resolves.toBeNull() + }) + + it('drops a mint reply that lands after a newer switch', async () => { + const reply = deferred() + mint.mockReturnValueOnce(reply.promise) + const pending = grants.tokenFor(viewA, 'ws-1') + grants.allowView(viewA, 'ws-2') + signInAt('ws-2') + reply.resolve(minted('ws-1')) + + await expect(pending).resolves.toBeNull() + }) + + it('drops a mint reply that lands after sign-out, and forgets its token', async () => { + const reply = deferred() + mint.mockReturnValueOnce(reply.promise) + const pending = grants.tokenFor(viewA, 'ws-1') + signInAt(null) + grants.endAll() + reply.resolve(minted('ws-1')) + + await expect(pending).resolves.toBeNull() + signInAt('ws-1') + grants.allowDesktop('ws-1') + await grants.tokenFor(viewA, 'ws-1') + expect(mint).toHaveBeenCalledTimes(2) + }) + + it('forgets every view allowlist at sign-out', async () => { + grants.allowView(viewA, 'ws-2') + grants.endAll() + signInAt('ws-2') + + await expect(grants.tokenFor(viewA, 'ws-2')).resolves.toBeNull() + }) + + it.each([ + ['a failed mint', { kind: 'failed', status: 503 } as const], + ['an unavailable workspace', { kind: 'failed', status: 404 } as const] + ])('hands out nothing after %s', async (_name, result) => { + mint.mockResolvedValueOnce(result) + + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBeNull() + }) + + describe('while Cloud refuses to mint for this grant', () => { + beforeEach(() => { + mint.mockResolvedValue({ kind: 'refused' }) + }) + + it('keeps handing the pinned access token, and stops asking Cloud', async () => { + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe(accessToken('ws-1')) + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe(accessToken('ws-1')) + expect(mint).toHaveBeenCalledOnce() + }) + + it('never hands an access token holding scopes this build did not ask for', async () => { + grants = new ViewWorkspaceGrants( + { + currentWorkspaceId: () => 'ws-1', + getAccessToken: async () => accessToken('ws-1', 'comfy-cloud:user:read mint') + }, + mint + ) + + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBeNull() + }) + }) +}) diff --git a/src/main/lib/viewWorkspaceGrants.ts b/src/main/lib/viewWorkspaceGrants.ts new file mode 100644 index 000000000..3fed3486d --- /dev/null +++ b/src/main/lib/viewWorkspaceGrants.ts @@ -0,0 +1,147 @@ +/** + * What a local ComfyUI view may hold, decided in main. A view gets a token only + * for Desktop's current workspace, only when that workspace is on its + * allowlist, and never Desktop's OAuth access token once Cloud mints workspace + * tokens for it. Sign-in and sign-out end every grant, so a reply that lands + * after them reaches no view. + */ +import type { WebContents } from 'electron' + +import { scopesOf, workspaceIdOf } from '../cloud/claims' +import { CLOUD_CONFIG } from '../cloud/config' +import { mintWorkspaceToken } from '../cloud/workspaceToken' +import type { WorkspaceTokenMint } from '../cloud/workspaceToken' +import { getCloudSession } from '../devplatform/session' + +const MINT_REFRESH_SKEW_MS = 60_000 +const REQUESTED_SCOPES: ReadonlySet = new Set(CLOUD_CONFIG.scope.split(' ')) + +export interface GrantSession { + currentWorkspaceId(): string | null + getAccessToken(): Promise +} + +export type MintWorkspaceToken = ( + accessToken: string, + workspaceId: string +) => Promise + +interface MintedToken { + token: string + expiresAt: number +} + +/** Holds only the scopes this build asks for, so it cannot mint for other workspaces. */ +function isPinnedGrantToken(accessToken: string): boolean { + return scopesOf(accessToken).every((scope) => REQUESTED_SCOPES.has(scope)) +} + +export class ViewWorkspaceGrants { + private epoch = 0 + private seeded = false + private desktopAllowed = new Set() + private viewAllowed = new WeakMap>() + private minted = new Map() + private minting = new Map>() + private mintRefusedFor: string | null = null + + constructor( + private readonly session: GrantSession, + private readonly mint: MintWorkspaceToken = mintWorkspaceToken + ) {} + + /** Desktop UI (sign-in, dashboard) chose `workspaceId`: every view may hold it. */ + allowDesktop(workspaceId: string | undefined): void { + this.seed() + if (workspaceId) this.desktopAllowed.add(workspaceId) + } + + /** `view` itself asked to switch to `workspaceId`. */ + allowView(view: WebContents, workspaceId: string): void { + this.seed() + const allowed = this.viewAllowed.get(view) ?? new Set() + allowed.add(workspaceId) + this.viewAllowed.set(view, allowed) + } + + /** Sign-in or sign-out: forget every allowlist and token, and drop replies in flight. */ + endAll(): void { + this.epoch += 1 + this.seeded = true + this.desktopAllowed = new Set() + this.viewAllowed = new WeakMap() + this.minted = new Map() + this.minting = new Map() + this.mintRefusedFor = null + } + + async tokenFor(view: WebContents, workspaceId: string): Promise { + if (!this.mayHold(view, workspaceId)) return null + const epoch = this.epoch + const token = await this.workspaceToken(workspaceId, epoch) + return epoch === this.epoch && this.mayHold(view, workspaceId) ? token : null + } + + private seed(): void { + if (this.seeded) return + this.seeded = true + const current = this.session.currentWorkspaceId() + if (current) this.desktopAllowed.add(current) + } + + private mayHold(view: WebContents, workspaceId: string): boolean { + this.seed() + if (this.session.currentWorkspaceId() !== workspaceId) return false + return ( + this.desktopAllowed.has(workspaceId) || this.viewAllowed.get(view)?.has(workspaceId) === true + ) + } + + private async workspaceToken(workspaceId: string, epoch: number): Promise { + const accessToken = await this.session.getAccessToken() + if (!accessToken || workspaceIdOf(accessToken) !== workspaceId) return null + const cached = this.minted.get(workspaceId) + if (cached && cached.expiresAt - MINT_REFRESH_SKEW_MS > Date.now()) return cached.token + if (this.mintRefusedFor === accessToken) return this.unmintedToken(accessToken) + + const result = await this.mintOnce(accessToken, workspaceId) + if (epoch !== this.epoch) return null + if (result.kind === 'minted') { + this.minted.set(workspaceId, { token: result.token, expiresAt: result.expiresAt }) + return result.token + } + if (result.kind === 'refused') { + this.mintRefusedFor = accessToken + return this.unmintedToken(accessToken) + } + return null + } + + private unmintedToken(accessToken: string): string | null { + return isPinnedGrantToken(accessToken) ? accessToken : null + } + + private mintOnce(accessToken: string, workspaceId: string): Promise { + const inFlight = this.minting.get(workspaceId) + if (inFlight) return inFlight + const minting = this.minting + const pending = this.mint(accessToken, workspaceId).finally(() => { + if (minting.get(workspaceId) === pending) minting.delete(workspaceId) + }) + minting.set(workspaceId, pending) + return pending + } +} + +let grants: ViewWorkspaceGrants | null = null + +/** The process-wide view grants, bound to the shared CloudSession. */ +export function getViewWorkspaceGrants(): ViewWorkspaceGrants { + if (!grants) grants = new ViewWorkspaceGrants(getCloudSession()) + return grants +} + +/** @internal: reset the singleton between tests. */ +export function _resetForTest(): void { + grants = null +} From 97d95ef285c6b03166b01f5c9a404ad3d70579b4 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sat, 7 Nov 2026 15:56:06 -0500 Subject: [PATCH 02/75] feat(auth): give local views only minted tokens and ask pre-mint-scope 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. --- src/main/cloud/claims.ts | 7 ++-- src/main/cloud/config.ts | 5 ++- src/main/cloud/workspaceToken.test.ts | 9 +---- src/main/cloud/workspaceToken.ts | 8 ---- src/main/lib/embeddedSession.test.ts | 14 ++++++- src/main/lib/embeddedSession.ts | 4 +- src/main/lib/viewWorkspaceGrants.test.ts | 50 +++++++++++------------- src/main/lib/viewWorkspaceGrants.ts | 33 ++++------------ 8 files changed, 54 insertions(+), 76 deletions(-) diff --git a/src/main/cloud/claims.ts b/src/main/cloud/claims.ts index 45122f444..894c2fb05 100644 --- a/src/main/cloud/claims.ts +++ b/src/main/cloud/claims.ts @@ -1,5 +1,6 @@ import { Buffer } from 'node:buffer' +import { WORKSPACE_MINT_SCOPE } from './config' import type { AuthStatus } from './types' /** Claims read (never verified here; the server does that) from the access-token JWT. */ @@ -49,10 +50,10 @@ export function workspaceIdOf(accessToken: string): string | null { return decodeJwtPayload(accessToken)?.workspace_id ?? null } -/** The OAuth scopes a token says it carries; empty when it names none. */ -export function scopesOf(accessToken: string): string[] { +/** The grant behind this token can mint workspace tokens; false for grants from before the mint scope. */ +export function canMintWorkspaceTokens(accessToken: string): boolean { const scope = decodeJwtPayload(accessToken)?.scope - return typeof scope === 'string' ? scope.split(' ').filter(Boolean) : [] + return typeof scope === 'string' && scope.split(' ').includes(WORKSPACE_MINT_SCOPE) } /** The account subject a token belongs to, or null for malformed/legacy tokens. */ diff --git a/src/main/cloud/config.ts b/src/main/cloud/config.ts index a197e58fe..0dde318ce 100644 --- a/src/main/cloud/config.ts +++ b/src/main/cloud/config.ts @@ -6,6 +6,9 @@ const DEFAULT_ISSUER = 'https://cloud.comfy.org' const DEFAULT_CLIENT_ID = 'comfy-desktop' +/** Lets a grant mint workspace tokens at `POST /api/auth/token`. Placeholder until Cloud names it. */ +export const WORKSPACE_MINT_SCOPE = 'comfy-cloud:workspace-token:mint' + export const CLOUD_ISSUER = process.env.COMFY_CLOUD_ISSUER || DEFAULT_ISSUER export const CLOUD_CONFIG = { @@ -16,7 +19,7 @@ export const CLOUD_CONFIG = { /** Workspace REST base (same host as the issuer). */ apiBase: `${CLOUD_ISSUER}/api`, clientId: process.env.COMFY_CLOUD_CLIENT_ID || DEFAULT_CLIENT_ID, - scope: 'comfy-cloud:user:read', + scope: `comfy-cloud:user:read ${WORKSPACE_MINT_SCOPE}`, resource: `${CLOUD_ISSUER}/api`, audience: 'comfy-cloud' } as const diff --git a/src/main/cloud/workspaceToken.test.ts b/src/main/cloud/workspaceToken.test.ts index 12a9040ea..eb8c772f9 100644 --- a/src/main/cloud/workspaceToken.test.ts +++ b/src/main/cloud/workspaceToken.test.ts @@ -35,14 +35,9 @@ describe('mintWorkspaceToken', () => { ) }) - it('reports a grant Cloud will not mint for as refused', async () => { - respond(403, { code: 'oauth_token_mint_refused', message: 'no' }) - - await expect(mintWorkspaceToken('oauth-access', 'ws-1')).resolves.toEqual({ kind: 'refused' }) - }) - it.each([ - ['another 403', 403, { code: 'sso_required' }], + ['a refused grant', 403, { code: 'oauth_token_mint_refused' }], + ['an SSO-enforced workspace', 403, { code: 'sso_required' }], ['an unavailable workspace', 404, { code: 'NOT_FOUND' }], ['a rate limit', 429, {}], ['a server error', 500, {}], diff --git a/src/main/cloud/workspaceToken.ts b/src/main/cloud/workspaceToken.ts index 2fd60b6a1..b3e366d2e 100644 --- a/src/main/cloud/workspaceToken.ts +++ b/src/main/cloud/workspaceToken.ts @@ -6,12 +6,9 @@ import { CLOUD_CONFIG } from './config' const DEFAULT_TIMEOUT_MS = 20_000 -const OAUTH_MINT_REFUSED = 'oauth_token_mint_refused' -/** `refused`: Cloud does not let this grant mint a workspace token at all. */ export type WorkspaceTokenMint = | { kind: 'minted'; token: string; expiresAt: number } - | { kind: 'refused' } | { kind: 'failed'; status: number | null } export interface MintWorkspaceTokenOptions { @@ -27,10 +24,6 @@ function mintedFrom(body: unknown): WorkspaceTokenMint | null { return Number.isFinite(expiresAtMs) ? { kind: 'minted', token, expiresAt: expiresAtMs } : null } -function errorCodeOf(body: unknown): unknown { - return body && typeof body === 'object' ? (body as { code?: unknown }).code : undefined -} - export async function mintWorkspaceToken( accessToken: string, workspaceId: string, @@ -53,7 +46,6 @@ export async function mintWorkspaceToken( return { kind: 'failed', status: null } } const body: unknown = await res.json().catch(() => null) - if (res.status === 403 && errorCodeOf(body) === OAUTH_MINT_REFUSED) return { kind: 'refused' } if (!res.ok) return { kind: 'failed', status: res.status } return mintedFrom(body) ?? { kind: 'failed', status: res.status } } diff --git a/src/main/lib/embeddedSession.test.ts b/src/main/lib/embeddedSession.test.ts index a6238afa5..a71b71ee4 100644 --- a/src/main/lib/embeddedSession.test.ts +++ b/src/main/lib/embeddedSession.test.ts @@ -39,11 +39,12 @@ import { switchWorkspaceForSender } from './embeddedSession' import type { EmbeddedSessionSender } from './embeddedSession' +import { CLOUD_CONFIG } from '../cloud/config' import { _resetForTest as resetViewGrants } from './viewWorkspaceGrants' function jwt(claims: Record): string { const b64 = (value: unknown): string => Buffer.from(JSON.stringify(value)).toString('base64url') - return `${b64({ alg: 'ES256' })}.${b64(claims)}.sig` + return `${b64({ alg: 'ES256' })}.${b64({ scope: CLOUD_CONFIG.scope, ...claims })}.sig` } const ACCESS = jwt({ sub: 'user-1', email: 'a@example.com', workspace_id: 'ws-1' }) @@ -209,6 +210,17 @@ describe('embeddedSession', () => { expect(mocks.getAccessToken).not.toHaveBeenCalled() }) + it('asks a view to sign in again, and hands it nothing, while the grant predates the mint scope', async () => { + mocks.getAccessToken.mockResolvedValue( + jwt({ sub: 'user-1', workspace_id: 'ws-1', scope: 'comfy-cloud:user:read' }) + ) + const { event } = view('http://127.0.0.1:8000') + + await expect(stateForSender(event)).resolves.toEqual({ status: 'signed_out' }) + await expect(workspaceTokenForSender(event, 'ws-1')).resolves.toBeNull() + expect(mocks.mint).not.toHaveBeenCalled() + }) + it('reads signed_out when Desktop has no session', async () => { mocks.getAccessToken.mockResolvedValue(null) const { event } = view('http://127.0.0.1:8000') diff --git a/src/main/lib/embeddedSession.ts b/src/main/lib/embeddedSession.ts index 24582a37f..e55592d46 100644 --- a/src/main/lib/embeddedSession.ts +++ b/src/main/lib/embeddedSession.ts @@ -11,7 +11,7 @@ */ import type { WebContents, WebFrameMain } from 'electron' -import { identityOf } from '../cloud/claims' +import { canMintWorkspaceTokens, identityOf } from '../cloud/claims' import { getCloudSession } from '../devplatform/session' import { comfyWindows, findEntryByComfySender } from '../host/registry' import type { ComfyWindowEntry } from '../host/registry' @@ -75,7 +75,7 @@ export function isTrustedSender({ sender, senderFrame }: EmbeddedSessionSender): async function sessionState(): Promise { if (!(await isEmbeddedSessionEnabled())) return DISABLED const token = await getCloudSession().getAccessToken() - const identity = token ? identityOf(token) : null + const identity = token && canMintWorkspaceTokens(token) ? identityOf(token) : null return identity ? { status: 'signed_in', ...identity } : { status: 'signed_out' } } diff --git a/src/main/lib/viewWorkspaceGrants.test.ts b/src/main/lib/viewWorkspaceGrants.test.ts index afcb58eac..93d5dbe7a 100644 --- a/src/main/lib/viewWorkspaceGrants.test.ts +++ b/src/main/lib/viewWorkspaceGrants.test.ts @@ -6,6 +6,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' vi.mock('../devplatform/session', () => ({ getCloudSession: () => ({}) })) +import { CLOUD_CONFIG } from '../cloud/config' import type { WorkspaceTokenMint } from '../cloud/workspaceToken' import { ViewWorkspaceGrants } from './viewWorkspaceGrants' @@ -14,7 +15,7 @@ function jwt(claims: Record): string { return `${b64({ alg: 'ES256' })}.${b64(claims)}.sig` } -function accessToken(workspaceId: string, scope = 'comfy-cloud:user:read'): string { +function accessToken(workspaceId: string, scope: string = CLOUD_CONFIG.scope): string { return jwt({ sub: 'user-1', workspace_id: workspaceId, scope }) } @@ -149,36 +150,29 @@ describe('ViewWorkspaceGrants', () => { await expect(grants.tokenFor(viewA, 'ws-2')).resolves.toBeNull() }) - it.each([ - ['a failed mint', { kind: 'failed', status: 503 } as const], - ['an unavailable workspace', { kind: 'failed', status: 404 } as const] - ])('hands out nothing after %s', async (_name, result) => { - mint.mockResolvedValueOnce(result) + it.each<[string, number | null]>([ + ['a refused grant', 403], + ['an SSO-enforced workspace', 403], + ['an unavailable workspace', 404], + ['a rate limit', 429], + ['a server error', 503], + ['a network error', null] + ])('hands out nothing after %s', async (_name, status) => { + mint.mockResolvedValue({ kind: 'failed', status }) await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBeNull() }) - describe('while Cloud refuses to mint for this grant', () => { - beforeEach(() => { - mint.mockResolvedValue({ kind: 'refused' }) - }) - - it('keeps handing the pinned access token, and stops asking Cloud', async () => { - await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe(accessToken('ws-1')) - await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe(accessToken('ws-1')) - expect(mint).toHaveBeenCalledOnce() - }) - - it('never hands an access token holding scopes this build did not ask for', async () => { - grants = new ViewWorkspaceGrants( - { - currentWorkspaceId: () => 'ws-1', - getAccessToken: async () => accessToken('ws-1', 'comfy-cloud:user:read mint') - }, - mint - ) - - await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBeNull() - }) + it('hands out nothing, and does not ask Cloud, for a grant without the mint scope', async () => { + grants = new ViewWorkspaceGrants( + { + currentWorkspaceId: () => 'ws-1', + getAccessToken: async () => accessToken('ws-1', 'comfy-cloud:user:read') + }, + mint + ) + + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBeNull() + expect(mint).not.toHaveBeenCalled() }) }) diff --git a/src/main/lib/viewWorkspaceGrants.ts b/src/main/lib/viewWorkspaceGrants.ts index 3fed3486d..bedc381b0 100644 --- a/src/main/lib/viewWorkspaceGrants.ts +++ b/src/main/lib/viewWorkspaceGrants.ts @@ -1,20 +1,18 @@ /** * What a local ComfyUI view may hold, decided in main. A view gets a token only * for Desktop's current workspace, only when that workspace is on its - * allowlist, and never Desktop's OAuth access token once Cloud mints workspace - * tokens for it. Sign-in and sign-out end every grant, so a reply that lands + * allowlist, and only a minted workspace token, never Desktop's OAuth access + * token. Sign-in and sign-out end every grant, so a reply that lands * after them reaches no view. */ import type { WebContents } from 'electron' -import { scopesOf, workspaceIdOf } from '../cloud/claims' -import { CLOUD_CONFIG } from '../cloud/config' +import { canMintWorkspaceTokens, workspaceIdOf } from '../cloud/claims' import { mintWorkspaceToken } from '../cloud/workspaceToken' import type { WorkspaceTokenMint } from '../cloud/workspaceToken' import { getCloudSession } from '../devplatform/session' const MINT_REFRESH_SKEW_MS = 60_000 -const REQUESTED_SCOPES: ReadonlySet = new Set(CLOUD_CONFIG.scope.split(' ')) export interface GrantSession { currentWorkspaceId(): string | null @@ -31,11 +29,6 @@ interface MintedToken { expiresAt: number } -/** Holds only the scopes this build asks for, so it cannot mint for other workspaces. */ -function isPinnedGrantToken(accessToken: string): boolean { - return scopesOf(accessToken).every((scope) => REQUESTED_SCOPES.has(scope)) -} - export class ViewWorkspaceGrants { private epoch = 0 private seeded = false @@ -43,7 +36,6 @@ export class ViewWorkspaceGrants { private viewAllowed = new WeakMap>() private minted = new Map() private minting = new Map>() - private mintRefusedFor: string | null = null constructor( private readonly session: GrantSession, @@ -72,7 +64,6 @@ export class ViewWorkspaceGrants { this.viewAllowed = new WeakMap() this.minted = new Map() this.minting = new Map() - this.mintRefusedFor = null } async tokenFor(view: WebContents, workspaceId: string): Promise { @@ -100,25 +91,15 @@ export class ViewWorkspaceGrants { private async workspaceToken(workspaceId: string, epoch: number): Promise { const accessToken = await this.session.getAccessToken() if (!accessToken || workspaceIdOf(accessToken) !== workspaceId) return null + if (!canMintWorkspaceTokens(accessToken)) return null const cached = this.minted.get(workspaceId) if (cached && cached.expiresAt - MINT_REFRESH_SKEW_MS > Date.now()) return cached.token - if (this.mintRefusedFor === accessToken) return this.unmintedToken(accessToken) const result = await this.mintOnce(accessToken, workspaceId) if (epoch !== this.epoch) return null - if (result.kind === 'minted') { - this.minted.set(workspaceId, { token: result.token, expiresAt: result.expiresAt }) - return result.token - } - if (result.kind === 'refused') { - this.mintRefusedFor = accessToken - return this.unmintedToken(accessToken) - } - return null - } - - private unmintedToken(accessToken: string): string | null { - return isPinnedGrantToken(accessToken) ? accessToken : null + if (result.kind !== 'minted') return null + this.minted.set(workspaceId, { token: result.token, expiresAt: result.expiresAt }) + return result.token } private mintOnce(accessToken: string, workspaceId: string): Promise { From a53ca1d96f059ea7ec7faa6788ebbfc82cc7e673 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sat, 7 Nov 2026 23:36:43 -0500 Subject: [PATCH 03/75] fix: bind view workspace tokens to the account and drop pre-sign-out requests before minting --- src/main/cloud/workspaceToken.ts | 6 +--- src/main/lib/viewWorkspaceGrants.test.ts | 38 +++++++++++++++++++++++- src/main/lib/viewWorkspaceGrants.ts | 35 ++++++++++++---------- 3 files changed, 58 insertions(+), 21 deletions(-) diff --git a/src/main/cloud/workspaceToken.ts b/src/main/cloud/workspaceToken.ts index b3e366d2e..abc0286ec 100644 --- a/src/main/cloud/workspaceToken.ts +++ b/src/main/cloud/workspaceToken.ts @@ -1,8 +1,4 @@ -/** - * Workspace token mint: `POST {apiBase}/auth/token` with Desktop's OAuth access - * token as the Bearer. The minted Cloud JWT is what a local ComfyUI view may - * hold; the OAuth access token stays in main. - */ +/** Mints a workspace token at `POST {apiBase}/auth/token` with Desktop's OAuth access token. */ import { CLOUD_CONFIG } from './config' const DEFAULT_TIMEOUT_MS = 20_000 diff --git a/src/main/lib/viewWorkspaceGrants.test.ts b/src/main/lib/viewWorkspaceGrants.test.ts index 93d5dbe7a..ec9e783af 100644 --- a/src/main/lib/viewWorkspaceGrants.test.ts +++ b/src/main/lib/viewWorkspaceGrants.test.ts @@ -16,7 +16,7 @@ function jwt(claims: Record): string { } function accessToken(workspaceId: string, scope: string = CLOUD_CONFIG.scope): string { - return jwt({ sub: 'user-1', workspace_id: workspaceId, scope }) + return jwt({ sub: user, workspace_id: workspaceId, scope }) } function minted(workspaceId: string): WorkspaceTokenMint { @@ -39,6 +39,7 @@ const viewA = { id: 'a' } as unknown as WebContents const viewB = { id: 'b' } as unknown as WebContents let current: string | null +let user: string let mint: ReturnType< typeof vi.fn<(token: string, workspaceId: string) => Promise> > @@ -49,6 +50,7 @@ function signInAt(workspaceId: string | null): void { } beforeEach(() => { + user = 'user-1' signInAt('ws-1') mint = vi.fn(async (_token: string, workspaceId: string) => minted(workspaceId)) grants = new ViewWorkspaceGrants( @@ -131,6 +133,7 @@ describe('ViewWorkspaceGrants', () => { const reply = deferred() mint.mockReturnValueOnce(reply.promise) const pending = grants.tokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(mint).toHaveBeenCalledOnce()) signInAt(null) grants.endAll() reply.resolve(minted('ws-1')) @@ -175,4 +178,37 @@ describe('ViewWorkspaceGrants', () => { await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBeNull() expect(mint).not.toHaveBeenCalled() }) + + it('never hands one account a token minted for another account in the same workspace', async () => { + await grants.tokenFor(viewA, 'ws-1') + user = 'user-2' + + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe('minted-ws-1') + expect(mint).toHaveBeenCalledTimes(2) + expect(mint).toHaveBeenLastCalledWith(accessToken('ws-1'), 'ws-1') + }) + + it('does not let a request from before sign-out start a mint the next session joins', async () => { + const before = deferred() + let reads = 0 + grants = new ViewWorkspaceGrants( + { + currentWorkspaceId: () => current, + getAccessToken: () => + reads++ === 0 ? before.promise : Promise.resolve(accessToken('ws-1')) + }, + mint + ) + const stale = grants.tokenFor(viewA, 'ws-1') + const firstUserToken = accessToken('ws-1') + grants.endAll() + grants.allowDesktop('ws-1') + user = 'user-2' + before.resolve(firstUserToken) + + await expect(stale).resolves.toBeNull() + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe('minted-ws-1') + expect(mint).toHaveBeenCalledOnce() + expect(mint).toHaveBeenCalledWith(accessToken('ws-1'), 'ws-1') + }) }) diff --git a/src/main/lib/viewWorkspaceGrants.ts b/src/main/lib/viewWorkspaceGrants.ts index bedc381b0..482ab176c 100644 --- a/src/main/lib/viewWorkspaceGrants.ts +++ b/src/main/lib/viewWorkspaceGrants.ts @@ -1,13 +1,6 @@ -/** - * What a local ComfyUI view may hold, decided in main. A view gets a token only - * for Desktop's current workspace, only when that workspace is on its - * allowlist, and only a minted workspace token, never Desktop's OAuth access - * token. Sign-in and sign-out end every grant, so a reply that lands - * after them reaches no view. - */ import type { WebContents } from 'electron' -import { canMintWorkspaceTokens, workspaceIdOf } from '../cloud/claims' +import { canMintWorkspaceTokens, subjectOf, workspaceIdOf } from '../cloud/claims' import { mintWorkspaceToken } from '../cloud/workspaceToken' import type { WorkspaceTokenMint } from '../cloud/workspaceToken' import { getCloudSession } from '../devplatform/session' @@ -24,6 +17,10 @@ export type MintWorkspaceToken = ( workspaceId: string ) => Promise +function mintKey(subject: string, workspaceId: string): string { + return JSON.stringify([subject, workspaceId]) +} + interface MintedToken { token: string expiresAt: number @@ -90,26 +87,34 @@ export class ViewWorkspaceGrants { private async workspaceToken(workspaceId: string, epoch: number): Promise { const accessToken = await this.session.getAccessToken() + if (epoch !== this.epoch) return null if (!accessToken || workspaceIdOf(accessToken) !== workspaceId) return null if (!canMintWorkspaceTokens(accessToken)) return null - const cached = this.minted.get(workspaceId) + const subject = subjectOf(accessToken) + if (!subject) return null + const key = mintKey(subject, workspaceId) + const cached = this.minted.get(key) if (cached && cached.expiresAt - MINT_REFRESH_SKEW_MS > Date.now()) return cached.token - const result = await this.mintOnce(accessToken, workspaceId) + const result = await this.mintOnce(accessToken, key, workspaceId) if (epoch !== this.epoch) return null if (result.kind !== 'minted') return null - this.minted.set(workspaceId, { token: result.token, expiresAt: result.expiresAt }) + this.minted.set(key, { token: result.token, expiresAt: result.expiresAt }) return result.token } - private mintOnce(accessToken: string, workspaceId: string): Promise { - const inFlight = this.minting.get(workspaceId) + private mintOnce( + accessToken: string, + key: string, + workspaceId: string + ): Promise { + const inFlight = this.minting.get(key) if (inFlight) return inFlight const minting = this.minting const pending = this.mint(accessToken, workspaceId).finally(() => { - if (minting.get(workspaceId) === pending) minting.delete(workspaceId) + if (minting.get(key) === pending) minting.delete(key) }) - minting.set(workspaceId, pending) + minting.set(key, pending) return pending } } From b3437a134a947c9b7e0037d4c9a2eea5c4c1f218 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sat, 7 Nov 2026 23:48:26 -0500 Subject: [PATCH 04/75] fix: drop view tokens minted for a replaced account and keep superseded sign-ins off the view grants --- src/main/cloud/session.ts | 13 ++++++++++++- src/main/lib/embeddedSession.test.ts | 3 ++- .../lib/ipc/registerDevPlatformHandlers.test.ts | 12 ++++++++++++ src/main/lib/ipc/registerDevPlatformHandlers.ts | 10 +++++++--- src/main/lib/viewWorkspaceGrants.test.ts | 16 ++++++++++++++++ src/main/lib/viewWorkspaceGrants.ts | 3 ++- 6 files changed, 51 insertions(+), 6 deletions(-) diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index e26bfc5b8..45c662f4d 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -7,7 +7,7 @@ * the main process; the UI only ever gets {@link AuthStatus} + {@link Workspace}. */ import type { TokenProvider } from '../comfybuilder' -import { workspaceIdOf } from './claims' +import { subjectOf, workspaceIdOf } from './claims' import type { OAuthOptions } from './oauth' import { openAuthorizePage, refresh, signIn } from './oauth' import { @@ -76,6 +76,17 @@ export class CloudSession { return getAuthStatus().signedIn } + /** Bumped by every login, workspace switch and logout. */ + currentAuthGeneration(): number { + return this.authGeneration + } + + /** The account the active token belongs to, or null when signed out. */ + currentSubject(): string | null { + const t = loadTokens() + return t ? subjectOf(t.accessToken) : null + } + /** The workspace the active token is scoped to, or null when signed out. */ currentWorkspaceId(): string | null { const t = loadTokens() diff --git a/src/main/lib/embeddedSession.test.ts b/src/main/lib/embeddedSession.test.ts index a71b71ee4..17333006a 100644 --- a/src/main/lib/embeddedSession.test.ts +++ b/src/main/lib/embeddedSession.test.ts @@ -15,7 +15,8 @@ vi.mock('./embeddedSessionFlag', () => ({ vi.mock('../devplatform/session', () => ({ getCloudSession: () => ({ getAccessToken: mocks.getAccessToken, - currentWorkspaceId: () => mocks.current + currentWorkspaceId: () => mocks.current, + currentSubject: () => (mocks.current ? 'user-1' : null) }) })) vi.mock('../cloud/workspaceToken', () => ({ diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts index a73ff8cb8..d71ba3b85 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts @@ -7,6 +7,7 @@ const mocks = vi.hoisted(() => ({ openSystemModalAsync: vi.fn(async () => false), // session login: vi.fn(), + currentAuthGeneration: vi.fn(() => 1), logout: vi.fn(), status: vi.fn(), isSignedIn: vi.fn(), @@ -70,6 +71,7 @@ vi.mock('../../popups/systemModal', () => ({ vi.mock('../../devplatform/session', () => ({ getCloudSession: () => ({ login: mocks.login, + currentAuthGeneration: mocks.currentAuthGeneration, logout: mocks.logout, status: mocks.status, isSignedIn: mocks.isSignedIn, @@ -201,6 +203,16 @@ describe('registerDevPlatformHandlers', () => { ) }) + it('signIn leaves view grants alone when a newer switch superseded it', async () => { + mocks.currentAuthGeneration.mockReturnValueOnce(1).mockReturnValueOnce(2) + mocks.login.mockResolvedValue({ signedIn: true, workspaceId: 'w2' }) + + await handler('comfybuilder:signIn')({}) + + expect(mocks.endViewGrants).not.toHaveBeenCalled() + expect(mocks.allowDesktopWorkspace).not.toHaveBeenCalled() + }) + // The regression that made a file-menu sign-in look like nothing happened: // the host window loads no page, so broadcasting only to `getAllWindows()` // reaches an empty webContents and the account chip never repaints. diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.ts b/src/main/lib/ipc/registerDevPlatformHandlers.ts index 0993ece95..df3e877c4 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.ts @@ -121,10 +121,14 @@ export function broadcastAuthChanged(status: AuthStatus): void { export async function signInToCloud(): Promise { const session = getCloudSession() clearVersionCache() - const status = await session.login() + const login = session.login() + const generation = session.currentAuthGeneration() + const status = await login clearVersionCache() - getViewWorkspaceGrants().endAll() - getViewWorkspaceGrants().allowDesktop(status.workspaceId) + if (session.currentAuthGeneration() === generation) { + getViewWorkspaceGrants().endAll() + getViewWorkspaceGrants().allowDesktop(status.workspaceId) + } broadcastAuthChanged(status) return status } diff --git a/src/main/lib/viewWorkspaceGrants.test.ts b/src/main/lib/viewWorkspaceGrants.test.ts index ec9e783af..f80a96c86 100644 --- a/src/main/lib/viewWorkspaceGrants.test.ts +++ b/src/main/lib/viewWorkspaceGrants.test.ts @@ -56,6 +56,7 @@ beforeEach(() => { grants = new ViewWorkspaceGrants( { currentWorkspaceId: () => current, + currentSubject: () => (current ? user : null), getAccessToken: async () => (current ? accessToken(current) : null) }, mint @@ -170,6 +171,7 @@ describe('ViewWorkspaceGrants', () => { grants = new ViewWorkspaceGrants( { currentWorkspaceId: () => 'ws-1', + currentSubject: () => user, getAccessToken: async () => accessToken('ws-1', 'comfy-cloud:user:read') }, mint @@ -194,6 +196,7 @@ describe('ViewWorkspaceGrants', () => { grants = new ViewWorkspaceGrants( { currentWorkspaceId: () => current, + currentSubject: () => (current ? user : null), getAccessToken: () => reads++ === 0 ? before.promise : Promise.resolve(accessToken('ws-1')) }, @@ -211,4 +214,17 @@ describe('ViewWorkspaceGrants', () => { expect(mint).toHaveBeenCalledOnce() expect(mint).toHaveBeenCalledWith(accessToken('ws-1'), 'ws-1') }) + + it('drops a mint reply that lands after another account signed in to the same workspace', async () => { + const reply = deferred() + mint.mockReturnValueOnce(reply.promise) + const pending = grants.tokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(mint).toHaveBeenCalledOnce()) + user = 'user-2' + reply.resolve(minted('ws-1')) + + await expect(pending).resolves.toBeNull() + await grants.tokenFor(viewA, 'ws-1') + expect(mint).toHaveBeenCalledTimes(2) + }) }) diff --git a/src/main/lib/viewWorkspaceGrants.ts b/src/main/lib/viewWorkspaceGrants.ts index 482ab176c..675b87ed3 100644 --- a/src/main/lib/viewWorkspaceGrants.ts +++ b/src/main/lib/viewWorkspaceGrants.ts @@ -9,6 +9,7 @@ const MINT_REFRESH_SKEW_MS = 60_000 export interface GrantSession { currentWorkspaceId(): string | null + currentSubject(): string | null getAccessToken(): Promise } @@ -97,7 +98,7 @@ export class ViewWorkspaceGrants { if (cached && cached.expiresAt - MINT_REFRESH_SKEW_MS > Date.now()) return cached.token const result = await this.mintOnce(accessToken, key, workspaceId) - if (epoch !== this.epoch) return null + if (epoch !== this.epoch || this.session.currentSubject() !== subject) return null if (result.kind !== 'minted') return null this.minted.set(key, { token: result.token, expiresAt: result.expiresAt }) return result.token From 515b9f8d7c0951c555a2d9c5752f15761bf62ffe Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sat, 7 Nov 2026 23:51:35 -0500 Subject: [PATCH 05/75] fix: check the account when delivering a cached view token --- src/main/lib/viewWorkspaceGrants.test.ts | 21 +++++++++++++++++++++ src/main/lib/viewWorkspaceGrants.ts | 17 ++++++++++++----- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/src/main/lib/viewWorkspaceGrants.test.ts b/src/main/lib/viewWorkspaceGrants.test.ts index f80a96c86..c98e93122 100644 --- a/src/main/lib/viewWorkspaceGrants.test.ts +++ b/src/main/lib/viewWorkspaceGrants.test.ts @@ -227,4 +227,25 @@ describe('ViewWorkspaceGrants', () => { await grants.tokenFor(viewA, 'ws-1') expect(mint).toHaveBeenCalledTimes(2) }) + + it('does not hand a cached token to an account that signed in while it was being read', async () => { + const firstUserToken = accessToken('ws-1') + const slowRead = deferred() + let reads = 0 + grants = new ViewWorkspaceGrants( + { + currentWorkspaceId: () => current, + currentSubject: () => (current ? user : null), + getAccessToken: () => (reads++ === 0 ? Promise.resolve(firstUserToken) : slowRead.promise) + }, + mint + ) + await grants.tokenFor(viewA, 'ws-1') + const pending = grants.tokenFor(viewA, 'ws-1') + user = 'user-2' + slowRead.resolve(firstUserToken) + + await expect(pending).resolves.toBeNull() + expect(mint).toHaveBeenCalledOnce() + }) }) diff --git a/src/main/lib/viewWorkspaceGrants.ts b/src/main/lib/viewWorkspaceGrants.ts index 675b87ed3..aa1085f30 100644 --- a/src/main/lib/viewWorkspaceGrants.ts +++ b/src/main/lib/viewWorkspaceGrants.ts @@ -22,6 +22,11 @@ function mintKey(subject: string, workspaceId: string): string { return JSON.stringify([subject, workspaceId]) } +interface HeldToken { + token: string + subject: string +} + interface MintedToken { token: string expiresAt: number @@ -67,8 +72,9 @@ export class ViewWorkspaceGrants { async tokenFor(view: WebContents, workspaceId: string): Promise { if (!this.mayHold(view, workspaceId)) return null const epoch = this.epoch - const token = await this.workspaceToken(workspaceId, epoch) - return epoch === this.epoch && this.mayHold(view, workspaceId) ? token : null + const held = await this.workspaceToken(workspaceId, epoch) + if (!held || epoch !== this.epoch || !this.mayHold(view, workspaceId)) return null + return this.session.currentSubject() === held.subject ? held.token : null } private seed(): void { @@ -86,7 +92,7 @@ export class ViewWorkspaceGrants { ) } - private async workspaceToken(workspaceId: string, epoch: number): Promise { + private async workspaceToken(workspaceId: string, epoch: number): Promise { const accessToken = await this.session.getAccessToken() if (epoch !== this.epoch) return null if (!accessToken || workspaceIdOf(accessToken) !== workspaceId) return null @@ -95,13 +101,14 @@ export class ViewWorkspaceGrants { if (!subject) return null const key = mintKey(subject, workspaceId) const cached = this.minted.get(key) - if (cached && cached.expiresAt - MINT_REFRESH_SKEW_MS > Date.now()) return cached.token + if (cached && cached.expiresAt - MINT_REFRESH_SKEW_MS > Date.now()) + return { token: cached.token, subject } const result = await this.mintOnce(accessToken, key, workspaceId) if (epoch !== this.epoch || this.session.currentSubject() !== subject) return null if (result.kind !== 'minted') return null this.minted.set(key, { token: result.token, expiresAt: result.expiresAt }) - return result.token + return { token: result.token, subject } } private mintOnce( From f61e0357e161cb4aa2d6107b2e7d7728aa5cb222 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 09:14:31 -0500 Subject: [PATCH 06/75] feat: report view workspace token mints and mirror failures to Datadog --- src/main/lib/viewWorkspaceGrants.test.ts | 27 +++++++++++++++++++++++- src/main/lib/viewWorkspaceGrants.ts | 26 ++++++++++++++++++++--- src/shared/datadogMirroredEvents.test.ts | 5 +++++ src/shared/datadogMirroredEvents.ts | 3 +++ 4 files changed, 57 insertions(+), 4 deletions(-) diff --git a/src/main/lib/viewWorkspaceGrants.test.ts b/src/main/lib/viewWorkspaceGrants.test.ts index c98e93122..f86d7c752 100644 --- a/src/main/lib/viewWorkspaceGrants.test.ts +++ b/src/main/lib/viewWorkspaceGrants.test.ts @@ -5,10 +5,16 @@ import type { WebContents } from 'electron' import { beforeEach, describe, expect, it, vi } from 'vitest' vi.mock('../devplatform/session', () => ({ getCloudSession: () => ({}) })) +vi.mock('./telemetry', () => ({ emit: vi.fn() })) import { CLOUD_CONFIG } from '../cloud/config' import type { WorkspaceTokenMint } from '../cloud/workspaceToken' -import { ViewWorkspaceGrants } from './viewWorkspaceGrants' +import * as mainTelemetry from './telemetry' +import { + VIEW_TOKEN_MINT_FAILED_EVENT, + VIEW_TOKEN_MINTED_EVENT, + ViewWorkspaceGrants +} from './viewWorkspaceGrants' function jwt(claims: Record): string { const b64 = (value: unknown): string => Buffer.from(JSON.stringify(value)).toString('base64url') @@ -50,6 +56,7 @@ function signInAt(workspaceId: string | null): void { } beforeEach(() => { + vi.mocked(mainTelemetry.emit).mockClear() user = 'user-1' signInAt('ws-1') mint = vi.fn(async (_token: string, workspaceId: string) => minted(workspaceId)) @@ -64,6 +71,24 @@ beforeEach(() => { }) describe('ViewWorkspaceGrants', () => { + it('reports one minted event for views sharing a mint and none for a cached token', async () => { + await Promise.all([grants.tokenFor(viewA, 'ws-1'), grants.tokenFor(viewB, 'ws-1')]) + await grants.tokenFor(viewA, 'ws-1') + + expect(vi.mocked(mainTelemetry.emit).mock.calls).toEqual([[VIEW_TOKEN_MINTED_EVENT]]) + }) + + it.each([ + [{ kind: 'failed', status: 403 } as const, { reason: 'http', http_status: 403 }], + [{ kind: 'failed', status: null } as const, { reason: 'network' }] + ])('reports a failed mint %j', async (result, properties) => { + mint.mockResolvedValueOnce(result) + + expect(await grants.tokenFor(viewA, 'ws-1')).toBeNull() + + expect(mainTelemetry.emit).toHaveBeenCalledWith(VIEW_TOKEN_MINT_FAILED_EVENT, properties) + }) + it('hands a view the minted token for the workspace Desktop started in, never the access token', async () => { const token = await grants.tokenFor(viewA, 'ws-1') diff --git a/src/main/lib/viewWorkspaceGrants.ts b/src/main/lib/viewWorkspaceGrants.ts index aa1085f30..3e1cb028c 100644 --- a/src/main/lib/viewWorkspaceGrants.ts +++ b/src/main/lib/viewWorkspaceGrants.ts @@ -4,9 +4,24 @@ import { canMintWorkspaceTokens, subjectOf, workspaceIdOf } from '../cloud/claim import { mintWorkspaceToken } from '../cloud/workspaceToken' import type { WorkspaceTokenMint } from '../cloud/workspaceToken' import { getCloudSession } from '../devplatform/session' +import * as mainTelemetry from './telemetry' const MINT_REFRESH_SKEW_MS = 60_000 +export const VIEW_TOKEN_MINTED_EVENT = 'comfy.desktop.auth.view_token_minted' +export const VIEW_TOKEN_MINT_FAILED_EVENT = 'comfy.desktop.auth.view_token_mint_failed' + +function reportMint(result: WorkspaceTokenMint): void { + if (result.kind === 'minted') { + mainTelemetry.emit(VIEW_TOKEN_MINTED_EVENT) + return + } + mainTelemetry.emit( + VIEW_TOKEN_MINT_FAILED_EVENT, + result.status === null ? { reason: 'network' } : { reason: 'http', http_status: result.status } + ) +} + export interface GrantSession { currentWorkspaceId(): string | null currentSubject(): string | null @@ -119,9 +134,14 @@ export class ViewWorkspaceGrants { const inFlight = this.minting.get(key) if (inFlight) return inFlight const minting = this.minting - const pending = this.mint(accessToken, workspaceId).finally(() => { - if (minting.get(key) === pending) minting.delete(key) - }) + const pending = this.mint(accessToken, workspaceId) + .then((result) => { + reportMint(result) + return result + }) + .finally(() => { + if (minting.get(key) === pending) minting.delete(key) + }) minting.set(key, pending) return pending } diff --git a/src/shared/datadogMirroredEvents.test.ts b/src/shared/datadogMirroredEvents.test.ts index 12f4cdd1c..59a1b4413 100644 --- a/src/shared/datadogMirroredEvents.test.ts +++ b/src/shared/datadogMirroredEvents.test.ts @@ -18,6 +18,11 @@ describe('isDatadogMirroredEvent', () => { expect(isDatadogMirroredEvent('comfy.desktop.comfyui.boot_completed')).toBe(false) }) + it('mirrors view_token_mint_failed but not view_token_minted', () => { + expect(isDatadogMirroredEvent('comfy.desktop.auth.view_token_mint_failed')).toBe(true) + expect(isDatadogMirroredEvent('comfy.desktop.auth.view_token_minted')).toBe(false) + }) + // The onboarding→install handoff (#1224) splits the same way: install.not_started // is the abort/failure signal ops alerts on; install.dispatched is the paired // funnel success gate (PostHog only). diff --git a/src/shared/datadogMirroredEvents.ts b/src/shared/datadogMirroredEvents.ts index 334eddf9c..dbbd45f19 100644 --- a/src/shared/datadogMirroredEvents.ts +++ b/src/shared/datadogMirroredEvents.ts @@ -28,6 +28,9 @@ */ export const DATADOG_MIRRORED_EVENT_NAMES: ReadonlySet = new Set([ + // Minting a view's workspace token failed. The grant stays in main, so a + // refusal or outage here leaves the hosted view without a token. + 'comfy.desktop.auth.view_token_mint_failed', // ComfyUI execution failures — alert on execution error rate per release // and per gpu_tier. 'comfy.desktop.execution.error', From 3c60527bac4402166368e29616224105dadb794e Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 21:37:47 -0500 Subject: [PATCH 07/75] feat(auth): classify workspace mint replies into outcomes 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. --- src/main/cloud/workspaceToken.test.ts | 123 +++++++++++++++++++++++--- src/main/cloud/workspaceToken.ts | 60 ++++++++++++- 2 files changed, 168 insertions(+), 15 deletions(-) diff --git a/src/main/cloud/workspaceToken.test.ts b/src/main/cloud/workspaceToken.test.ts index eb8c772f9..ebf82a3bb 100644 --- a/src/main/cloud/workspaceToken.test.ts +++ b/src/main/cloud/workspaceToken.test.ts @@ -1,12 +1,13 @@ // @vitest-environment node import { afterEach, describe, expect, it, vi } from 'vitest' -import { mintWorkspaceToken } from './workspaceToken' +import { classifyMint, mintWorkspaceToken } from './workspaceToken' +import type { WorkspaceTokenMint } from './workspaceToken' -function respond(status: number, body: unknown): void { +function respond(status: number, body: unknown, headers: Record = {}): void { vi.stubGlobal( 'fetch', - vi.fn(async () => new Response(JSON.stringify(body), { status })) + vi.fn(async () => new Response(JSON.stringify(body), { status, headers })) ) } @@ -36,19 +37,43 @@ describe('mintWorkspaceToken', () => { }) it.each([ - ['a refused grant', 403, { code: 'oauth_token_mint_refused' }], - ['an SSO-enforced workspace', 403, { code: 'sso_required' }], - ['an unavailable workspace', 404, { code: 'NOT_FOUND' }], - ['a rate limit', 429, {}], - ['a server error', 500, {}], - ['a body without a token', 200, { expires_at: '2026-11-07T12:15:00Z' }], - ['an unreadable expiry', 200, { token: 'cloud-jwt', expires_at: 'soon' }] - ])('reports %s as failed', async (_name, status, body) => { + ['a refused grant', 403, { code: 'oauth_token_mint_refused' }, 'oauth_token_mint_refused'], + ['an SSO-enforced workspace', 403, { code: 'sso_required' }, 'sso_required'], + ['an unavailable workspace', 404, { code: 'NOT_FOUND' }, 'NOT_FOUND'], + ['a rate limit', 429, {}, undefined], + ['a server error', 500, {}, undefined], + [ + 'a disabled mint', + 503, + { code: 'oauth_workspace_mint_disabled' }, + 'oauth_workspace_mint_disabled' + ], + ['a non-string code', 403, { code: 7 }, undefined], + ['a body without a token', 200, { expires_at: '2026-11-07T12:15:00Z' }, undefined], + ['an unreadable expiry', 200, { token: 'cloud-jwt', expires_at: 'soon' }, undefined] + ])('reports %s as failed with its error code', async (_name, status, body, code) => { respond(status, body) await expect(mintWorkspaceToken('oauth-access', 'ws-1')).resolves.toEqual({ kind: 'failed', - status + status, + ...(code ? { code } : {}) + }) + }) + + it.each([ + ['120', 120], + ['0', 0], + ['Wed, 21 Oct 2026 07:28:00 GMT', undefined], + ['-5', undefined], + ['', undefined] + ])('reads a Retry-After of %j', async (header, retryAfterSeconds) => { + respond(429, {}, { 'Retry-After': header }) + + await expect(mintWorkspaceToken('oauth-access', 'ws-1')).resolves.toEqual({ + kind: 'failed', + status: 429, + ...(retryAfterSeconds === undefined ? {} : { retryAfterSeconds }) }) }) @@ -66,3 +91,77 @@ describe('mintWorkspaceToken', () => { }) }) }) + +describe('classifyMint', () => { + const failed = (status: number | null, code?: string): WorkspaceTokenMint => ({ + kind: 'failed', + status, + ...(code ? { code } : {}) + }) + + it('passes a minted token through', () => { + const mint: WorkspaceTokenMint = { kind: 'minted', token: 't', expiresAt: 1 } + + expect(classifyMint(mint)).toEqual(mint) + }) + + it.each([ + ['404 NOT_FOUND', failed(404, 'NOT_FOUND'), { kind: 'unavailable' }], + [ + '403 sso_required', + failed(403, 'sso_required'), + { kind: 'reauthorize', reason: 'sso_required' } + ], + ['403 with no code', failed(403), { kind: 'refused' }], + [ + '403 account_outside_organization', + failed(403, 'account_outside_organization'), + { kind: 'refused' } + ], + [ + '403 personal_workspace_disabled', + failed(403, 'personal_workspace_disabled'), + { kind: 'refused' } + ], + ['403 workspace_access_denied', failed(403, 'workspace_access_denied'), { kind: 'refused' }], + ['403 oauth_token_mint_refused', failed(403, 'oauth_token_mint_refused'), { kind: 'refused' }], + ['403 insufficient_scope', failed(403, 'insufficient_scope'), { kind: 'refused' }], + [ + '403 oauth_derived_mint_refused', + failed(403, 'oauth_derived_mint_refused'), + { kind: 'refused' } + ], + ['400', failed(400), { kind: 'refused' }], + [ + '401 oauth_grant_ended', + failed(401, 'oauth_grant_ended'), + { kind: 'reauthorize', reason: 'grant_ended' } + ], + ['plain 401', failed(401), { kind: 'reauthorize', reason: 'grant_ended' }], + [ + '503 oauth_workspace_mint_disabled', + failed(503, 'oauth_workspace_mint_disabled'), + { kind: 'reauthorize', reason: 'mint_disabled' } + ], + ['503 of another kind', failed(503, 'maintenance'), { kind: 'retryable' }], + [ + '500 with the disabled code', + failed(500, 'oauth_workspace_mint_disabled'), + { kind: 'retryable' } + ], + ['429', failed(429), { kind: 'retryable' }], + ['500', failed(500), { kind: 'retryable' }], + ['503', failed(503), { kind: 'retryable' }], + ['a network failure', failed(null), { kind: 'retryable' }], + ['a malformed 200', failed(200), { kind: 'retryable' }] + ])('classifies %s', (_name, mint, outcome) => { + expect(classifyMint(mint)).toEqual(outcome) + }) + + it('carries Retry-After on a retryable outcome', () => { + expect(classifyMint({ kind: 'failed', status: 429, retryAfterSeconds: 30 })).toEqual({ + kind: 'retryable', + retryAfterSeconds: 30 + }) + }) +}) diff --git a/src/main/cloud/workspaceToken.ts b/src/main/cloud/workspaceToken.ts index abc0286ec..604f7b900 100644 --- a/src/main/cloud/workspaceToken.ts +++ b/src/main/cloud/workspaceToken.ts @@ -5,13 +5,60 @@ const DEFAULT_TIMEOUT_MS = 20_000 export type WorkspaceTokenMint = | { kind: 'minted'; token: string; expiresAt: number } - | { kind: 'failed'; status: number | null } + | { kind: 'failed'; status: number | null; code?: string; retryAfterSeconds?: number } + +/** Why Desktop needs a browser sign-in before it can mint. */ +export type ReauthorizeReason = + | 'sso_required' + | 'grant_ended' + | 'mint_scope_missing' + | 'mint_disabled' + +const MINT_DISABLED_CODE = 'oauth_workspace_mint_disabled' + +/** What a mint reply means for the caller. `grant_ended` is every 401, including an expired access token. */ +export type WorkspaceMintOutcome = + | { kind: 'minted'; token: string; expiresAt: number } + | { kind: 'unavailable' } + | { kind: 'reauthorize'; reason: ReauthorizeReason } + | { kind: 'refused' } + | { kind: 'retryable'; retryAfterSeconds?: number } + +/** Classify one mint reply. A null status is a network failure; a 2xx failure is a malformed body. */ +export function classifyMint(mint: WorkspaceTokenMint): WorkspaceMintOutcome { + if (mint.kind === 'minted') return mint + const { status, code, retryAfterSeconds } = mint + if (status === 503 && code === MINT_DISABLED_CODE) + return { kind: 'reauthorize', reason: 'mint_disabled' } + if (status === null || status === 429 || status >= 500 || status < 300) { + return retryAfterSeconds === undefined + ? { kind: 'retryable' } + : { kind: 'retryable', retryAfterSeconds } + } + if (status === 401) return { kind: 'reauthorize', reason: 'grant_ended' } + if (status === 404) return { kind: 'unavailable' } + if (status === 403 && code === 'sso_required') + return { kind: 'reauthorize', reason: 'sso_required' } + return { kind: 'refused' } +} export interface MintWorkspaceTokenOptions { apiBase?: string timeoutMs?: number } +function errorCodeOf(body: unknown): string | undefined { + if (!body || typeof body !== 'object') return undefined + const { code } = body as { code?: unknown } + return typeof code === 'string' ? code : undefined +} + +function retryAfterSecondsOf(res: Response): number | undefined { + const header = res.headers.get('Retry-After') + const seconds = header === null || header.trim() === '' ? Number.NaN : Number(header) + return Number.isFinite(seconds) && seconds >= 0 ? seconds : undefined +} + function mintedFrom(body: unknown): WorkspaceTokenMint | null { if (!body || typeof body !== 'object') return null const { token, expires_at: expiresAt } = body as { token?: unknown; expires_at?: unknown } @@ -42,6 +89,13 @@ export async function mintWorkspaceToken( return { kind: 'failed', status: null } } const body: unknown = await res.json().catch(() => null) - if (!res.ok) return { kind: 'failed', status: res.status } - return mintedFrom(body) ?? { kind: 'failed', status: res.status } + if (res.ok) return mintedFrom(body) ?? { kind: 'failed', status: res.status } + const code = errorCodeOf(body) + const retryAfterSeconds = retryAfterSecondsOf(res) + return { + kind: 'failed', + status: res.status, + ...(code === undefined ? {} : { code }), + ...(retryAfterSeconds === undefined ? {} : { retryAfterSeconds }) + } } From efe4c57cbddda4c2a9dff98edfe56ac937e9d053 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 21:38:37 -0500 Subject: [PATCH 08/75] feat(auth): add the desktop_workspace_mint_switch ops flag 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. --- src/main/index.ts | 3 + src/main/lib/workspaceMintSwitchFlag.test.ts | 95 ++++++++++++++++++++ src/main/lib/workspaceMintSwitchFlag.ts | 22 +++++ 3 files changed, 120 insertions(+) create mode 100644 src/main/lib/workspaceMintSwitchFlag.test.ts create mode 100644 src/main/lib/workspaceMintSwitchFlag.ts diff --git a/src/main/index.ts b/src/main/index.ts index 31624bd06..017266f69 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -123,6 +123,7 @@ import { initExperiments } from './lib/experiments' import { initCloudFreeRuns } from './lib/cloudFreeRuns' import { initCoreBetaFlags, refreshCoreBetaFlags } from './lib/coreBetaCampaignFlags' import { initEmbeddedSessionFlag } from './lib/embeddedSessionFlag' +import { initWorkspaceMintSwitchFlag } from './lib/workspaceMintSwitchFlag' import { initStaffFlagTargeting } from './lib/staffFlagTargeting' import { initUserTier } from './lib/userTier' import { readSmartAppControlState } from './lib/smartAppControl' @@ -1552,6 +1553,8 @@ if (app.isPackaged && !app.requestSingleInstanceLock()) { void initEmbeddedSessionFlag({ distinctId: installationId }) + void initWorkspaceMintSwitchFlag({ distinctId: installationId }) + const locale = (settings.get('language') as string | undefined) || app.getLocale().split('-')[0] i18n.init(locale) diff --git a/src/main/lib/workspaceMintSwitchFlag.test.ts b/src/main/lib/workspaceMintSwitchFlag.test.ts new file mode 100644 index 000000000..7464b299c --- /dev/null +++ b/src/main/lib/workspaceMintSwitchFlag.test.ts @@ -0,0 +1,95 @@ +import fs from 'fs' +import os from 'os' +import path from 'path' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const getOpsFlagResult = vi.fn() +vi.mock('./telemetry', () => ({ + getOpsFlagResult: (...args: unknown[]) => getOpsFlagResult(...args) +})) + +let configDirectory = '' +vi.mock('./paths', () => ({ configDir: () => configDirectory })) + +import { + _resetForTest, + initWorkspaceMintSwitchFlag, + isWorkspaceMintSwitchEnabled, + WORKSPACE_MINT_SWITCH_FLAG_KEY +} from './workspaceMintSwitchFlag' + +const BOOT = { distinctId: 'install-1' } + +function bootAnswering(result: unknown): Promise { + getOpsFlagResult.mockResolvedValueOnce(result) + return initWorkspaceMintSwitchFlag(BOOT) +} + +beforeEach(() => { + configDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'mint-switch-flag-')) + getOpsFlagResult.mockReset() + _resetForTest() +}) + +afterEach(() => { + _resetForTest() + fs.rmSync(configDirectory, { recursive: true, force: true }) +}) + +describe('workspace mint switch flag', () => { + it('is on before any fetch', async () => { + await expect(isWorkspaceMintSwitchEnabled()).resolves.toBe(true) + }) + + it('stays on when PostHog is unreachable with nothing saved', async () => { + await bootAnswering({ kind: 'unreachable' }) + + await expect(isWorkspaceMintSwitchEnabled()).resolves.toBe(true) + expect(getOpsFlagResult.mock.calls[0]?.[0]).toBe(WORKSPACE_MINT_SWITCH_FLAG_KEY) + }) + + it('turns off when the flag serves false', async () => { + await bootAnswering({ kind: 'value', value: false }) + + await expect(isWorkspaceMintSwitchEnabled()).resolves.toBe(false) + }) + + it('a fetched kill sticks on the next launch while PostHog is unreachable', async () => { + await bootAnswering({ kind: 'value', value: false }) + _resetForTest() + + await bootAnswering({ kind: 'unreachable' }) + + await expect(isWorkspaceMintSwitchEnabled()).resolves.toBe(false) + }) + + it('a kill that arrives after the deadline applies and sticks', async () => { + await bootAnswering({ kind: 'unreachable' }) + const late = getOpsFlagResult.mock.calls[0]?.[3] as (result: unknown) => void + + late({ kind: 'value', value: false }) + + await expect(isWorkspaceMintSwitchEnabled()).resolves.toBe(false) + _resetForTest() + await bootAnswering({ kind: 'unreachable' }) + await expect(isWorkspaceMintSwitchEnabled()).resolves.toBe(false) + }) + + it('a later true lifts a saved kill', async () => { + await bootAnswering({ kind: 'value', value: false }) + _resetForTest() + + await bootAnswering({ kind: 'value', value: true }) + await vi.waitFor(() => expect(getOpsFlagResult).toHaveBeenCalledTimes(2)) + await new Promise((resolve) => setImmediate(resolve)) + + await expect(isWorkspaceMintSwitchEnabled()).resolves.toBe(true) + }) + + it('ignores a value that is not a boolean', async () => { + await bootAnswering({ kind: 'value', value: 'control' }) + + await expect(isWorkspaceMintSwitchEnabled()).resolves.toBe(true) + }) +}) diff --git a/src/main/lib/workspaceMintSwitchFlag.ts b/src/main/lib/workspaceMintSwitchFlag.ts new file mode 100644 index 000000000..2d458933f --- /dev/null +++ b/src/main/lib/workspaceMintSwitchFlag.ts @@ -0,0 +1,22 @@ +/** + * Kill switch for minting workspace tokens from Desktop's grant. Serving `false` is the kill, so + * create it enabled at 100%. Fails open and persists: an unreachable PostHog holds the last answer. + */ +import { makeOpsFlag } from './opsFlag' + +export const WORKSPACE_MINT_SWITCH_FLAG_KEY = 'desktop_workspace_mint_switch' + +const flag = makeOpsFlag({ + key: WORKSPACE_MINT_SWITCH_FLAG_KEY, + fallback: true, + parse: (value) => (typeof value === 'boolean' ? value : undefined), + persist: true +}) + +/** Boot-time fetch. Idempotent within a process; never rejects. */ +export const initWorkspaceMintSwitchFlag = flag.init + +export const isWorkspaceMintSwitchEnabled = flag.get + +/** @internal exposed for tests. */ +export const _resetForTest = flag._resetForTest From 923fbe6b09bde26a4c9618905c7a21446e61d924 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 21:39:32 -0500 Subject: [PATCH 09/75] feat(auth): keep one grant and switch workspaces by minting, with no 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. --- src/main/cloud/index.ts | 13 +- src/main/cloud/session.test.ts | 1326 ++++++++++++++--- src/main/cloud/session.ts | 411 +++-- src/main/cloud/tokenStore.test.ts | 311 +++- src/main/cloud/tokenStore.ts | 232 ++- src/main/cloud/types.ts | 7 + src/main/cloud/workspaces.ts | 6 +- src/main/lib/embeddedSession.test.ts | 43 +- src/main/lib/embeddedSession.ts | 17 +- .../ipc/registerDevPlatformHandlers.test.ts | 54 + .../lib/ipc/registerDevPlatformHandlers.ts | 33 +- src/main/lib/viewWorkspaceGrants.test.ts | 93 +- src/main/lib/viewWorkspaceGrants.ts | 46 +- src/types/comfyDesktopBridge.ts | 4 +- src/types/ipc.ts | 11 +- 15 files changed, 2083 insertions(+), 524 deletions(-) diff --git a/src/main/cloud/index.ts b/src/main/cloud/index.ts index d25dd096f..c0e254462 100644 --- a/src/main/cloud/index.ts +++ b/src/main/cloud/index.ts @@ -10,7 +10,7 @@ * const session = new CloudSession() * await session.login() // system-browser PKCE * const workspaces = await session.listWorkspaces() // choose workspace - * await session.switchWorkspace(chosen.id) // activate scoped credentials + * await session.switchWorkspace(chosen.id) // mint and activate its token * const client = new ComfyBuilderClient({ auth: session.asTokenProvider() }) * const builds = await client.listBuilds() // scoped to that workspace * ``` @@ -18,10 +18,17 @@ export { CloudSession } from './session' export { signIn, refresh } from './oauth' export { listWorkspaceMembers, listWorkspaces } from './workspaces' -// Raw token accessors (`loadTokens`/`saveTokens`) stay off this barrel: +// Raw token accessors (`loadGrant`/`saveGrant`) stay off this barrel: // direct reads/writes would bypass CloudSession's single-flight refresh and // auth-generation guards. Callers go through CloudSession. export { getAuthStatus, clearTokens } from './tokenStore' export { statusFromAccessToken, workspaceIdOf } from './claims' export { CLOUD_CONFIG, CLOUD_ISSUER } from './config' -export type { AuthStatus, AuthTokens, Workspace, WorkspaceMember } from './types' +export type { + AuthStatus, + AuthTokens, + Workspace, + WorkspaceMember, + WorkspaceSwitchFailure, + WorkspaceSwitchStatus +} from './types' diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index 0079c27e0..1f7f1858f 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -1,217 +1,442 @@ // @vitest-environment node +import * as fs from 'node:fs' +import * as os from 'node:os' +import * as path from 'node:path' + import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +const electronState = vi.hoisted(() => ({ userData: '' })) + +vi.mock('electron', () => ({ + app: { getPath: vi.fn(() => electronState.userData) }, + safeStorage: { + isEncryptionAvailable: vi.fn(() => true), + encryptString: vi.fn((value: string) => Buffer.from(value, 'utf-8')), + decryptString: vi.fn((value: Buffer) => value.toString('utf-8')) + }, + shell: { openExternal: vi.fn(() => Promise.resolve()) } +})) vi.mock('./oauth', () => ({ signIn: vi.fn(), refresh: vi.fn(), openAuthorizePage: vi.fn(() => Promise.resolve()) })) -vi.mock('./tokenStore', () => ({ - activateWorkspace: vi.fn(), - clearTokens: vi.fn(), - getAuthStatus: vi.fn(), - loadTokens: vi.fn(), - loadWorkspaceTokens: vi.fn(), - replaceWorkspaceTokens: vi.fn(), - saveTokens: vi.fn(), - saveWorkspaceNames: vi.fn() -})) vi.mock('./workspaces', () => ({ - listWorkspaces: vi.fn(async () => [{ id: 'w-1' }]), + listWorkspaces: vi.fn(async () => [{ id: 'w-1', name: 'One', type: 'team', role: 'member' }]), listWorkspaceMembers: vi.fn(async () => [{ id: 'user-1', name: 'One' }]) })) +vi.mock('../lib/telemetry', () => ({ emit: vi.fn() })) +vi.mock('../lib/workspaceMintSwitchFlag', () => ({ + isWorkspaceMintSwitchEnabled: vi.fn(async () => true) +})) -import { statusFromAccessToken, workspaceIdOf } from './claims' +import * as mainTelemetry from '../lib/telemetry' +import { isWorkspaceMintSwitchEnabled } from '../lib/workspaceMintSwitchFlag' +import { statusFromAccessToken } from './claims' +import { CLOUD_CONFIG } from './config' import { openAuthorizePage, refresh, signIn } from './oauth' -import { CloudSession } from './session' import { - activateWorkspace, - clearTokens, - getAuthStatus, - loadTokens, - loadWorkspaceTokens, - replaceWorkspaceTokens, - saveTokens, - saveWorkspaceNames -} from './tokenStore' + CloudSession, + WORKSPACE_RETURNED_TO_ANCHOR_EVENT, + WORKSPACE_SWITCH_BROWSER_EVENT, + WORKSPACE_SWITCH_EVENT +} from './session' +import { SignInFailure } from './signInFailure' +import { _resetForTest, clearTokens, saveGrant } from './tokenStore' import type { AuthTokens } from './types' import { listWorkspaceMembers, listWorkspaces } from './workspaces' const mocked = vi.mocked -const future = Date.now() + 3_600_000 -const past = Date.now() - 1_000 - -let active: AuthTokens | null -let bundles: Map +const FUTURE = Date.now() + 3_600_000 +const PAST = Date.now() - 1_000 +const READ_ONLY_SCOPE = 'comfy-cloud:user:read' -function jwt(workspaceId: string, suffix = ''): string { +function jwt(claims: Record): string { const b64 = (value: unknown): string => Buffer.from(JSON.stringify(value), 'utf-8').toString('base64url') - return `${b64({ alg: 'RS256' })}.${b64({ sub: 'user-1', workspace_id: workspaceId })}.sig${suffix}` + return `${b64({ alg: 'RS256' })}.${b64(claims)}.sig` +} + +interface GrantOptions { + expiresAt?: number + scope?: string + revision?: string + subject?: string } -function makeTokens(workspaceId: string, expiresAt = future, suffix = ''): AuthTokens { +function grantOn(workspaceId: string, options: GrantOptions = {}): AuthTokens { + const { + expiresAt = FUTURE, + scope = CLOUD_CONFIG.scope, + revision = '', + subject = 'user-1' + } = options return { - accessToken: jwt(workspaceId, suffix), - refreshToken: `refresh-${workspaceId}${suffix}`, + accessToken: jwt({ + sub: subject, + email: `${subject}@example.com`, + workspace_id: workspaceId, + workspace_type: 'team', + role: 'owner', + scope, + revision + }), + refreshToken: `refresh-${workspaceId}${revision}`, expiresAt } } -function cache(tokens: AuthTokens, makeActive = false): void { - const workspaceId = workspaceIdOf(tokens.accessToken) - if (workspaceId) bundles.set(workspaceId, tokens) - if (makeActive) active = tokens +function mintedJwt(workspaceId: string, subject = 'user-1'): string { + return jwt({ + sub: subject, + email: `${subject}@example.com`, + workspace_id: workspaceId, + workspace_type: 'team', + role: 'member' + }) +} + +function json(status: number, body: unknown, headers: Record = {}): Response { + return new Response(JSON.stringify(body), { status, headers }) +} + +function minted(workspaceId: string, expiresAt = FUTURE): Response { + return json(200, { + token: mintedJwt(workspaceId), + expires_at: new Date(expiresAt).toISOString() + }) +} + +interface MintRequest { + workspaceId: string + bearer: string +} + +type MintReply = (request: MintRequest) => Response | Promise + +let mintReply: MintReply +let mintRequests: MintRequest[] + +function signedInResult(tokens: AuthTokens): Awaited> { + return { tokens, status: statusFromAccessToken(tokens.accessToken) } +} + +function deferred() { + let resolve: (value: T) => void = () => {} + const promise = new Promise((r) => { + resolve = r + }) + return { promise, resolve } +} + +function switchEvents(): unknown[] { + return mocked(mainTelemetry.emit) + .mock.calls.filter(([event]) => event === WORKSPACE_SWITCH_EVENT) + .map(([, context]) => context) +} + +function browserEvents(): unknown[] { + return mocked(mainTelemetry.emit) + .mock.calls.filter(([event]) => event === WORKSPACE_SWITCH_BROWSER_EVENT) + .map(([, context]) => context) +} + +function mintDisabled(): Response { + return json(503, { code: 'oauth_workspace_mint_disabled' }) +} + +function killMintSwitch(): void { + mocked(isWorkspaceMintSwitchEnabled).mockResolvedValue(false) +} + +function refreshFailure(kind: 'network' | 'timeout' | 'http', httpStatus?: number): SignInFailure { + if (kind === 'http') { + return new SignInFailure('refresh failed', 'server_error', { httpStatus }) + } + return new SignInFailure('refresh failed', kind) +} + +function vaultOnDisk(): Record { + return JSON.parse( + fs.readFileSync(path.join(electronState.userData, 'comfy-cloud-auth.bin'), 'utf-8') + ) as Record } beforeEach(() => { - active = null - bundles = new Map() - mocked(loadTokens).mockImplementation(() => active) - mocked(loadWorkspaceTokens).mockImplementation((workspaceId) => - workspaceId ? (bundles.get(workspaceId) ?? null) : null - ) - mocked(activateWorkspace).mockImplementation((workspaceId) => { - const tokens = bundles.get(workspaceId) ?? null - if (tokens) active = tokens - return tokens - }) - mocked(saveTokens).mockImplementation((tokens) => cache(tokens, true)) - mocked(replaceWorkspaceTokens).mockImplementation( - (workspaceId, expectedAccessToken, expectedRefreshToken, tokens) => { - if (!workspaceId) return false - const current = bundles.get(workspaceId) - if ( - !current || - current.accessToken !== expectedAccessToken || - current.refreshToken !== expectedRefreshToken - ) { - return false + electronState.userData = fs.mkdtempSync(path.join(os.tmpdir(), 'comfy-cloud-session-')) + _resetForTest() + mintRequests = [] + mintReply = ({ workspaceId }) => minted(workspaceId) + mocked(isWorkspaceMintSwitchEnabled).mockResolvedValue(true) + vi.stubGlobal( + 'fetch', + vi.fn(async (_url: string, init: RequestInit) => { + const request = { + workspaceId: (JSON.parse(String(init.body)) as { workspace_id: string }).workspace_id, + bearer: new Headers(init.headers).get('Authorization')?.replace('Bearer ', '') ?? '' } - bundles.set(workspaceId, tokens) - if (active?.accessToken === expectedAccessToken) active = tokens - return true - } - ) - mocked(clearTokens).mockImplementation(() => { - active = null - bundles.clear() - }) - mocked(getAuthStatus).mockImplementation(() => - active ? statusFromAccessToken(active.accessToken) : { signedIn: false } + mintRequests.push(request) + return mintReply(request) + }) ) }) -afterEach(() => vi.clearAllMocks()) +afterEach(() => { + clearTokens() + _resetForTest() + fs.rmSync(electronState.userData, { recursive: true, force: true }) + vi.unstubAllGlobals() + vi.clearAllMocks() + mocked(signIn).mockReset() + mocked(refresh).mockReset() +}) describe('CloudSession access tokens', () => { - it('returns null when signed out and an unexpired token without refreshing', async () => { + it('returns null when signed out and the grant token while active on the anchor', async () => { const session = new CloudSession() await expect(session.getAccessToken()).resolves.toBeNull() - const tokens = makeTokens('w1') - cache(tokens, true) - await expect(session.getAccessToken()).resolves.toBe(tokens.accessToken) + const grant = grantOn('w1') + saveGrant(grant) + + await expect(session.getAccessToken()).resolves.toBe(grant.accessToken) expect(refresh).not.toHaveBeenCalled() + expect(mintRequests).toEqual([]) }) - it('single-flights and persists a refresh rotation', async () => { - const stale = makeTokens('w1', past) - const fresh = makeTokens('w1', future, '-fresh') - cache(stale, true) - let finishRefresh!: (tokens: AuthTokens) => void - mocked(refresh).mockReturnValue( - new Promise((resolve) => { - finishRefresh = resolve - }) - ) + it('single-flights and persists a grant refresh rotation', async () => { + const stale = grantOn('w1', { expiresAt: PAST }) + const fresh = grantOn('w1', { revision: '-fresh' }) + saveGrant(stale) + const rotation = deferred() + mocked(refresh).mockReturnValue(rotation.promise) const session = new CloudSession() - const calls = [session.getAccessToken(), session.getAccessToken(), session.getAccessToken()] - finishRefresh(fresh) + const calls = [ + session.getAccessToken(), + session.getAccessToken(), + session.getGrantAccessToken() + ] + rotation.resolve(fresh) await expect(Promise.all(calls)).resolves.toEqual([ fresh.accessToken, fresh.accessToken, fresh.accessToken ]) - expect(refresh).toHaveBeenCalledOnce() - expect(replaceWorkspaceTokens).toHaveBeenCalledExactlyOnceWith( - 'w1', - stale.accessToken, - stale.refreshToken, - fresh - ) + expect(refresh).toHaveBeenCalledExactlyOnceWith(stale.refreshToken) + expect(vaultOnDisk().grant).toEqual(fresh) }) - it('isolates concurrent refresh rotations for different workspaces', async () => { - const staleOne = makeTokens('w1', past) - const freshOne = makeTokens('w1', future, '-fresh') - const staleTwo = makeTokens('w2', past) - const freshTwo = makeTokens('w2', future, '-fresh') - cache(staleOne, true) - cache(staleTwo) - const refreshes = new Map void>() - mocked(refresh).mockImplementation( - (refreshToken) => - new Promise((resolve) => { - refreshes.set(refreshToken, resolve) - }) - ) + it('does not let a refresh completion restore credentials after logout', async () => { + saveGrant(grantOn('w1', { expiresAt: PAST })) + const rotation = deferred() + mocked(refresh).mockReturnValue(rotation.promise) + const session = new CloudSession() + + const request = session.getAccessToken() + session.logout() + rotation.resolve(grantOn('w1', { revision: '-fresh' })) + + await expect(request).resolves.toBeNull() + expect(session.isSignedIn()).toBe(false) + }) + + it('keeps a grant rotation that lands after a switch but activates nothing', async () => { + saveGrant(grantOn('w1', { expiresAt: PAST })) + const fresh = grantOn('w1', { revision: '-fresh' }) + const rotation = deferred() + mocked(refresh).mockReturnValue(rotation.promise) const session = new CloudSession() const oldRequest = session.getAccessToken() const switching = session.switchWorkspace('w2') - expect(refresh).toHaveBeenCalledTimes(2) - refreshes.get(staleTwo.refreshToken!)!(freshTwo) - await expect(switching).resolves.toMatchObject({ workspaceId: 'w2' }) - refreshes.get(staleOne.refreshToken!)!(freshOne) + rotation.resolve(fresh) + await expect(switching).resolves.toMatchObject({ workspaceId: 'w2' }) await expect(oldRequest).resolves.toBeNull() - expect(active).toEqual(freshTwo) - expect(bundles.get('w1')).toEqual(freshOne) + expect(session.currentWorkspaceId()).toBe('w2') + expect(vaultOnDisk().grant).toEqual(fresh) }) - it('does not let a refresh completion restore credentials after logout', async () => { - const stale = makeTokens('w1', past) - const fresh = makeTokens('w1', future, '-fresh') - cache(stale, true) - let finishRefresh!: (tokens: AuthTokens) => void - mocked(refresh).mockReturnValue( - new Promise((resolve) => { - finishRefresh = resolve - }) - ) + it('returns no token for API calls while a refresh fails for a transient reason', async () => { + saveGrant(grantOn('w1', { expiresAt: PAST })) + mocked(refresh).mockRejectedValue(refreshFailure('network')) + + await expect(new CloudSession().getAccessToken()).resolves.toBeNull() + }) + + it('returns the stale grant token after a definitive refusal so the 401 ends the session', async () => { + const stale = grantOn('w1', { expiresAt: PAST }) + saveGrant(stale) + mocked(refresh).mockRejectedValue(refreshFailure('http', 400)) + + await expect(new CloudSession().getAccessToken()).resolves.toBe(stale.accessToken) + }) + + it('re-mints a minted token near expiry once for concurrent callers, with no browser', async () => { + saveGrant(grantOn('w1')) + mintReply = ({ workspaceId }) => minted(workspaceId, Date.now() + 30_000) + const session = new CloudSession() + await session.switchWorkspace('w2') + mintRequests = [] + mintReply = ({ workspaceId }) => minted(workspaceId) + + const tokens = await Promise.all([session.getAccessToken(), session.getAccessToken()]) + + expect(tokens).toEqual([mintedJwt('w2'), mintedJwt('w2')]) + expect(mintRequests).toHaveLength(1) + expect(signIn).not.toHaveBeenCalled() + }) + + it('keeps a still valid minted token when its re-mint fails', async () => { + saveGrant(grantOn('w1')) + mintReply = ({ workspaceId }) => minted(workspaceId, Date.now() + 30_000) + const session = new CloudSession() + await session.switchWorkspace('w2') + mintReply = () => json(500, {}) + + await expect(session.getAccessToken()).resolves.toBe(mintedJwt('w2')) + expect(signIn).not.toHaveBeenCalled() + }) +}) + +describe('CloudSession background token reads never open the browser', () => { + async function activeOnMintedToken(expiresAt = PAST): Promise { + saveGrant(grantOn('w1')) + mintReply = ({ workspaceId }) => minted(workspaceId, expiresAt) const session = new CloudSession() + await session.switchWorkspace('w2') + mintRequests = [] + return session + } + + function returnedToAnchorEvents(): unknown[] { + return mocked(mainTelemetry.emit) + .mock.calls.filter(([event]) => event === WORKSPACE_RETURNED_TO_ANCHOR_EVENT) + .map(([, context]) => context) + } + + it.each<[string, () => void, string]>([ + ['the server kill switch', () => (mintReply = mintDisabled), 'mint_disabled'], + ['the Desktop ops flag', killMintSwitch, 'mint_disabled'], + ['a lost membership', () => (mintReply = () => json(404, {})), 'unavailable'], + [ + 'a refused mint', + () => (mintReply = () => json(403, { code: 'workspace_access_denied' })), + 'refused' + ], + ['an SSO policy', () => (mintReply = () => json(403, { code: 'sso_required' })), 'sso_required'] + ])('%s returns active B to the anchor and announces it, once', async (_name, arrange, reason) => { + const session = await activeOnMintedToken() + const onReturned = vi.fn() + session.setReturnedToAnchorHandler(onReturned) + arrange() + const grant = grantOn('w1') + + await expect( + Promise.all([session.getAccessToken(), session.getAccessToken()]) + ).resolves.toEqual([null, null]) + + expect(signIn).not.toHaveBeenCalled() + expect(openAuthorizePage).not.toHaveBeenCalled() + expect(onReturned).toHaveBeenCalledOnce() + expect(session.currentWorkspaceId()).toBe('w1') + expect(session.status()).toMatchObject({ workspaceId: 'w1' }) + expect(returnedToAnchorEvents()).toEqual([{ reason }]) + await expect(session.getAccessToken()).resolves.toBe(grant.accessToken) + }) + + it('an ended grant returns to the anchor, whose 401 then ends the session as today', async () => { + const session = await activeOnMintedToken() + const onReturned = vi.fn() + session.setReturnedToAnchorHandler(onReturned) + mintReply = () => json(401, { code: 'oauth_grant_ended' }) + mocked(refresh).mockRejectedValue(refreshFailure('http', 400)) + + await expect(session.getAccessToken()).resolves.toBeNull() + + expect(signIn).not.toHaveBeenCalled() + expect(onReturned).toHaveBeenCalledOnce() + expect(session.currentWorkspaceId()).toBe('w1') + const onSignedOut = vi.fn() + session.asTokenProvider(onSignedOut).onUnauthorized?.(grantOn('w1').accessToken) + expect(onSignedOut).toHaveBeenCalledOnce() + }) + + it.each<[string, () => Response]>([ + ['a rate limit', () => json(429, {})], + ['an outage', () => json(500, {})], + ['a 503 of another kind', () => json(503, { code: 'maintenance' })] + ])('%s stays on B with no token, no browser and no announcement', async (_name, reply) => { + const session = await activeOnMintedToken() + const onReturned = vi.fn() + session.setReturnedToAnchorHandler(onReturned) + mintReply = reply + + await expect(session.getAccessToken()).resolves.toBeNull() + + expect(signIn).not.toHaveBeenCalled() + expect(onReturned).not.toHaveBeenCalled() + expect(session.currentWorkspaceId()).toBe('w2') + }) + + it('keeps using a still valid token through a kill, then returns once it expires', async () => { + const session = await activeOnMintedToken(Date.now() + 30_000) + const onReturned = vi.fn() + session.setReturnedToAnchorHandler(onReturned) + killMintSwitch() + + await expect(session.getAccessToken()).resolves.toBe(mintedJwt('w2')) + + expect(onReturned).not.toHaveBeenCalled() + expect(session.currentWorkspaceId()).toBe('w2') + expect(signIn).not.toHaveBeenCalled() + }) + + it('a re-mint that lands after a newer switch does not move the active workspace', async () => { + const session = await activeOnMintedToken() + const onReturned = vi.fn() + session.setReturnedToAnchorHandler(onReturned) + const slow = deferred() + mintReply = () => slow.promise const request = session.getAccessToken() - session.logout() - finishRefresh(fresh) + await vi.waitFor(() => expect(mintRequests).toHaveLength(1)) + mintReply = ({ workspaceId }) => minted(workspaceId) + await session.switchWorkspace('w3') + slow.resolve(mintDisabled()) await expect(request).resolves.toBeNull() - expect(active).toBeNull() - expect(replaceWorkspaceTokens).toHaveReturnedWith(false) + expect(onReturned).not.toHaveBeenCalled() + expect(session.currentWorkspaceId()).toBe('w3') }) }) -describe('CloudSession browser auth', () => { +describe('CloudSession browser sign-in', () => { it('single-flights repeated login requests', async () => { - let finishLogin!: (value: Awaited>) => void - mocked(signIn).mockReturnValue( - new Promise((resolve) => { - finishLogin = resolve - }) - ) + const pending = deferred>>() + mocked(signIn).mockReturnValue(pending.promise) const session = new CloudSession() const first = session.login() const second = session.login() - const tokens = makeTokens('w1') - finishLogin({ tokens, status: statusFromAccessToken(tokens.accessToken) }) + pending.resolve(signedInResult(grantOn('w1'))) await expect(Promise.all([first, second])).resolves.toHaveLength(2) expect(signIn).toHaveBeenCalledOnce() - expect(saveTokens).toHaveBeenCalledExactlyOnceWith(tokens) + expect(session.currentWorkspaceId()).toBe('w1') + }) + + it('moves to the consented workspace on a fresh login', async () => { + saveGrant(grantOn('w1')) + mocked(signIn).mockResolvedValue(signedInResult(grantOn('w3'))) + const session = new CloudSession() + await session.switchWorkspace('w2') + + await session.login() + + expect(session.currentWorkspaceId()).toBe('w3') }) it('reopens the pending sign-in page when login is requested again', async () => { @@ -248,133 +473,822 @@ describe('CloudSession browser auth', () => { }) it('does not persist browser auth that finishes after logout', async () => { - let finishLogin!: (value: Awaited>) => void - mocked(signIn).mockReturnValue( - new Promise((resolve) => { - finishLogin = resolve - }) - ) + const pending = deferred>>() + mocked(signIn).mockReturnValue(pending.promise) const session = new CloudSession() const login = session.login() session.logout() - const tokens = makeTokens('w1') - finishLogin({ tokens, status: statusFromAccessToken(tokens.accessToken) }) + pending.resolve(signedInResult(grantOn('w1'))) await expect(login).resolves.toEqual({ signedIn: false }) - expect(saveTokens).not.toHaveBeenCalled() + expect(session.isSignedIn()).toBe(false) }) }) -describe('CloudSession workspaces', () => { - it('switches A to B to A from cache without browser auth', async () => { - const workspaceOne = makeTokens('w1') - const workspaceTwo = makeTokens('w2') - cache(workspaceOne, true) - cache(workspaceTwo) +describe('CloudSession.switchWorkspace with no browser', () => { + it('T-V1: A to B to C to A signs in once and each new workspace is one mint', async () => { + mocked(signIn).mockResolvedValue(signedInResult(grantOn('wA'))) + const session = new CloudSession() + await session.login() + + await expect(session.switchWorkspace('wB')).resolves.toMatchObject({ workspaceId: 'wB' }) + await expect(session.switchWorkspace('wC')).resolves.toMatchObject({ workspaceId: 'wC' }) + await expect(session.switchWorkspace('wA')).resolves.toMatchObject({ workspaceId: 'wA' }) + await expect(session.switchWorkspace('wB')).resolves.toMatchObject({ workspaceId: 'wB' }) + + expect(signIn).toHaveBeenCalledOnce() + expect(openAuthorizePage).not.toHaveBeenCalled() + expect(mintRequests.map(({ workspaceId }) => workspaceId)).toEqual(['wB', 'wC']) + expect(switchEvents()).toEqual([ + { outcome: 'minted' }, + { outcome: 'minted' }, + { outcome: 'anchor' }, + { outcome: 'cached' } + ]) + expect(browserEvents()).toEqual([]) + }) + + it('stores minted tokens without a refresh token and API calls use them', async () => { + const grant = grantOn('w1') + saveGrant(grant) + const session = new CloudSession() + + await session.switchWorkspace('w2') + + expect(mintRequests).toEqual([{ workspaceId: 'w2', bearer: grant.accessToken }]) + await expect(session.getAccessToken()).resolves.toBe(mintedJwt('w2')) + await expect(session.getGrantAccessToken()).resolves.toBe(grant.accessToken) + expect(session.currentSubject()).toBe('user-1') + expect(vaultOnDisk()).toMatchObject({ + version: 2, + activeWorkspaceId: 'w2', + grant, + workspaceTokens: { w2: { accessToken: mintedJwt('w2') } } + }) + expect((vaultOnDisk().workspaceTokens as Record).w2).not.toHaveProperty( + 'refreshToken' + ) + }) + + it('re-mints an expired minted token on the next switch, with no browser', async () => { + saveGrant(grantOn('w1')) + mintReply = ({ workspaceId }) => minted(workspaceId, PAST) const session = new CloudSession() + await session.switchWorkspace('w2') + await session.switchWorkspace('w1') + mintReply = ({ workspaceId }) => minted(workspaceId) await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) - await expect(session.switchWorkspace('w1')).resolves.toMatchObject({ workspaceId: 'w1' }) - expect(activateWorkspace).toHaveBeenNthCalledWith(1, 'w2') - expect(activateWorkspace).toHaveBeenNthCalledWith(2, 'w1') + expect(mintRequests).toHaveLength(2) expect(signIn).not.toHaveBeenCalled() }) - it('refreshes an expired cached workspace independently before activating it', async () => { - const workspaceOne = makeTokens('w1') - const staleTwo = makeTokens('w2', past) - const freshTwo = makeTokens('w2', future, '-fresh') - cache(workspaceOne, true) - cache(staleTwo) - mocked(refresh).mockResolvedValue(freshTwo) + it('refreshes an expired grant before minting', async () => { + const stale = grantOn('w1', { expiresAt: PAST }) + const fresh = grantOn('w1', { revision: '-fresh' }) + saveGrant(stale) + mocked(refresh).mockResolvedValue(fresh) await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) - expect(refresh).toHaveBeenCalledExactlyOnceWith(staleTwo.refreshToken) - expect(activateWorkspace).toHaveBeenCalledExactlyOnceWith('w2') + expect(mintRequests).toEqual([{ workspaceId: 'w2', bearer: fresh.accessToken }]) expect(signIn).not.toHaveBeenCalled() }) - it('uses browser auth when the active workspace can no longer refresh', async () => { - const stale = makeTokens('w1', past) - const authorized = makeTokens('w1', future, '-authorized') - cache(stale, true) - mocked(refresh).mockRejectedValue(new Error('revoked')) - mocked(signIn).mockResolvedValue({ - tokens: authorized, - status: statusFromAccessToken(authorized.accessToken) + it('shares one flight between concurrent switches to the same workspace', async () => { + saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) + mocked(signIn).mockResolvedValue(signedInResult(grantOn('w2'))) + const session = new CloudSession() + + await Promise.all([session.switchWorkspace('w2'), session.switchWorkspace('w2')]) + + expect(signIn).toHaveBeenCalledOnce() + }) + + it.each<[string, () => Response, string, string]>([ + ['T-V2: non-member 404', () => json(404, { code: 'NOT_FOUND' }), 'unavailable', 'unavailable'], + [ + 'account_outside_organization', + () => json(403, { code: 'account_outside_organization' }), + 'refused', + 'unavailable' + ], + [ + 'personal_workspace_disabled', + () => json(403, { code: 'personal_workspace_disabled' }), + 'refused', + 'unavailable' + ], + [ + 'insufficient_scope', + () => json(403, { code: 'insufficient_scope' }), + 'refused', + 'unavailable' + ], + ['a rate limit', () => json(429, {}, { 'Retry-After': '60' }), 'retryable', 'retryable'], + ['a server error', () => json(500, {}), 'retryable', 'retryable'], + ['a malformed 200', () => json(200, { token: '' }), 'retryable', 'retryable'] + ])( + '%s stays on the current workspace with no browser', + async (_name, reply, outcome, failure) => { + saveGrant(grantOn('w1')) + mintReply = reply + const session = new CloudSession() + + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w1', + workspaceSwitchFailure: failure + }) + + expect(signIn).not.toHaveBeenCalled() + expect(openAuthorizePage).not.toHaveBeenCalled() + expect(session.currentWorkspaceId()).toBe('w1') + expect(switchEvents()).toEqual([{ outcome }]) + expect(browserEvents()).toEqual([]) + } + ) + + it('a network failure stays on the current workspace with no browser', async () => { + saveGrant(grantOn('w1')) + mintReply = () => { + throw new TypeError('offline') + } + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w1', + workspaceSwitchFailure: 'retryable' + }) + + expect(signIn).not.toHaveBeenCalled() + }) + + it('respects Retry-After instead of asking Cloud again', async () => { + saveGrant(grantOn('w1')) + mintReply = () => json(429, {}, { 'Retry-After': '60' }) + const session = new CloudSession() + + await session.switchWorkspace('w2') + await expect(session.switchWorkspace('w3')).resolves.toMatchObject({ + workspaceSwitchFailure: 'retryable' + }) + + expect(mintRequests).toHaveLength(1) + }) + + it('rejects a minted token for another workspace or account', async () => { + saveGrant(grantOn('w1')) + mintReply = () => + json(200, { token: mintedJwt('w9'), expires_at: new Date(FUTURE).toISOString() }) + const session = new CloudSession() + + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w1', + workspaceSwitchFailure: 'retryable' + }) + + mintReply = () => + json(200, { token: mintedJwt('w2', 'user-2'), expires_at: new Date(FUTURE).toISOString() }) + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w1', + workspaceSwitchFailure: 'retryable' + }) + }) + + it('does not attach a failure to a successful switch', async () => { + saveGrant(grantOn('w1')) + + const reply = await new CloudSession().switchWorkspace('w2') + + expect(reply).not.toHaveProperty('workspaceSwitchFailure') + }) +}) + +describe('CloudSession.switchWorkspace reauthorize', () => { + it('T-V4: sso_required opens one browser carrying B and then succeeds', async () => { + saveGrant(grantOn('w1')) + mintReply = () => json(403, { code: 'sso_required' }) + const sso = grantOn('w2', { revision: '-sso' }) + mocked(signIn).mockResolvedValue(signedInResult(sso)) + const session = new CloudSession() + + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) + + expect(signIn).toHaveBeenCalledExactlyOnceWith({ workspaceId: 'w2' }) + expect(vaultOnDisk().grant).toEqual(sso) + expect(switchEvents()).toEqual([{ outcome: 'browser', reauthorize_reason: 'sso_required' }]) + expect(browserEvents()).toEqual([{ reauthorize_reason: 'sso_required' }]) + }) + + it('consent picking another workspace still ends on B with one mint', async () => { + saveGrant(grantOn('w1')) + let replies = 0 + mintReply = ({ workspaceId }) => + replies++ === 0 ? json(403, { code: 'sso_required' }) : minted(workspaceId) + const consented = grantOn('w3') + mocked(signIn).mockResolvedValue(signedInResult(consented)) + const session = new CloudSession() + + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) + + expect(signIn).toHaveBeenCalledOnce() + expect(mintRequests).toHaveLength(2) + expect(mintRequests[1]).toEqual({ workspaceId: 'w2', bearer: consented.accessToken }) + expect(vaultOnDisk().grant).toEqual(consented) + }) + + it('T-V9: 401 with refresh refused runs one reauthorize, then switching works', async () => { + saveGrant(grantOn('w1')) + let replies = 0 + mintReply = ({ workspaceId }) => + replies++ === 0 + ? json(401, { message: 'workspace membership not found' }) + : minted(workspaceId) + mocked(refresh).mockRejectedValue(refreshFailure('http', 401)) + mocked(signIn).mockResolvedValue(signedInResult(grantOn('w3'))) + const session = new CloudSession() + + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) + await expect(session.switchWorkspace('w4')).resolves.toMatchObject({ workspaceId: 'w4' }) + + expect(refresh).toHaveBeenCalledOnce() + expect(signIn).toHaveBeenCalledExactlyOnceWith({ workspaceId: 'w2' }) + expect(browserEvents()).toEqual([{ reauthorize_reason: 'grant_ended' }]) + }) + + it('401 with a good refresh retries the mint once with no browser', async () => { + const fresh = grantOn('w1', { revision: '-fresh' }) + saveGrant(grantOn('w1')) + let replies = 0 + mintReply = ({ workspaceId }) => (replies++ === 0 ? json(401, {}) : minted(workspaceId)) + mocked(refresh).mockResolvedValue(fresh) + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w2' + }) + + expect(mintRequests[1]).toMatchObject({ bearer: fresh.accessToken }) + expect(signIn).not.toHaveBeenCalled() + }) + + it('a second 401 after a good refresh is reauthorize', async () => { + saveGrant(grantOn('w1')) + mintReply = () => json(401, { code: 'oauth_grant_ended' }) + mocked(refresh).mockResolvedValue(grantOn('w1', { revision: '-fresh' })) + mocked(signIn).mockResolvedValue(signedInResult(grantOn('w2'))) + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w2' + }) + + expect(mintRequests).toHaveLength(2) + expect(signIn).toHaveBeenCalledOnce() + }) + + it.each<[string, SignInFailure]>([ + ['network', refreshFailure('network')], + ['timeout', refreshFailure('timeout')], + ['HTTP 500', refreshFailure('http', 500)], + ['HTTP 503', refreshFailure('http', 503)], + ['HTTP 429', refreshFailure('http', 429)] + ])('a %s refresh failure after a 401 reports retryable with no browser', async (_name, error) => { + saveGrant(grantOn('w1')) + mintReply = () => json(401, {}) + mocked(refresh).mockRejectedValue(error) + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w1', + workspaceSwitchFailure: 'retryable' }) + expect(signIn).not.toHaveBeenCalled() + expect(switchEvents()).toEqual([{ outcome: 'retryable' }]) + }) + + it.each<[string, SignInFailure]>([ + ['network', refreshFailure('network')], + ['HTTP 500', refreshFailure('http', 500)] + ])( + 'a %s refresh failure on an expired grant never mints or opens the browser', + async (_name, error) => { + saveGrant(grantOn('w1', { expiresAt: PAST })) + mocked(refresh).mockRejectedValue(error) + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + workspaceSwitchFailure: 'retryable' + }) + + expect(mintRequests).toEqual([]) + expect(signIn).not.toHaveBeenCalled() + } + ) + + it.each<[number]>([[400], [401]])( + 'an HTTP %i refresh refusal on an expired grant opens one browser', + async (httpStatus) => { + saveGrant(grantOn('w1', { expiresAt: PAST })) + mocked(refresh).mockRejectedValue(refreshFailure('http', httpStatus)) + mocked(signIn).mockResolvedValue(signedInResult(grantOn('w2'))) + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w2' + }) + + expect(signIn).toHaveBeenCalledExactlyOnceWith({ workspaceId: 'w2' }) + } + ) + + it('switching to the anchor with a refused refresh opens one browser', async () => { + saveGrant(grantOn('w1', { expiresAt: PAST })) + mocked(refresh).mockRejectedValue(refreshFailure('http', 400)) + mocked(signIn).mockResolvedValue(signedInResult(grantOn('w1', { revision: '-new' }))) + await expect(new CloudSession().switchWorkspace('w1')).resolves.toMatchObject({ workspaceId: 'w1' }) - expect(refresh).toHaveBeenCalledExactlyOnceWith(stale.refreshToken) expect(signIn).toHaveBeenCalledExactlyOnceWith({ workspaceId: 'w1' }) - expect(saveTokens).toHaveBeenCalledExactlyOnceWith(authorized) }) - it('uses browser auth for an uncached workspace and rejects a different selection', async () => { - const workspaceOne = makeTokens('w1') - cache(workspaceOne, true) - mocked(signIn).mockResolvedValue({ - tokens: workspaceOne, - status: statusFromAccessToken(workspaceOne.accessToken) + it('switching to the anchor during a refresh outage activates with no browser', async () => { + saveGrant(grantOn('w1', { expiresAt: PAST })) + mocked(refresh).mockRejectedValue(refreshFailure('network')) + + await expect(new CloudSession().switchWorkspace('w1')).resolves.toMatchObject({ + workspaceId: 'w1' }) + expect(signIn).not.toHaveBeenCalled() + }) + + it('a second refusal after the browser trip does not open another', async () => { + saveGrant(grantOn('w1')) + mintReply = () => json(403, { code: 'sso_required' }) + mocked(signIn).mockResolvedValue(signedInResult(grantOn('w3'))) + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ - workspaceId: 'w1' + workspaceSwitchFailure: 'retryable' + }) + + expect(signIn).toHaveBeenCalledOnce() + }) + + it('a workspace refused after the browser trip reports unavailable', async () => { + saveGrant(grantOn('w1')) + let replies = 0 + mintReply = () => (replies++ === 0 ? json(403, { code: 'sso_required' }) : json(404, {})) + mocked(signIn).mockResolvedValue(signedInResult(grantOn('w3'))) + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + workspaceSwitchFailure: 'unavailable' + }) + }) + + it('a cancelled browser trip stays put and reports retryable', async () => { + saveGrant(grantOn('w1')) + mintReply = () => json(403, { code: 'sso_required' }) + mocked(signIn).mockRejectedValue(new SignInFailure('access_denied', 'cancelled')) + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w1', + workspaceSwitchFailure: 'retryable' }) + }) + + it('a different account in the browser replaces the vault', async () => { + saveGrant(grantOn('w1')) + const held = new CloudSession() + await held.switchWorkspace('w2') + mintRequests = [] + mintReply = () => json(403, { code: 'sso_required' }) + mocked(signIn).mockResolvedValue(signedInResult(grantOn('w9', { subject: 'user-2' }))) + + await held.switchWorkspace('w3') + + expect(held.currentSubject()).toBe('user-2') + expect(held.currentWorkspaceId()).toBe('w9') + expect(vaultOnDisk().workspaceTokens).toEqual({}) + }) +}) + +describe('CloudSession mint kill switches', () => { + it('a server 503 disabled opens one browser carrying B, which activates with no further mint', async () => { + saveGrant(grantOn('w1')) + mintReply = mintDisabled + const consented = grantOn('w2') + mocked(signIn).mockResolvedValue(signedInResult(consented)) + const session = new CloudSession() + + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) expect(signIn).toHaveBeenCalledExactlyOnceWith({ workspaceId: 'w2' }) - expect(saveTokens).not.toHaveBeenCalled() + expect(mintRequests).toHaveLength(1) + expect(vaultOnDisk().grant).toEqual(consented) + expect(switchEvents()).toEqual([{ outcome: 'browser', reauthorize_reason: 'mint_disabled' }]) + expect(browserEvents()).toEqual([{ reauthorize_reason: 'mint_disabled' }]) }) - it('stores first-time workspace authorization for later silent activation', async () => { - const workspaceOne = makeTokens('w1') - const workspaceTwo = makeTokens('w2') - cache(workspaceOne, true) - mocked(signIn).mockResolvedValue({ - tokens: workspaceTwo, - status: statusFromAccessToken(workspaceTwo.accessToken) + it('a 503 of any other kind stays retryable with no browser', async () => { + saveGrant(grantOn('w1')) + mintReply = () => json(503, { code: 'maintenance' }) + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w1', + workspaceSwitchFailure: 'retryable' }) + + expect(signIn).not.toHaveBeenCalled() + }) + + it('no loop: consent on another workspace and a second 503 stays on the current one', async () => { + const original = grantOn('w1') + saveGrant(original) + mintReply = mintDisabled + mocked(signIn).mockResolvedValue(signedInResult(grantOn('w3'))) + const session = new CloudSession() + + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w1', + workspaceSwitchFailure: 'retryable' + }) + + expect(signIn).toHaveBeenCalledOnce() + expect(mintRequests).toHaveLength(2) + await expect(session.getAccessToken()).resolves.toBe(original.accessToken) + }) + + it('the ops flag off skips the mint and opens one browser carrying B', async () => { + saveGrant(grantOn('w1')) + killMintSwitch() + mocked(signIn).mockResolvedValue(signedInResult(grantOn('w2'))) const session = new CloudSession() + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) + + expect(mintRequests).toEqual([]) + expect(signIn).toHaveBeenCalledExactlyOnceWith({ workspaceId: 'w2' }) + expect(browserEvents()).toEqual([{ reauthorize_reason: 'mint_disabled' }]) + }) + + it('no loop: the ops flag off and consent on another workspace opens no second browser', async () => { + saveGrant(grantOn('w1')) + killMintSwitch() + mocked(signIn).mockResolvedValue(signedInResult(grantOn('w3'))) + const session = new CloudSession() + + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w1', + workspaceSwitchFailure: 'retryable' + }) + + expect(mintRequests).toEqual([]) + expect(signIn).toHaveBeenCalledOnce() + }) + + it('the ops flag off still activates a valid minted token and the anchor with no browser', async () => { + saveGrant(grantOn('w1')) + const session = new CloudSession() + await session.switchWorkspace('w2') + await session.switchWorkspace('w1') + mintRequests = [] + killMintSwitch() + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) await expect(session.switchWorkspace('w1')).resolves.toMatchObject({ workspaceId: 'w1' }) + + expect(mintRequests).toEqual([]) + expect(signIn).not.toHaveBeenCalled() + }) + + it('degraded mode: each workspace is one browser, and the previous anchor stays reachable', async () => { + saveGrant(grantOn('w1')) + killMintSwitch() + mocked(signIn).mockImplementation(async (options) => + signedInResult(grantOn(options?.workspaceId ?? 'w1')) + ) + const session = new CloudSession() + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) + await expect(session.switchWorkspace('w1')).resolves.toMatchObject({ workspaceId: 'w1' }) expect(signIn).toHaveBeenCalledOnce() - expect(saveTokens).toHaveBeenCalledExactlyOnceWith(workspaceTwo) + expect(mintRequests).toEqual([]) + }) +}) + +describe('CloudSession regressions', () => { + it('a version 1 vault on first launch is a scopeless grant: one browser, then it mints', async () => { + const legacy = grantOn('w1', { scope: READ_ONLY_SCOPE }) + fs.writeFileSync( + path.join(electronState.userData, 'comfy-cloud-auth.bin'), + JSON.stringify({ + version: 1, + activeKey: 'workspace:w1', + subject: 'user-1', + bundles: { + 'workspace:w1': legacy, + 'workspace:w2': grantOn('w2', { scope: READ_ONLY_SCOPE }) + } + }) + ) + _resetForTest() + mocked(signIn).mockResolvedValue(signedInResult(grantOn('w3'))) + const session = new CloudSession() + + expect(session.status()).toMatchObject({ signedIn: true, workspaceId: 'w1' }) + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) + + expect(signIn).toHaveBeenCalledOnce() + expect(vaultOnDisk().version).toBe(2) + }) + + it('sign-out during a mint leaves nothing behind and opens no browser', async () => { + saveGrant(grantOn('w1')) + const reply = deferred() + mintReply = () => reply.promise + const session = new CloudSession() + + const switching = session.switchWorkspace('w2') + await vi.waitFor(() => expect(mintRequests).toHaveLength(1)) + session.logout() + reply.resolve(mintDisabled()) + + await expect(switching).resolves.toEqual({ signedIn: false }) + expect(signIn).not.toHaveBeenCalled() }) - it('listWorkspaces and the provider use only the active token', async () => { - const tokens = makeTokens('w1') - cache(tokens, true) + it('sign-out then a new switch does not join the signed-out flight', async () => { + saveGrant(grantOn('w1')) + const reply = deferred() + mintReply = () => reply.promise const session = new CloudSession() + + const stale = session.switchWorkspace('w2') + await vi.waitFor(() => expect(mintRequests).toHaveLength(1)) + session.logout() + saveGrant(grantOn('w1')) + mintReply = ({ workspaceId }) => minted(workspaceId) + + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) + reply.resolve(minted('w2')) + await stale + + expect(mintRequests).toHaveLength(2) + }) +}) + +describe('CloudSession grants without the mint scope (T-V29)', () => { + it('opens exactly one browser, asks Cloud nothing first, and then mints', async () => { + saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) + mocked(signIn).mockResolvedValue(signedInResult(grantOn('w3'))) + const session = new CloudSession() + + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) + + expect(signIn).toHaveBeenCalledExactlyOnceWith({ workspaceId: 'w2' }) + expect(mintRequests).toHaveLength(1) + expect(browserEvents()).toEqual([{ reauthorize_reason: 'mint_scope_missing' }]) + }) + + it('needs no browser to reach its own anchor', async () => { + saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) + + await expect(new CloudSession().switchWorkspace('w1')).resolves.toMatchObject({ + workspaceId: 'w1' + }) + + expect(signIn).not.toHaveBeenCalled() + }) + + it('cannot loop: a sign-in that returns no scope stays put, reports retryable and is telemetered', async () => { + saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) + mocked(signIn).mockResolvedValue( + signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) + ) + const session = new CloudSession() + + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w1', + workspaceSwitchFailure: 'retryable' + }) + + expect(signIn).toHaveBeenCalledOnce() + expect(mintRequests).toEqual([]) + expect(switchEvents()).toEqual([ + { outcome: 'browser', reauthorize_reason: 'mint_scope_missing' }, + { outcome: 'retryable', reauthorize_reason: 'scope_not_granted' } + ]) + expect(browserEvents()).toEqual([ + { reauthorize_reason: 'mint_scope_missing' }, + { reauthorize_reason: 'scope_not_granted' } + ]) + }) + + it('reports scope_not_granted when an sso sign-in narrows a grant that could mint', async () => { + saveGrant(grantOn('w1')) + mintReply = () => json(403, { code: 'sso_required' }) + mocked(signIn).mockResolvedValue(signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE }))) + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + workspaceSwitchFailure: 'retryable' + }) + + expect(signIn).toHaveBeenCalledOnce() + expect(browserEvents()).toContainEqual({ reauthorize_reason: 'scope_not_granted' }) + }) + + it('a scopeless grant consented on B activates B, since an anchor needs no mint', async () => { + saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) + mocked(signIn).mockResolvedValue(signedInResult(grantOn('w2', { scope: READ_ONLY_SCOPE }))) + + const reply = await new CloudSession().switchWorkspace('w2') + + expect(reply).toMatchObject({ workspaceId: 'w2' }) + expect(reply).not.toHaveProperty('workspaceSwitchFailure') + expect(signIn).toHaveBeenCalledOnce() + expect(browserEvents()).toContainEqual({ reauthorize_reason: 'scope_not_granted' }) + }) +}) + +describe('CloudSession fencing (T-V27)', () => { + it('drops a mint reply that lands after logout', async () => { + saveGrant(grantOn('w1')) + const reply = deferred() + mintReply = () => reply.promise + const session = new CloudSession() + + const switching = session.switchWorkspace('w2') + await vi.waitFor(() => expect(mintRequests).toHaveLength(1)) + session.logout() + reply.resolve(minted('w2')) + + await expect(switching).resolves.toEqual({ signedIn: false }) + expect(session.isSignedIn()).toBe(false) + expect(fs.existsSync(path.join(electronState.userData, 'comfy-cloud-auth.bin'))).toBe(false) + }) + + it('drops a mint reply that lands after a newer switch, activating and storing nothing', async () => { + saveGrant(grantOn('w1')) + const slow = deferred() + mintReply = ({ workspaceId }) => (workspaceId === 'w2' ? slow.promise : minted(workspaceId)) + const session = new CloudSession() + + const older = session.switchWorkspace('w2') + await vi.waitFor(() => expect(mintRequests).toHaveLength(1)) + await session.switchWorkspace('w3') + slow.resolve(minted('w2')) + await older + + expect(session.currentWorkspaceId()).toBe('w3') + expect(Object.keys(vaultOnDisk().workspaceTokens as object)).toEqual(['w3']) + expect(switchEvents()).toEqual([{ outcome: 'minted' }]) + }) + + it('a mint from before A to B to A does not satisfy the later switch to the same workspace', async () => { + saveGrant(grantOn('w1')) + const slow = deferred() + const replies = [slow.promise] + mintReply = ({ workspaceId }) => replies.shift() ?? minted(workspaceId) + const session = new CloudSession() + + const first = session.switchWorkspace('w2') + await vi.waitFor(() => expect(mintRequests).toHaveLength(1)) + await session.switchWorkspace('w1') + const second = session.switchWorkspace('w2') + await vi.waitFor(() => expect(mintRequests).toHaveLength(2)) + await second + slow.resolve(json(500, {})) + await first + + expect(session.currentWorkspaceId()).toBe('w2') + }) + + it('drops a sign-in that finishes after a newer switch', async () => { + saveGrant(grantOn('w1')) + mintReply = ({ workspaceId }) => + workspaceId === 'w2' ? json(403, { code: 'sso_required' }) : minted(workspaceId) + const pending = deferred>>() + mocked(signIn).mockReturnValue(pending.promise) + const original = grantOn('w1') + const session = new CloudSession() + + const older = session.switchWorkspace('w2') + await vi.waitFor(() => expect(signIn).toHaveBeenCalledOnce()) + await session.switchWorkspace('w3') + pending.resolve(signedInResult(grantOn('w2', { revision: '-late' }))) + await older + + expect(session.currentWorkspaceId()).toBe('w3') + expect(vaultOnDisk().grant).toEqual(original) + }) + + it('drops a sign-in that finishes after logout', async () => { + saveGrant(grantOn('w1')) + mintReply = () => json(403, { code: 'sso_required' }) + const pending = deferred>>() + mocked(signIn).mockReturnValue(pending.promise) + const session = new CloudSession() + + const switching = session.switchWorkspace('w2') + await vi.waitFor(() => expect(signIn).toHaveBeenCalledOnce()) + session.logout() + pending.resolve(signedInResult(grantOn('w2'))) + + await expect(switching).resolves.toEqual({ signedIn: false }) + expect(session.isSignedIn()).toBe(false) + }) + + it('does not let a re-mint from before logout reach the next account', async () => { + saveGrant(grantOn('w1')) + mintReply = ({ workspaceId }) => minted(workspaceId, Date.now() + 30_000) + const session = new CloudSession() + await session.switchWorkspace('w2') + const slow = deferred() + mintReply = () => slow.promise + + const request = session.getAccessToken() + await vi.waitFor(() => expect(mintRequests).toHaveLength(2)) + session.logout() + saveGrant(grantOn('w1', { subject: 'user-2' })) + slow.resolve(minted('w2')) + + await expect(request).resolves.toBeNull() + expect(vaultOnDisk().workspaceTokens).toEqual({}) + }) +}) + +describe('CloudSession status and catalog', () => { + it('reports the active workspace from the minted token, stale claims included', async () => { + saveGrant(grantOn('w1')) + mintReply = ({ workspaceId }) => minted(workspaceId, Date.now() + 1) + const session = new CloudSession() + + await session.switchWorkspace('w2') + + expect(session.status()).toMatchObject({ + signedIn: true, + workspaceId: 'w2', + workspaceType: 'team', + role: 'member', + email: 'user-1@example.com' + }) + expect(session.currentWorkspaceId()).toBe('w2') + }) + + it('lists workspaces with the grant and members with the active token', async () => { + const grant = grantOn('w1') + saveGrant(grant) + const session = new CloudSession() + await session.switchWorkspace('w2') + await session.listWorkspaces() - expect(listWorkspaces).toHaveBeenCalledWith(tokens.accessToken) - expect(saveWorkspaceNames).toHaveBeenCalledExactlyOnceWith(tokens.accessToken, [{ id: 'w-1' }]) + await session.listWorkspaceMembers() + expect(listWorkspaces).toHaveBeenCalledExactlyOnceWith(grant.accessToken) + expect(listWorkspaceMembers).toHaveBeenCalledExactlyOnceWith(mintedJwt('w2')) + }) +}) + +describe('CloudSession token provider', () => { + it('logs out when the grant token is rejected', () => { + const grant = grantOn('w1') + saveGrant(grant) + const session = new CloudSession() const onSignedOut = vi.fn() - const provider = session.asTokenProvider(onSignedOut) - await expect(provider.getAccessToken()).resolves.toBe(tokens.accessToken) - provider.onUnauthorized?.(tokens.accessToken) - expect(clearTokens).toHaveBeenCalledOnce() + + session.asTokenProvider(onSignedOut).onUnauthorized?.(grant.accessToken) + + expect(session.isSignedIn()).toBe(false) expect(onSignedOut).toHaveBeenCalledOnce() }) - it('lists members using only the active workspace token', async () => { - const tokens = makeTokens('w1') - cache(tokens, true) + it('drops only a rejected minted token, stays signed in, and re-mints with no browser', async () => { + saveGrant(grantOn('w1')) + const session = new CloudSession() + await session.switchWorkspace('w2') + const onSignedOut = vi.fn() + const provider = session.asTokenProvider(onSignedOut) - await expect(new CloudSession().listWorkspaceMembers()).resolves.toEqual([ - { id: 'user-1', name: 'One' } - ]) - expect(listWorkspaceMembers).toHaveBeenCalledExactlyOnceWith(tokens.accessToken) + provider.onUnauthorized?.(mintedJwt('w2')) + + expect(onSignedOut).not.toHaveBeenCalled() + expect(session.status()).toMatchObject({ signedIn: true, workspaceId: 'w2' }) + await expect(provider.getAccessToken()).resolves.toBe(mintedJwt('w2')) + expect(mintRequests).toHaveLength(2) + expect(signIn).not.toHaveBeenCalled() + }) + + it('ignores a rejected token it no longer holds', () => { + saveGrant(grantOn('w1')) + const session = new CloudSession() + const onSignedOut = vi.fn() + + session.asTokenProvider(onSignedOut).onUnauthorized?.('older-token') + + expect(session.isSignedIn()).toBe(true) + expect(onSignedOut).not.toHaveBeenCalled() }) }) diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index 45c662f4d..e8d231a93 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -7,35 +7,107 @@ * the main process; the UI only ever gets {@link AuthStatus} + {@link Workspace}. */ import type { TokenProvider } from '../comfybuilder' -import { subjectOf, workspaceIdOf } from './claims' -import type { OAuthOptions } from './oauth' +import * as mainTelemetry from '../lib/telemetry' +import { isWorkspaceMintSwitchEnabled } from '../lib/workspaceMintSwitchFlag' +import { canMintWorkspaceTokens, subjectOf, workspaceIdOf } from './claims' import { openAuthorizePage, refresh, signIn } from './oauth' +import { SignInFailure } from './signInFailure' import { activateWorkspace, clearTokens, + dropWorkspaceToken, getAuthStatus, - loadTokens, - loadWorkspaceTokens, - replaceWorkspaceTokens, - saveTokens, - saveWorkspaceNames + loadActiveWorkspaceId, + loadGrant, + loadWorkspaceToken, + replaceGrant, + saveGrant, + saveWorkspaceNames, + saveWorkspaceToken } from './tokenStore' -import type { AuthStatus, AuthTokens, Workspace, WorkspaceMember } from './types' +import type { + AuthStatus, + AuthTokens, + Workspace, + WorkspaceMember, + WorkspaceSwitchFailure, + WorkspaceSwitchStatus +} from './types' +import { classifyMint, mintWorkspaceToken } from './workspaceToken' +import type { ReauthorizeReason, WorkspaceMintOutcome } from './workspaceToken' import { listWorkspaceMembers, listWorkspaces } from './workspaces' -/** Refresh an access token this many ms before it actually expires. */ +/** Refresh or re-mint an access token this many ms before it actually expires. */ const REFRESH_SKEW_MS = 60_000 +/** One event per switch decision. `outcome` is how the goal of no further consent is measured. */ +export const WORKSPACE_SWITCH_EVENT = 'comfy.desktop.auth.workspace_switch' +/** Mirrored to Datadog: every browser trip a workspace switch causes. */ +export const WORKSPACE_SWITCH_BROWSER_EVENT = 'comfy.desktop.auth.workspace_switch_browser' +/** Mirrored to Datadog: a token read could not renew the active workspace, so it went back to the anchor. */ +export const WORKSPACE_RETURNED_TO_ANCHOR_EVENT = 'comfy.desktop.auth.workspace_returned_to_anchor' + +type WorkspaceSwitchOutcome = + | 'cached' + | 'anchor' + | 'minted' + | 'browser' + | 'unavailable' + | 'retryable' + | 'refused' + +type BrowserReason = ReauthorizeReason | 'scope_not_granted' + +type GrantRefresh = 'refreshed' | 'ended' | 'unavailable' + +const RETRYABLE: WorkspaceMintOutcome = { kind: 'retryable' } + +function isFresh(tokens: AuthTokens): boolean { + return tokens.expiresAt - REFRESH_SKEW_MS > Date.now() +} + +function isGrantRejected(outcome: WorkspaceMintOutcome): boolean { + return outcome.kind === 'reauthorize' && outcome.reason === 'grant_ended' +} + +function isDefinitiveRefreshRefusal(error: unknown): boolean { + return error instanceof SignInFailure && (error.httpStatus === 400 || error.httpStatus === 401) +} + +function refreshFailureOutcome(refreshed: GrantRefresh): WorkspaceMintOutcome { + return refreshed === 'ended' ? { kind: 'reauthorize', reason: 'grant_ended' } : RETRYABLE +} + +function reportSwitch(outcome: WorkspaceSwitchOutcome, reason?: BrowserReason): void { + mainTelemetry.emit( + WORKSPACE_SWITCH_EVENT, + reason ? { outcome, reauthorize_reason: reason } : { outcome } + ) +} + +function reportBrowser(outcome: WorkspaceSwitchOutcome, reason: BrowserReason): void { + reportSwitch(outcome, reason) + mainTelemetry.emit(WORKSPACE_SWITCH_BROWSER_EVENT, { reauthorize_reason: reason }) +} + export class CloudSession { - /** Refresh rotations are single-flight per workspace token family. */ - private readonly refreshing = new Map>() + private readonly refreshing = new Map>() + private readonly minting = new Map>() + private switching: { workspaceId: string; result: Promise } | null = null + private mintBlockedUntil = 0 private loginInFlight: Promise | null = null private loginAuthorizeUrl: string | null = null + private returnedToAnchorHandler: (() => void) | null = null - /** Latest browser-auth intent. Older flows may finish, but cannot replace - * tokens chosen by a newer login, workspace switch, or logout. */ + /** Latest auth intent. Older flows may finish, but cannot change what a newer + * login, workspace switch, or logout chose. */ private authGeneration = 0 + /** Called after a token read moved the active workspace back to the anchor. */ + setReturnedToAnchorHandler(handler: () => void): void { + this.returnedToAnchorHandler = handler + } + /** Start the PKCE sign-in (system browser); persists tokens on success. * A repeat request while one is pending reopens its browser page, since the * user may have closed it or hit an IdP error there. */ @@ -44,18 +116,33 @@ export class CloudSession { if (this.loginAuthorizeUrl) void openAuthorizePage(this.loginAuthorizeUrl).catch(() => {}) return this.loginInFlight } + this.switching = null const generation = ++this.authGeneration - const login = this.authenticateAtGeneration(generation, { - onAuthorizeUrl: (url) => { - if (generation === this.authGeneration) this.loginAuthorizeUrl = url - } - }).finally(() => { + const login = this.signInAtGeneration(generation).finally(() => { if (this.loginInFlight === login) this.clearPendingLogin() }) this.loginInFlight = login return login } + private async signInAtGeneration(generation: number): Promise { + const { tokens, status } = await signIn({ + onAuthorizeUrl: (url) => { + if (generation === this.authGeneration) this.loginAuthorizeUrl = url + } + }) + if (generation !== this.authGeneration) return this.status() + this.storeSignedInGrant(tokens) + const anchor = workspaceIdOf(tokens.accessToken) + if (anchor) activateWorkspace(anchor) + return status + } + + private storeSignedInGrant(tokens: AuthTokens): void { + this.mintBlockedUntil = 0 + saveGrant(tokens) + } + private clearPendingLogin(): void { this.loginInFlight = null this.loginAuthorizeUrl = null @@ -64,6 +151,8 @@ export class CloudSession { /** Forget tokens. Installed environments are untouched. */ logout(): void { this.authGeneration += 1 + this.switching = null + this.mintBlockedUntil = 0 this.clearPendingLogin() clearTokens() } @@ -81,69 +170,152 @@ export class CloudSession { return this.authGeneration } - /** The account the active token belongs to, or null when signed out. */ + /** The account the grant belongs to, or null when signed out. */ currentSubject(): string | null { - const t = loadTokens() - return t ? subjectOf(t.accessToken) : null + const grant = loadGrant() + return grant ? subjectOf(grant.accessToken) : null } - /** The workspace the active token is scoped to, or null when signed out. */ + /** The active workspace, or null when signed out. */ currentWorkspaceId(): string | null { - const t = loadTokens() - return t ? workspaceIdOf(t.accessToken) : null + return loadActiveWorkspaceId() } - /** - * A valid access token, refreshing it first if it is expired (or about to be) - * and a refresh token is available. Null when signed out or the refresh fails. - */ + /** The grant's access token for minting and scope checks. After a failed refresh it is the stale one. */ + async getGrantAccessToken(): Promise { + const grant = loadGrant() + if (!grant) return null + if (!isFresh(grant) && grant.refreshToken) await this.refreshGrant(grant) + return loadGrant()?.accessToken ?? null + } + + /** The token for API calls in the active workspace, null when it cannot get one. + * A definitively refused grant returns its stale token, so the API's 401 ends the session. */ async getAccessToken(): Promise { - const tokens = loadTokens() - if (!tokens) return null - if (tokens.expiresAt - REFRESH_SKEW_MS > Date.now() || !tokens.refreshToken) - return tokens.accessToken - const workspaceId = workspaceIdOf(tokens.accessToken) - await this.refreshWorkspaceTokens(workspaceId, tokens) - const active = loadTokens() - return active && workspaceIdOf(active.accessToken) === workspaceId ? active.accessToken : null - } - - private refreshKey(workspaceId: string | null, refreshToken: string): string { - return `${workspaceId === null ? 'default' : `workspace:${workspaceId}`}\0${refreshToken}` - } - - private refreshWorkspaceTokens( - workspaceId: string | null, - tokens: AuthTokens - ): Promise { - const key = this.refreshKey(workspaceId, tokens.refreshToken ?? '') - const inFlight = this.refreshing.get(key) + const grant = loadGrant() + if (!grant) return null + const generation = this.authGeneration + const workspaceId = loadActiveWorkspaceId() + if (!workspaceId || workspaceId === workspaceIdOf(grant.accessToken)) { + if (isFresh(grant) || !grant.refreshToken) return grant.accessToken + const refreshed = await this.refreshGrant(grant) + if (refreshed === 'unavailable' || generation !== this.authGeneration) return null + return loadGrant()?.accessToken ?? null + } + const held = loadWorkspaceToken(workspaceId) + if (held && isFresh(held)) return held.accessToken + + const outcome = await this.mintForWorkspace(workspaceId, generation) + if (generation !== this.authGeneration) return null + if (outcome.kind === 'minted') return outcome.token + if (held && held.expiresAt > Date.now()) return held.accessToken + if (outcome.kind !== 'retryable') this.returnToAnchor(workspaceId, outcome) + return null + } + + private returnToAnchor( + workspaceId: string, + outcome: Exclude + ): void { + const grant = loadGrant() + const anchor = grant && workspaceIdOf(grant.accessToken) + if (!anchor || loadActiveWorkspaceId() !== workspaceId) return + activateWorkspace(anchor) + mainTelemetry.emit(WORKSPACE_RETURNED_TO_ANCHOR_EVENT, { + reason: outcome.kind === 'reauthorize' ? outcome.reason : outcome.kind + }) + this.returnedToAnchorHandler?.() + } + + private refreshGrant(grant: AuthTokens): Promise { + const refreshToken = grant.refreshToken + if (!refreshToken) return Promise.resolve('ended') + const inFlight = this.refreshing.get(refreshToken) if (inFlight) return inFlight - const refreshing = this.doRefresh(workspaceId, tokens).finally(() => { - if (this.refreshing.get(key) === refreshing) this.refreshing.delete(key) + const refreshing = this.rotateGrant(grant, refreshToken).finally(() => { + if (this.refreshing.get(refreshToken) === refreshing) this.refreshing.delete(refreshToken) }) - this.refreshing.set(key, refreshing) + this.refreshing.set(refreshToken, refreshing) return refreshing } - private async doRefresh( - workspaceId: string | null, - tokens: AuthTokens - ): Promise { - const refreshToken = tokens.refreshToken - if (!refreshToken) return tokens + private async rotateGrant(grant: AuthTokens, refreshToken: string): Promise { try { - const rotated = await refresh(refreshToken) - const saved = replaceWorkspaceTokens(workspaceId, tokens.accessToken, refreshToken, rotated) - return saved ? rotated : loadWorkspaceTokens(workspaceId) - } catch { - return loadWorkspaceTokens(workspaceId) + replaceGrant(grant.accessToken, refreshToken, await refresh(refreshToken)) + return 'refreshed' + } catch (error) { + return isDefinitiveRefreshRefusal(error) ? 'ended' : 'unavailable' + } + } + + private mintForWorkspace(workspaceId: string, generation: number): Promise { + const key = JSON.stringify([generation, workspaceId]) + const inFlight = this.minting.get(key) + if (inFlight) return inFlight + const minting = this.mintWithGrant(workspaceId, generation) + .then((outcome) => this.storeMinted(workspaceId, generation, outcome)) + .finally(() => { + if (this.minting.get(key) === minting) this.minting.delete(key) + }) + this.minting.set(key, minting) + return minting + } + + private storeMinted( + workspaceId: string, + generation: number, + outcome: WorkspaceMintOutcome + ): WorkspaceMintOutcome { + if (outcome.kind !== 'minted' || generation !== this.authGeneration) return outcome + const grant = loadGrant() + if ( + !grant || + workspaceIdOf(outcome.token) !== workspaceId || + subjectOf(outcome.token) !== subjectOf(grant.accessToken) + ) { + return RETRYABLE + } + saveWorkspaceToken(workspaceId, { accessToken: outcome.token, expiresAt: outcome.expiresAt }) + return outcome + } + + private async mintWithGrant( + workspaceId: string, + generation: number + ): Promise { + if (!(await isWorkspaceMintSwitchEnabled())) { + return { kind: 'reauthorize', reason: 'mint_disabled' } + } + const grant = loadGrant() + if (!grant) return RETRYABLE + if (!canMintWorkspaceTokens(grant.accessToken)) + return { kind: 'reauthorize', reason: 'mint_scope_missing' } + if (!isFresh(grant)) { + const refreshed = await this.refreshGrant(grant) + if (refreshed !== 'refreshed') return refreshFailureOutcome(refreshed) } + const first = await this.postMint(workspaceId, generation) + if (!isGrantRejected(first)) return first + const current = loadGrant() + if (!current) return RETRYABLE + const refreshed = await this.refreshGrant(current) + if (refreshed !== 'refreshed') return refreshFailureOutcome(refreshed) + return this.postMint(workspaceId, generation) + } + + private async postMint(workspaceId: string, generation: number): Promise { + const grant = loadGrant() + if (!grant || generation !== this.authGeneration || Date.now() < this.mintBlockedUntil) + return RETRYABLE + const outcome = classifyMint(await mintWorkspaceToken(grant.accessToken, workspaceId)) + if (outcome.kind === 'retryable' && outcome.retryAfterSeconds !== undefined) + this.mintBlockedUntil = Date.now() + outcome.retryAfterSeconds * 1000 + return outcome } /** The signed-in user's workspaces; unavailable catalogs reject rather than imply removal. */ async listWorkspaces(): Promise { - const token = await this.getAccessToken() + const token = await this.getGrantAccessToken() if (!token) return [] const workspaces = await listWorkspaces(token) saveWorkspaceNames(token, workspaces) @@ -157,36 +329,102 @@ export class CloudSession { return listWorkspaceMembers(token) } - /** Activate cached workspace credentials, using browser auth only when needed. */ - async switchWorkspace(workspaceId: string): Promise { + /** Activate `workspaceId`. Only a refused grant, an SSO policy, a missing mint scope or a + * mint kill switch opens the browser; every other failure stays put and says so. */ + switchWorkspace(workspaceId: string): Promise { + if (this.switching?.workspaceId === workspaceId) return this.switching.result this.clearPendingLogin() const generation = ++this.authGeneration - const current = loadTokens() - let cached = - current && workspaceIdOf(current.accessToken) === workspaceId - ? current - : loadWorkspaceTokens(workspaceId) - if (cached?.refreshToken && cached.expiresAt - REFRESH_SKEW_MS <= Date.now()) { - cached = await this.refreshWorkspaceTokens(workspaceId, cached) + const result = this.runSwitch(workspaceId, generation).finally(() => { + if (this.switching?.result === result) this.switching = null + }) + this.switching = { workspaceId, result } + return result + } + + private async runSwitch(workspaceId: string, generation: number): Promise { + const grant = loadGrant() + if (!grant) return this.status() + if (workspaceId === workspaceIdOf(grant.accessToken)) { + return this.switchToAnchor(workspaceId, generation, grant) } + const held = loadWorkspaceToken(workspaceId) + if (held && held.expiresAt > Date.now()) return this.activated(workspaceId, 'cached') + + const outcome = await this.mintForWorkspace(workspaceId, generation) if (generation !== this.authGeneration) return this.status() - if (cached && cached.expiresAt > Date.now()) { - if (cached !== current) activateWorkspace(workspaceId) - return this.status() + switch (outcome.kind) { + case 'minted': + return this.activated(workspaceId, 'minted') + case 'unavailable': + reportSwitch('unavailable') + return this.stayed('unavailable') + case 'refused': + reportSwitch('refused') + return this.stayed('unavailable') + case 'retryable': + reportSwitch('retryable') + return this.stayed('retryable') + case 'reauthorize': + return this.reauthorize(workspaceId, generation, outcome.reason) + } + } + + private async switchToAnchor( + workspaceId: string, + generation: number, + grant: AuthTokens + ): Promise { + if (!isFresh(grant)) { + const refreshed = await this.refreshGrant(grant) + if (generation !== this.authGeneration) return this.status() + if (refreshed === 'ended') return this.reauthorize(workspaceId, generation, 'grant_ended') } - return this.authenticateAtGeneration(generation, { workspaceId }) + return this.activated(workspaceId, 'anchor') } - private async authenticateAtGeneration( + private activated(workspaceId: string, outcome: WorkspaceSwitchOutcome): WorkspaceSwitchStatus { + activateWorkspace(workspaceId) + reportSwitch(outcome) + return this.status() + } + + private stayed(failure: WorkspaceSwitchFailure): WorkspaceSwitchStatus { + return { ...this.status(), workspaceSwitchFailure: failure } + } + + private async reauthorize( + workspaceId: string, generation: number, - options: OAuthOptions - ): Promise { - const { workspaceId } = options - const { tokens, status } = await signIn(options) + reason: ReauthorizeReason + ): Promise { + reportBrowser('browser', reason) + let tokens: AuthTokens + try { + ;({ tokens } = await signIn({ workspaceId })) + } catch { + return generation === this.authGeneration ? this.stayed('retryable') : this.status() + } if (generation !== this.authGeneration) return this.status() - if (workspaceId && status.workspaceId !== workspaceId) return this.status() - saveTokens(tokens) - return status + this.storeSignedInGrant(tokens) + + const canMint = canMintWorkspaceTokens(tokens.accessToken) + const isAnchor = workspaceId === workspaceIdOf(tokens.accessToken) + if (!canMint) reportBrowser(isAnchor ? 'anchor' : 'retryable', 'scope_not_granted') + if (isAnchor) { + activateWorkspace(workspaceId) + return this.status() + } + if (!canMint) return this.stayed('retryable') + + const outcome = await this.mintForWorkspace(workspaceId, generation) + if (generation !== this.authGeneration) return this.status() + if (outcome.kind === 'minted') { + activateWorkspace(workspaceId) + return this.status() + } + const unavailable = outcome.kind === 'unavailable' || outcome.kind === 'refused' + return this.stayed(unavailable ? 'unavailable' : 'retryable') } /** Adapter for the comfy-builder client's auth seam. */ @@ -194,9 +432,8 @@ export class CloudSession { return { getAccessToken: () => this.getAccessToken(), onUnauthorized: (rejectedAccessToken) => { - // A request issued before a newer login may return 401 afterward. Only - // invalidate the exact token the server rejected, never the new session. - if (loadTokens()?.accessToken !== rejectedAccessToken) return + if (dropWorkspaceToken(rejectedAccessToken)) return + if (loadGrant()?.accessToken !== rejectedAccessToken) return this.logout() onSignedOut?.() } diff --git a/src/main/cloud/tokenStore.test.ts b/src/main/cloud/tokenStore.test.ts index 63c6d2a0f..e9ffa9073 100644 --- a/src/main/cloud/tokenStore.test.ts +++ b/src/main/cloud/tokenStore.test.ts @@ -19,13 +19,16 @@ import { _resetForTest, activateWorkspace, clearTokens, + dropWorkspaceToken, getAuthStatus, getCachedWorkspaceName, - loadTokens, - loadWorkspaceTokens, - replaceWorkspaceTokens, - saveTokens, - saveWorkspaceNames + loadActiveWorkspaceId, + loadGrant, + loadWorkspaceToken, + replaceGrant, + saveGrant, + saveWorkspaceNames, + saveWorkspaceToken } from './tokenStore' import type { AuthTokens } from './types' @@ -49,7 +52,23 @@ function tokens(subject: string, workspaceId: string, suffix = ''): AuthTokens { } } -describe('workspace token vault', () => { +function mintedToken(subject: string, workspaceId: string): AuthTokens { + return { accessToken: jwt(subject, workspaceId), expiresAt: Date.now() + 900_000 } +} + +function vaultPath(): string { + return path.join(electronState.userData, 'comfy-cloud-auth.bin') +} + +function writeVault(payload: unknown): void { + fs.writeFileSync(vaultPath(), Buffer.from(JSON.stringify(payload), 'utf-8')) +} + +function readVault(): Record { + return JSON.parse(fs.readFileSync(vaultPath(), 'utf-8')) as Record +} + +describe('grant vault', () => { beforeEach(() => { electronState.userData = fs.mkdtempSync(path.join(os.tmpdir(), 'comfy-cloud-tokens-')) electronState.encryptionAvailable = true @@ -62,40 +81,134 @@ describe('workspace token vault', () => { _resetForTest() }) - it('keeps independent workspace bundles and reactivates either one', () => { - const workspaceOne = tokens('user-1', 'w1') - const workspaceTwo = tokens('user-1', 'w2') + it('persists one grant plus minted tokens as version 2', () => { + const grant = tokens('user-1', 'w1') + const minted = mintedToken('user-1', 'w2') + saveGrant(grant) + saveWorkspaceToken('w2', minted) + activateWorkspace('w2') - saveTokens(workspaceOne) - saveTokens(workspaceTwo) - expect(loadTokens()).toEqual(workspaceTwo) + expect(readVault()).toEqual({ + version: 2, + subject: 'user-1', + grant, + activeWorkspaceId: 'w2', + workspaceTokens: { w2: minted } + }) + + _resetForTest() - expect(activateWorkspace('w1')).toEqual(workspaceOne) - expect(loadTokens()).toEqual(workspaceOne) - expect(loadWorkspaceTokens('w2')).toEqual(workspaceTwo) + expect(loadGrant()).toEqual(grant) + expect(loadActiveWorkspaceId()).toBe('w2') + expect(loadWorkspaceToken('w2')).toEqual(minted) }) - it('clears cached workspaces when browser auth changes account', () => { - saveTokens(tokens('user-1', 'w1')) - saveTokens(tokens('user-1', 'w2')) - saveWorkspaceNames(loadTokens()!.accessToken, [ - { id: 'w1', name: 'Workspace One', type: 'team', role: 'owner' }, + it('activates only the anchor or a workspace with a held token', () => { + saveGrant(tokens('user-1', 'w1')) + saveWorkspaceToken('w2', mintedToken('user-1', 'w2')) + + expect(activateWorkspace('w3')).toBe(false) + expect(loadActiveWorkspaceId()).toBe('w1') + expect(activateWorkspace('w2')).toBe(true) + expect(loadActiveWorkspaceId()).toBe('w2') + expect(activateWorkspace('w1')).toBe(true) + expect(loadActiveWorkspaceId()).toBe('w1') + }) + + it('reports status from the active token, and from the grant identity once it is dropped', () => { + saveGrant(tokens('user-1', 'w1')) + saveWorkspaceToken('w2', mintedToken('user-1', 'w2')) + saveWorkspaceNames(loadGrant()!.accessToken, [ { id: 'w2', name: 'Workspace Two', type: 'team', role: 'member' } ]) + activateWorkspace('w2') + + expect(getAuthStatus()).toMatchObject({ workspaceId: 'w2', workspaceName: 'Workspace Two' }) + + expect(dropWorkspaceToken(jwt('user-1', 'w2'))).toBe(true) + + expect(getAuthStatus()).toMatchObject({ + signedIn: true, + workspaceId: 'w2', + workspaceName: 'Workspace Two' + }) + expect(loadWorkspaceToken('w2')).toBeNull() + }) + + it('dropping an unknown or grant token changes nothing', () => { + saveGrant(tokens('user-1', 'w1')) + + expect(dropWorkspaceToken('unknown')).toBe(false) + expect(dropWorkspaceToken(loadGrant()!.accessToken)).toBe(false) + expect(loadGrant()).not.toBeNull() + }) + + it('replaces the grant for the same account and keeps its held tokens and active workspace', () => { + saveGrant(tokens('user-1', 'w1')) + const held = mintedToken('user-1', 'w2') + saveWorkspaceToken('w2', held) + activateWorkspace('w2') + + const next = tokens('user-1', 'w3') + saveGrant(next) + + expect(loadGrant()).toEqual(next) + expect(loadActiveWorkspaceId()).toBe('w2') + expect(loadWorkspaceToken('w2')).toEqual(held) + }) + + it('keeps the old access token, without its refresh token, for the old anchor when re-anchored', () => { + const previous = tokens('user-1', 'w1') + saveGrant(previous) + + saveGrant(tokens('user-1', 'w3')) + + expect(loadActiveWorkspaceId()).toBe('w1') + expect(loadWorkspaceToken('w1')).toEqual({ + accessToken: previous.accessToken, + expiresAt: previous.expiresAt + }) + expect(getAuthStatus()).toMatchObject({ workspaceId: 'w1' }) + }) + + it('moves to the new anchor when the old anchor token has expired', () => { + saveGrant({ ...tokens('user-1', 'w1'), expiresAt: Date.now() - 1000 }) + + saveGrant(tokens('user-1', 'w3')) + + expect(loadActiveWorkspaceId()).toBe('w3') + expect(loadWorkspaceToken('w1')).toBeNull() + }) + + it('clears everything when browser auth changes account', () => { + saveGrant(tokens('user-1', 'w1')) + saveWorkspaceToken('w2', mintedToken('user-1', 'w2')) + saveWorkspaceNames(loadGrant()!.accessToken, [ + { id: 'w1', name: 'Workspace One', type: 'team', role: 'owner' } + ]) const otherAccount = tokens('user-2', 'w3') - saveTokens(otherAccount) + saveGrant(otherAccount) - expect(loadTokens()).toEqual(otherAccount) - expect(loadWorkspaceTokens('w1')).toBeNull() - expect(loadWorkspaceTokens('w2')).toBeNull() - expect(getAuthStatus().workspaceName).toBeUndefined() + expect(loadGrant()).toEqual(otherAccount) + expect(loadActiveWorkspaceId()).toBe('w3') + expect(loadWorkspaceToken('w2')).toBeNull() + expect(getCachedWorkspaceName('w1')).toBeNull() + }) + + it('does not keep minted tokens when the new account identity cannot be proven', () => { + saveGrant({ accessToken: tokenWithoutSubject('w1'), expiresAt: Date.now() + 1000 }) + saveWorkspaceToken('w2', mintedToken('user-1', 'w2')) + + saveGrant({ accessToken: tokenWithoutSubject('w3'), expiresAt: Date.now() + 1000 }) + + expect(loadWorkspaceToken('w2')).toBeNull() }) it('restores the active workspace name after a process restart', () => { - const active = tokens('user-1', 'w1') - saveTokens(active) - saveWorkspaceNames(active.accessToken, [ + const grant = tokens('user-1', 'w1') + saveGrant(grant) + saveWorkspaceNames(grant.accessToken, [ { id: 'w1', name: 'Workspace One', type: 'team', role: 'owner' }, { id: 'w2', name: 'Workspace Two', type: 'team', role: 'member' } ]) @@ -112,8 +225,8 @@ describe('workspace token vault', () => { it('rejects workspace names from a request belonging to another account', () => { const stale = tokens('user-1', 'w1') - saveTokens(stale) - saveTokens(tokens('user-2', 'w2')) + saveGrant(stale) + saveGrant(tokens('user-2', 'w2')) saveWorkspaceNames(stale.accessToken, [ { id: 'w1', name: 'Workspace One', type: 'team', role: 'owner' } @@ -122,56 +235,114 @@ describe('workspace token vault', () => { expect(getAuthStatus().workspaceName).toBeUndefined() }) - it('does not retain bundles when the new account identity cannot be proven', () => { - saveTokens({ accessToken: tokenWithoutSubject('w1'), expiresAt: Date.now() + 1000 }) - saveTokens({ accessToken: tokenWithoutSubject('w2'), expiresAt: Date.now() + 1000 }) + it('rotates the grant only when it still matches', () => { + const grant = tokens('user-1', 'w1') + const rotated = tokens('user-1', 'w1', '-rotated') + saveGrant(grant) - expect(loadWorkspaceTokens('w1')).toBeNull() - expect(loadWorkspaceTokens('w2')).not.toBeNull() + expect(replaceGrant('other', grant.refreshToken!, rotated)).toBe(false) + expect(replaceGrant(grant.accessToken, 'other', rotated)).toBe(false) + expect(replaceGrant(grant.accessToken, grant.refreshToken!, rotated)).toBe(true) + expect(loadGrant()).toEqual(rotated) }) - it('rotates only the matching workspace bundle', () => { - const workspaceOne = tokens('user-1', 'w1') - const workspaceTwo = tokens('user-1', 'w2') - const rotated = tokens('user-1', 'w1', '-rotated') - saveTokens(workspaceOne) - saveTokens(workspaceTwo) + it('rejects a rotation for another workspace or account', () => { + const grant = tokens('user-1', 'w1') + saveGrant(grant) + + expect(replaceGrant(grant.accessToken, grant.refreshToken!, tokens('user-1', 'w2'))).toBe(false) + expect(replaceGrant(grant.accessToken, grant.refreshToken!, tokens('user-2', 'w1'))).toBe(false) + expect(loadGrant()).toEqual(grant) + }) + + it('keeps tokens in memory only when secure storage is unavailable', () => { + electronState.encryptionAvailable = false + const grant = tokens('user-1', 'w1') - expect( - replaceWorkspaceTokens('w1', workspaceOne.accessToken, workspaceOne.refreshToken!, rotated) - ).toBe(true) - expect(loadWorkspaceTokens('w1')).toEqual(rotated) - expect(loadWorkspaceTokens('w2')).toEqual(workspaceTwo) + saveGrant(grant) + + expect(loadGrant()).toEqual(grant) + expect(fs.existsSync(vaultPath())).toBe(false) }) - it('rejects a refresh response scoped to another workspace', () => { - const workspaceOne = tokens('user-1', 'w1') - saveTokens(workspaceOne) + it('migrates a version 1 vault: the active bundle becomes the grant, others are dropped', () => { + const active = tokens('user-1', 'w2') + writeVault({ + version: 1, + activeKey: 'workspace:w2', + subject: 'user-1', + bundles: { 'workspace:w1': tokens('user-1', 'w1'), 'workspace:w2': active }, + workspaceNames: { w2: 'Workspace Two' } + }) - expect( - replaceWorkspaceTokens( - 'w1', - workspaceOne.accessToken, - workspaceOne.refreshToken!, - tokens('user-1', 'w2') - ) - ).toBe(false) - expect(loadWorkspaceTokens('w1')).toEqual(workspaceOne) + expect(loadGrant()).toEqual(active) + expect(loadActiveWorkspaceId()).toBe('w2') + expect(loadWorkspaceToken('w1')).toBeNull() + expect(getAuthStatus()).toMatchObject({ workspaceId: 'w2', workspaceName: 'Workspace Two' }) + expect(readVault()).toEqual({ + version: 2, + subject: 'user-1', + grant: active, + activeWorkspaceId: 'w2', + workspaceTokens: {}, + workspaceNames: { w2: 'Workspace Two' } + }) }) it('migrates the original single-token payload', () => { const legacy = tokens('user-1', 'w1') - fs.writeFileSync( - path.join(electronState.userData, 'comfy-cloud-auth.bin'), - Buffer.from(JSON.stringify(legacy), 'utf-8') - ) - - expect(loadTokens()).toEqual(legacy) - expect(loadWorkspaceTokens('w1')).toEqual(legacy) - - const persisted = JSON.parse( - fs.readFileSync(path.join(electronState.userData, 'comfy-cloud-auth.bin'), 'utf-8') - ) as { version?: number } - expect(persisted.version).toBe(1) + writeVault(legacy) + + expect(loadGrant()).toEqual(legacy) + expect(loadActiveWorkspaceId()).toBe('w1') + expect(readVault()).toMatchObject({ version: 2 }) + }) + + it.each<[string, unknown]>([ + ['an unknown version', { version: 3, grant: tokens('user-1', 'w1') }], + [ + 'a version 2 vault with no grant', + { version: 2, activeWorkspaceId: 'w1', workspaceTokens: {} } + ], + [ + 'a version 2 vault with a malformed minted token', + { + version: 2, + grant: tokens('user-1', 'w1'), + activeWorkspaceId: 'w1', + workspaceTokens: { w2: { accessToken: 7 } } + } + ], + [ + 'a version 2 vault with a non-string active workspace', + { version: 2, grant: tokens('user-1', 'w1'), activeWorkspaceId: 7, workspaceTokens: {} } + ], + [ + 'a version 2 vault with malformed names', + { + version: 2, + grant: tokens('user-1', 'w1'), + activeWorkspaceId: 'w1', + workspaceTokens: {}, + workspaceNames: { w1: 7 } + } + ], + [ + 'a version 1 vault whose active bundle is missing', + { version: 1, activeKey: 'workspace:w2', bundles: { 'workspace:w1': tokens('user-1', 'w1') } } + ], + [ + 'a version 1 vault with a malformed bundle', + { + version: 1, + activeKey: 'workspace:w1', + bundles: { 'workspace:w1': tokens('user-1', 'w1'), 'workspace:w2': { accessToken: 7 } } + } + ] + ])('reads %s as signed out', (_name, payload) => { + writeVault(payload) + + expect(loadGrant()).toBeNull() + expect(getAuthStatus()).toEqual({ signedIn: false }) }) }) diff --git a/src/main/cloud/tokenStore.ts b/src/main/cloud/tokenStore.ts index 94218a34a..155646200 100644 --- a/src/main/cloud/tokenStore.ts +++ b/src/main/cloud/tokenStore.ts @@ -12,11 +12,19 @@ import { statusFromAccessToken, subjectOf, workspaceIdOf } from './claims' import type { AuthStatus, AuthTokens, Workspace } from './types' const AUTH_FILENAME = 'comfy-cloud-auth.bin' -const VAULT_VERSION = 1 -const DEFAULT_WORKSPACE_KEY = 'default' +const VAULT_VERSION = 2 interface TokenVault { version: typeof VAULT_VERSION + subject?: string + grant: AuthTokens + activeWorkspaceId: string | null + workspaceTokens: Record + workspaceNames?: Record +} + +interface LegacyVault { + version: 1 activeKey: string subject?: string bundles: Record @@ -60,44 +68,56 @@ function isTokens(v: unknown): v is AuthTokens { ) } -function isVault(v: unknown): v is TokenVault { - const vault = v as TokenVault - if ( - !v || - typeof v !== 'object' || - vault.version !== VAULT_VERSION || - typeof vault.activeKey !== 'string' || - (vault.subject !== undefined && typeof vault.subject !== 'string') || - !vault.bundles || - typeof vault.bundles !== 'object' || - Array.isArray(vault.bundles) || - (vault.workspaceNames !== undefined && - (!vault.workspaceNames || - typeof vault.workspaceNames !== 'object' || - Array.isArray(vault.workspaceNames) || - !Object.values(vault.workspaceNames).every((name) => typeof name === 'string'))) - ) { - return false - } - return isTokens(vault.bundles[vault.activeKey]) && Object.values(vault.bundles).every(isTokens) +function isRecord(v: unknown): v is Record { + return !!v && typeof v === 'object' && !Array.isArray(v) +} + +function isWorkspaceNames(v: unknown): boolean { + return ( + v === undefined || (isRecord(v) && Object.values(v).every((name) => typeof name === 'string')) + ) } -function workspaceKey(workspaceId: string | null): string { - return workspaceId === null ? DEFAULT_WORKSPACE_KEY : `workspace:${workspaceId}` +function isVault(v: unknown): v is TokenVault { + if (!isRecord(v) || v.version !== VAULT_VERSION) return false + return ( + isTokens(v.grant) && + (v.activeWorkspaceId === null || typeof v.activeWorkspaceId === 'string') && + (v.subject === undefined || typeof v.subject === 'string') && + isRecord(v.workspaceTokens) && + Object.values(v.workspaceTokens).every(isTokens) && + isWorkspaceNames(v.workspaceNames) + ) } -function tokensKey(tokens: AuthTokens): string { - return workspaceKey(workspaceIdOf(tokens.accessToken)) +function isLegacyVault(v: unknown): v is LegacyVault { + if (!isRecord(v) || v.version !== 1 || typeof v.activeKey !== 'string') return false + return ( + (v.subject === undefined || typeof v.subject === 'string') && + isRecord(v.bundles) && + Object.values(v.bundles).every(isTokens) && + isWorkspaceNames(v.workspaceNames) + ) } -function vaultFor(tokens: AuthTokens): TokenVault { - const key = tokensKey(tokens) - const subject = subjectOf(tokens.accessToken) +function vaultFor(grant: AuthTokens): TokenVault { + const subject = subjectOf(grant.accessToken) return { version: VAULT_VERSION, - activeKey: key, ...(subject ? { subject } : {}), - bundles: { [key]: tokens } + grant, + activeWorkspaceId: workspaceIdOf(grant.accessToken), + workspaceTokens: {} + } +} + +function migratedVault(legacy: LegacyVault): TokenVault | null { + const active = legacy.bundles[legacy.activeKey] + if (!active) return null + return { + ...vaultFor(active), + ...(legacy.subject ? { subject: legacy.subject } : {}), + ...(legacy.workspaceNames ? { workspaceNames: legacy.workspaceNames } : {}) } } @@ -130,40 +150,86 @@ function loadVault(): TokenVault | null { cachedVault = parsed return cachedVault } - if (isTokens(parsed)) { - // Migrate the original single-token payload without signing the user out. - const migrated = vaultFor(parsed) - persistVault(migrated) - return migrated - } - return null + const migrated = isLegacyVault(parsed) + ? migratedVault(parsed) + : isTokens(parsed) + ? vaultFor(parsed) + : null + if (migrated) persistVault(migrated) + return migrated } catch { return null } } -/** Save and activate a browser-auth token bundle. A changed account replaces the vault. */ -export function saveTokens(tokens: AuthTokens): void { +function holdsToken(vault: TokenVault, workspaceId: string | null): boolean { + return ( + workspaceId === workspaceIdOf(vault.grant.accessToken) || + (workspaceId !== null && workspaceId in vault.workspaceTokens) + ) +} + +/** Store the grant from a browser sign-in. A changed account replaces the vault. The old access + * token stays held for its old anchor; an active workspace with no held token moves to the new one. */ +export function saveGrant(grant: AuthTokens): void { const current = loadVault() - const nextSubject = subjectOf(tokens.accessToken) - const accountChanged = current !== null && (!nextSubject || current.subject !== nextSubject) - const vault = accountChanged || !current ? vaultFor(tokens) : current - const key = tokensKey(tokens) - vault.activeKey = key - vault.bundles[key] = tokens - if (nextSubject) vault.subject = nextSubject - persistVault(vault) + const subject = subjectOf(grant.accessToken) + if (!current || !subject || current.subject !== subject) { + persistVault(vaultFor(grant)) + return + } + const previous = current.grant + const previousAnchor = workspaceIdOf(previous.accessToken) + if ( + previousAnchor && + previousAnchor !== workspaceIdOf(grant.accessToken) && + previous.expiresAt > Date.now() + ) { + current.workspaceTokens[previousAnchor] = { + accessToken: previous.accessToken, + expiresAt: previous.expiresAt + } + } + current.grant = grant + if (!holdsToken(current, current.activeWorkspaceId)) + current.activeWorkspaceId = workspaceIdOf(grant.accessToken) + persistVault(current) +} + +/** The OAuth grant bundle, the only one carrying a refresh token. */ +export function loadGrant(): AuthTokens | null { + return loadVault()?.grant ?? null +} + +/** The workspace API calls act in, or null when signed out or the grant has no workspace claim. */ +export function loadActiveWorkspaceId(): string | null { + return loadVault()?.activeWorkspaceId ?? null } -/** The active workspace's token bundle. */ -export function loadTokens(): AuthTokens | null { +/** A token minted for `workspaceId`, without changing the active workspace. */ +export function loadWorkspaceToken(workspaceId: string): AuthTokens | null { + return loadVault()?.workspaceTokens[workspaceId] ?? null +} + +/** Store a token minted for `workspaceId`, without changing the active workspace. */ +export function saveWorkspaceToken(workspaceId: string, tokens: AuthTokens): void { const vault = loadVault() - return vault?.bundles[vault.activeKey] ?? null + if (!vault) return + vault.workspaceTokens[workspaceId] = tokens + persistVault(vault) } -/** A cached workspace token bundle, without changing the active workspace. */ -export function loadWorkspaceTokens(workspaceId: string | null): AuthTokens | null { - return loadVault()?.bundles[workspaceKey(workspaceId)] ?? null +/** Forget the minted token with this exact value. False when no minted token matches. */ +export function dropWorkspaceToken(accessToken: string): boolean { + const vault = loadVault() + if (!vault) return false + const entry = Object.entries(vault.workspaceTokens).find( + ([, tokens]) => tokens.accessToken === accessToken + ) + if (!entry) return false + delete vault.workspaceTokens[entry[0]] + persistVault(vault) + return true } /** Cache workspace names only when the response belongs to the current account. */ @@ -182,39 +248,32 @@ export function getCachedWorkspaceName(workspaceId: string): string | null { return loadVault()?.workspaceNames?.[workspaceId] ?? null } -/** Activate a cached workspace. Returns null when it has never been authorized. */ -export function activateWorkspace(workspaceId: string): AuthTokens | null { +/** Make `workspaceId` active. False, and no change, unless it is the anchor or a token is held for it. */ +export function activateWorkspace(workspaceId: string): boolean { const vault = loadVault() - if (!vault) return null - const key = workspaceKey(workspaceId) - const tokens = vault.bundles[key] - if (!tokens) return null - vault.activeKey = key + if (!vault || !holdsToken(vault, workspaceId)) return false + vault.activeWorkspaceId = workspaceId persistVault(vault) - return tokens + return true } -/** Compare-and-swap one workspace's tokens after refresh rotation. */ -export function replaceWorkspaceTokens( - workspaceId: string | null, +/** Compare-and-swap the grant after refresh rotation. */ +export function replaceGrant( expectedAccessToken: string, expectedRefreshToken: string, - tokens: AuthTokens + grant: AuthTokens ): boolean { const vault = loadVault() - if (!vault) return false - const key = workspaceKey(workspaceId) - const current = vault.bundles[key] if ( - !current || - current.accessToken !== expectedAccessToken || - current.refreshToken !== expectedRefreshToken || - workspaceIdOf(tokens.accessToken) !== workspaceId || - subjectOf(tokens.accessToken) !== subjectOf(current.accessToken) + !vault || + vault.grant.accessToken !== expectedAccessToken || + vault.grant.refreshToken !== expectedRefreshToken || + workspaceIdOf(grant.accessToken) !== workspaceIdOf(expectedAccessToken) || + subjectOf(grant.accessToken) !== subjectOf(expectedAccessToken) ) { return false } - vault.bundles[key] = tokens + vault.grant = grant persistVault(vault) return true } @@ -228,13 +287,24 @@ export function clearTokens(): void { } } +function activeToken(vault: TokenVault): string | null { + const active = vault.activeWorkspaceId + if (active === workspaceIdOf(vault.grant.accessToken)) return vault.grant.accessToken + return (active && vault.workspaceTokens[active]?.accessToken) || null +} + export function getAuthStatus(): AuthStatus { - const t = loadTokens() - if (!t) return { signedIn: false } - const status = statusFromAccessToken(t.accessToken) - const workspaceName = status.workspaceId - ? loadVault()?.workspaceNames?.[status.workspaceId] - : undefined + const vault = loadVault() + if (!vault) return { signedIn: false } + const token = activeToken(vault) + const status: AuthStatus = token + ? statusFromAccessToken(token) + : { + signedIn: true, + email: statusFromAccessToken(vault.grant.accessToken).email, + workspaceId: vault.activeWorkspaceId ?? undefined + } + const workspaceName = status.workspaceId ? vault.workspaceNames?.[status.workspaceId] : undefined return workspaceName ? { ...status, workspaceName } : status } diff --git a/src/main/cloud/types.ts b/src/main/cloud/types.ts index 6d18a0602..93cbe397d 100644 --- a/src/main/cloud/types.ts +++ b/src/main/cloud/types.ts @@ -26,6 +26,13 @@ export interface AuthStatus { role?: string } +export type WorkspaceSwitchFailure = 'unavailable' | 'retryable' + +/** The reply to a workspace switch: the resulting status, plus why it stayed put when it did. */ +export interface WorkspaceSwitchStatus extends AuthStatus { + workspaceSwitchFailure?: WorkspaceSwitchFailure +} + /** One workspace the signed-in user belongs to (GET /api/workspaces). */ export interface Workspace { id: string diff --git a/src/main/cloud/workspaces.ts b/src/main/cloud/workspaces.ts index 2235adf1b..c0257f1ab 100644 --- a/src/main/cloud/workspaces.ts +++ b/src/main/cloud/workspaces.ts @@ -2,9 +2,9 @@ * Workspace client: list the workspaces a signed-in user belongs to. * * `GET {apiBase}/workspaces` (the ingest service) returns the caller's - * workspaces. Switching the ACTIVE workspace is a re-auth, not a call here (a - * PKCE cloud token is scoped at consent time and cannot be silently re-scoped); - * `CloudSession.switchWorkspace` drives that. This module is read-only listing. + * workspaces. Switching the ACTIVE workspace mints that workspace's token from + * the OAuth grant, with no browser; `CloudSession.switchWorkspace` drives that. + * This module is read-only listing. */ import { CLOUD_CONFIG } from './config' import type { Workspace, WorkspaceMember } from './types' diff --git a/src/main/lib/embeddedSession.test.ts b/src/main/lib/embeddedSession.test.ts index 17333006a..45c3d0512 100644 --- a/src/main/lib/embeddedSession.test.ts +++ b/src/main/lib/embeddedSession.test.ts @@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const mocks = vi.hoisted(() => ({ enabled: true, - getAccessToken: vi.fn<() => Promise>(), + getGrantAccessToken: vi.fn<() => Promise>(), mint: vi.fn(), current: 'ws-1', entries: [] as unknown[] @@ -14,9 +14,10 @@ vi.mock('./embeddedSessionFlag', () => ({ })) vi.mock('../devplatform/session', () => ({ getCloudSession: () => ({ - getAccessToken: mocks.getAccessToken, + getGrantAccessToken: mocks.getGrantAccessToken, currentWorkspaceId: () => mocks.current, - currentSubject: () => (mocks.current ? 'user-1' : null) + currentSubject: () => (mocks.current ? 'user-1' : null), + currentAuthGeneration: () => 0 }) })) vi.mock('../cloud/workspaceToken', () => ({ @@ -79,7 +80,7 @@ function view(comfyUrl: string, options: ViewOptions = {}) { beforeEach(() => { mocks.enabled = true mocks.entries = [] - mocks.getAccessToken.mockReset().mockResolvedValue(ACCESS) + mocks.getGrantAccessToken.mockReset().mockResolvedValue(ACCESS) mocks.mint .mockReset() .mockResolvedValue({ kind: 'minted', token: MINTED, expiresAt: Date.now() + 900_000 }) @@ -115,7 +116,7 @@ describe('embeddedSession', () => { await expect(stateForSender(event)).resolves.toEqual({ status: 'disabled' }) await expect(workspaceTokenForSender(event, 'ws-1')).resolves.toBeNull() - expect(mocks.getAccessToken).not.toHaveBeenCalled() + expect(mocks.getGrantAccessToken).not.toHaveBeenCalled() }) it.each([ @@ -136,9 +137,7 @@ describe('embeddedSession', () => { it('switches a signed-in view to the workspace it names and returns the new state', async () => { const { event } = view('http://127.0.0.1:8000') const switchWorkspace = vi.fn(async () => { - mocks.getAccessToken.mockResolvedValue( - jwt({ sub: 'user-1', email: 'a@example.com', workspace_id: 'ws-2' }) - ) + mocks.current = 'ws-2' }) await expect(switchWorkspaceForSender(event, 'ws-2', switchWorkspace)).resolves.toEqual({ @@ -155,7 +154,6 @@ describe('embeddedSession', () => { const bystander = view('http://127.0.0.1:8001') const switchWorkspace = vi.fn(async () => { mocks.current = 'ws-2' - mocks.getAccessToken.mockResolvedValue(jwt({ sub: 'user-1', workspace_id: 'ws-2' })) }) await switchWorkspaceForSender(switcher.event, 'ws-2', switchWorkspace) @@ -170,7 +168,7 @@ describe('embeddedSession', () => { ['an empty workspace', 'http://127.0.0.1:8000', '', ACCESS, undefined], ['a non-string workspace', 'http://127.0.0.1:8000', 42, ACCESS, undefined] ])('does not switch for %s', async (_name, comfyUrl, workspaceId, token, expected) => { - mocks.getAccessToken.mockResolvedValue(token) + mocks.getGrantAccessToken.mockResolvedValue(token) const { event } = view(comfyUrl) const switchWorkspace = vi.fn(async () => undefined) @@ -208,11 +206,11 @@ describe('embeddedSession', () => { await expect(stateForSender(event)).resolves.toEqual({ status: 'disabled' }) await expect(workspaceTokenForSender(event, 'ws-1')).resolves.toBeNull() - expect(mocks.getAccessToken).not.toHaveBeenCalled() + expect(mocks.getGrantAccessToken).not.toHaveBeenCalled() }) it('asks a view to sign in again, and hands it nothing, while the grant predates the mint scope', async () => { - mocks.getAccessToken.mockResolvedValue( + mocks.getGrantAccessToken.mockResolvedValue( jwt({ sub: 'user-1', workspace_id: 'ws-1', scope: 'comfy-cloud:user:read' }) ) const { event } = view('http://127.0.0.1:8000') @@ -222,8 +220,20 @@ describe('embeddedSession', () => { expect(mocks.mint).not.toHaveBeenCalled() }) + it('reports the active workspace, not the workspace the grant is anchored on', async () => { + mocks.current = 'ws-2' + const { event } = view('http://127.0.0.1:8000') + + await expect(stateForSender(event)).resolves.toEqual({ + status: 'signed_in', + userId: 'user-1', + email: 'a@example.com', + workspaceId: 'ws-2' + }) + }) + it('reads signed_out when Desktop has no session', async () => { - mocks.getAccessToken.mockResolvedValue(null) + mocks.getGrantAccessToken.mockResolvedValue(null) const { event } = view('http://127.0.0.1:8000') await expect(stateForSender(event)).resolves.toEqual({ status: 'signed_out' }) @@ -256,13 +266,14 @@ describe('embeddedSession', () => { it('drops an older broadcast that finishes after a newer one', async () => { const local = view('http://127.0.0.1:8000') let finishOlder: (token: string | null) => void = () => {} - mocks.getAccessToken.mockReturnValueOnce( + mocks.getGrantAccessToken.mockReturnValueOnce( new Promise((resolve) => { finishOlder = resolve }) ) - const newer = jwt({ sub: 'user-1', workspace_id: 'ws-2' }) - mocks.getAccessToken.mockResolvedValueOnce(newer) + const newer = jwt({ sub: 'user-1', workspace_id: 'ws-1' }) + mocks.getGrantAccessToken.mockResolvedValueOnce(newer) + mocks.current = 'ws-2' const older = broadcastEmbeddedSessionChanged() await broadcastEmbeddedSessionChanged() diff --git a/src/main/lib/embeddedSession.ts b/src/main/lib/embeddedSession.ts index e55592d46..c45a13d29 100644 --- a/src/main/lib/embeddedSession.ts +++ b/src/main/lib/embeddedSession.ts @@ -4,7 +4,7 @@ * there and run partner nodes. * * Only a workspace token minted for the view's allowed workspace and the - * identity read from Desktop's access token cross to the renderer; the OAuth + * identity read from Desktop's grant cross to the renderer; the OAuth * grant stays in main. Only the main frame of a * registered comfyView, still on the loopback ComfyUI Desktop loaded into it, * is served. Remote and LAN servers never receive the token. @@ -74,9 +74,18 @@ export function isTrustedSender({ sender, senderFrame }: EmbeddedSessionSender): async function sessionState(): Promise { if (!(await isEmbeddedSessionEnabled())) return DISABLED - const token = await getCloudSession().getAccessToken() - const identity = token && canMintWorkspaceTokens(token) ? identityOf(token) : null - return identity ? { status: 'signed_in', ...identity } : { status: 'signed_out' } + const session = getCloudSession() + const grant = await session.getGrantAccessToken() + const identity = grant && canMintWorkspaceTokens(grant) ? identityOf(grant) : null + if (!identity) return { status: 'signed_out' } + const { userId, email } = identity + const workspaceId = session.currentWorkspaceId() + return { + status: 'signed_in', + userId, + ...(email ? { email } : {}), + ...(workspaceId ? { workspaceId } : {}) + } } export async function stateForSender( diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts index d71ba3b85..eefa3f63f 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts @@ -15,6 +15,8 @@ const mocks = vi.hoisted(() => ({ listWorkspaceMembers: vi.fn(), switchWorkspace: vi.fn(), setUnauthorizedHandler: vi.fn(), + setReturnedToAnchorHandler: vi.fn(), + currentSubject: vi.fn(() => 'user-1' as string | null), clearVersionCache: vi.fn(), getVersionCacheGeneration: vi.fn(() => 3), // client + policy @@ -72,6 +74,8 @@ vi.mock('../../devplatform/session', () => ({ getCloudSession: () => ({ login: mocks.login, currentAuthGeneration: mocks.currentAuthGeneration, + currentSubject: mocks.currentSubject, + setReturnedToAnchorHandler: mocks.setReturnedToAnchorHandler, logout: mocks.logout, status: mocks.status, isSignedIn: mocks.isSignedIn, @@ -499,6 +503,56 @@ describe('registerDevPlatformHandlers', () => { expect(win.webContents.send).toHaveBeenCalledWith('comfybuilder:authChanged', status) }) + it('forgets view allowlists when a switch signs in as a different account', async () => { + mocks.currentSubject.mockReturnValueOnce('user-1').mockReturnValueOnce('user-2') + mocks.switchWorkspace.mockResolvedValue({ signedIn: true, workspaceId: 'w9' }) + mocks.endViewGrants.mockClear() + mocks.allowDesktopWorkspace.mockClear() + + await handler('comfybuilder:switchWorkspace')({}, 'w2') + + expect(mocks.endViewGrants).toHaveBeenCalledOnce() + expect(mocks.allowDesktopWorkspace).toHaveBeenLastCalledWith('w9') + }) + + it('keeps view allowlists when a switch stays on the same account', async () => { + mocks.switchWorkspace.mockResolvedValue({ signedIn: true, workspaceId: 'w2' }) + mocks.endViewGrants.mockClear() + + await handler('comfybuilder:switchWorkspace')({}, 'w2') + + expect(mocks.endViewGrants).not.toHaveBeenCalled() + }) + + it('announces a token read returning to the anchor and lets views hold it', () => { + const win = { webContents: { isDestroyed: () => false, send: vi.fn() } } + mocks.getAllWindows.mockReturnValue([win]) + const status = { signedIn: true, workspaceId: 'w1', workspaceType: 'team' } + mocks.status.mockReturnValue(status) + const onReturned = mocks.setReturnedToAnchorHandler.mock.calls.at(-1)![0] as () => void + mocks.clearVersionCache.mockClear() + + onReturned() + + expect(mocks.allowDesktopWorkspace).toHaveBeenLastCalledWith('w1') + expect(mocks.clearVersionCache).toHaveBeenCalledOnce() + expect(win.webContents.send).toHaveBeenCalledExactlyOnceWith('comfybuilder:authChanged', status) + }) + + it('keeps a switch failure on the reply and off the broadcast', async () => { + const win = { webContents: { isDestroyed: () => false, send: vi.fn() } } + mocks.getAllWindows.mockReturnValue([win]) + const status = { signedIn: true, workspaceId: 'w1', workspaceType: 'team' } + mocks.switchWorkspace.mockResolvedValue({ ...status, workspaceSwitchFailure: 'unavailable' }) + + await expect(handler('comfybuilder:switchWorkspace')({}, 'w2')).resolves.toEqual({ + ...status, + workspaceSwitchFailure: 'unavailable' + }) + + expect(win.webContents.send).toHaveBeenCalledExactlyOnceWith('comfybuilder:authChanged', status) + }) + it('captures fresh state, creates a draft, and opens the validated Platform URL', async () => { const result = await handler('comfybuilder:promoteLocalInstance')({}, 'local-1') diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.ts b/src/main/lib/ipc/registerDevPlatformHandlers.ts index df3e877c4..5c02afb0a 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.ts @@ -34,7 +34,7 @@ import { } from '../../devplatform/builds' import type { BuildRow } from '../../devplatform/builds' import { clearVersionCache, getVersionCacheGeneration } from '../../devplatform/versionCache' -import type { AuthStatus, Workspace } from '../../cloud' +import type { AuthStatus, Workspace, WorkspaceSwitchStatus } from '../../cloud' import { installations, defaultInstallDir, @@ -134,17 +134,23 @@ export async function signInToCloud(): Promise { } /** - * Activate `workspaceId`'s credentials and announce the result. Cached - * credentials activate silently; first access or expired, unusable ones run - * browser auth because cloud tokens are scoped at consent time. Shared by the - * chooser and the hosted ComfyUI view. + * Activate `workspaceId` and announce the result; `CloudSession` decides whether a browser is + * needed. A failure stays on this reply and off the broadcast. Shared by the chooser and the + * hosted ComfyUI view. */ -export async function switchCloudWorkspace(workspaceId: string): Promise { +export async function switchCloudWorkspace(workspaceId: string): Promise { + const session = getCloudSession() + const subjectBefore = session.currentSubject() clearVersionCache() - const status = await getCloudSession().switchWorkspace(workspaceId) + const reply = await session.switchWorkspace(workspaceId) clearVersionCache() + const { workspaceSwitchFailure: _failure, ...status } = reply + if (session.currentSubject() !== subjectBefore) { + getViewWorkspaceGrants().endAll() + getViewWorkspaceGrants().allowDesktop(status.workspaceId) + } broadcastAuthChanged(status) - return status + return reply } /** @@ -215,6 +221,12 @@ export function registerDevPlatformHandlers(): void { clearVersionCache() broadcastAuthChanged(SIGNED_OUT) }) + session.setReturnedToAnchorHandler(() => { + const status = session.status() + getViewWorkspaceGrants().allowDesktop(status.workspaceId) + clearVersionCache() + broadcastAuthChanged(status) + }) // Build ids whose install-kickoff is mid-flight, so a double-click cannot // create two records for the same build. @@ -285,10 +297,7 @@ export function registerDevPlatformHandlers(): void { } if (!workspaceId) return { ok: false, message: 'No active workspace.' } if (status.workspaceId !== workspaceId) { - clearVersionCache() - const switched = await session.switchWorkspace(workspaceId) - clearVersionCache() - broadcastAuthChanged(switched) + const switched = await switchCloudWorkspace(workspaceId) if (!switched.signedIn || switched.workspaceId !== workspaceId) { return { ok: false, message: 'Could not activate the instance workspace.' } } diff --git a/src/main/lib/viewWorkspaceGrants.test.ts b/src/main/lib/viewWorkspaceGrants.test.ts index f86d7c752..ce2e19e3e 100644 --- a/src/main/lib/viewWorkspaceGrants.test.ts +++ b/src/main/lib/viewWorkspaceGrants.test.ts @@ -46,6 +46,7 @@ const viewB = { id: 'b' } as unknown as WebContents let current: string | null let user: string +let generation: number let mint: ReturnType< typeof vi.fn<(token: string, workspaceId: string) => Promise> > @@ -53,19 +54,28 @@ let grants: ViewWorkspaceGrants function signInAt(workspaceId: string | null): void { current = workspaceId + generation += 1 +} + +function grantSession( + getGrantAccessToken: () => Promise +): ConstructorParameters[0] { + return { + currentWorkspaceId: () => current, + currentSubject: () => (current ? user : null), + currentAuthGeneration: () => generation, + getGrantAccessToken + } } beforeEach(() => { vi.mocked(mainTelemetry.emit).mockClear() user = 'user-1' + generation = 0 signInAt('ws-1') mint = vi.fn(async (_token: string, workspaceId: string) => minted(workspaceId)) grants = new ViewWorkspaceGrants( - { - currentWorkspaceId: () => current, - currentSubject: () => (current ? user : null), - getAccessToken: async () => (current ? accessToken(current) : null) - }, + grantSession(async () => (current ? accessToken('ws-1') : null)), mint ) }) @@ -96,6 +106,14 @@ describe('ViewWorkspaceGrants', () => { expect(mint).toHaveBeenCalledWith(accessToken('ws-1'), 'ws-1') }) + it('mints a workspace other than the grant anchor from the grant token', async () => { + grants.allowView(viewA, 'ws-2') + signInAt('ws-2') + + await expect(grants.tokenFor(viewA, 'ws-2')).resolves.toBe('minted-ws-2') + expect(mint).toHaveBeenCalledExactlyOnceWith(accessToken('ws-1'), 'ws-2') + }) + it('reuses a minted token until it nears expiry', async () => { await grants.tokenFor(viewA, 'ws-1') await grants.tokenFor(viewB, 'ws-1') @@ -155,6 +173,52 @@ describe('ViewWorkspaceGrants', () => { await expect(pending).resolves.toBeNull() }) + it('T-V27: drops a mint reply for A that lands after A to B to A, and does not cache it', async () => { + grants.allowView(viewA, 'ws-2') + const stale = deferred() + mint.mockReturnValueOnce(stale.promise) + const pending = grants.tokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(mint).toHaveBeenCalledOnce()) + signInAt('ws-2') + signInAt('ws-1') + stale.resolve({ kind: 'minted', token: 'stale-ws-1', expiresAt: Date.now() + 15 * 60_000 }) + + await expect(pending).resolves.toBeNull() + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe('minted-ws-1') + expect(mint).toHaveBeenCalledTimes(2) + }) + + it('T-V27: a request after A to B to A does not join the mint from before the switch', async () => { + const stale = deferred() + mint.mockReturnValueOnce(stale.promise) + const older = grants.tokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(mint).toHaveBeenCalledOnce()) + signInAt('ws-2') + signInAt('ws-1') + + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe('minted-ws-1') + stale.resolve({ kind: 'minted', token: 'stale-ws-1', expiresAt: Date.now() + 15 * 60_000 }) + + await expect(older).resolves.toBeNull() + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe('minted-ws-1') + expect(mint).toHaveBeenCalledTimes(2) + }) + + it('drops a grant read that lands after A to B to A', async () => { + const slowRead = deferred() + grants = new ViewWorkspaceGrants( + grantSession(() => slowRead.promise), + mint + ) + const pending = grants.tokenFor(viewA, 'ws-1') + signInAt('ws-2') + signInAt('ws-1') + slowRead.resolve(accessToken('ws-1')) + + await expect(pending).resolves.toBeNull() + expect(mint).not.toHaveBeenCalled() + }) + it('drops a mint reply that lands after sign-out, and forgets its token', async () => { const reply = deferred() mint.mockReturnValueOnce(reply.promise) @@ -194,11 +258,7 @@ describe('ViewWorkspaceGrants', () => { it('hands out nothing, and does not ask Cloud, for a grant without the mint scope', async () => { grants = new ViewWorkspaceGrants( - { - currentWorkspaceId: () => 'ws-1', - currentSubject: () => user, - getAccessToken: async () => accessToken('ws-1', 'comfy-cloud:user:read') - }, + grantSession(async () => accessToken('ws-1', 'comfy-cloud:user:read')), mint ) @@ -219,12 +279,7 @@ describe('ViewWorkspaceGrants', () => { const before = deferred() let reads = 0 grants = new ViewWorkspaceGrants( - { - currentWorkspaceId: () => current, - currentSubject: () => (current ? user : null), - getAccessToken: () => - reads++ === 0 ? before.promise : Promise.resolve(accessToken('ws-1')) - }, + grantSession(() => (reads++ === 0 ? before.promise : Promise.resolve(accessToken('ws-1')))), mint ) const stale = grants.tokenFor(viewA, 'ws-1') @@ -258,11 +313,7 @@ describe('ViewWorkspaceGrants', () => { const slowRead = deferred() let reads = 0 grants = new ViewWorkspaceGrants( - { - currentWorkspaceId: () => current, - currentSubject: () => (current ? user : null), - getAccessToken: () => (reads++ === 0 ? Promise.resolve(firstUserToken) : slowRead.promise) - }, + grantSession(() => (reads++ === 0 ? Promise.resolve(firstUserToken) : slowRead.promise)), mint ) await grants.tokenFor(viewA, 'ws-1') diff --git a/src/main/lib/viewWorkspaceGrants.ts b/src/main/lib/viewWorkspaceGrants.ts index 3e1cb028c..253f28792 100644 --- a/src/main/lib/viewWorkspaceGrants.ts +++ b/src/main/lib/viewWorkspaceGrants.ts @@ -1,6 +1,6 @@ import type { WebContents } from 'electron' -import { canMintWorkspaceTokens, subjectOf, workspaceIdOf } from '../cloud/claims' +import { canMintWorkspaceTokens, subjectOf } from '../cloud/claims' import { mintWorkspaceToken } from '../cloud/workspaceToken' import type { WorkspaceTokenMint } from '../cloud/workspaceToken' import { getCloudSession } from '../devplatform/session' @@ -25,7 +25,8 @@ function reportMint(result: WorkspaceTokenMint): void { export interface GrantSession { currentWorkspaceId(): string | null currentSubject(): string | null - getAccessToken(): Promise + currentAuthGeneration(): number + getGrantAccessToken(): Promise } export type MintWorkspaceToken = ( @@ -37,6 +38,11 @@ function mintKey(subject: string, workspaceId: string): string { return JSON.stringify([subject, workspaceId]) } +interface MintFence { + epoch: number + generation: number +} + interface HeldToken { token: string subject: string @@ -86,12 +92,20 @@ export class ViewWorkspaceGrants { async tokenFor(view: WebContents, workspaceId: string): Promise { if (!this.mayHold(view, workspaceId)) return null - const epoch = this.epoch - const held = await this.workspaceToken(workspaceId, epoch) - if (!held || epoch !== this.epoch || !this.mayHold(view, workspaceId)) return null + const fence = this.currentFence() + const held = await this.workspaceToken(workspaceId, fence) + if (!held || !this.isCurrent(fence) || !this.mayHold(view, workspaceId)) return null return this.session.currentSubject() === held.subject ? held.token : null } + private currentFence(): MintFence { + return { epoch: this.epoch, generation: this.session.currentAuthGeneration() } + } + + private isCurrent(fence: MintFence): boolean { + return fence.epoch === this.epoch && fence.generation === this.session.currentAuthGeneration() + } + private seed(): void { if (this.seeded) return this.seeded = true @@ -107,11 +121,9 @@ export class ViewWorkspaceGrants { ) } - private async workspaceToken(workspaceId: string, epoch: number): Promise { - const accessToken = await this.session.getAccessToken() - if (epoch !== this.epoch) return null - if (!accessToken || workspaceIdOf(accessToken) !== workspaceId) return null - if (!canMintWorkspaceTokens(accessToken)) return null + private async workspaceToken(workspaceId: string, fence: MintFence): Promise { + const accessToken = await this.session.getGrantAccessToken() + if (!this.isCurrent(fence) || !accessToken || !canMintWorkspaceTokens(accessToken)) return null const subject = subjectOf(accessToken) if (!subject) return null const key = mintKey(subject, workspaceId) @@ -119,8 +131,8 @@ export class ViewWorkspaceGrants { if (cached && cached.expiresAt - MINT_REFRESH_SKEW_MS > Date.now()) return { token: cached.token, subject } - const result = await this.mintOnce(accessToken, key, workspaceId) - if (epoch !== this.epoch || this.session.currentSubject() !== subject) return null + const result = await this.mintOnce(accessToken, key, workspaceId, fence) + if (!this.isCurrent(fence) || this.session.currentSubject() !== subject) return null if (result.kind !== 'minted') return null this.minted.set(key, { token: result.token, expiresAt: result.expiresAt }) return { token: result.token, subject } @@ -129,9 +141,11 @@ export class ViewWorkspaceGrants { private mintOnce( accessToken: string, key: string, - workspaceId: string + workspaceId: string, + fence: MintFence ): Promise { - const inFlight = this.minting.get(key) + const flight = JSON.stringify([fence.generation, key]) + const inFlight = this.minting.get(flight) if (inFlight) return inFlight const minting = this.minting const pending = this.mint(accessToken, workspaceId) @@ -140,9 +154,9 @@ export class ViewWorkspaceGrants { return result }) .finally(() => { - if (minting.get(key) === pending) minting.delete(key) + if (minting.get(flight) === pending) minting.delete(flight) }) - minting.set(key, pending) + minting.set(flight, pending) return pending } } diff --git a/src/types/comfyDesktopBridge.ts b/src/types/comfyDesktopBridge.ts index 814dc904e..ff0f5724e 100644 --- a/src/types/comfyDesktopBridge.ts +++ b/src/types/comfyDesktopBridge.ts @@ -134,8 +134,8 @@ export interface ComfyDesktop2AuthBridge { /** Signs Desktop out of its account (every view follows) and resolves with * the resulting state; Desktop may keep the session if an install needs it. */ signOut(): Promise - /** Re-scopes Desktop's session to `workspaceId` (browser consent the first - * time) and resolves with the resulting state; every view follows. */ + /** Re-scopes Desktop's session to `workspaceId` (no browser unless the server + * requires a new sign-in) and resolves with the resulting state; every view follows. */ switchWorkspace(workspaceId: string): Promise /** Fires when Desktop signs in, signs out or switches workspace. */ onChanged(callback: (state: ComfyDesktop2AuthState) => void): () => void diff --git a/src/types/ipc.ts b/src/types/ipc.ts index ee188fc50..efdbbdcb2 100644 --- a/src/types/ipc.ts +++ b/src/types/ipc.ts @@ -8,8 +8,13 @@ export type { FirstUseMode } // Dev-platform (cloud auth + comfy-builder) renderer-safe types. Re-exported // from the cloud library so the renderer imports them from one place; tokens // are never part of these shapes. -import type { AuthStatus, Workspace } from '../main/cloud/types' -export type { AuthStatus, Workspace } +import type { + AuthStatus, + Workspace, + WorkspaceSwitchFailure, + WorkspaceSwitchStatus +} from '../main/cloud/types' +export type { AuthStatus, Workspace, WorkspaceSwitchFailure, WorkspaceSwitchStatus } // One Core beta activation card, as main resolves it for the title bar. Re-exported from its // producer rather than restated here: this file's header forbids duplicating types, and an @@ -1718,7 +1723,7 @@ export interface ElectronApi { getAuthStatus(): Promise onAuthChanged(callback: (status: AuthStatus) => void): Unsubscribe listWorkspaces(): Promise - switchWorkspace(workspaceId: string): Promise + switchWorkspace(workspaceId: string): Promise listBuilds(): Promise openBuildsPage(workspaceId: string): Promise installBuild(request: InstallBuildRequest): Promise From def5a4163e97c9f4add64cd7eaeccbf80bb82bbc Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 21:40:28 -0500 Subject: [PATCH 10/75] feat(auth): mirror workspace switch browser trips and anchor returns 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. --- src/shared/datadogMirroredEvents.test.ts | 6 ++++++ src/shared/datadogMirroredEvents.ts | 2 ++ 2 files changed, 8 insertions(+) diff --git a/src/shared/datadogMirroredEvents.test.ts b/src/shared/datadogMirroredEvents.test.ts index 59a1b4413..37d685ed0 100644 --- a/src/shared/datadogMirroredEvents.test.ts +++ b/src/shared/datadogMirroredEvents.test.ts @@ -23,6 +23,12 @@ describe('isDatadogMirroredEvent', () => { expect(isDatadogMirroredEvent('comfy.desktop.auth.view_token_minted')).toBe(false) }) + it('mirrors workspace_switch_browser but not workspace_switch', () => { + expect(isDatadogMirroredEvent('comfy.desktop.auth.workspace_switch_browser')).toBe(true) + expect(isDatadogMirroredEvent('comfy.desktop.auth.workspace_returned_to_anchor')).toBe(true) + expect(isDatadogMirroredEvent('comfy.desktop.auth.workspace_switch')).toBe(false) + }) + // The onboarding→install handoff (#1224) splits the same way: install.not_started // is the abort/failure signal ops alerts on; install.dispatched is the paired // funnel success gate (PostHog only). diff --git a/src/shared/datadogMirroredEvents.ts b/src/shared/datadogMirroredEvents.ts index dbbd45f19..d92a2d459 100644 --- a/src/shared/datadogMirroredEvents.ts +++ b/src/shared/datadogMirroredEvents.ts @@ -31,6 +31,8 @@ export const DATADOG_MIRRORED_EVENT_NAMES: ReadonlySet = new Set([ // Minting a view's workspace token failed. The grant stays in main, so a // refusal or outage here leaves the hosted view without a token. 'comfy.desktop.auth.view_token_mint_failed', + 'comfy.desktop.auth.workspace_switch_browser', + 'comfy.desktop.auth.workspace_returned_to_anchor', // ComfyUI execution failures — alert on execution error rate per release // and per gpu_tier. 'comfy.desktop.execution.error', From a2a9212d08cf9b1c8756ec032bbba465e7c805de Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 21:41:25 -0500 Subject: [PATCH 11/75] feat(auth): show a failed workspace switch in the instance-selection 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. --- locales/en.json | 2 + locales/zh.json | 2 + src/renderer/src/stores/authStore.test.ts | 50 +++++++++ src/renderer/src/stores/authStore.ts | 17 ++- .../src/stores/dashboardScopeStore.test.ts | 13 +++ src/renderer/src/views/ChooserView.test.ts | 103 ++++++++++++++++++ src/renderer/src/views/ChooserView.vue | 25 ++++- 7 files changed, 207 insertions(+), 5 deletions(-) diff --git a/locales/en.json b/locales/en.json index df0eef034..866a95684 100644 --- a/locales/en.json +++ b/locales/en.json @@ -1352,6 +1352,8 @@ "personalLabel": "Personal", "switchLabel": "Workspace", "currentFallback": "Current workspace", + "switchUnavailable": "This workspace is unavailable.", + "switchRetryable": "Couldn't switch workspace. Check your connection and try again.", "instanceCountLabel": "INSTANCES", "loadError": "Couldn't load workspaces. Retry", "refresh": "Refresh workspaces", diff --git a/locales/zh.json b/locales/zh.json index 44fb14a14..3feeecf0c 100644 --- a/locales/zh.json +++ b/locales/zh.json @@ -1352,6 +1352,8 @@ "personalLabel": "个人", "switchLabel": "工作区", "currentFallback": "当前工作区", + "switchUnavailable": "此工作区不可用。", + "switchRetryable": "无法切换工作区。请检查网络连接后重试。", "instanceCountLabel": "实例", "loadError": "无法加载工作区,请重试", "refresh": "刷新工作区", diff --git a/src/renderer/src/stores/authStore.test.ts b/src/renderer/src/stores/authStore.test.ts index 67b97ca03..e07013adb 100644 --- a/src/renderer/src/stores/authStore.test.ts +++ b/src/renderer/src/stores/authStore.test.ts @@ -192,6 +192,56 @@ describe('useAuthStore', () => { expect(store.loadingBuilds).toBe(false) }) + it('keeps a switch failure out of status until the next switch or status change', async () => { + api.getAuthStatus.mockResolvedValue({ signedIn: true, workspaceId: 'w1' }) + const store = useAuthStore() + await store.whenReady() + api.switchWorkspace.mockResolvedValueOnce({ + signedIn: true, + workspaceId: 'w1', + workspaceSwitchFailure: 'unavailable' + }) + + await store.switchWorkspace('w2') + + expect(store.workspaceSwitchFailure).toBe('unavailable') + expect(store.status).toEqual({ signedIn: true, workspaceId: 'w1' }) + + const nextSwitch = deferred<{ signedIn: boolean; workspaceId: string }>() + api.switchWorkspace.mockReturnValueOnce(nextSwitch.promise) + const switching = store.switchWorkspace('w3') + expect(store.workspaceSwitchFailure).toBeUndefined() + nextSwitch.resolve({ signedIn: true, workspaceId: 'w3' }) + await switching + + api.switchWorkspace.mockResolvedValueOnce({ + signedIn: true, + workspaceId: 'w3', + workspaceSwitchFailure: 'retryable' + }) + await store.switchWorkspace('w2') + expect(store.workspaceSwitchFailure).toBe('retryable') + + authChangedCb?.({ signedIn: true, workspaceId: 'w4' }) + expect(store.workspaceSwitchFailure).toBeUndefined() + }) + + it('does not let an older switch failure overwrite a newer switch', async () => { + api.getAuthStatus.mockResolvedValue({ signedIn: true, workspaceId: 'w1' }) + const store = useAuthStore() + await store.whenReady() + const older = deferred>() + api.switchWorkspace.mockReturnValueOnce(older.promise) + api.switchWorkspace.mockResolvedValueOnce({ signedIn: true, workspaceId: 'w3' }) + + const first = store.switchWorkspace('w2') + await store.switchWorkspace('w3') + older.resolve({ signedIn: true, workspaceId: 'w3', workspaceSwitchFailure: 'retryable' }) + await first + + expect(store.workspaceSwitchFailure).toBeUndefined() + }) + it('switchWorkspace adopts the new status and drops the stale build cache', async () => { api.signIn.mockResolvedValue({ signedIn: true, workspaceId: 'w1' }) const store = useAuthStore() diff --git a/src/renderer/src/stores/authStore.ts b/src/renderer/src/stores/authStore.ts index 4b78f093f..17dc1902d 100644 --- a/src/renderer/src/stores/authStore.ts +++ b/src/renderer/src/stores/authStore.ts @@ -1,7 +1,7 @@ import { computed, onScopeDispose, ref } from 'vue' import { defineStore } from 'pinia' -import type { AuthStatus, ElectronApi, Workspace } from '../../../types/ipc' +import type { AuthStatus, ElectronApi, Workspace, WorkspaceSwitchFailure } from '../../../types/ipc' import { isPersonalWorkspace, PERSONAL_WORKSPACE_ID } from '../../../shared/workspaces' import type { Build } from '../devplatform/types' @@ -33,6 +33,8 @@ export const useAuthStore = defineStore('auth', () => { // workspace (both otherwise leave the arrays empty). const workspacesError = ref(false) const buildsError = ref(false) + const workspaceSwitchFailure = ref() + let latestSwitch = 0 const comfybuilderApi = (window as Window & { api: ElectronApi }).api.comfybuilder /** Bumped on every authoritative status change (push, sign-in, switch, @@ -63,6 +65,7 @@ export const useAuthStore = defineStore('auth', () => { loadingBuilds.value = false workspacesError.value = false buildsError.value = false + workspaceSwitchFailure.value = undefined } /** The session identity the scoped caches are keyed on. */ @@ -159,11 +162,16 @@ export const useAuthStore = defineStore('auth', () => { } } - /** Activate the workspace for remote operations. Main uses cached credentials - * when available and opens browser auth only when authorization is needed. */ + /** Activate the workspace for remote operations. Main mints its token with no + * browser unless the server requires a new sign-in, and stays on the current + * workspace when it cannot; `workspaceSwitchFailure` then says why. */ async function switchWorkspace(workspaceId: string): Promise { - const next = await comfybuilderApi.switchWorkspace(workspaceId) + const thisSwitch = ++latestSwitch + workspaceSwitchFailure.value = undefined + const { workspaceSwitchFailure: failure, ...next } = + await comfybuilderApi.switchWorkspace(workspaceId) applyAuthoritativeStatus(next) + if (thisSwitch === latestSwitch) workspaceSwitchFailure.value = failure return next } @@ -220,6 +228,7 @@ export const useAuthStore = defineStore('auth', () => { buildsLoaded, workspacesError, buildsError, + workspaceSwitchFailure, isSignedIn, personalWorkspace, initializeWorkspaceContext, diff --git a/src/renderer/src/stores/dashboardScopeStore.test.ts b/src/renderer/src/stores/dashboardScopeStore.test.ts index f3c875804..b736f9af6 100644 --- a/src/renderer/src/stores/dashboardScopeStore.test.ts +++ b/src/renderer/src/stores/dashboardScopeStore.test.ts @@ -189,6 +189,19 @@ describe('useDashboardScopeStore', () => { expect(scope.selectedWorkspaceId).toBe('w3') }) + it('follows a return to a personal anchor', async () => { + const scope = useDashboardScopeStore() + await scope.initialize() + authChanged({ ...signedIn, workspaceId: 'w2' }) + await flushPromises() + expect(scope.selectedWorkspaceId).toBe('w2') + + authChanged({ signedIn: true, workspaceId: 'p1', workspaceType: 'personal' }) + await flushPromises() + + expect(scope.selectedWorkspaceId).toBe('personal') + }) + it('follows authenticated switches only while viewing the old active scope', async () => { const scope = useDashboardScopeStore() await scope.initialize() diff --git a/src/renderer/src/views/ChooserView.test.ts b/src/renderer/src/views/ChooserView.test.ts index 55bdb23e5..d9b01b60c 100644 --- a/src/renderer/src/views/ChooserView.test.ts +++ b/src/renderer/src/views/ChooserView.test.ts @@ -75,6 +75,8 @@ const messages = { currentFallback: 'Current workspace', instanceCountLabel: 'INSTANCES', loadError: "Couldn't load workspaces. Retry", + switchUnavailable: 'This workspace is unavailable.', + switchRetryable: "Couldn't switch workspace. Try again.", refresh: 'Refresh workspaces', promoteToWorkspace: 'Create Build', promoteToWorkspaceHint: 'Create a Build from this instance in Comfy Developer Platform.', @@ -867,6 +869,107 @@ describe('ChooserView', () => { expect(api.comfybuilder.listBuilds).toHaveBeenCalledOnce() }) + it.each([ + ['unavailable', 'This workspace is unavailable.'], + ['retryable', "Couldn't switch workspace. Try again."] + ])( + 'shows a %s switch failure inline, opens no modal, and fetches no Builds for the wrong workspace', + async (failure, message) => { + const api = installMockApiSignedIn([], [], { id: 'w1', name: 'Workspace A' }) + api.comfybuilder.listWorkspaces.mockResolvedValue([ + { id: 'w1', name: 'Workspace A', type: 'team', role: 'admin' }, + { id: 'w2', name: 'Workspace B', type: 'team', role: 'admin' } + ]) + api.comfybuilder.switchWorkspace.mockResolvedValue({ + signedIn: true, + workspaceType: 'team', + workspaceId: 'w1', + workspaceSwitchFailure: failure + }) + const wrapper = mountChooser() + await flushPromises() + api.comfybuilder.listBuilds.mockClear() + expect(wrapper.find('[data-testid="chooser-workspace-switch-failure"]').exists()).toBe(false) + + await wrapper.get('[data-testid="devplatform-workspace-selector"]').trigger('click') + await wrapper.get('[data-testid="devplatform-workspace-w2"]').trigger('click') + await flushPromises() + + expect(wrapper.get('[data-testid="chooser-workspace-switch-failure"]').text()).toBe(message) + expect(mockModal.alert).not.toHaveBeenCalled() + expect(api.comfybuilder.listBuilds).not.toHaveBeenCalled() + } + ) + + it('follows main back to the anchor: selection and status converge with no new switch', async () => { + const api = installMockApiSignedIn([], [], { id: 'w1', name: 'Workspace A' }) + api.comfybuilder.listWorkspaces.mockResolvedValue([ + { id: 'w1', name: 'Workspace A', type: 'team', role: 'admin' }, + { id: 'w2', name: 'Workspace B', type: 'team', role: 'admin' } + ]) + api.comfybuilder.switchWorkspace.mockImplementation(async (workspaceId: string) => ({ + signedIn: true, + workspaceType: 'team', + workspaceId + })) + let authChanged: (status: unknown) => void = () => {} + api.comfybuilder.onAuthChanged.mockImplementation(((callback: (status: unknown) => void) => { + authChanged = callback + return () => {} + }) as never) + const wrapper = mountChooser() + await flushPromises() + await wrapper.get('[data-testid="devplatform-workspace-selector"]').trigger('click') + await wrapper.get('[data-testid="devplatform-workspace-w2"]').trigger('click') + await flushPromises() + expect(wrapper.get('[data-testid="devplatform-workspace-selector"]').text()).toContain( + 'Workspace B' + ) + api.comfybuilder.switchWorkspace.mockClear() + api.comfybuilder.listBuilds.mockClear() + + authChanged({ signedIn: true, workspaceType: 'team', workspaceId: 'w1' }) + await flushPromises() + + expect(wrapper.get('[data-testid="devplatform-workspace-selector"]').text()).toContain( + 'Workspace A' + ) + expect(useDashboardScopeStore().selectedWorkspaceId).toBe('w1') + expect(api.comfybuilder.switchWorkspace).not.toHaveBeenCalled() + expect(api.comfybuilder.listBuilds).toHaveBeenCalledOnce() + }) + + it('retries a failed switch from the refresh button and clears the failure', async () => { + const api = installMockApiSignedIn([], [], { id: 'w1', name: 'Workspace A' }) + api.comfybuilder.listWorkspaces.mockResolvedValue([ + { id: 'w1', name: 'Workspace A', type: 'team', role: 'admin' }, + { id: 'w2', name: 'Workspace B', type: 'team', role: 'admin' } + ]) + api.comfybuilder.switchWorkspace.mockResolvedValueOnce({ + signedIn: true, + workspaceType: 'team', + workspaceId: 'w1', + workspaceSwitchFailure: 'retryable' + }) + const wrapper = mountChooser() + await flushPromises() + await wrapper.get('[data-testid="devplatform-workspace-selector"]').trigger('click') + await wrapper.get('[data-testid="devplatform-workspace-w2"]').trigger('click') + await flushPromises() + api.comfybuilder.switchWorkspace.mockResolvedValueOnce({ + signedIn: true, + workspaceType: 'team', + workspaceId: 'w2' + }) + + await wrapper.find('[data-testid="chooser-workspace-refresh"]').trigger('click') + await flushPromises() + + expect(api.comfybuilder.switchWorkspace).toHaveBeenCalledTimes(2) + expect(api.comfybuilder.switchWorkspace).toHaveBeenLastCalledWith('w2') + expect(wrapper.find('[data-testid="chooser-workspace-switch-failure"]').exists()).toBe(false) + }) + it('refreshes workspace membership and Builds', async () => { const api = installMockApiSignedIn([], [], { id: 'w1', name: 'Comfy Design Team' }) const wrapper = mountChooser() diff --git a/src/renderer/src/views/ChooserView.vue b/src/renderer/src/views/ChooserView.vue index c2f920071..f069a8e67 100644 --- a/src/renderer/src/views/ChooserView.vue +++ b/src/renderer/src/views/ChooserView.vue @@ -127,7 +127,8 @@ watch( } if ( generation !== buildPrefetchGeneration || - selectedManagedWorkspaceId.value !== workspaceId + selectedManagedWorkspaceId.value !== workspaceId || + authStore.status.workspaceId !== workspaceId ) return await authStore.fetchBuilds() @@ -161,6 +162,10 @@ const refreshingWorkspace = computed(() => authStore.loadingWorkspaces || authSt async function refreshWorkspace(): Promise { emitTelemetryAction('comfy.desktop.workspace.refresh', {}) + const selected = selectedManagedWorkspaceId.value + if (selected && authStore.status.workspaceId !== selected) { + await authStore.switchWorkspace(selected).catch(() => {}) + } await Promise.all([authStore.fetchWorkspaces(), authStore.fetchBuilds()]) } @@ -341,6 +346,19 @@ const gridHandlers = { {{ scopedInstallCount }} +
+

+ {{ + authStore.workspaceSwitchFailure === 'unavailable' + ? t('devPlatform.workspace.switchUnavailable') + : t('devPlatform.workspace.switchRetryable') + }} +

+
Date: Sun, 8 Nov 2026 22:19:15 -0500 Subject: [PATCH 12/75] fix(auth): treat only invalid_grant and invalid_client as an ended grant 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. --- src/main/cloud/oauth.test.ts | 16 ++++++ src/main/cloud/oauth.ts | 13 ++++- src/main/cloud/session.test.ts | 71 +++++++++++++++++++++++---- src/main/cloud/session.ts | 40 +++++++++------ src/main/cloud/signInFailure.ts | 5 +- src/main/cloud/workspaceToken.test.ts | 2 +- src/main/cloud/workspaceToken.ts | 10 +++- 7 files changed, 127 insertions(+), 30 deletions(-) diff --git a/src/main/cloud/oauth.test.ts b/src/main/cloud/oauth.test.ts index 9cd8225a7..557b0a97b 100644 --- a/src/main/cloud/oauth.test.ts +++ b/src/main/cloud/oauth.test.ts @@ -59,6 +59,22 @@ describe('oauth.refresh', () => { expect((await refresh('old', { tokenUrl: 'https://c/oauth/token' })).refreshToken).toBe('new') }) + it.each<[string, number, unknown, string | undefined]>([ + ['invalid_grant', 400, { error: 'invalid_grant', error_description: 'x' }, 'invalid_grant'], + ['invalid_client', 400, { error: 'invalid_client' }, 'invalid_client'], + ['a body with no error', 400, { message: 'nope' }, undefined], + ['a non-string error', 400, { error: 7 }, undefined], + ['a non-object body', 401, 'nope', undefined] + ])('keeps the OAuth error code from %s', async (_name, status, body, oauthError) => { + stub(status, body) + + await expect(refresh('r', { tokenUrl: 'https://c/oauth/token' })).rejects.toMatchObject({ + name: 'SignInFailure', + httpStatus: status, + oauthError + }) + }) + it('rejects a response missing access_token', async () => { stub(200, { expires_in: 3600 }) await expect(refresh('r', { tokenUrl: 'https://c/oauth/token' })).rejects.toThrow( diff --git a/src/main/cloud/oauth.ts b/src/main/cloud/oauth.ts index 967c3abb9..460e7acbd 100644 --- a/src/main/cloud/oauth.ts +++ b/src/main/cloud/oauth.ts @@ -63,6 +63,17 @@ function toTokens(r: TokenResponse, fallbackRefresh?: string): AuthTokens { } } +function oauthErrorOf(body: string): string | undefined { + try { + const parsed: unknown = JSON.parse(body) + const error = + parsed && typeof parsed === 'object' ? (parsed as { error?: unknown }).error : null + return typeof error === 'string' ? error : undefined + } catch { + return undefined + } +} + async function requestToken(tokenUrl: string, body: URLSearchParams): Promise { const controller = new AbortController() // Keep the abort armed until the body is fully read, so a slow/unbounded body @@ -86,7 +97,7 @@ async function requestToken(tokenUrl: string, body: URLSearchParams): Promise { diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index 1f7f1858f..bf0ede210 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -149,6 +149,10 @@ function killMintSwitch(): void { mocked(isWorkspaceMintSwitchEnabled).mockResolvedValue(false) } +function refreshRefused(oauthError = 'invalid_grant', httpStatus = 400): SignInFailure { + return new SignInFailure('refresh refused', 'server_error', { httpStatus, oauthError }) +} + function refreshFailure(kind: 'network' | 'timeout' | 'http', httpStatus?: number): SignInFailure { if (kind === 'http') { return new SignInFailure('refresh failed', 'server_error', { httpStatus }) @@ -269,7 +273,7 @@ describe('CloudSession access tokens', () => { it('returns the stale grant token after a definitive refusal so the 401 ends the session', async () => { const stale = grantOn('w1', { expiresAt: PAST }) saveGrant(stale) - mocked(refresh).mockRejectedValue(refreshFailure('http', 400)) + mocked(refresh).mockRejectedValue(refreshRefused()) await expect(new CloudSession().getAccessToken()).resolves.toBe(stale.accessToken) }) @@ -352,7 +356,7 @@ describe('CloudSession background token reads never open the browser', () => { const onReturned = vi.fn() session.setReturnedToAnchorHandler(onReturned) mintReply = () => json(401, { code: 'oauth_grant_ended' }) - mocked(refresh).mockRejectedValue(refreshFailure('http', 400)) + mocked(refresh).mockRejectedValue(refreshRefused()) await expect(session.getAccessToken()).resolves.toBeNull() @@ -364,6 +368,19 @@ describe('CloudSession background token reads never open the browser', () => { expect(onSignedOut).toHaveBeenCalledOnce() }) + it('a plain second 401 on a token read stays on B', async () => { + const session = await activeOnMintedToken() + const onReturned = vi.fn() + session.setReturnedToAnchorHandler(onReturned) + mintReply = () => json(401, {}) + mocked(refresh).mockResolvedValue(grantOn('w1', { revision: '-fresh' })) + + await expect(session.getAccessToken()).resolves.toBeNull() + + expect(onReturned).not.toHaveBeenCalled() + expect(session.currentWorkspaceId()).toBe('w2') + }) + it.each<[string, () => Response]>([ ['a rate limit', () => json(429, {})], ['an outage', () => json(500, {})], @@ -707,7 +724,7 @@ describe('CloudSession.switchWorkspace reauthorize', () => { replies++ === 0 ? json(401, { message: 'workspace membership not found' }) : minted(workspaceId) - mocked(refresh).mockRejectedValue(refreshFailure('http', 401)) + mocked(refresh).mockRejectedValue(refreshRefused('invalid_client')) mocked(signIn).mockResolvedValue(signedInResult(grantOn('w3'))) const session = new CloudSession() @@ -734,7 +751,7 @@ describe('CloudSession.switchWorkspace reauthorize', () => { expect(signIn).not.toHaveBeenCalled() }) - it('a second 401 after a good refresh is reauthorize', async () => { + it('a second oauth_grant_ended 401 after a good refresh is reauthorize', async () => { saveGrant(grantOn('w1')) mintReply = () => json(401, { code: 'oauth_grant_ended' }) mocked(refresh).mockResolvedValue(grantOn('w1', { revision: '-fresh' })) @@ -753,7 +770,11 @@ describe('CloudSession.switchWorkspace reauthorize', () => { ['timeout', refreshFailure('timeout')], ['HTTP 500', refreshFailure('http', 500)], ['HTTP 503', refreshFailure('http', 503)], - ['HTTP 429', refreshFailure('http', 429)] + ['HTTP 429', refreshFailure('http', 429)], + ['plain HTTP 400', refreshFailure('http', 400)], + ['plain HTTP 401', refreshFailure('http', 401)], + ['HTTP 400 with another OAuth error', refreshRefused('invalid_request')], + ['HTTP 500 carrying invalid_grant', refreshRefused('invalid_grant', 500)] ])('a %s refresh failure after a 401 reports retryable with no browser', async (_name, error) => { saveGrant(grantOn('w1')) mintReply = () => json(401, {}) @@ -786,11 +807,11 @@ describe('CloudSession.switchWorkspace reauthorize', () => { } ) - it.each<[number]>([[400], [401]])( - 'an HTTP %i refresh refusal on an expired grant opens one browser', - async (httpStatus) => { + it.each<[string]>([['invalid_grant'], ['invalid_client']])( + 'a %s refresh refusal on an expired grant opens one browser', + async (oauthError) => { saveGrant(grantOn('w1', { expiresAt: PAST })) - mocked(refresh).mockRejectedValue(refreshFailure('http', httpStatus)) + mocked(refresh).mockRejectedValue(refreshRefused(oauthError)) mocked(signIn).mockResolvedValue(signedInResult(grantOn('w2'))) await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ @@ -801,9 +822,39 @@ describe('CloudSession.switchWorkspace reauthorize', () => { } ) + it('a plain second 401 after a good refresh reports retryable with no browser', async () => { + saveGrant(grantOn('w1')) + mintReply = () => json(401, { message: 'workspace membership not found' }) + mocked(refresh).mockResolvedValue(grantOn('w1', { revision: '-fresh' })) + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w1', + workspaceSwitchFailure: 'retryable' + }) + + expect(mintRequests).toHaveLength(2) + expect(refresh).toHaveBeenCalledOnce() + expect(signIn).not.toHaveBeenCalled() + }) + + it('a first oauth_grant_ended 401 still refreshes once before deciding', async () => { + saveGrant(grantOn('w1')) + let replies = 0 + mintReply = ({ workspaceId }) => + replies++ === 0 ? json(401, { code: 'oauth_grant_ended' }) : minted(workspaceId) + mocked(refresh).mockResolvedValue(grantOn('w1', { revision: '-fresh' })) + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w2' + }) + + expect(refresh).toHaveBeenCalledOnce() + expect(signIn).not.toHaveBeenCalled() + }) + it('switching to the anchor with a refused refresh opens one browser', async () => { saveGrant(grantOn('w1', { expiresAt: PAST })) - mocked(refresh).mockRejectedValue(refreshFailure('http', 400)) + mocked(refresh).mockRejectedValue(refreshRefused()) mocked(signIn).mockResolvedValue(signedInResult(grantOn('w1', { revision: '-new' }))) await expect(new CloudSession().switchWorkspace('w1')).resolves.toMatchObject({ diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index e8d231a93..cf2099748 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -60,21 +60,26 @@ type BrowserReason = ReauthorizeReason | 'scope_not_granted' type GrantRefresh = 'refreshed' | 'ended' | 'unavailable' -const RETRYABLE: WorkspaceMintOutcome = { kind: 'retryable' } +type SettledMintOutcome = Exclude + +const RETRYABLE: SettledMintOutcome = { kind: 'retryable' } + +const ENDED_GRANT_OAUTH_ERRORS: ReadonlySet = new Set(['invalid_grant', 'invalid_client']) function isFresh(tokens: AuthTokens): boolean { return tokens.expiresAt - REFRESH_SKEW_MS > Date.now() } -function isGrantRejected(outcome: WorkspaceMintOutcome): boolean { - return outcome.kind === 'reauthorize' && outcome.reason === 'grant_ended' -} - function isDefinitiveRefreshRefusal(error: unknown): boolean { - return error instanceof SignInFailure && (error.httpStatus === 400 || error.httpStatus === 401) + return ( + error instanceof SignInFailure && + (error.httpStatus === 400 || error.httpStatus === 401) && + error.oauthError !== undefined && + ENDED_GRANT_OAUTH_ERRORS.has(error.oauthError) + ) } -function refreshFailureOutcome(refreshed: GrantRefresh): WorkspaceMintOutcome { +function refreshFailureOutcome(refreshed: GrantRefresh): SettledMintOutcome { return refreshed === 'ended' ? { kind: 'reauthorize', reason: 'grant_ended' } : RETRYABLE } @@ -92,7 +97,7 @@ function reportBrowser(outcome: WorkspaceSwitchOutcome, reason: BrowserReason): export class CloudSession { private readonly refreshing = new Map>() - private readonly minting = new Map>() + private readonly minting = new Map>() private switching: { workspaceId: string; result: Promise } | null = null private mintBlockedUntil = 0 private loginInFlight: Promise | null = null @@ -215,7 +220,7 @@ export class CloudSession { private returnToAnchor( workspaceId: string, - outcome: Exclude + outcome: Exclude ): void { const grant = loadGrant() const anchor = grant && workspaceIdOf(grant.accessToken) @@ -248,7 +253,7 @@ export class CloudSession { } } - private mintForWorkspace(workspaceId: string, generation: number): Promise { + private mintForWorkspace(workspaceId: string, generation: number): Promise { const key = JSON.stringify([generation, workspaceId]) const inFlight = this.minting.get(key) if (inFlight) return inFlight @@ -264,8 +269,8 @@ export class CloudSession { private storeMinted( workspaceId: string, generation: number, - outcome: WorkspaceMintOutcome - ): WorkspaceMintOutcome { + outcome: SettledMintOutcome + ): SettledMintOutcome { if (outcome.kind !== 'minted' || generation !== this.authGeneration) return outcome const grant = loadGrant() if ( @@ -282,7 +287,7 @@ export class CloudSession { private async mintWithGrant( workspaceId: string, generation: number - ): Promise { + ): Promise { if (!(await isWorkspaceMintSwitchEnabled())) { return { kind: 'reauthorize', reason: 'mint_disabled' } } @@ -295,12 +300,17 @@ export class CloudSession { if (refreshed !== 'refreshed') return refreshFailureOutcome(refreshed) } const first = await this.postMint(workspaceId, generation) - if (!isGrantRejected(first)) return first + if ( + first.kind !== 'unauthorized' && + !(first.kind === 'reauthorize' && first.reason === 'grant_ended') + ) + return first const current = loadGrant() if (!current) return RETRYABLE const refreshed = await this.refreshGrant(current) if (refreshed !== 'refreshed') return refreshFailureOutcome(refreshed) - return this.postMint(workspaceId, generation) + const second = await this.postMint(workspaceId, generation) + return second.kind === 'unauthorized' ? RETRYABLE : second } private async postMint(workspaceId: string, generation: number): Promise { diff --git a/src/main/cloud/signInFailure.ts b/src/main/cloud/signInFailure.ts index 1d50da981..e386b71c8 100644 --- a/src/main/cloud/signInFailure.ts +++ b/src/main/cloud/signInFailure.ts @@ -11,15 +11,18 @@ export class SignInFailure extends Error { override readonly name = 'SignInFailure' readonly reason: SignInFailureReason readonly httpStatus: number | undefined + /** The token endpoint's RFC 6749 `error` code, for decisions only: never report it. */ + readonly oauthError: string | undefined constructor( message: string, reason: SignInFailureReason, - options: { httpStatus?: number; cause?: unknown } = {} + options: { httpStatus?: number; oauthError?: string; cause?: unknown } = {} ) { super(message, { cause: options.cause }) this.reason = reason this.httpStatus = options.httpStatus + this.oauthError = options.oauthError } } diff --git a/src/main/cloud/workspaceToken.test.ts b/src/main/cloud/workspaceToken.test.ts index ebf82a3bb..bf674a18b 100644 --- a/src/main/cloud/workspaceToken.test.ts +++ b/src/main/cloud/workspaceToken.test.ts @@ -137,7 +137,7 @@ describe('classifyMint', () => { failed(401, 'oauth_grant_ended'), { kind: 'reauthorize', reason: 'grant_ended' } ], - ['plain 401', failed(401), { kind: 'reauthorize', reason: 'grant_ended' }], + ['plain 401', failed(401), { kind: 'unauthorized' }], [ '503 oauth_workspace_mint_disabled', failed(503, 'oauth_workspace_mint_disabled'), diff --git a/src/main/cloud/workspaceToken.ts b/src/main/cloud/workspaceToken.ts index 604f7b900..66f510d44 100644 --- a/src/main/cloud/workspaceToken.ts +++ b/src/main/cloud/workspaceToken.ts @@ -15,11 +15,13 @@ export type ReauthorizeReason = | 'mint_disabled' const MINT_DISABLED_CODE = 'oauth_workspace_mint_disabled' +const GRANT_ENDED_CODE = 'oauth_grant_ended' -/** What a mint reply means for the caller. `grant_ended` is every 401, including an expired access token. */ +/** What a mint reply means for the caller. `unauthorized` is a 401 that does not say the grant ended. */ export type WorkspaceMintOutcome = | { kind: 'minted'; token: string; expiresAt: number } | { kind: 'unavailable' } + | { kind: 'unauthorized' } | { kind: 'reauthorize'; reason: ReauthorizeReason } | { kind: 'refused' } | { kind: 'retryable'; retryAfterSeconds?: number } @@ -35,7 +37,11 @@ export function classifyMint(mint: WorkspaceTokenMint): WorkspaceMintOutcome { ? { kind: 'retryable' } : { kind: 'retryable', retryAfterSeconds } } - if (status === 401) return { kind: 'reauthorize', reason: 'grant_ended' } + if (status === 401) { + return code === GRANT_ENDED_CODE + ? { kind: 'reauthorize', reason: 'grant_ended' } + : { kind: 'unauthorized' } + } if (status === 404) return { kind: 'unavailable' } if (status === 403 && code === 'sso_required') return { kind: 'reauthorize', reason: 'sso_required' } From 2994475dd722089ca03203c1948e41d36bc82a92 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 22:20:18 -0500 Subject: [PATCH 13/75] fix(auth): report a switch to an expired anchor as retryable during a 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. --- src/main/cloud/session.test.ts | 39 +++++++++++++++++++++++++++++++--- src/main/cloud/session.ts | 14 ++++++++++-- 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index bf0ede210..67e304a54 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -864,14 +864,47 @@ describe('CloudSession.switchWorkspace reauthorize', () => { expect(signIn).toHaveBeenCalledExactlyOnceWith({ workspaceId: 'w1' }) }) - it('switching to the anchor during a refresh outage activates with no browser', async () => { + it('switching to an expired anchor during a refresh outage stays put and reports retryable', async () => { saveGrant(grantOn('w1', { expiresAt: PAST })) + mocked(refresh).mockResolvedValueOnce(grantOn('w1', { expiresAt: PAST, revision: '-2' })) + const session = new CloudSession() + await session.switchWorkspace('w2') mocked(refresh).mockRejectedValue(refreshFailure('network')) - await expect(new CloudSession().switchWorkspace('w1')).resolves.toMatchObject({ - workspaceId: 'w1' + await expect(session.switchWorkspace('w1')).resolves.toMatchObject({ + workspaceId: 'w2', + workspaceSwitchFailure: 'retryable' + }) + + expect(session.currentWorkspaceId()).toBe('w2') + expect(signIn).not.toHaveBeenCalled() + expect(switchEvents().at(-1)).toEqual({ outcome: 'retryable' }) + }) + + it('switching to a still valid anchor during a refresh outage works and its token is usable', async () => { + const grant = grantOn('w1', { expiresAt: Date.now() + 30_000 }) + saveGrant(grant) + mocked(refresh).mockRejectedValue(refreshFailure('network')) + const session = new CloudSession() + + const reply = await session.switchWorkspace('w1') + + expect(reply).toMatchObject({ workspaceId: 'w1' }) + expect(reply).not.toHaveProperty('workspaceSwitchFailure') + await expect(session.getAccessToken()).resolves.toBe(grant.accessToken) + expect(signIn).not.toHaveBeenCalled() + }) + + it('a still valid grant keeps minting during a refresh outage', async () => { + const grant = grantOn('w1', { expiresAt: Date.now() + 30_000 }) + saveGrant(grant) + mocked(refresh).mockRejectedValue(refreshFailure('network')) + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w2' }) + expect(mintRequests).toEqual([{ workspaceId: 'w2', bearer: grant.accessToken }]) expect(signIn).not.toHaveBeenCalled() }) diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index cf2099748..c4bf031ba 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -70,6 +70,10 @@ function isFresh(tokens: AuthTokens): boolean { return tokens.expiresAt - REFRESH_SKEW_MS > Date.now() } +function isExpired(tokens: AuthTokens): boolean { + return tokens.expiresAt <= Date.now() +} + function isDefinitiveRefreshRefusal(error: unknown): boolean { return ( error instanceof SignInFailure && @@ -204,7 +208,8 @@ export class CloudSession { if (!workspaceId || workspaceId === workspaceIdOf(grant.accessToken)) { if (isFresh(grant) || !grant.refreshToken) return grant.accessToken const refreshed = await this.refreshGrant(grant) - if (refreshed === 'unavailable' || generation !== this.authGeneration) return null + if (generation !== this.authGeneration) return null + if (refreshed === 'unavailable' && isExpired(grant)) return null return loadGrant()?.accessToken ?? null } const held = loadWorkspaceToken(workspaceId) @@ -297,7 +302,8 @@ export class CloudSession { return { kind: 'reauthorize', reason: 'mint_scope_missing' } if (!isFresh(grant)) { const refreshed = await this.refreshGrant(grant) - if (refreshed !== 'refreshed') return refreshFailureOutcome(refreshed) + if (refreshed === 'ended' || (refreshed === 'unavailable' && isExpired(grant))) + return refreshFailureOutcome(refreshed) } const first = await this.postMint(workspaceId, generation) if ( @@ -389,6 +395,10 @@ export class CloudSession { const refreshed = await this.refreshGrant(grant) if (generation !== this.authGeneration) return this.status() if (refreshed === 'ended') return this.reauthorize(workspaceId, generation, 'grant_ended') + if (refreshed === 'unavailable' && isExpired(grant)) { + reportSwitch('retryable') + return this.stayed('retryable') + } } return this.activated(workspaceId, 'anchor') } From cdc55fa76fa5b61ac05a068b968d129f93eab8fa Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 22:21:41 -0500 Subject: [PATCH 14/75] fix(auth): fence the mint backoff on generation and account 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. --- src/main/cloud/session.test.ts | 46 ++++++++++++++++++++++++++++++++++ src/main/cloud/session.ts | 8 +++++- 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index 67e304a54..9691c67c9 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -656,6 +656,52 @@ describe('CloudSession.switchWorkspace with no browser', () => { expect(mintRequests).toHaveLength(1) }) + it('a late 429 from before logout does not throttle the next account', async () => { + saveGrant(grantOn('w1')) + const late = deferred() + mintReply = () => late.promise + const session = new CloudSession() + const stale = session.switchWorkspace('w2') + await vi.waitFor(() => expect(mintRequests).toHaveLength(1)) + + session.logout() + saveGrant(grantOn('w5', { subject: 'user-2' })) + late.resolve(json(429, {}, { 'Retry-After': '3600' })) + await stale + mintReply = () => json(404, {}) + await session.switchWorkspace('w6') + + expect(mintRequests).toHaveLength(2) + }) + + it('a late 429 from a previous account in the same generation does not throttle the new one', async () => { + saveGrant(grantOn('w1')) + const held = new CloudSession() + mintReply = ({ workspaceId }) => minted(workspaceId, PAST) + await held.switchWorkspace('w2') + const late = deferred() + const pendingSignIn = deferred>>() + mocked(signIn).mockReturnValue(pendingSignIn.promise) + mintRequests = [] + mintReply = ({ workspaceId }) => + workspaceId === 'w3' ? json(403, { code: 'sso_required' }) : late.promise + + const switching = held.switchWorkspace('w3') + await vi.waitFor(() => expect(signIn).toHaveBeenCalledOnce()) + const read = held.getAccessToken() + await vi.waitFor(() => expect(mintRequests).toHaveLength(2)) + pendingSignIn.resolve(signedInResult(grantOn('w3', { subject: 'user-2' }))) + await switching + late.resolve(json(429, {}, { 'Retry-After': '3600' })) + await read + mintRequests = [] + mintReply = () => json(404, {}) + + await held.switchWorkspace('w6') + + expect(mintRequests).toHaveLength(1) + }) + it('rejects a minted token for another workspace or account', async () => { saveGrant(grantOn('w1')) mintReply = () => diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index c4bf031ba..af77f885a 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -324,8 +324,14 @@ export class CloudSession { if (!grant || generation !== this.authGeneration || Date.now() < this.mintBlockedUntil) return RETRYABLE const outcome = classifyMint(await mintWorkspaceToken(grant.accessToken, workspaceId)) - if (outcome.kind === 'retryable' && outcome.retryAfterSeconds !== undefined) + if ( + outcome.kind === 'retryable' && + outcome.retryAfterSeconds !== undefined && + generation === this.authGeneration && + subjectOf(grant.accessToken) === this.currentSubject() + ) { this.mintBlockedUntil = Date.now() + outcome.retryAfterSeconds * 1000 + } return outcome } From eb5127d90b0ed9e910ad9dedf239d55188d1b0c8 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 22:22:20 -0500 Subject: [PATCH 15/75] fix(auth): hold off the browser after a sign-in returned no mint scope 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. --- src/main/cloud/session.test.ts | 97 ++++++++++++++++++++++++++++++++++ src/main/cloud/session.ts | 7 +++ 2 files changed, 104 insertions(+) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index 9691c67c9..40565d594 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -1217,6 +1217,103 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { ]) }) + it('a second and third switch after a scopeless sign-in stay put with no browser', async () => { + saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) + mocked(signIn).mockResolvedValue( + signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) + ) + const session = new CloudSession() + await session.switchWorkspace('w2') + const browserTrips = browserEvents().length + + for (const workspaceId of ['w2', 'w3']) { + await expect(session.switchWorkspace(workspaceId)).resolves.toMatchObject({ + workspaceId: 'w1', + workspaceSwitchFailure: 'retryable' + }) + } + + expect(signIn).toHaveBeenCalledOnce() + expect(browserEvents()).toHaveLength(browserTrips) + expect(mintRequests).toEqual([]) + expect(switchEvents().at(-1)).toEqual({ + outcome: 'retryable', + reauthorize_reason: 'scope_not_granted' + }) + }) + + it('a scopeless grant on B reaches its anchor and asks no browser for the next workspace', async () => { + saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) + mocked(signIn).mockResolvedValue(signedInResult(grantOn('w2', { scope: READ_ONLY_SCOPE }))) + const session = new CloudSession() + await session.switchWorkspace('w2') + + await expect(session.switchWorkspace('w3')).resolves.toMatchObject({ + workspaceId: 'w2', + workspaceSwitchFailure: 'retryable' + }) + + expect(signIn).toHaveBeenCalledOnce() + }) + + it('an explicit sign-in with the scope lifts the hold and switching mints again', async () => { + saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) + mocked(signIn).mockResolvedValueOnce( + signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) + ) + const session = new CloudSession() + await session.switchWorkspace('w2') + mocked(signIn).mockResolvedValueOnce(signedInResult(grantOn('w1', { revision: '-scoped' }))) + + await session.login() + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) + + expect(signIn).toHaveBeenCalledTimes(2) + expect(mintRequests).toHaveLength(1) + }) + + it('an explicit sign-in that also returns no scope keeps ordinary switches off the browser', async () => { + saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) + mocked(signIn).mockResolvedValue( + signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) + ) + const session = new CloudSession() + + await session.login() + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ + workspaceSwitchFailure: 'retryable' + }) + + expect(signIn).toHaveBeenCalledOnce() + }) + + it('logout resets the hold', async () => { + saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) + mocked(signIn).mockResolvedValue( + signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) + ) + const session = new CloudSession() + await session.switchWorkspace('w2') + + session.logout() + saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) + await session.switchWorkspace('w2') + + expect(signIn).toHaveBeenCalledTimes(2) + }) + + it('a restart may ask once more, since the hold lives in the session', async () => { + saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) + mocked(signIn).mockResolvedValue( + signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) + ) + await new CloudSession().switchWorkspace('w2') + + await new CloudSession().switchWorkspace('w2') + + expect(signIn).toHaveBeenCalledTimes(2) + }) + it('reports scope_not_granted when an sso sign-in narrows a grant that could mint', async () => { saveGrant(grantOn('w1')) mintReply = () => json(403, { code: 'sso_required' }) diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index af77f885a..81b0505a4 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -104,6 +104,7 @@ export class CloudSession { private readonly minting = new Map>() private switching: { workspaceId: string; result: Promise } | null = null private mintBlockedUntil = 0 + private browserReturnedNoMintScope = false private loginInFlight: Promise | null = null private loginAuthorizeUrl: string | null = null private returnedToAnchorHandler: (() => void) | null = null @@ -149,6 +150,7 @@ export class CloudSession { private storeSignedInGrant(tokens: AuthTokens): void { this.mintBlockedUntil = 0 + this.browserReturnedNoMintScope = !canMintWorkspaceTokens(tokens.accessToken) saveGrant(tokens) } @@ -162,6 +164,7 @@ export class CloudSession { this.authGeneration += 1 this.switching = null this.mintBlockedUntil = 0 + this.browserReturnedNoMintScope = false this.clearPendingLogin() clearTokens() } @@ -388,6 +391,10 @@ export class CloudSession { reportSwitch('retryable') return this.stayed('retryable') case 'reauthorize': + if (outcome.reason === 'mint_scope_missing' && this.browserReturnedNoMintScope) { + reportSwitch('retryable', 'scope_not_granted') + return this.stayed('retryable') + } return this.reauthorize(workspaceId, generation, outcome.reason) } } From 70b19b478091f0f85f59955b17e86348ad419a8b Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 22:24:01 -0500 Subject: [PATCH 16/75] fix(auth): apply the mint kill switch to view minting through one session 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. --- src/main/cloud/session.ts | 9 +- src/main/lib/embeddedSession.test.ts | 3 +- .../lib/viewWorkspaceGrants.session.test.ts | 174 ++++++++++++++++++ src/main/lib/viewWorkspaceGrants.test.ts | 3 +- src/main/lib/viewWorkspaceGrants.ts | 3 + 5 files changed, 189 insertions(+), 3 deletions(-) create mode 100644 src/main/lib/viewWorkspaceGrants.session.test.ts diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index 81b0505a4..5ddb78975 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -113,6 +113,13 @@ export class CloudSession { * login, workspace switch, or logout chose. */ private authGeneration = 0 + /** The one mint policy: the grant's anchor always, any other workspace unless the ops flag killed it. */ + async isWorkspaceMintAllowed(workspaceId: string): Promise { + const grant = loadGrant() + if (grant && workspaceIdOf(grant.accessToken) === workspaceId) return true + return isWorkspaceMintSwitchEnabled() + } + /** Called after a token read moved the active workspace back to the anchor. */ setReturnedToAnchorHandler(handler: () => void): void { this.returnedToAnchorHandler = handler @@ -296,7 +303,7 @@ export class CloudSession { workspaceId: string, generation: number ): Promise { - if (!(await isWorkspaceMintSwitchEnabled())) { + if (!(await this.isWorkspaceMintAllowed(workspaceId))) { return { kind: 'reauthorize', reason: 'mint_disabled' } } const grant = loadGrant() diff --git a/src/main/lib/embeddedSession.test.ts b/src/main/lib/embeddedSession.test.ts index 45c3d0512..54d1bd419 100644 --- a/src/main/lib/embeddedSession.test.ts +++ b/src/main/lib/embeddedSession.test.ts @@ -17,7 +17,8 @@ vi.mock('../devplatform/session', () => ({ getGrantAccessToken: mocks.getGrantAccessToken, currentWorkspaceId: () => mocks.current, currentSubject: () => (mocks.current ? 'user-1' : null), - currentAuthGeneration: () => 0 + currentAuthGeneration: () => 0, + isWorkspaceMintAllowed: async () => true }) })) vi.mock('../cloud/workspaceToken', () => ({ diff --git a/src/main/lib/viewWorkspaceGrants.session.test.ts b/src/main/lib/viewWorkspaceGrants.session.test.ts new file mode 100644 index 000000000..19a6830b9 --- /dev/null +++ b/src/main/lib/viewWorkspaceGrants.session.test.ts @@ -0,0 +1,174 @@ +// @vitest-environment node +import * as fs from 'node:fs' +import * as os from 'node:os' +import * as path from 'node:path' + +import type { WebContents } from 'electron' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const electronState = vi.hoisted(() => ({ userData: '' })) + +vi.mock('electron', () => ({ + app: { getPath: vi.fn(() => electronState.userData) }, + safeStorage: { + isEncryptionAvailable: vi.fn(() => true), + encryptString: vi.fn((value: string) => Buffer.from(value, 'utf-8')), + decryptString: vi.fn((value: Buffer) => value.toString('utf-8')) + }, + shell: { openExternal: vi.fn(() => Promise.resolve()) } +})) +vi.mock('../cloud/oauth', () => ({ + signIn: vi.fn(), + refresh: vi.fn(), + openAuthorizePage: vi.fn(() => Promise.resolve()) +})) +vi.mock('../devplatform/session', () => ({ getCloudSession: () => ({}) })) +vi.mock('./telemetry', () => ({ emit: vi.fn() })) +vi.mock('./workspaceMintSwitchFlag', () => ({ + isWorkspaceMintSwitchEnabled: vi.fn(async () => true) +})) + +import { CLOUD_CONFIG } from '../cloud/config' +import { openAuthorizePage, signIn } from '../cloud/oauth' +import { CloudSession } from '../cloud/session' +import { _resetForTest, clearTokens, saveGrant } from '../cloud/tokenStore' +import type { AuthTokens } from '../cloud/types' +import { ViewWorkspaceGrants } from './viewWorkspaceGrants' +import { isWorkspaceMintSwitchEnabled } from './workspaceMintSwitchFlag' + +const FUTURE = Date.now() + 3_600_000 +const view = { id: 'view' } as unknown as WebContents + +function jwt(claims: Record): string { + const b64 = (value: unknown): string => + Buffer.from(JSON.stringify(value), 'utf-8').toString('base64url') + return `${b64({ alg: 'RS256' })}.${b64(claims)}.sig` +} + +const GRANT: AuthTokens = { + accessToken: jwt({ sub: 'user-1', workspace_id: 'w1', scope: CLOUD_CONFIG.scope }), + refreshToken: 'refresh-w1', + expiresAt: FUTURE +} + +function mintedJwt(workspaceId: string): string { + return jwt({ sub: 'user-1', workspace_id: workspaceId }) +} + +let session: CloudSession +let grants: ViewWorkspaceGrants +let mintReply: (workspaceId: string) => Response +let mintRequests: string[] + +function kill(): void { + vi.mocked(isWorkspaceMintSwitchEnabled).mockResolvedValue(false) +} + +beforeEach(() => { + electronState.userData = fs.mkdtempSync(path.join(os.tmpdir(), 'view-grants-session-')) + _resetForTest() + vi.mocked(isWorkspaceMintSwitchEnabled).mockResolvedValue(true) + mintRequests = [] + mintReply = (workspaceId) => + new Response( + JSON.stringify({ + token: mintedJwt(workspaceId), + expires_at: new Date(FUTURE).toISOString() + }), + { status: 200 } + ) + vi.stubGlobal( + 'fetch', + vi.fn(async (_url: string, init: RequestInit) => { + const workspaceId = (JSON.parse(String(init.body)) as { workspace_id: string }).workspace_id + mintRequests.push(workspaceId) + return mintReply(workspaceId) + }) + ) + saveGrant(GRANT) + session = new CloudSession() + grants = new ViewWorkspaceGrants(session) +}) + +afterEach(() => { + clearTokens() + _resetForTest() + fs.rmSync(electronState.userData, { recursive: true, force: true }) + vi.unstubAllGlobals() + vi.clearAllMocks() +}) + +async function activeOnW2(): Promise { + await session.switchWorkspace('w2') + grants.allowDesktop('w2') + mintRequests = [] +} + +describe('view token path through a real session', () => { + it('mints a non-anchor workspace while the mint switch is on', async () => { + await activeOnW2() + + await expect(grants.tokenFor(view, 'w2')).resolves.toBe(mintedJwt('w2')) + + expect(mintRequests).toEqual(['w2']) + }) + + it('the ops flag off refuses a view mint for a non-anchor workspace, with no browser', async () => { + await activeOnW2() + kill() + + await expect(grants.tokenFor(view, 'w2')).resolves.toBeNull() + + expect(mintRequests).toEqual([]) + expect(signIn).not.toHaveBeenCalled() + expect(openAuthorizePage).not.toHaveBeenCalled() + }) + + it('the ops flag off leaves a mint for the anchor working', async () => { + kill() + + await expect(grants.tokenFor(view, 'w1')).resolves.toBe(mintedJwt('w1')) + + expect(mintRequests).toEqual(['w1']) + expect(signIn).not.toHaveBeenCalled() + }) + + it('a token the view already holds keeps working through a kill until it expires', async () => { + await activeOnW2() + await grants.tokenFor(view, 'w2') + mintRequests = [] + kill() + + await expect(grants.tokenFor(view, 'w2')).resolves.toBe(mintedJwt('w2')) + + expect(mintRequests).toEqual([]) + }) + + it('a server kill refuses a view mint with no browser', async () => { + await activeOnW2() + mintReply = () => + new Response(JSON.stringify({ code: 'oauth_workspace_mint_disabled' }), { status: 503 }) + + await expect(grants.tokenFor(view, 'w2')).resolves.toBeNull() + + expect(signIn).not.toHaveBeenCalled() + expect(openAuthorizePage).not.toHaveBeenCalled() + }) + + it('a kill landing while the policy is read drops the request after a newer switch', async () => { + await activeOnW2() + let release: (enabled: boolean) => void = () => {} + vi.mocked(isWorkspaceMintSwitchEnabled).mockReturnValueOnce( + new Promise((resolve) => { + release = resolve + }) + ) + const pending = grants.tokenFor(view, 'w2') + await vi.waitFor(() => expect(isWorkspaceMintSwitchEnabled).toHaveBeenCalled()) + await session.switchWorkspace('w1') + release(true) + + await expect(pending).resolves.toBeNull() + expect(mintRequests).toEqual([]) + }) +}) diff --git a/src/main/lib/viewWorkspaceGrants.test.ts b/src/main/lib/viewWorkspaceGrants.test.ts index ce2e19e3e..5ef35f98f 100644 --- a/src/main/lib/viewWorkspaceGrants.test.ts +++ b/src/main/lib/viewWorkspaceGrants.test.ts @@ -64,7 +64,8 @@ function grantSession( currentWorkspaceId: () => current, currentSubject: () => (current ? user : null), currentAuthGeneration: () => generation, - getGrantAccessToken + getGrantAccessToken, + isWorkspaceMintAllowed: async () => true } } diff --git a/src/main/lib/viewWorkspaceGrants.ts b/src/main/lib/viewWorkspaceGrants.ts index 253f28792..7f6c52a0a 100644 --- a/src/main/lib/viewWorkspaceGrants.ts +++ b/src/main/lib/viewWorkspaceGrants.ts @@ -27,6 +27,7 @@ export interface GrantSession { currentSubject(): string | null currentAuthGeneration(): number getGrantAccessToken(): Promise + isWorkspaceMintAllowed(workspaceId: string): Promise } export type MintWorkspaceToken = ( @@ -131,6 +132,8 @@ export class ViewWorkspaceGrants { if (cached && cached.expiresAt - MINT_REFRESH_SKEW_MS > Date.now()) return { token: cached.token, subject } + const allowed = await this.session.isWorkspaceMintAllowed(workspaceId) + if (!allowed || !this.isCurrent(fence)) return null const result = await this.mintOnce(accessToken, key, workspaceId, fence) if (!this.isCurrent(fence) || this.session.currentSubject() !== subject) return null if (result.kind !== 'minted') return null From a6f4a24fd77bc9b3b32204f385b736b8b8336e60 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 22:25:41 -0500 Subject: [PATCH 17/75] fix(auth): let views hold the workspace a promotion moved to 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. --- .../ipc/registerDevPlatformHandlers.test.ts | 92 +++++++++++++++++++ .../lib/ipc/registerDevPlatformHandlers.ts | 1 + .../lib/viewWorkspaceGrants.session.test.ts | 2 +- 3 files changed, 94 insertions(+), 1 deletion(-) diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts index eefa3f63f..2e5138e50 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts @@ -128,6 +128,10 @@ vi.mock('./shared', () => ({ i18n: { t: mocks.translate } })) +import type { WebContents } from 'electron' + +import { CLOUD_CONFIG } from '../../cloud/config' +import type * as ViewGrantsModule from '../viewWorkspaceGrants' import { registerDevPlatformHandlers, signInToCloud } from './registerDevPlatformHandlers' import { comfyWindows, type ComfyWindowEntry } from '../../host/registry' @@ -539,6 +543,94 @@ describe('registerDevPlatformHandlers', () => { expect(win.webContents.send).toHaveBeenCalledExactlyOnceWith('comfybuilder:authChanged', status) }) + describe('promotion that moves to another workspace', () => { + const inW2 = { + id: 'local-1', + name: 'Local One', + sourceId: 'standalone', + workspaceId: 'w2', + status: 'installed', + installPath: '/installs/local-1' + } + + function jwt(claims: Record): string { + const b64 = (value: unknown): string => + Buffer.from(JSON.stringify(value)).toString('base64url') + return `${b64({ alg: 'ES256' })}.${b64(claims)}.sig` + } + + async function realViewGrants(active: () => string) { + const { ViewWorkspaceGrants } = + await vi.importActual('../viewWorkspaceGrants') + const grants = new ViewWorkspaceGrants( + { + currentWorkspaceId: active, + currentSubject: () => 'user-1', + currentAuthGeneration: () => 1, + getGrantAccessToken: async () => + jwt({ sub: 'user-1', workspace_id: 'w1', scope: CLOUD_CONFIG.scope }), + isWorkspaceMintAllowed: async () => true + }, + async (_grant, workspaceId) => ({ + kind: 'minted', + token: jwt({ sub: 'user-1', workspace_id: workspaceId }), + expiresAt: Date.now() + 900_000 + }) + ) + grants.allowDesktop(active()) + mocks.allowDesktopWorkspace.mockImplementation((workspaceId) => + grants.allowDesktop(workspaceId) + ) + return grants + } + + afterEach(() => { + mocks.allowDesktopWorkspace.mockReset() + }) + + it('lets a view hold the workspace it moved to', async () => { + let active = 'w1' + const grants = await realViewGrants(() => active) + const view = { id: 'view' } as unknown as WebContents + mocks.get.mockResolvedValue(inW2) + mocks.switchWorkspace.mockImplementation(async (workspaceId: string) => { + active = workspaceId + const status = { signedIn: true, workspaceId, workspaceType: 'team' } + mocks.status.mockReturnValue(status) + return status + }) + mocks.createBuildDraft.mockResolvedValue({ + buildId: 'build-2', + workspaceId: 'w2', + editUrl: '/profile/builds/new?workspace=w2&edit=build-2' + }) + + await expect(handler('comfybuilder:promoteLocalInstance')({}, 'local-1')).resolves.toEqual({ + ok: true + }) + + await expect(grants.tokenFor(view, 'w2')).resolves.toBe( + jwt({ sub: 'user-1', workspace_id: 'w2' }) + ) + }) + + it('adds nothing to the allowlist when the switch stayed on the current workspace', async () => { + mocks.get.mockResolvedValue(inW2) + mocks.switchWorkspace.mockResolvedValue({ + signedIn: true, + workspaceId: 'w1', + workspaceSwitchFailure: 'unavailable' + }) + + await expect(handler('comfybuilder:promoteLocalInstance')({}, 'local-1')).resolves.toEqual({ + ok: false, + message: 'Could not activate the instance workspace.' + }) + + expect(mocks.allowDesktopWorkspace).not.toHaveBeenCalledWith('w2') + }) + }) + it('keeps a switch failure on the reply and off the broadcast', async () => { const win = { webContents: { isDestroyed: () => false, send: vi.fn() } } mocks.getAllWindows.mockReturnValue([win]) diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.ts b/src/main/lib/ipc/registerDevPlatformHandlers.ts index 5c02afb0a..a4b2d3c91 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.ts @@ -301,6 +301,7 @@ export function registerDevPlatformHandlers(): void { if (!switched.signedIn || switched.workspaceId !== workspaceId) { return { ok: false, message: 'Could not activate the instance workspace.' } } + getViewWorkspaceGrants().allowDesktop(workspaceId) } const filename = await saveSnapshot(inst.installPath, inst, 'manual') diff --git a/src/main/lib/viewWorkspaceGrants.session.test.ts b/src/main/lib/viewWorkspaceGrants.session.test.ts index 19a6830b9..ef5a7f2f4 100644 --- a/src/main/lib/viewWorkspaceGrants.session.test.ts +++ b/src/main/lib/viewWorkspaceGrants.session.test.ts @@ -155,7 +155,7 @@ describe('view token path through a real session', () => { expect(openAuthorizePage).not.toHaveBeenCalled() }) - it('a kill landing while the policy is read drops the request after a newer switch', async () => { + it('a newer switch while the policy is read drops the view request', async () => { await activeOnW2() let release: (enabled: boolean) => void = () => {} vi.mocked(isWorkspaceMintSwitchEnabled).mockReturnValueOnce( From 77acce73e838eaab6887f48017245f17916e0681 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 22:27:07 -0500 Subject: [PATCH 18/75] test(auth): make the token vault tests detect bypassed encryption 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. --- src/main/cloud/session.test.ts | 36 +++++++++++++++-------- src/main/cloud/tokenStore.test.ts | 48 ++++++++++++++++++++++++++++--- 2 files changed, 68 insertions(+), 16 deletions(-) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index 40565d594..37011d13a 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -11,8 +11,14 @@ vi.mock('electron', () => ({ app: { getPath: vi.fn(() => electronState.userData) }, safeStorage: { isEncryptionAvailable: vi.fn(() => true), - encryptString: vi.fn((value: string) => Buffer.from(value, 'utf-8')), - decryptString: vi.fn((value: Buffer) => value.toString('utf-8')) + encryptString: vi.fn((value: string) => + Buffer.from(`enc:${Buffer.from(value, 'utf-8').toString('base64')}`, 'utf-8') + ), + decryptString: vi.fn((value: Buffer) => { + const text = value.toString('utf-8') + if (!text.startsWith('enc:')) throw new Error('not encrypted') + return Buffer.from(text.slice(4), 'base64').toString('utf-8') + }) }, shell: { openExternal: vi.fn(() => Promise.resolve()) } })) @@ -30,6 +36,8 @@ vi.mock('../lib/workspaceMintSwitchFlag', () => ({ isWorkspaceMintSwitchEnabled: vi.fn(async () => true) })) +import { safeStorage } from 'electron' + import * as mainTelemetry from '../lib/telemetry' import { isWorkspaceMintSwitchEnabled } from '../lib/workspaceMintSwitchFlag' import { statusFromAccessToken } from './claims' @@ -162,7 +170,9 @@ function refreshFailure(kind: 'network' | 'timeout' | 'http', httpStatus?: numbe function vaultOnDisk(): Record { return JSON.parse( - fs.readFileSync(path.join(electronState.userData, 'comfy-cloud-auth.bin'), 'utf-8') + safeStorage.decryptString( + fs.readFileSync(path.join(electronState.userData, 'comfy-cloud-auth.bin')) + ) ) as Record } @@ -1114,15 +1124,17 @@ describe('CloudSession regressions', () => { const legacy = grantOn('w1', { scope: READ_ONLY_SCOPE }) fs.writeFileSync( path.join(electronState.userData, 'comfy-cloud-auth.bin'), - JSON.stringify({ - version: 1, - activeKey: 'workspace:w1', - subject: 'user-1', - bundles: { - 'workspace:w1': legacy, - 'workspace:w2': grantOn('w2', { scope: READ_ONLY_SCOPE }) - } - }) + safeStorage.encryptString( + JSON.stringify({ + version: 1, + activeKey: 'workspace:w1', + subject: 'user-1', + bundles: { + 'workspace:w1': legacy, + 'workspace:w2': grantOn('w2', { scope: READ_ONLY_SCOPE }) + } + }) + ) ) _resetForTest() mocked(signIn).mockResolvedValue(signedInResult(grantOn('w3'))) diff --git a/src/main/cloud/tokenStore.test.ts b/src/main/cloud/tokenStore.test.ts index e9ffa9073..787a3e0ae 100644 --- a/src/main/cloud/tokenStore.test.ts +++ b/src/main/cloud/tokenStore.test.ts @@ -10,11 +10,19 @@ vi.mock('electron', () => ({ app: { getPath: vi.fn(() => electronState.userData) }, safeStorage: { isEncryptionAvailable: vi.fn(() => electronState.encryptionAvailable), - encryptString: vi.fn((value: string) => Buffer.from(value, 'utf-8')), - decryptString: vi.fn((value: Buffer) => value.toString('utf-8')) + encryptString: vi.fn((value: string) => + Buffer.from(`enc:${Buffer.from(value, 'utf-8').toString('base64')}`, 'utf-8') + ), + decryptString: vi.fn((value: Buffer) => { + const text = value.toString('utf-8') + if (!text.startsWith('enc:')) throw new Error('not encrypted') + return Buffer.from(text.slice(4), 'base64').toString('utf-8') + }) } })) +import { safeStorage } from 'electron' + import { _resetForTest, activateWorkspace, @@ -61,11 +69,14 @@ function vaultPath(): string { } function writeVault(payload: unknown): void { - fs.writeFileSync(vaultPath(), Buffer.from(JSON.stringify(payload), 'utf-8')) + fs.writeFileSync(vaultPath(), safeStorage.encryptString(JSON.stringify(payload))) } function readVault(): Record { - return JSON.parse(fs.readFileSync(vaultPath(), 'utf-8')) as Record + return JSON.parse(safeStorage.decryptString(fs.readFileSync(vaultPath()))) as Record< + string, + unknown + > } describe('grant vault', () => { @@ -103,6 +114,35 @@ describe('grant vault', () => { expect(loadWorkspaceToken('w2')).toEqual(minted) }) + it('writes the grant and minted tokens only through safeStorage', () => { + const grant = tokens('user-1', 'w1') + const minted = mintedToken('user-1', 'w2') + saveGrant(grant) + saveWorkspaceToken('w2', minted) + + const onDisk = fs.readFileSync(vaultPath(), 'utf-8') + + expect(onDisk.startsWith('enc:')).toBe(true) + expect(onDisk).not.toContain(grant.accessToken) + expect(onDisk).not.toContain(grant.refreshToken) + expect(onDisk).not.toContain(minted.accessToken) + }) + + it('reads an unencrypted vault as signed out', () => { + fs.writeFileSync( + vaultPath(), + JSON.stringify({ + version: 2, + grant: tokens('user-1', 'w1'), + activeWorkspaceId: 'w1', + workspaceTokens: {} + }) + ) + + expect(loadGrant()).toBeNull() + expect(getAuthStatus()).toEqual({ signedIn: false }) + }) + it('activates only the anchor or a workspace with a held token', () => { saveGrant(tokens('user-1', 'w1')) saveWorkspaceToken('w2', mintedToken('user-1', 'w2')) From 1a3bad9e119be484a41f6e17accb9f934cf72775 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 22:27:44 -0500 Subject: [PATCH 19/75] fix(auth): validate the workspace and subject of a token minted for a 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. --- src/main/lib/embeddedSession.test.ts | 16 ++++--- src/main/lib/viewWorkspaceGrants.test.ts | 57 ++++++++++++++++++------ src/main/lib/viewWorkspaceGrants.ts | 4 +- 3 files changed, 57 insertions(+), 20 deletions(-) diff --git a/src/main/lib/embeddedSession.test.ts b/src/main/lib/embeddedSession.test.ts index 54d1bd419..2246a993e 100644 --- a/src/main/lib/embeddedSession.test.ts +++ b/src/main/lib/embeddedSession.test.ts @@ -51,7 +51,11 @@ function jwt(claims: Record): string { } const ACCESS = jwt({ sub: 'user-1', email: 'a@example.com', workspace_id: 'ws-1' }) -const MINTED = jwt({ sub: 'user-1', workspace_id: 'ws-1', auth_method: 'cloud' }) +function mintedFor(workspaceId: string): string { + return jwt({ sub: 'user-1', workspace_id: workspaceId, auth_method: 'cloud' }) +} + +const MINTED = mintedFor('ws-1') interface ViewOptions { frameUrl?: string @@ -82,9 +86,11 @@ beforeEach(() => { mocks.enabled = true mocks.entries = [] mocks.getGrantAccessToken.mockReset().mockResolvedValue(ACCESS) - mocks.mint - .mockReset() - .mockResolvedValue({ kind: 'minted', token: MINTED, expiresAt: Date.now() + 900_000 }) + mocks.mint.mockReset().mockImplementation(async (_grant: string, workspaceId: string) => ({ + kind: 'minted', + token: mintedFor(workspaceId), + expiresAt: Date.now() + 900_000 + })) mocks.current = 'ws-1' resetViewGrants() }) @@ -159,7 +165,7 @@ describe('embeddedSession', () => { await switchWorkspaceForSender(switcher.event, 'ws-2', switchWorkspace) - await expect(workspaceTokenForSender(switcher.event, 'ws-2')).resolves.toBe(MINTED) + await expect(workspaceTokenForSender(switcher.event, 'ws-2')).resolves.toBe(mintedFor('ws-2')) await expect(workspaceTokenForSender(bystander.event, 'ws-2')).resolves.toBeNull() }) diff --git a/src/main/lib/viewWorkspaceGrants.test.ts b/src/main/lib/viewWorkspaceGrants.test.ts index 5ef35f98f..a12197596 100644 --- a/src/main/lib/viewWorkspaceGrants.test.ts +++ b/src/main/lib/viewWorkspaceGrants.test.ts @@ -25,10 +25,18 @@ function accessToken(workspaceId: string, scope: string = CLOUD_CONFIG.scope): s return jwt({ sub: user, workspace_id: workspaceId, scope }) } +function mintedToken(workspaceId: string): string { + return jwt({ sub: user, workspace_id: workspaceId }) +} + +function staleToken(workspaceId: string): string { + return jwt({ sub: user, workspace_id: workspaceId, stale: true }) +} + function minted(workspaceId: string): WorkspaceTokenMint { return { kind: 'minted', - token: `minted-${workspaceId}`, + token: mintedToken(workspaceId), expiresAt: Date.now() + 15 * 60_000 } } @@ -103,7 +111,7 @@ describe('ViewWorkspaceGrants', () => { it('hands a view the minted token for the workspace Desktop started in, never the access token', async () => { const token = await grants.tokenFor(viewA, 'ws-1') - expect(token).toBe('minted-ws-1') + expect(token).toBe(mintedToken('ws-1')) expect(mint).toHaveBeenCalledWith(accessToken('ws-1'), 'ws-1') }) @@ -111,10 +119,23 @@ describe('ViewWorkspaceGrants', () => { grants.allowView(viewA, 'ws-2') signInAt('ws-2') - await expect(grants.tokenFor(viewA, 'ws-2')).resolves.toBe('minted-ws-2') + await expect(grants.tokenFor(viewA, 'ws-2')).resolves.toBe(mintedToken('ws-2')) expect(mint).toHaveBeenCalledExactlyOnceWith(accessToken('ws-1'), 'ws-2') }) + it.each<[string, () => string]>([ + ['another workspace', () => jwt({ sub: user, workspace_id: 'ws-9' })], + ['another account', () => jwt({ sub: 'user-9', workspace_id: 'ws-1' })], + ['a token with no claims', () => 'opaque-token'] + ])('refuses and does not cache a minted token for %s', async (_name, token) => { + mint.mockResolvedValueOnce({ kind: 'minted', token: token(), expiresAt: Date.now() + 900_000 }) + + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBeNull() + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe(mintedToken('ws-1')) + + expect(mint).toHaveBeenCalledTimes(2) + }) + it('reuses a minted token until it nears expiry', async () => { await grants.tokenFor(viewA, 'ws-1') await grants.tokenFor(viewB, 'ws-1') @@ -128,7 +149,7 @@ describe('ViewWorkspaceGrants', () => { grants.tokenFor(viewA, 'ws-1') ]) - expect(tokens).toEqual(['minted-ws-1', 'minted-ws-1']) + expect(tokens).toEqual([mintedToken('ws-1'), mintedToken('ws-1')]) expect(mint).toHaveBeenCalledOnce() }) @@ -141,7 +162,7 @@ describe('ViewWorkspaceGrants', () => { grants.allowView(viewA, 'ws-2') signInAt('ws-2') - await expect(grants.tokenFor(viewA, 'ws-2')).resolves.toBe('minted-ws-2') + await expect(grants.tokenFor(viewA, 'ws-2')).resolves.toBe(mintedToken('ws-2')) await expect(grants.tokenFor(viewB, 'ws-2')).resolves.toBeNull() }) @@ -149,8 +170,8 @@ describe('ViewWorkspaceGrants', () => { grants.allowDesktop('ws-2') signInAt('ws-2') - await expect(grants.tokenFor(viewA, 'ws-2')).resolves.toBe('minted-ws-2') - await expect(grants.tokenFor(viewB, 'ws-2')).resolves.toBe('minted-ws-2') + await expect(grants.tokenFor(viewA, 'ws-2')).resolves.toBe(mintedToken('ws-2')) + await expect(grants.tokenFor(viewB, 'ws-2')).resolves.toBe(mintedToken('ws-2')) }) it('stops handing out a workspace once the view moved on', async () => { @@ -182,10 +203,14 @@ describe('ViewWorkspaceGrants', () => { await vi.waitFor(() => expect(mint).toHaveBeenCalledOnce()) signInAt('ws-2') signInAt('ws-1') - stale.resolve({ kind: 'minted', token: 'stale-ws-1', expiresAt: Date.now() + 15 * 60_000 }) + stale.resolve({ + kind: 'minted', + token: staleToken('ws-1'), + expiresAt: Date.now() + 15 * 60_000 + }) await expect(pending).resolves.toBeNull() - await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe('minted-ws-1') + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe(mintedToken('ws-1')) expect(mint).toHaveBeenCalledTimes(2) }) @@ -197,11 +222,15 @@ describe('ViewWorkspaceGrants', () => { signInAt('ws-2') signInAt('ws-1') - await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe('minted-ws-1') - stale.resolve({ kind: 'minted', token: 'stale-ws-1', expiresAt: Date.now() + 15 * 60_000 }) + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe(mintedToken('ws-1')) + stale.resolve({ + kind: 'minted', + token: staleToken('ws-1'), + expiresAt: Date.now() + 15 * 60_000 + }) await expect(older).resolves.toBeNull() - await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe('minted-ws-1') + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe(mintedToken('ws-1')) expect(mint).toHaveBeenCalledTimes(2) }) @@ -271,7 +300,7 @@ describe('ViewWorkspaceGrants', () => { await grants.tokenFor(viewA, 'ws-1') user = 'user-2' - await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe('minted-ws-1') + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe(mintedToken('ws-1')) expect(mint).toHaveBeenCalledTimes(2) expect(mint).toHaveBeenLastCalledWith(accessToken('ws-1'), 'ws-1') }) @@ -291,7 +320,7 @@ describe('ViewWorkspaceGrants', () => { before.resolve(firstUserToken) await expect(stale).resolves.toBeNull() - await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe('minted-ws-1') + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe(mintedToken('ws-1')) expect(mint).toHaveBeenCalledOnce() expect(mint).toHaveBeenCalledWith(accessToken('ws-1'), 'ws-1') }) diff --git a/src/main/lib/viewWorkspaceGrants.ts b/src/main/lib/viewWorkspaceGrants.ts index 7f6c52a0a..69f8be0b9 100644 --- a/src/main/lib/viewWorkspaceGrants.ts +++ b/src/main/lib/viewWorkspaceGrants.ts @@ -1,6 +1,6 @@ import type { WebContents } from 'electron' -import { canMintWorkspaceTokens, subjectOf } from '../cloud/claims' +import { canMintWorkspaceTokens, subjectOf, workspaceIdOf } from '../cloud/claims' import { mintWorkspaceToken } from '../cloud/workspaceToken' import type { WorkspaceTokenMint } from '../cloud/workspaceToken' import { getCloudSession } from '../devplatform/session' @@ -137,6 +137,8 @@ export class ViewWorkspaceGrants { const result = await this.mintOnce(accessToken, key, workspaceId, fence) if (!this.isCurrent(fence) || this.session.currentSubject() !== subject) return null if (result.kind !== 'minted') return null + if (workspaceIdOf(result.token) !== workspaceId || subjectOf(result.token) !== subject) + return null this.minted.set(key, { token: result.token, expiresAt: result.expiresAt }) return { token: result.token, subject } } From 30ffc8c1ae57d563796dc66ffa67f0d689fb75c1 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 22:34:25 -0500 Subject: [PATCH 20/75] test(auth): pin the backoff generation fence and lifting the scope hold Two mutants survived: both guards were correct but only incidentally covered. --- src/main/cloud/session.test.ts | 41 ++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index 37011d13a..7ec1808e6 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -684,6 +684,24 @@ describe('CloudSession.switchWorkspace with no browser', () => { expect(mintRequests).toHaveLength(2) }) + it('a late 429 from before logout does not throttle the same account signing back in', async () => { + saveGrant(grantOn('w1')) + const late = deferred() + mintReply = () => late.promise + const session = new CloudSession() + const stale = session.switchWorkspace('w2') + await vi.waitFor(() => expect(mintRequests).toHaveLength(1)) + + session.logout() + saveGrant(grantOn('w1')) + late.resolve(json(429, {}, { 'Retry-After': '3600' })) + await stale + mintReply = ({ workspaceId }) => minted(workspaceId) + + await expect(session.switchWorkspace('w3')).resolves.toMatchObject({ workspaceId: 'w3' }) + expect(mintRequests).toHaveLength(2) + }) + it('a late 429 from a previous account in the same generation does not throttle the new one', async () => { saveGrant(grantOn('w1')) const held = new CloudSession() @@ -1284,6 +1302,29 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { expect(mintRequests).toHaveLength(1) }) + it('a grant that can mint lifts the hold, so one that later narrows can ask again', async () => { + saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) + mocked(signIn).mockResolvedValueOnce( + signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) + ) + const session = new CloudSession() + await session.switchWorkspace('w2') + mocked(signIn).mockResolvedValueOnce( + signedInResult(grantOn('w1', { expiresAt: PAST, revision: '-scoped' })) + ) + await session.login() + mocked(refresh).mockResolvedValue( + grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-narrow' }) + ) + mintReply = () => json(403, { code: 'insufficient_scope' }) + await session.switchWorkspace('w2') + mocked(signIn).mockResolvedValueOnce(signedInResult(grantOn('w3'))) + + await expect(session.switchWorkspace('w3')).resolves.toMatchObject({ workspaceId: 'w3' }) + + expect(signIn).toHaveBeenCalledTimes(3) + }) + it('an explicit sign-in that also returns no scope keeps ordinary switches off the browser', async () => { saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) mocked(signIn).mockResolvedValue( From 27a936b9a34466cb7e2132e60bf0eda422abe0b0 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 22:43:54 -0500 Subject: [PATCH 21/75] fix(auth): keep the withheld mint scope in the vault across restarts 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. --- src/main/cloud/session.test.ts | 65 ++++++++++++++++++++++++++++++- src/main/cloud/session.ts | 8 ++-- src/main/cloud/tokenStore.test.ts | 65 +++++++++++++++++++++++++++++++ src/main/cloud/tokenStore.ts | 17 ++++++-- 4 files changed, 146 insertions(+), 9 deletions(-) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index 7ec1808e6..4bba0d388 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -1355,14 +1355,77 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { expect(signIn).toHaveBeenCalledTimes(2) }) - it('a restart may ask once more, since the hold lives in the session', async () => { + it('a restart keeps the hold: no second browser across sessions', async () => { saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) mocked(signIn).mockResolvedValue( signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) ) await new CloudSession().switchWorkspace('w2') + _resetForTest() + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w1', + workspaceSwitchFailure: 'retryable' + }) + + expect(signIn).toHaveBeenCalledOnce() + expect(vaultOnDisk().mintScopeWithheld).toBe(true) + }) + + it('a pre-upgrade grant gets its one trip on first launch, then the hold survives restarts', async () => { + fs.writeFileSync( + path.join(electronState.userData, 'comfy-cloud-auth.bin'), + safeStorage.encryptString( + JSON.stringify({ + version: 1, + activeKey: 'workspace:w1', + subject: 'user-1', + bundles: { 'workspace:w1': grantOn('w1', { scope: READ_ONLY_SCOPE }) } + }) + ) + ) + _resetForTest() + mocked(signIn).mockResolvedValue( + signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) + ) + expect(vaultOnDisk().mintScopeWithheld).toBeUndefined() await new CloudSession().switchWorkspace('w2') + expect(signIn).toHaveBeenCalledOnce() + _resetForTest() + await new CloudSession().switchWorkspace('w2') + + expect(signIn).toHaveBeenCalledOnce() + }) + + it('a restart with a scoped sign-in in between mints: the grant that can mint cleared the hold', async () => { + saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) + mocked(signIn).mockResolvedValueOnce( + signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) + ) + const session = new CloudSession() + await session.switchWorkspace('w2') + mocked(signIn).mockResolvedValueOnce(signedInResult(grantOn('w1', { revision: '-scoped' }))) + await session.login() + _resetForTest() + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w2' + }) + + expect(signIn).toHaveBeenCalledTimes(2) + expect(vaultOnDisk()).not.toHaveProperty('mintScopeWithheld') + }) + + it('an explicit sign-in can still try after a restart', async () => { + saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) + mocked(signIn).mockResolvedValue( + signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) + ) + await new CloudSession().switchWorkspace('w2') + _resetForTest() + + await new CloudSession().login() expect(signIn).toHaveBeenCalledTimes(2) }) diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index 5ddb78975..57ba5705a 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -17,6 +17,7 @@ import { clearTokens, dropWorkspaceToken, getAuthStatus, + isMintScopeWithheld, loadActiveWorkspaceId, loadGrant, loadWorkspaceToken, @@ -104,7 +105,6 @@ export class CloudSession { private readonly minting = new Map>() private switching: { workspaceId: string; result: Promise } | null = null private mintBlockedUntil = 0 - private browserReturnedNoMintScope = false private loginInFlight: Promise | null = null private loginAuthorizeUrl: string | null = null private returnedToAnchorHandler: (() => void) | null = null @@ -157,8 +157,7 @@ export class CloudSession { private storeSignedInGrant(tokens: AuthTokens): void { this.mintBlockedUntil = 0 - this.browserReturnedNoMintScope = !canMintWorkspaceTokens(tokens.accessToken) - saveGrant(tokens) + saveGrant(tokens, { mintScopeWithheld: !canMintWorkspaceTokens(tokens.accessToken) }) } private clearPendingLogin(): void { @@ -171,7 +170,6 @@ export class CloudSession { this.authGeneration += 1 this.switching = null this.mintBlockedUntil = 0 - this.browserReturnedNoMintScope = false this.clearPendingLogin() clearTokens() } @@ -398,7 +396,7 @@ export class CloudSession { reportSwitch('retryable') return this.stayed('retryable') case 'reauthorize': - if (outcome.reason === 'mint_scope_missing' && this.browserReturnedNoMintScope) { + if (outcome.reason === 'mint_scope_missing' && isMintScopeWithheld()) { reportSwitch('retryable', 'scope_not_granted') return this.stayed('retryable') } diff --git a/src/main/cloud/tokenStore.test.ts b/src/main/cloud/tokenStore.test.ts index 787a3e0ae..05d19b58d 100644 --- a/src/main/cloud/tokenStore.test.ts +++ b/src/main/cloud/tokenStore.test.ts @@ -23,6 +23,7 @@ vi.mock('electron', () => ({ import { safeStorage } from 'electron' +import { CLOUD_CONFIG } from './config' import { _resetForTest, activateWorkspace, @@ -30,6 +31,7 @@ import { dropWorkspaceToken, getAuthStatus, getCachedWorkspaceName, + isMintScopeWithheld, loadActiveWorkspaceId, loadGrant, loadWorkspaceToken, @@ -46,6 +48,12 @@ function jwt(subject: string, workspaceId: string): string { return `${b64({ alg: 'RS256' })}.${b64({ sub: subject, workspace_id: workspaceId })}.sig` } +function jwtWithScope(subject: string, workspaceId: string, scope: string): string { + const b64 = (value: unknown): string => + Buffer.from(JSON.stringify(value), 'utf-8').toString('base64url') + return `${b64({ alg: 'RS256' })}.${b64({ sub: subject, workspace_id: workspaceId, scope })}.sig` +} + function tokenWithoutSubject(workspaceId: string): string { const b64 = (value: unknown): string => Buffer.from(JSON.stringify(value), 'utf-8').toString('base64url') @@ -143,6 +151,53 @@ describe('grant vault', () => { expect(getAuthStatus()).toEqual({ signedIn: false }) }) + it('persists a withheld mint scope on the grant and clears it with a grant that can mint', () => { + saveGrant(tokens('user-1', 'w1'), { mintScopeWithheld: true }) + _resetForTest() + expect(isMintScopeWithheld()).toBe(true) + + saveGrant(tokens('user-1', 'w1', '-next')) + _resetForTest() + expect(isMintScopeWithheld()).toBe(false) + expect(readVault()).not.toHaveProperty('mintScopeWithheld') + }) + + it('forgets a withheld mint scope on logout and on a changed account', () => { + saveGrant(tokens('user-1', 'w1'), { mintScopeWithheld: true }) + saveGrant(tokens('user-2', 'w1')) + expect(isMintScopeWithheld()).toBe(false) + + saveGrant(tokens('user-2', 'w1'), { mintScopeWithheld: true }) + clearTokens() + expect(isMintScopeWithheld()).toBe(false) + }) + + it('a rotation that can mint clears a withheld scope and one that cannot keeps it', () => { + const scopeless = tokens('user-1', 'w1') + saveGrant(scopeless, { mintScopeWithheld: true }) + const rotated = tokens('user-1', 'w1', '-rotated') + replaceGrant(scopeless.accessToken, scopeless.refreshToken!, rotated) + expect(isMintScopeWithheld()).toBe(true) + + const scoped = { + accessToken: jwtWithScope('user-1', 'w1', CLOUD_CONFIG.scope), + refreshToken: 'refresh-scoped', + expiresAt: Date.now() + 3_600_000 + } + replaceGrant(rotated.accessToken, rotated.refreshToken!, scoped) + expect(isMintScopeWithheld()).toBe(false) + }) + + it('never sets a withheld scope when migrating a version 1 vault', () => { + writeVault({ + version: 1, + activeKey: 'workspace:w1', + bundles: { 'workspace:w1': tokens('user-1', 'w1') } + }) + + expect(isMintScopeWithheld()).toBe(false) + }) + it('activates only the anchor or a workspace with a held token', () => { saveGrant(tokens('user-1', 'w1')) saveWorkspaceToken('w2', mintedToken('user-1', 'w2')) @@ -339,6 +394,16 @@ describe('grant vault', () => { }) it.each<[string, unknown]>([ + [ + 'a version 2 vault with a malformed scope hold', + { + version: 2, + grant: tokens('user-1', 'w1'), + activeWorkspaceId: 'w1', + workspaceTokens: {}, + mintScopeWithheld: 'yes' + } + ], ['an unknown version', { version: 3, grant: tokens('user-1', 'w1') }], [ 'a version 2 vault with no grant', diff --git a/src/main/cloud/tokenStore.ts b/src/main/cloud/tokenStore.ts index 155646200..cf6d0b876 100644 --- a/src/main/cloud/tokenStore.ts +++ b/src/main/cloud/tokenStore.ts @@ -8,7 +8,7 @@ import { app, safeStorage } from 'electron' import * as fs from 'fs' import * as path from 'path' -import { statusFromAccessToken, subjectOf, workspaceIdOf } from './claims' +import { canMintWorkspaceTokens, statusFromAccessToken, subjectOf, workspaceIdOf } from './claims' import type { AuthStatus, AuthTokens, Workspace } from './types' const AUTH_FILENAME = 'comfy-cloud-auth.bin' @@ -18,6 +18,7 @@ interface TokenVault { version: typeof VAULT_VERSION subject?: string grant: AuthTokens + mintScopeWithheld?: true activeWorkspaceId: string | null workspaceTokens: Record workspaceNames?: Record @@ -82,6 +83,7 @@ function isVault(v: unknown): v is TokenVault { if (!isRecord(v) || v.version !== VAULT_VERSION) return false return ( isTokens(v.grant) && + (v.mintScopeWithheld === undefined || v.mintScopeWithheld === true) && (v.activeWorkspaceId === null || typeof v.activeWorkspaceId === 'string') && (v.subject === undefined || typeof v.subject === 'string') && isRecord(v.workspaceTokens) && @@ -171,13 +173,16 @@ function holdsToken(vault: TokenVault, workspaceId: string | null): boolean { /** Store the grant from a browser sign-in. A changed account replaces the vault. The old access * token stays held for its old anchor; an active workspace with no held token moves to the new one. */ -export function saveGrant(grant: AuthTokens): void { +export function saveGrant(grant: AuthTokens, options: { mintScopeWithheld?: boolean } = {}): void { + const withheld = options.mintScopeWithheld ? ({ mintScopeWithheld: true } as const) : {} const current = loadVault() const subject = subjectOf(grant.accessToken) if (!current || !subject || current.subject !== subject) { - persistVault(vaultFor(grant)) + persistVault({ ...vaultFor(grant), ...withheld }) return } + delete current.mintScopeWithheld + Object.assign(current, withheld) const previous = current.grant const previousAnchor = workspaceIdOf(previous.accessToken) if ( @@ -196,6 +201,11 @@ export function saveGrant(grant: AuthTokens): void { persistVault(current) } +/** A browser sign-in returned this grant without the mint scope, so another trip would not help. */ +export function isMintScopeWithheld(): boolean { + return loadVault()?.mintScopeWithheld === true +} + /** The OAuth grant bundle, the only one carrying a refresh token. */ export function loadGrant(): AuthTokens | null { return loadVault()?.grant ?? null @@ -274,6 +284,7 @@ export function replaceGrant( return false } vault.grant = grant + if (canMintWorkspaceTokens(grant.accessToken)) delete vault.mintScopeWithheld persistVault(vault) return true } From b14a44693440890fa103b87d1e2cc5d74dd2c8ab Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 22:44:49 -0500 Subject: [PATCH 22/75] fix(auth): fence the view permission writes of a workspace switch on 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. --- .../ipc/registerDevPlatformHandlers.test.ts | 80 ++++++++++++++++++- .../lib/ipc/registerDevPlatformHandlers.ts | 9 ++- 2 files changed, 86 insertions(+), 3 deletions(-) diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts index 2e5138e50..19372c223 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts @@ -132,7 +132,11 @@ import type { WebContents } from 'electron' import { CLOUD_CONFIG } from '../../cloud/config' import type * as ViewGrantsModule from '../viewWorkspaceGrants' -import { registerDevPlatformHandlers, signInToCloud } from './registerDevPlatformHandlers' +import { + registerDevPlatformHandlers, + signInToCloud, + switchCloudWorkspace +} from './registerDevPlatformHandlers' import { comfyWindows, type ComfyWindowEntry } from '../../host/registry' type IpcHandler = (event: unknown, ...args: unknown[]) => unknown @@ -631,6 +635,80 @@ describe('registerDevPlatformHandlers', () => { }) }) + it('T-V27: an old switch finishing after another account took over changes no view permission', async () => { + const jwt = (claims: Record): string => { + const b64 = (value: unknown): string => + Buffer.from(JSON.stringify(value)).toString('base64url') + return `${b64({ alg: 'ES256' })}.${b64(claims)}.sig` + } + let active = 'w1' + let subject = 'user-1' + let generation = 1 + const { ViewWorkspaceGrants } = + await vi.importActual('../viewWorkspaceGrants') + const grants = new ViewWorkspaceGrants( + { + currentWorkspaceId: () => active, + currentSubject: () => subject, + currentAuthGeneration: () => generation, + getGrantAccessToken: async () => + jwt({ sub: subject, workspace_id: 'home', scope: CLOUD_CONFIG.scope }), + isWorkspaceMintAllowed: async () => true + }, + async (_grant, workspaceId) => ({ + kind: 'minted', + token: jwt({ sub: subject, workspace_id: workspaceId }), + expiresAt: Date.now() + 900_000 + }) + ) + grants.allowDesktop('w1') + mocks.endViewGrants.mockImplementation(() => grants.endAll()) + mocks.allowDesktopWorkspace.mockImplementation((workspaceId) => + grants.allowDesktop(workspaceId) + ) + mocks.currentAuthGeneration.mockImplementation(() => generation) + mocks.currentSubject.mockImplementation(() => subject) + const viewV = { id: 'view-v' } as unknown as WebContents + const otherView = { id: 'other-view' } as unknown as WebContents + let finishOldSwitch: (status: Record) => void = () => {} + mocks.switchWorkspace.mockImplementationOnce(() => { + generation += 1 + return new Promise((resolve) => { + finishOldSwitch = resolve + }) + }) + + const oldSwitch = switchCloudWorkspace('w2') + + mocks.login.mockImplementationOnce(async () => { + generation += 1 + subject = 'user-2' + active = 'u2-home' + return { signedIn: true, workspaceId: 'u2-home' } + }) + await signInToCloud() + + grants.allowView(viewV, 'X') + mocks.switchWorkspace.mockImplementationOnce(async () => { + generation += 1 + active = 'X' + return { signedIn: true, workspaceId: 'X' } + }) + await switchCloudWorkspace('X') + + finishOldSwitch({ signedIn: true, workspaceId: 'X' }) + await oldSwitch + + await expect(grants.tokenFor(otherView, 'X')).resolves.toBeNull() + await expect(grants.tokenFor(viewV, 'X')).resolves.toBe( + jwt({ sub: 'user-2', workspace_id: 'X' }) + ) + mocks.endViewGrants.mockReset() + mocks.allowDesktopWorkspace.mockReset() + mocks.currentAuthGeneration.mockReset().mockReturnValue(1) + mocks.currentSubject.mockReset().mockReturnValue('user-1') + }) + it('keeps a switch failure on the reply and off the broadcast', async () => { const win = { webContents: { isDestroyed: () => false, send: vi.fn() } } mocks.getAllWindows.mockReturnValue([win]) diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.ts b/src/main/lib/ipc/registerDevPlatformHandlers.ts index a4b2d3c91..3af9cdb2d 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.ts @@ -142,10 +142,15 @@ export async function switchCloudWorkspace(workspaceId: string): Promise Date: Sun, 8 Nov 2026 22:46:04 -0500 Subject: [PATCH 23/75] fix(auth): refuse a mint reply that is already expired 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. --- src/main/cloud/session.test.ts | 26 ++++++++++++++----- src/main/cloud/workspaceToken.test.ts | 13 +++++++--- src/main/cloud/workspaceToken.ts | 2 +- .../lib/viewWorkspaceGrants.session.test.ts | 20 ++++++++++++++ 4 files changed, 51 insertions(+), 10 deletions(-) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index 4bba0d388..3d2f87fba 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -50,7 +50,7 @@ import { WORKSPACE_SWITCH_EVENT } from './session' import { SignInFailure } from './signInFailure' -import { _resetForTest, clearTokens, saveGrant } from './tokenStore' +import { _resetForTest, clearTokens, saveGrant, saveWorkspaceToken } from './tokenStore' import type { AuthTokens } from './types' import { listWorkspaceMembers, listWorkspaces } from './workspaces' @@ -318,9 +318,9 @@ describe('CloudSession access tokens', () => { describe('CloudSession background token reads never open the browser', () => { async function activeOnMintedToken(expiresAt = PAST): Promise { saveGrant(grantOn('w1')) - mintReply = ({ workspaceId }) => minted(workspaceId, expiresAt) const session = new CloudSession() await session.switchWorkspace('w2') + saveWorkspaceToken('w2', { accessToken: mintedJwt('w2'), expiresAt }) mintRequests = [] return session } @@ -558,13 +558,27 @@ describe('CloudSession.switchWorkspace with no browser', () => { ) }) - it('re-mints an expired minted token on the next switch, with no browser', async () => { + it('refuses a mint reply that is already expired: nothing is stored or activated', async () => { saveGrant(grantOn('w1')) mintReply = ({ workspaceId }) => minted(workspaceId, PAST) const session = new CloudSession() + + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w1', + workspaceSwitchFailure: 'retryable' + }) + + expect(session.currentWorkspaceId()).toBe('w1') + expect(vaultOnDisk().workspaceTokens).toEqual({}) + expect(signIn).not.toHaveBeenCalled() + }) + + it('re-mints an expired minted token on the next switch, with no browser', async () => { + saveGrant(grantOn('w1')) + const session = new CloudSession() await session.switchWorkspace('w2') await session.switchWorkspace('w1') - mintReply = ({ workspaceId }) => minted(workspaceId) + saveWorkspaceToken('w2', { accessToken: mintedJwt('w2'), expiresAt: PAST }) await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) @@ -705,8 +719,8 @@ describe('CloudSession.switchWorkspace with no browser', () => { it('a late 429 from a previous account in the same generation does not throttle the new one', async () => { saveGrant(grantOn('w1')) const held = new CloudSession() - mintReply = ({ workspaceId }) => minted(workspaceId, PAST) await held.switchWorkspace('w2') + saveWorkspaceToken('w2', { accessToken: mintedJwt('w2'), expiresAt: PAST }) const late = deferred() const pendingSignIn = deferred>>() mocked(signIn).mockReturnValue(pendingSignIn.promise) @@ -1566,10 +1580,10 @@ describe('CloudSession fencing (T-V27)', () => { describe('CloudSession status and catalog', () => { it('reports the active workspace from the minted token, stale claims included', async () => { saveGrant(grantOn('w1')) - mintReply = ({ workspaceId }) => minted(workspaceId, Date.now() + 1) const session = new CloudSession() await session.switchWorkspace('w2') + saveWorkspaceToken('w2', { accessToken: mintedJwt('w2'), expiresAt: PAST }) expect(session.status()).toMatchObject({ signedIn: true, diff --git a/src/main/cloud/workspaceToken.test.ts b/src/main/cloud/workspaceToken.test.ts index bf674a18b..ba168514b 100644 --- a/src/main/cloud/workspaceToken.test.ts +++ b/src/main/cloud/workspaceToken.test.ts @@ -17,14 +17,15 @@ afterEach(() => { describe('mintWorkspaceToken', () => { it('posts the workspace with the access token as Bearer', async () => { - respond(200, { token: 'cloud-jwt', expires_at: '2026-11-07T12:15:00Z' }) + const expiresAt = new Date(Date.now() + 900_000).toISOString() + respond(200, { token: 'cloud-jwt', expires_at: expiresAt }) await expect( mintWorkspaceToken('oauth-access', 'ws-2', { apiBase: 'https://cloud.test/api/' }) ).resolves.toEqual({ kind: 'minted', token: 'cloud-jwt', - expiresAt: Date.parse('2026-11-07T12:15:00Z') + expiresAt: Date.parse(expiresAt) }) expect(fetch).toHaveBeenCalledWith( 'https://cloud.test/api/auth/token', @@ -50,7 +51,13 @@ describe('mintWorkspaceToken', () => { ], ['a non-string code', 403, { code: 7 }, undefined], ['a body without a token', 200, { expires_at: '2026-11-07T12:15:00Z' }, undefined], - ['an unreadable expiry', 200, { token: 'cloud-jwt', expires_at: 'soon' }, undefined] + ['an unreadable expiry', 200, { token: 'cloud-jwt', expires_at: 'soon' }, undefined], + [ + 'an expiry already past', + 200, + { token: 'cloud-jwt', expires_at: new Date(Date.now() - 1000).toISOString() }, + undefined + ] ])('reports %s as failed with its error code', async (_name, status, body, code) => { respond(status, body) diff --git a/src/main/cloud/workspaceToken.ts b/src/main/cloud/workspaceToken.ts index 66f510d44..bb96f6590 100644 --- a/src/main/cloud/workspaceToken.ts +++ b/src/main/cloud/workspaceToken.ts @@ -70,7 +70,7 @@ function mintedFrom(body: unknown): WorkspaceTokenMint | null { const { token, expires_at: expiresAt } = body as { token?: unknown; expires_at?: unknown } if (typeof token !== 'string' || token === '' || typeof expiresAt !== 'string') return null const expiresAtMs = Date.parse(expiresAt) - return Number.isFinite(expiresAtMs) ? { kind: 'minted', token, expiresAt: expiresAtMs } : null + return expiresAtMs > Date.now() ? { kind: 'minted', token, expiresAt: expiresAtMs } : null } export async function mintWorkspaceToken( diff --git a/src/main/lib/viewWorkspaceGrants.session.test.ts b/src/main/lib/viewWorkspaceGrants.session.test.ts index ef5a7f2f4..c83d1eec1 100644 --- a/src/main/lib/viewWorkspaceGrants.session.test.ts +++ b/src/main/lib/viewWorkspaceGrants.session.test.ts @@ -133,6 +133,26 @@ describe('view token path through a real session', () => { expect(signIn).not.toHaveBeenCalled() }) + it('refuses to deliver or cache a token that is already expired', async () => { + const expired = (workspaceId: string): Response => + new Response( + JSON.stringify({ + token: mintedJwt(workspaceId), + expires_at: new Date(Date.now() - 1000).toISOString() + }), + { status: 200 } + ) + const good = mintReply + await activeOnW2() + mintReply = expired + + await expect(grants.tokenFor(view, 'w2')).resolves.toBeNull() + + mintReply = good + await expect(grants.tokenFor(view, 'w2')).resolves.toBe(mintedJwt('w2')) + expect(mintRequests).toEqual(['w2', 'w2']) + }) + it('a token the view already holds keeps working through a kill until it expires', async () => { await activeOnW2() await grants.tokenFor(view, 'w2') From 642e9a985cc1b95b173cf8850a64c9c125c9603b Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 22:47:10 -0500 Subject: [PATCH 24/75] fix(auth): re-establish the wizard's workspace before refreshing its 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. --- .../src/views/InstallWizardModal.test.ts | 94 +++++++++++++++++++ src/renderer/src/views/InstallWizardModal.vue | 9 +- 2 files changed, 101 insertions(+), 2 deletions(-) diff --git a/src/renderer/src/views/InstallWizardModal.test.ts b/src/renderer/src/views/InstallWizardModal.test.ts index 404ce52e5..cd6db41f3 100644 --- a/src/renderer/src/views/InstallWizardModal.test.ts +++ b/src/renderer/src/views/InstallWizardModal.test.ts @@ -692,6 +692,100 @@ describe('InstallWizardModal workspace Builds', () => { ]) }) + describe('after Desktop returned to the anchor workspace', () => { + const readyBuild = { id: 'ready', name: 'Workspace Two Build', state: 'installable' } + + async function openOnW2ThenReturnToAnchor() { + signInToWorkspace([]) + let authChanged: (status: unknown) => void = () => {} + ;(window.api.comfybuilder.onAuthChanged as ReturnType).mockImplementation( + (callback: (status: unknown) => void) => { + authChanged = callback + return () => {} + } + ) + const switchWorkspace = window.api.comfybuilder.switchWorkspace as ReturnType + const listBuilds = window.api.comfybuilder.listBuilds as ReturnType + switchWorkspace.mockResolvedValue({ + signedIn: true, + workspaceId: 'w2', + workspaceType: 'team' + }) + listBuilds.mockResolvedValue([readyBuild]) + const wrapper = mountModal() + await flushPromises() + await ( + wrapper.vm as unknown as { open: (opts: { workspaceId: string }) => Promise } + ).open({ workspaceId: 'w2' }) + await flushPromises() + expect(wrapper.getComponent(BaseSelect).props('options')).toHaveLength(1) + authChanged({ signedIn: true, workspaceId: 'w1', workspaceType: 'team' }) + await flushPromises() + expect(wrapper.getComponent(BaseSelect).props('options')).toEqual([]) + switchWorkspace.mockClear() + listBuilds.mockClear() + return { wrapper, switchWorkspace, listBuilds } + } + + it('Refresh re-establishes the target workspace before fetching its Builds', async () => { + const { wrapper, switchWorkspace, listBuilds } = await openOnW2ThenReturnToAnchor() + + await wrapper.get('.workspace-build-refresh').trigger('click') + await flushPromises() + + expect(switchWorkspace).toHaveBeenCalledExactlyOnceWith('w2') + expect(listBuilds).toHaveBeenCalledOnce() + expect(switchWorkspace.mock.invocationCallOrder[0]).toBeLessThan( + listBuilds.mock.invocationCallOrder[0]! + ) + expect(wrapper.getComponent(BaseSelect).props('options')).toEqual([ + { value: 'ready', label: 'Workspace Two Build' } + ]) + }) + + it('Refresh fetches nothing for the anchor when the target cannot be re-established', async () => { + const { wrapper, switchWorkspace, listBuilds } = await openOnW2ThenReturnToAnchor() + switchWorkspace.mockResolvedValue({ + signedIn: true, + workspaceId: 'w1', + workspaceType: 'team', + workspaceSwitchFailure: 'retryable' + }) + + await wrapper.get('.workspace-build-refresh').trigger('click') + await flushPromises() + + expect(listBuilds).not.toHaveBeenCalled() + expect(wrapper.emitted('close')).toHaveLength(1) + }) + }) + + it('Refresh on the target workspace only fetches and keeps the selected Build', async () => { + signInToWorkspace([]) + const switchWorkspace = window.api.comfybuilder.switchWorkspace as ReturnType + switchWorkspace.mockResolvedValue({ signedIn: true, workspaceId: 'w2', workspaceType: 'team' }) + const listBuilds = window.api.comfybuilder.listBuilds as ReturnType + listBuilds.mockResolvedValue([ + { id: 'first', name: 'First', state: 'installable' }, + { id: 'second', name: 'Second', state: 'installable' } + ]) + const wrapper = mountModal() + await flushPromises() + await ( + wrapper.vm as unknown as { open: (opts: { workspaceId: string }) => Promise } + ).open({ workspaceId: 'w2' }) + await flushPromises() + wrapper.getComponent(BaseSelect).vm.$emit('update:modelValue', 'second') + await flushPromises() + switchWorkspace.mockClear() + + await wrapper.get('.workspace-build-refresh').trigger('click') + await flushPromises() + + expect(switchWorkspace).not.toHaveBeenCalled() + expect(wrapper.getComponent(BaseSelect).props('modelValue')).toBe('second') + }) + it('explains that a workspace switch may be waiting on browser authorization', async () => { signInToWorkspace([]) let finishAuthorization!: (status: { diff --git a/src/renderer/src/views/InstallWizardModal.vue b/src/renderer/src/views/InstallWizardModal.vue index 507aa7928..933d92b87 100644 --- a/src/renderer/src/views/InstallWizardModal.vue +++ b/src/renderer/src/views/InstallWizardModal.vue @@ -706,6 +706,11 @@ async function initializeManagedBuilds(gen: number, refreshBuilds: boolean): Pro } } +async function refreshManagedBuilds(): Promise { + if (authStore.status.workspaceId === managedWorkspaceId.value) await authStore.fetchBuilds() + else await initializeManagedBuilds(modeGeneration, true) +} + async function initializeLocalInstall(gen: number, requestedSource?: Source): Promise { void window.api .getUniqueName(DEFAULT_INSTALL_NAME) @@ -1382,7 +1387,7 @@ defineExpose({ open }) :title="$t('newInstall.refreshWorkspaceBuilds')" :aria-label="$t('newInstall.refreshWorkspaceBuilds')" :disabled="authStore.loadingBuilds" - @click="authStore.fetchBuilds()" + @click="refreshManagedBuilds" > {{ $t('devPlatform.build.loadError') }} From 2151ecd95feac2fe1e148b3580d9f6f05d4dddcb Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 23:02:04 -0500 Subject: [PATCH 25/75] fix(auth): treat a superseded switch as not completing a promotion 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. --- .../ipc/registerDevPlatformHandlers.test.ts | 195 ++++++++++++++++++ .../lib/ipc/registerDevPlatformHandlers.ts | 38 ++-- 2 files changed, 218 insertions(+), 15 deletions(-) diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts index 19372c223..729d78460 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts @@ -135,6 +135,7 @@ import type * as ViewGrantsModule from '../viewWorkspaceGrants' import { registerDevPlatformHandlers, signInToCloud, + signOutOfCloud, switchCloudWorkspace } from './registerDevPlatformHandlers' import { comfyWindows, type ComfyWindowEntry } from '../../host/registry' @@ -635,6 +636,200 @@ describe('registerDevPlatformHandlers', () => { }) }) + describe('promotion and a change of account', () => { + const jwt = (claims: Record): string => { + const b64 = (value: unknown): string => + Buffer.from(JSON.stringify(value)).toString('base64url') + return `${b64({ alg: 'ES256' })}.${b64(claims)}.sig` + } + const inB = { + id: 'local-1', + name: 'Local One', + sourceId: 'standalone', + workspaceId: 'B', + status: 'installed', + installPath: '/installs/local-1' + } + const auth = { active: 'A' as string | null, subject: 'user-1' as string | null, generation: 1 } + + function statusNow(): Record { + return auth.subject + ? { signedIn: true, workspaceId: auth.active, workspaceType: 'team' } + : { signedIn: false } + } + + async function realViewGrants() { + const { ViewWorkspaceGrants } = + await vi.importActual('../viewWorkspaceGrants') + const grants = new ViewWorkspaceGrants( + { + currentWorkspaceId: () => auth.active, + currentSubject: () => auth.subject, + currentAuthGeneration: () => auth.generation, + getGrantAccessToken: async () => + auth.subject + ? jwt({ sub: auth.subject, workspace_id: 'home', scope: CLOUD_CONFIG.scope }) + : null, + isWorkspaceMintAllowed: async () => true + }, + async (_grant, workspaceId) => ({ + kind: 'minted', + token: jwt({ sub: auth.subject, workspace_id: workspaceId }), + expiresAt: Date.now() + 900_000 + }) + ) + grants.allowDesktop('A') + mocks.endViewGrants.mockImplementation(() => grants.endAll()) + mocks.allowDesktopWorkspace.mockImplementation((workspaceId) => + grants.allowDesktop(workspaceId) + ) + return grants + } + + beforeEach(() => { + auth.active = 'A' + auth.subject = 'user-1' + auth.generation = 1 + mocks.get.mockResolvedValue(inB) + mocks.status.mockImplementation(statusNow) + mocks.currentAuthGeneration.mockImplementation(() => auth.generation) + mocks.currentSubject.mockImplementation(() => auth.subject) + mocks.logout.mockImplementation(() => { + auth.generation += 1 + auth.subject = null + auth.active = null + }) + mocks.login.mockImplementation(async () => { + auth.generation += 1 + auth.subject = 'user-2' + auth.active = 'C' + return statusNow() + }) + }) + + afterEach(() => { + mocks.endViewGrants.mockReset() + mocks.allowDesktopWorkspace.mockReset() + mocks.currentAuthGeneration.mockReset().mockReturnValue(1) + mocks.currentSubject.mockReset().mockReturnValue('user-1') + mocks.status.mockReset() + mocks.logout.mockReset() + mocks.login.mockReset() + mocks.switchWorkspace.mockReset() + }) + + function pendingFirstSwitch(): (status: Record) => void { + let finish: (status: Record) => void = () => {} + mocks.switchWorkspace.mockImplementationOnce(() => { + auth.generation += 1 + return new Promise((resolve) => { + finish = resolve + }) + }) + return (status) => finish(status) + } + + function viewSwitchSucceeds(): void { + mocks.switchWorkspace.mockImplementationOnce(async (workspaceId: string) => { + auth.generation += 1 + auth.active = workspaceId + return statusNow() + }) + } + + it('a superseded switch completes nothing: no permission, no snapshot, no draft for the new account', async () => { + const grants = await realViewGrants() + const viewV = { id: 'view-v' } as unknown as WebContents + const otherView = { id: 'other-view' } as unknown as WebContents + const finishMint = pendingFirstSwitch() + + const promotion = handler('comfybuilder:promoteLocalInstance')({}, 'local-1') + await vi.waitFor(() => expect(mocks.switchWorkspace).toHaveBeenCalledOnce()) + + await signOutOfCloud(undefined) + await signInToCloud() + grants.allowView(viewV, 'B') + viewSwitchSucceeds() + await switchCloudWorkspace('B') + finishMint(statusNow()) + + await expect(promotion).resolves.toEqual({ + ok: false, + message: 'Could not activate the instance workspace.' + }) + await expect(grants.tokenFor(otherView, 'B')).resolves.toBeNull() + await expect(grants.tokenFor(viewV, 'B')).resolves.toBe( + jwt({ sub: 'user-2', workspace_id: 'B' }) + ) + expect(mocks.saveSnapshot).not.toHaveBeenCalled() + expect(mocks.createBuildDraft).not.toHaveBeenCalled() + expect(mocks.openExternal).not.toHaveBeenCalled() + }) + + it('does not start a switch for the old account after signing out while resolving the workspace', async () => { + mocks.get.mockResolvedValue({ ...inB, workspaceId: undefined }) + mocks.listWorkspaces.mockImplementation(async () => { + mocks.logout() + auth.subject = 'user-2' + auth.active = 'C' + return [{ id: 'personal-1', name: 'Personal', type: 'personal', role: 'owner' }] + }) + + await expect(handler('comfybuilder:promoteLocalInstance')({}, 'local-1')).resolves.toEqual({ + ok: false, + message: 'Could not activate the instance workspace.' + }) + + expect(mocks.switchWorkspace).not.toHaveBeenCalled() + }) + + it.each<[string, 'saveSnapshot' | 'createBuildDraft']>([ + ['capturing the snapshot', 'saveSnapshot'], + ['creating the draft', 'createBuildDraft'] + ])( + 'does not act for the old account when another signs in to the same workspace while %s', + async (_step, step) => { + auth.active = 'B' + mocks[step].mockImplementationOnce(async () => { + auth.subject = 'user-2' + auth.generation += 2 + return step === 'saveSnapshot' + ? 'fresh.json' + : { + buildId: 'build-2', + workspaceId: 'B', + editUrl: '/profile/builds/new?workspace=B&edit=build-2' + } + }) + + await expect(handler('comfybuilder:promoteLocalInstance')({}, 'local-1')).resolves.toEqual({ + ok: false, + message: 'The active workspace changed. Try again.' + }) + + expect(mocks.openExternal).not.toHaveBeenCalled() + if (step === 'saveSnapshot') expect(mocks.createBuildDraft).not.toHaveBeenCalled() + } + ) + + it('a joined switch to the same workspace still completes the promotion', async () => { + await realViewGrants() + mocks.switchWorkspace.mockImplementationOnce(async (workspaceId: string) => { + auth.active = workspaceId + return statusNow() + }) + mocks.createBuildDraft.mockResolvedValue({ + buildId: 'build-2', + workspaceId: 'B', + editUrl: '/profile/builds/new?workspace=B&edit=build-2' + }) + + await expect(handler('comfybuilder:promoteLocalInstance')({}, 'local-1')).resolves.toEqual({ + ok: true + }) + }) + }) + it('T-V27: an old switch finishing after another account took over changes no view permission', async () => { const jwt = (claims: Record): string => { const b64 = (value: unknown): string => diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.ts b/src/main/lib/ipc/registerDevPlatformHandlers.ts index 3af9cdb2d..cc04a7532 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.ts @@ -133,12 +133,9 @@ export async function signInToCloud(): Promise { return status } -/** - * Activate `workspaceId` and announce the result; `CloudSession` decides whether a browser is - * needed. A failure stays on this reply and off the broadcast. Shared by the chooser and the - * hosted ComfyUI view. - */ -export async function switchCloudWorkspace(workspaceId: string): Promise { +async function switchAndAnnounce( + workspaceId: string +): Promise<{ reply: WorkspaceSwitchStatus; superseded: boolean }> { const session = getCloudSession() const subjectBefore = session.currentSubject() clearVersionCache() @@ -147,15 +144,22 @@ export async function switchCloudWorkspace(workspaceId: string): Promise { + return (await switchAndAnnounce(workspaceId)).reply } /** @@ -291,6 +295,7 @@ export function registerDevPlatformHandlers(): void { } const status = session.status() if (!status.signedIn) return { ok: false, message: 'Not signed in.' } + const subject = session.currentSubject() let workspaceId: string | undefined if (!inst.workspaceId || inst.workspaceId === PERSONAL_WORKSPACE_ID) { workspaceId = @@ -302,8 +307,11 @@ export function registerDevPlatformHandlers(): void { } if (!workspaceId) return { ok: false, message: 'No active workspace.' } if (status.workspaceId !== workspaceId) { - const switched = await switchCloudWorkspace(workspaceId) - if (!switched.signedIn || switched.workspaceId !== workspaceId) { + if (session.currentSubject() !== subject) { + return { ok: false, message: 'Could not activate the instance workspace.' } + } + const { reply: switched, superseded } = await switchAndAnnounce(workspaceId) + if (superseded || !switched.signedIn || switched.workspaceId !== workspaceId) { return { ok: false, message: 'Could not activate the instance workspace.' } } getViewWorkspaceGrants().allowDesktop(workspaceId) @@ -322,7 +330,7 @@ export function registerDevPlatformHandlers(): void { ) { return { ok: false, message: 'The instance changed. Try again.' } } - if (session.status().workspaceId !== workspaceId) { + if (session.status().workspaceId !== workspaceId || session.currentSubject() !== subject) { return { ok: false, message: 'The active workspace changed. Try again.' } } @@ -339,7 +347,7 @@ export function registerDevPlatformHandlers(): void { ) { return { ok: false, message: 'The instance changed. Try again.' } } - if (session.status().workspaceId !== workspaceId) { + if (session.status().workspaceId !== workspaceId || session.currentSubject() !== subject) { return { ok: false, message: 'The active workspace changed. Try again.' } } // The portal's draft route receives a hand-off: it processes workspace From f13b8a6255f5d4ebfb07ee9acf8d26cf9e0c0732 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 23:04:10 -0500 Subject: [PATCH 26/75] fix(auth): derive a minted token's deadline from its own lifetime, not 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. --- src/main/cloud/claims.ts | 10 ++ src/main/cloud/session.test.ts | 22 ++++ src/main/cloud/workspaceToken.test.ts | 116 +++++++++++++++++- src/main/cloud/workspaceToken.ts | 15 ++- .../lib/viewWorkspaceGrants.session.test.ts | 25 ++++ 5 files changed, 184 insertions(+), 4 deletions(-) diff --git a/src/main/cloud/claims.ts b/src/main/cloud/claims.ts index 894c2fb05..1cc59aa2b 100644 --- a/src/main/cloud/claims.ts +++ b/src/main/cloud/claims.ts @@ -11,6 +11,8 @@ interface AccessTokenClaims { workspace_type?: string role?: string scope?: string + iat?: unknown + exp?: unknown } function decodeJwtPayload(token: string): AccessTokenClaims | null { @@ -56,6 +58,14 @@ export function canMintWorkspaceTokens(accessToken: string): boolean { return typeof scope === 'string' && scope.split(' ').includes(WORKSPACE_MINT_SCOPE) } +/** How long a token was issued for, in seconds, independent of any clock; null without usable claims. */ +export function lifetimeSecondsOf(accessToken: string): number | null { + const { iat, exp } = decodeJwtPayload(accessToken) ?? {} + if (typeof iat !== 'number' || typeof exp !== 'number') return null + const lifetime = exp - iat + return Number.isFinite(lifetime) ? lifetime : null +} + /** The account subject a token belongs to, or null for malformed/legacy tokens. */ export function subjectOf(accessToken: string): string | null { return decodeJwtPayload(accessToken)?.sub ?? null diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index 3d2f87fba..dd8d834c3 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -196,6 +196,7 @@ beforeEach(() => { }) afterEach(() => { + vi.useRealTimers() clearTokens() _resetForTest() fs.rmSync(electronState.userData, { recursive: true, force: true }) @@ -573,6 +574,27 @@ describe('CloudSession.switchWorkspace with no browser', () => { expect(signIn).not.toHaveBeenCalled() }) + it('a clock an hour ahead of the server still switches and keeps the token, with one mint', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + const serverNow = Date.now() + vi.setSystemTime(serverNow + 3_600_000) + saveGrant(grantOn('w1', { expiresAt: Date.now() + 3_600_000 })) + const token = jwt({ + sub: 'user-1', + workspace_id: 'w2', + iat: Math.floor(serverNow / 1000), + exp: Math.floor(serverNow / 1000) + 900 + }) + mintReply = () => json(200, { token, expires_at: new Date(serverNow + 900_000).toISOString() }) + const session = new CloudSession() + + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) + await expect(session.getAccessToken()).resolves.toBe(token) + + expect(mintRequests).toHaveLength(1) + expect(signIn).not.toHaveBeenCalled() + }) + it('re-mints an expired minted token on the next switch, with no browser', async () => { saveGrant(grantOn('w1')) const session = new CloudSession() diff --git a/src/main/cloud/workspaceToken.test.ts b/src/main/cloud/workspaceToken.test.ts index ba168514b..90cbdc7bb 100644 --- a/src/main/cloud/workspaceToken.test.ts +++ b/src/main/cloud/workspaceToken.test.ts @@ -1,5 +1,5 @@ // @vitest-environment node -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { classifyMint, mintWorkspaceToken } from './workspaceToken' import type { WorkspaceTokenMint } from './workspaceToken' @@ -99,6 +99,120 @@ describe('mintWorkspaceToken', () => { }) }) +describe('mintWorkspaceToken and the local clock', () => { + const SERVER_NOW_MS = Date.parse('2026-11-08T12:00:00Z') + const SERVER_NOW = SERVER_NOW_MS / 1000 + const HOUR_MS = 3_600_000 + const LIFETIME_MS = 900_000 + + function jwt(claims: Record): string { + const b64 = (value: unknown): string => + Buffer.from(JSON.stringify(value), 'utf-8').toString('base64url') + return `${b64({ alg: 'RS256' })}.${b64(claims)}.sig` + } + + function serverReply(claims: Record, expiresAtMs: number): void { + respond(200, { token: jwt(claims), expires_at: new Date(expiresAtMs).toISOString() }) + } + + function fifteenMinuteToken(): Record { + return { iat: SERVER_NOW, exp: SERVER_NOW + LIFETIME_MS / 1000 } + } + + beforeEach(() => { + vi.useFakeTimers({ toFake: ['Date'] }) + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it.each<[string, number]>([ + ['an hour ahead of', HOUR_MS], + ['a day ahead of', 24 * HOUR_MS], + ['an hour behind', -HOUR_MS], + ['matching', 0] + ])('a clock %s the server gets the token its real lifetime', async (_name, skewMs) => { + const clientNow = SERVER_NOW_MS + skewMs + vi.setSystemTime(clientNow) + serverReply(fifteenMinuteToken(), SERVER_NOW_MS + LIFETIME_MS) + + await expect(mintWorkspaceToken('oauth-access', 'ws-1')).resolves.toMatchObject({ + kind: 'minted', + expiresAt: clientNow + LIFETIME_MS + }) + }) + + it('a slow clock with transit time never stretches the token past its real validity', async () => { + const skewMs = -HOUR_MS + const clientStart = SERVER_NOW_MS + skewMs - 2_000 + vi.setSystemTime(clientStart) + vi.stubGlobal( + 'fetch', + vi.fn(async () => { + vi.setSystemTime(clientStart + 5_000) + return new Response( + JSON.stringify({ + token: jwt(fifteenMinuteToken()), + expires_at: new Date(SERVER_NOW_MS + LIFETIME_MS).toISOString() + }), + { status: 200 } + ) + }) + ) + const realExpiryOnClientClock = SERVER_NOW_MS + LIFETIME_MS + skewMs + + const mint = await mintWorkspaceToken('oauth-access', 'ws-1') + + expect(mint).toMatchObject({ kind: 'minted', expiresAt: clientStart + LIFETIME_MS }) + expect(mint.kind === 'minted' && mint.expiresAt).toBeLessThanOrEqual(realExpiryOnClientClock) + }) + + it('a parent-capped token keeps only its short lifetime', async () => { + vi.setSystemTime(SERVER_NOW_MS + HOUR_MS) + serverReply({ iat: SERVER_NOW, exp: SERVER_NOW + 30 }, SERVER_NOW_MS + 30_000) + + await expect(mintWorkspaceToken('oauth-access', 'ws-1')).resolves.toMatchObject({ + expiresAt: SERVER_NOW_MS + HOUR_MS + 30_000 + }) + }) + + it.each<[string, Record]>([ + ['a zero', { iat: SERVER_NOW, exp: SERVER_NOW }], + ['a negative', { iat: SERVER_NOW, exp: SERVER_NOW - 5 }] + ])('rejects %s lifetime even with a later expires_at', async (_name, claims) => { + vi.setSystemTime(SERVER_NOW_MS) + serverReply(claims, SERVER_NOW_MS + LIFETIME_MS) + + await expect(mintWorkspaceToken('oauth-access', 'ws-1')).resolves.toEqual({ + kind: 'failed', + status: 200 + }) + }) + + it.each<[string, Record]>([ + ['no iat', { exp: SERVER_NOW + 900 }], + ['no exp', { iat: SERVER_NOW }], + ['a non-numeric iat', { iat: 'now', exp: SERVER_NOW + 900 }], + ['no time claims', {}] + ])('a token with %s falls back to expires_at', async (_name, claims) => { + vi.setSystemTime(SERVER_NOW_MS) + const expiresAt = SERVER_NOW_MS + 120_000 + serverReply(claims, expiresAt) + + await expect(mintWorkspaceToken('oauth-access', 'ws-1')).resolves.toMatchObject({ + kind: 'minted', + expiresAt + }) + + serverReply(claims, SERVER_NOW_MS - 1) + await expect(mintWorkspaceToken('oauth-access', 'ws-1')).resolves.toEqual({ + kind: 'failed', + status: 200 + }) + }) +}) + describe('classifyMint', () => { const failed = (status: number | null, code?: string): WorkspaceTokenMint => ({ kind: 'failed', diff --git a/src/main/cloud/workspaceToken.ts b/src/main/cloud/workspaceToken.ts index bb96f6590..051e6cea0 100644 --- a/src/main/cloud/workspaceToken.ts +++ b/src/main/cloud/workspaceToken.ts @@ -1,4 +1,5 @@ /** Mints a workspace token at `POST {apiBase}/auth/token` with Desktop's OAuth access token. */ +import { lifetimeSecondsOf } from './claims' import { CLOUD_CONFIG } from './config' const DEFAULT_TIMEOUT_MS = 20_000 @@ -65,10 +66,17 @@ function retryAfterSecondsOf(res: Response): number | undefined { return Number.isFinite(seconds) && seconds >= 0 ? seconds : undefined } -function mintedFrom(body: unknown): WorkspaceTokenMint | null { +function mintedFrom(body: unknown, requestedAt: number): WorkspaceTokenMint | null { if (!body || typeof body !== 'object') return null const { token, expires_at: expiresAt } = body as { token?: unknown; expires_at?: unknown } - if (typeof token !== 'string' || token === '' || typeof expiresAt !== 'string') return null + if (typeof token !== 'string' || token === '') return null + const lifetimeSeconds = lifetimeSecondsOf(token) + if (lifetimeSeconds !== null) { + return lifetimeSeconds > 0 + ? { kind: 'minted', token, expiresAt: requestedAt + lifetimeSeconds * 1000 } + : null + } + if (typeof expiresAt !== 'string') return null const expiresAtMs = Date.parse(expiresAt) return expiresAtMs > Date.now() ? { kind: 'minted', token, expiresAt: expiresAtMs } : null } @@ -79,6 +87,7 @@ export async function mintWorkspaceToken( options: MintWorkspaceTokenOptions = {} ): Promise { const base = (options.apiBase ?? CLOUD_CONFIG.apiBase).replace(/\/+$/, '') + const requestedAt = Date.now() let res: Response try { res = await fetch(`${base}/auth/token`, { @@ -95,7 +104,7 @@ export async function mintWorkspaceToken( return { kind: 'failed', status: null } } const body: unknown = await res.json().catch(() => null) - if (res.ok) return mintedFrom(body) ?? { kind: 'failed', status: res.status } + if (res.ok) return mintedFrom(body, requestedAt) ?? { kind: 'failed', status: res.status } const code = errorCodeOf(body) const retryAfterSeconds = retryAfterSecondsOf(res) return { diff --git a/src/main/lib/viewWorkspaceGrants.session.test.ts b/src/main/lib/viewWorkspaceGrants.session.test.ts index c83d1eec1..996556c28 100644 --- a/src/main/lib/viewWorkspaceGrants.session.test.ts +++ b/src/main/lib/viewWorkspaceGrants.session.test.ts @@ -91,6 +91,7 @@ beforeEach(() => { }) afterEach(() => { + vi.useRealTimers() clearTokens() _resetForTest() fs.rmSync(electronState.userData, { recursive: true, force: true }) @@ -153,6 +154,30 @@ describe('view token path through a real session', () => { expect(mintRequests).toEqual(['w2', 'w2']) }) + it('a clock an hour ahead of the server still delivers a view token, with one mint', async () => { + await activeOnW2() + vi.useFakeTimers({ toFake: ['Date'] }) + const serverNow = Date.now() + vi.setSystemTime(serverNow + 3_600_000) + saveGrant({ ...GRANT, expiresAt: Date.now() + 3_600_000 }) + const token = jwt({ + sub: 'user-1', + workspace_id: 'w2', + iat: Math.floor(serverNow / 1000), + exp: Math.floor(serverNow / 1000) + 900 + }) + mintReply = () => + new Response( + JSON.stringify({ token, expires_at: new Date(serverNow + 900_000).toISOString() }), + { status: 200 } + ) + + await expect(grants.tokenFor(view, 'w2')).resolves.toBe(token) + await expect(grants.tokenFor(view, 'w2')).resolves.toBe(token) + + expect(mintRequests).toEqual(['w2']) + }) + it('a token the view already holds keeps working through a kill until it expires', async () => { await activeOnW2() await grants.tokenFor(view, 'w2') From ddc1544f9ed4924ba5fc51a1b39106119ca00ea2 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 23:18:17 -0500 Subject: [PATCH 27/75] fix(auth): refuse a minted token whose deadline passed before the reply 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. --- src/main/cloud/session.test.ts | 24 ++++++++++ src/main/cloud/workspaceToken.test.ts | 45 +++++++++++++++++++ src/main/cloud/workspaceToken.ts | 5 ++- .../lib/viewWorkspaceGrants.session.test.ts | 24 ++++++++++ 4 files changed, 96 insertions(+), 2 deletions(-) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index dd8d834c3..defdfb8b3 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -595,6 +595,30 @@ describe('CloudSession.switchWorkspace with no browser', () => { expect(signIn).not.toHaveBeenCalled() }) + it('refuses a real JWT whose deadline passed in transit: nothing is stored or activated', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + saveGrant(grantOn('w1', { expiresAt: Date.now() + 3_600_000 })) + mintReply = ({ workspaceId }) => { + const now = Math.floor(Date.now() / 1000) + const reply = json(200, { + token: jwt({ sub: 'user-1', workspace_id: workspaceId, iat: now, exp: now + 30 }), + expires_at: new Date(Date.now() + 30_000).toISOString() + }) + vi.setSystemTime(Date.now() + 60_000) + return reply + } + const session = new CloudSession() + + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w1', + workspaceSwitchFailure: 'retryable' + }) + + expect(session.currentWorkspaceId()).toBe('w1') + expect(vaultOnDisk().workspaceTokens).toEqual({}) + expect(signIn).not.toHaveBeenCalled() + }) + it('re-mints an expired minted token on the next switch, with no browser', async () => { saveGrant(grantOn('w1')) const session = new CloudSession() diff --git a/src/main/cloud/workspaceToken.test.ts b/src/main/cloud/workspaceToken.test.ts index 90cbdc7bb..d1b7b8665 100644 --- a/src/main/cloud/workspaceToken.test.ts +++ b/src/main/cloud/workspaceToken.test.ts @@ -190,6 +190,51 @@ describe('mintWorkspaceToken and the local clock', () => { }) }) + it('rejects a zero lifetime even when the clock steps back during the request', async () => { + vi.setSystemTime(SERVER_NOW_MS) + vi.stubGlobal( + 'fetch', + vi.fn(async () => { + vi.setSystemTime(SERVER_NOW_MS - 60_000) + return new Response( + JSON.stringify({ + token: jwt({ iat: SERVER_NOW, exp: SERVER_NOW }), + expires_at: new Date(SERVER_NOW_MS).toISOString() + }), + { status: 200 } + ) + }) + ) + + await expect(mintWorkspaceToken('oauth-access', 'ws-1')).resolves.toEqual({ + kind: 'failed', + status: 200 + }) + }) + + it('rejects a positive lifetime whose deadline passed before the reply arrived', async () => { + const clientStart = SERVER_NOW_MS + HOUR_MS + vi.setSystemTime(clientStart) + vi.stubGlobal( + 'fetch', + vi.fn(async () => { + vi.setSystemTime(clientStart + 30_000) + return new Response( + JSON.stringify({ + token: jwt({ iat: SERVER_NOW, exp: SERVER_NOW + 30 }), + expires_at: new Date(SERVER_NOW_MS + 30_000).toISOString() + }), + { status: 200 } + ) + }) + ) + + await expect(mintWorkspaceToken('oauth-access', 'ws-1')).resolves.toEqual({ + kind: 'failed', + status: 200 + }) + }) + it.each<[string, Record]>([ ['no iat', { exp: SERVER_NOW + 900 }], ['no exp', { iat: SERVER_NOW }], diff --git a/src/main/cloud/workspaceToken.ts b/src/main/cloud/workspaceToken.ts index 051e6cea0..913dff513 100644 --- a/src/main/cloud/workspaceToken.ts +++ b/src/main/cloud/workspaceToken.ts @@ -72,8 +72,9 @@ function mintedFrom(body: unknown, requestedAt: number): WorkspaceTokenMint | nu if (typeof token !== 'string' || token === '') return null const lifetimeSeconds = lifetimeSecondsOf(token) if (lifetimeSeconds !== null) { - return lifetimeSeconds > 0 - ? { kind: 'minted', token, expiresAt: requestedAt + lifetimeSeconds * 1000 } + const deadline = requestedAt + lifetimeSeconds * 1000 + return lifetimeSeconds > 0 && deadline > Date.now() + ? { kind: 'minted', token, expiresAt: deadline } : null } if (typeof expiresAt !== 'string') return null diff --git a/src/main/lib/viewWorkspaceGrants.session.test.ts b/src/main/lib/viewWorkspaceGrants.session.test.ts index 996556c28..5ec3e41d6 100644 --- a/src/main/lib/viewWorkspaceGrants.session.test.ts +++ b/src/main/lib/viewWorkspaceGrants.session.test.ts @@ -154,6 +154,30 @@ describe('view token path through a real session', () => { expect(mintRequests).toEqual(['w2', 'w2']) }) + it('refuses to deliver or cache a real JWT whose deadline passed in transit', async () => { + await activeOnW2() + const good = mintReply + vi.useFakeTimers({ toFake: ['Date'] }) + mintReply = (workspaceId) => { + const now = Math.floor(Date.now() / 1000) + const reply = new Response( + JSON.stringify({ + token: jwt({ sub: 'user-1', workspace_id: workspaceId, iat: now, exp: now + 30 }), + expires_at: new Date(Date.now() + 30_000).toISOString() + }), + { status: 200 } + ) + vi.setSystemTime(Date.now() + 60_000) + return reply + } + + await expect(grants.tokenFor(view, 'w2')).resolves.toBeNull() + + mintReply = good + await expect(grants.tokenFor(view, 'w2')).resolves.toBe(mintedJwt('w2')) + expect(mintRequests).toEqual(['w2', 'w2']) + }) + it('a clock an hour ahead of the server still delivers a view token, with one mint', async () => { await activeOnW2() vi.useFakeTimers({ toFake: ['Date'] }) From 6ec9e41ecb45a7876dfb50bbe742b0d537ec6a4d Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 23:27:19 -0500 Subject: [PATCH 28/75] fix(auth): let views hold a workspace reached through browser consent 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. --- src/main/cloud/session.ts | 26 +- .../lib/ipc/registerDevPlatformHandlers.ts | 4 +- .../ipc/switchCloudWorkspace.session.test.ts | 223 ++++++++++++++++++ 3 files changed, 244 insertions(+), 9 deletions(-) create mode 100644 src/main/lib/ipc/switchCloudWorkspace.session.test.ts diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index 57ba5705a..c3b01bf62 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -48,6 +48,11 @@ export const WORKSPACE_SWITCH_BROWSER_EVENT = 'comfy.desktop.auth.workspace_swit /** Mirrored to Datadog: a token read could not renew the active workspace, so it went back to the anchor. */ export const WORKSPACE_RETURNED_TO_ANCHOR_EVENT = 'comfy.desktop.auth.workspace_returned_to_anchor' +/** What `switchWorkspace` resolves with. `reachedThroughConsent` is for main only and never crosses IPC. */ +export interface SessionSwitchReply extends WorkspaceSwitchStatus { + reachedThroughConsent?: true +} + type WorkspaceSwitchOutcome = | 'cached' | 'anchor' @@ -103,7 +108,7 @@ function reportBrowser(outcome: WorkspaceSwitchOutcome, reason: BrowserReason): export class CloudSession { private readonly refreshing = new Map>() private readonly minting = new Map>() - private switching: { workspaceId: string; result: Promise } | null = null + private switching: { workspaceId: string; result: Promise } | null = null private mintBlockedUntil = 0 private loginInFlight: Promise | null = null private loginAuthorizeUrl: string | null = null @@ -361,7 +366,7 @@ export class CloudSession { /** Activate `workspaceId`. Only a refused grant, an SSO policy, a missing mint scope or a * mint kill switch opens the browser; every other failure stays put and says so. */ - switchWorkspace(workspaceId: string): Promise { + switchWorkspace(workspaceId: string): Promise { if (this.switching?.workspaceId === workspaceId) return this.switching.result this.clearPendingLogin() const generation = ++this.authGeneration @@ -372,7 +377,7 @@ export class CloudSession { return result } - private async runSwitch(workspaceId: string, generation: number): Promise { + private async runSwitch(workspaceId: string, generation: number): Promise { const grant = loadGrant() if (!grant) return this.status() if (workspaceId === workspaceIdOf(grant.accessToken)) { @@ -408,7 +413,7 @@ export class CloudSession { workspaceId: string, generation: number, grant: AuthTokens - ): Promise { + ): Promise { if (!isFresh(grant)) { const refreshed = await this.refreshGrant(grant) if (generation !== this.authGeneration) return this.status() @@ -435,7 +440,7 @@ export class CloudSession { workspaceId: string, generation: number, reason: ReauthorizeReason - ): Promise { + ): Promise { reportBrowser('browser', reason) let tokens: AuthTokens try { @@ -451,9 +456,9 @@ export class CloudSession { if (!canMint) reportBrowser(isAnchor ? 'anchor' : 'retryable', 'scope_not_granted') if (isAnchor) { activateWorkspace(workspaceId) - return this.status() + return this.afterConsent(this.status(), tokens) } - if (!canMint) return this.stayed('retryable') + if (!canMint) return this.afterConsent(this.stayed('retryable'), tokens) const outcome = await this.mintForWorkspace(workspaceId, generation) if (generation !== this.authGeneration) return this.status() @@ -462,7 +467,12 @@ export class CloudSession { return this.status() } const unavailable = outcome.kind === 'unavailable' || outcome.kind === 'refused' - return this.stayed(unavailable ? 'unavailable' : 'retryable') + return this.afterConsent(this.stayed(unavailable ? 'unavailable' : 'retryable'), tokens) + } + + private afterConsent(reply: WorkspaceSwitchStatus, tokens: AuthTokens): SessionSwitchReply { + const reached = loadActiveWorkspaceId() === workspaceIdOf(tokens.accessToken) + return reached ? { ...reply, reachedThroughConsent: true } : reply } /** Adapter for the comfy-builder client's auth seam. */ diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.ts b/src/main/lib/ipc/registerDevPlatformHandlers.ts index cc04a7532..d7b833a1b 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.ts @@ -141,13 +141,15 @@ async function switchAndAnnounce( clearVersionCache() const switching = session.switchWorkspace(workspaceId) const generation = session.currentAuthGeneration() - const reply = await switching + const { reachedThroughConsent, ...reply } = await switching clearVersionCache() const { workspaceSwitchFailure: _failure, ...status } = reply const superseded = session.currentAuthGeneration() !== generation if (!superseded && session.currentSubject() !== subjectBefore) { getViewWorkspaceGrants().endAll() getViewWorkspaceGrants().allowDesktop(status.workspaceId) + } else if (reachedThroughConsent) { + getViewWorkspaceGrants().allowDesktop(status.workspaceId) } broadcastAuthChanged(status) return { reply, superseded } diff --git a/src/main/lib/ipc/switchCloudWorkspace.session.test.ts b/src/main/lib/ipc/switchCloudWorkspace.session.test.ts new file mode 100644 index 000000000..74cf98df3 --- /dev/null +++ b/src/main/lib/ipc/switchCloudWorkspace.session.test.ts @@ -0,0 +1,223 @@ +// @vitest-environment node +import * as fs from 'node:fs' +import * as os from 'node:os' +import * as path from 'node:path' + +import type { WebContents } from 'electron' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const state = vi.hoisted(() => ({ + userData: '', + session: null as unknown, + windows: [] as unknown[] +})) + +vi.mock('electron', () => ({ + app: { getPath: vi.fn(() => state.userData) }, + safeStorage: { + isEncryptionAvailable: vi.fn(() => true), + encryptString: vi.fn((value: string) => Buffer.from(value, 'utf-8')), + decryptString: vi.fn((value: Buffer) => value.toString('utf-8')) + }, + BrowserWindow: { getAllWindows: () => state.windows }, + ipcMain: { handle: vi.fn() }, + shell: { openExternal: vi.fn(async () => {}) } +})) +vi.mock('../../cloud/oauth', () => ({ + signIn: vi.fn(), + refresh: vi.fn(), + openAuthorizePage: vi.fn(async () => {}) +})) +vi.mock('../../devplatform/session', () => ({ + getCloudSession: () => state.session, + getBuilderClient: vi.fn(), + setUnauthorizedHandler: vi.fn() +})) +vi.mock('../../devplatform/builds', () => ({ + resolveHost: vi.fn(), + resolveBuildRows: vi.fn(), + resolveHostArtifact: vi.fn(), + resolveSelectedHostArtifact: vi.fn() +})) +vi.mock('../../devplatform/versionCache', () => ({ + clearVersionCache: vi.fn(), + getVersionCacheGeneration: vi.fn(() => 0) +})) +vi.mock('../../popups/systemModal', () => ({ openSystemModalAsync: vi.fn() })) +vi.mock('./shared', () => ({ + installations: {}, + defaultInstallDir: vi.fn(), + sourceMap: {}, + saveSnapshot: vi.fn(), + loadSnapshot: vi.fn(), + getSnapshotCount: vi.fn(), + buildExportEnvelope: vi.fn(), + _broadcastToRenderer: vi.fn(), + _operationAborts: new Map(), + i18n: { t: (key: string) => key } +})) +vi.mock('../telemetry', () => ({ emit: vi.fn() })) +vi.mock('../embeddedSessionFlag', () => ({ isEmbeddedSessionEnabled: async () => false })) +vi.mock('../workspaceMintSwitchFlag', () => ({ isWorkspaceMintSwitchEnabled: async () => true })) + +import { CLOUD_CONFIG } from '../../cloud/config' +import { refresh, signIn } from '../../cloud/oauth' +import { CloudSession } from '../../cloud/session' +import { SignInFailure } from '../../cloud/signInFailure' +import { _resetForTest, clearTokens, saveGrant } from '../../cloud/tokenStore' +import type { AuthTokens } from '../../cloud/types' +import { _resetForTest as resetViewGrants, getViewWorkspaceGrants } from '../viewWorkspaceGrants' +import { switchCloudWorkspace } from './registerDevPlatformHandlers' + +const FUTURE = Date.now() + 3_600_000 +const PAST = Date.now() - 1_000 +const viewV = { id: 'view-v' } as unknown as WebContents +const otherView = { id: 'other-view' } as unknown as WebContents + +function jwt(claims: Record): string { + const b64 = (value: unknown): string => + Buffer.from(JSON.stringify(value), 'utf-8').toString('base64url') + return `${b64({ alg: 'RS256' })}.${b64(claims)}.sig` +} + +function grantOn(workspaceId: string, expiresAt = FUTURE): AuthTokens { + return { + accessToken: jwt({ sub: 'user-1', workspace_id: workspaceId, scope: CLOUD_CONFIG.scope }), + refreshToken: `refresh-${workspaceId}`, + expiresAt + } +} + +function mintedJwt(workspaceId: string): string { + return jwt({ sub: 'user-1', workspace_id: workspaceId }) +} + +function consented(tokens: AuthTokens): Awaited> { + return { tokens, status: { signedIn: true } } +} + +function minted(workspaceId: string): Response { + return new Response( + JSON.stringify({ token: mintedJwt(workspaceId), expires_at: new Date(FUTURE).toISOString() }), + { status: 200 } + ) +} + +let mintReply: (workspaceId: string) => Response +let send: ReturnType + +beforeEach(() => { + state.userData = fs.mkdtempSync(path.join(os.tmpdir(), 'switch-cloud-workspace-')) + _resetForTest() + resetViewGrants() + state.session = new CloudSession() + send = vi.fn() + state.windows = [{ webContents: { isDestroyed: () => false, send } }] + mintReply = minted + vi.stubGlobal( + 'fetch', + vi.fn(async (_url: string, init: RequestInit) => + mintReply((JSON.parse(String(init.body)) as { workspace_id: string }).workspace_id) + ) + ) +}) + +afterEach(() => { + clearTokens() + _resetForTest() + fs.rmSync(state.userData, { recursive: true, force: true }) + vi.unstubAllGlobals() + vi.clearAllMocks() + vi.mocked(signIn).mockReset() + vi.mocked(refresh).mockReset() +}) + +describe('switchCloudWorkspace with a real session, vault and view grants', () => { + it('consent landing on another workspace of the same account leaves views a usable token', async () => { + saveGrant(grantOn('A', PAST)) + getViewWorkspaceGrants().allowDesktop('A') + vi.mocked(refresh).mockRejectedValue( + new SignInFailure('refused', 'server_error', { + httpStatus: 400, + oauthError: 'invalid_grant' + }) + ) + vi.mocked(signIn).mockResolvedValue(consented(grantOn('C'))) + mintReply = (workspaceId) => + workspaceId === 'B' ? new Response('{}', { status: 404 }) : minted(workspaceId) + + const reply = await switchCloudWorkspace('B') + + expect(reply).toMatchObject({ workspaceId: 'C', workspaceSwitchFailure: 'unavailable' }) + expect(signIn).toHaveBeenCalledOnce() + await expect(getViewWorkspaceGrants().tokenFor(viewV, 'C')).resolves.toBe(mintedJwt('C')) + await expect(getViewWorkspaceGrants().tokenFor(otherView, 'C')).resolves.toBe(mintedJwt('C')) + }) + + it('consent on the requested workspace lets every view hold it', async () => { + saveGrant(grantOn('A')) + getViewWorkspaceGrants().allowDesktop('A') + mintReply = () => new Response(JSON.stringify({ code: 'sso_required' }), { status: 403 }) + vi.mocked(signIn).mockResolvedValue(consented(grantOn('X'))) + + await switchCloudWorkspace('X') + mintReply = minted + + await expect(getViewWorkspaceGrants().tokenFor(otherView, 'X')).resolves.toBe(mintedJwt('X')) + }) + + it('a view switch that mints stays isolated to that view', async () => { + saveGrant(grantOn('A')) + getViewWorkspaceGrants().allowDesktop('A') + getViewWorkspaceGrants().allowView(viewV, 'X') + + await expect(switchCloudWorkspace('X')).resolves.toMatchObject({ workspaceId: 'X' }) + + await expect(getViewWorkspaceGrants().tokenFor(viewV, 'X')).resolves.toBe(mintedJwt('X')) + await expect(getViewWorkspaceGrants().tokenFor(otherView, 'X')).resolves.toBeNull() + expect(signIn).not.toHaveBeenCalled() + }) + + it('a view switch that mints after a browser trip stays isolated to that view', async () => { + saveGrant(grantOn('A')) + getViewWorkspaceGrants().allowDesktop('A') + getViewWorkspaceGrants().allowView(viewV, 'X') + let replies = 0 + mintReply = (workspaceId) => + replies++ === 0 + ? new Response(JSON.stringify({ code: 'sso_required' }), { status: 403 }) + : minted(workspaceId) + vi.mocked(signIn).mockResolvedValue(consented(grantOn('C'))) + + await expect(switchCloudWorkspace('X')).resolves.toMatchObject({ workspaceId: 'X' }) + + await expect(getViewWorkspaceGrants().tokenFor(viewV, 'X')).resolves.toBe(mintedJwt('X')) + await expect(getViewWorkspaceGrants().tokenFor(otherView, 'X')).resolves.toBeNull() + }) + + it('a re-anchored grant that stays on the old workspace widens nothing', async () => { + saveGrant(grantOn('A')) + getViewWorkspaceGrants().allowDesktop('A') + mintReply = () => new Response(JSON.stringify({ code: 'sso_required' }), { status: 403 }) + vi.mocked(signIn).mockResolvedValue(consented(grantOn('C'))) + const allowDesktop = vi.spyOn(getViewWorkspaceGrants(), 'allowDesktop') + + await expect(switchCloudWorkspace('X')).resolves.toMatchObject({ + workspaceId: 'A', + workspaceSwitchFailure: 'retryable' + }) + + expect(allowDesktop).not.toHaveBeenCalled() + }) + + it('keeps the internal consent marker off the reply and the broadcast', async () => { + saveGrant(grantOn('A')) + mintReply = () => new Response(JSON.stringify({ code: 'sso_required' }), { status: 403 }) + vi.mocked(signIn).mockResolvedValue(consented(grantOn('X'))) + + const reply = await switchCloudWorkspace('X') + + expect(reply).not.toHaveProperty('reachedThroughConsent') + expect(send.mock.calls[0]?.[1]).not.toHaveProperty('reachedThroughConsent') + }) +}) From 0c693ff100ebdc4fd010a3de39dac12557af1743 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 23:28:23 -0500 Subject: [PATCH 29/75] fix(auth): count one workspace_switch_browser per real browser trip 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. --- src/main/cloud/session.test.ts | 17 +++++++++++------ src/main/cloud/session.ts | 12 ++++++------ 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index defdfb8b3..2b956daea 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -1301,10 +1301,7 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { { outcome: 'browser', reauthorize_reason: 'mint_scope_missing' }, { outcome: 'retryable', reauthorize_reason: 'scope_not_granted' } ]) - expect(browserEvents()).toEqual([ - { reauthorize_reason: 'mint_scope_missing' }, - { reauthorize_reason: 'scope_not_granted' } - ]) + expect(browserEvents()).toEqual([{ reauthorize_reason: 'mint_scope_missing' }]) }) it('a second and third switch after a scopeless sign-in stay put with no browser', async () => { @@ -1500,7 +1497,11 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { }) expect(signIn).toHaveBeenCalledOnce() - expect(browserEvents()).toContainEqual({ reauthorize_reason: 'scope_not_granted' }) + expect(switchEvents()).toContainEqual({ + outcome: 'retryable', + reauthorize_reason: 'scope_not_granted' + }) + expect(browserEvents()).toEqual([{ reauthorize_reason: 'sso_required' }]) }) it('a scopeless grant consented on B activates B, since an anchor needs no mint', async () => { @@ -1512,7 +1513,11 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { expect(reply).toMatchObject({ workspaceId: 'w2' }) expect(reply).not.toHaveProperty('workspaceSwitchFailure') expect(signIn).toHaveBeenCalledOnce() - expect(browserEvents()).toContainEqual({ reauthorize_reason: 'scope_not_granted' }) + expect(switchEvents()).toContainEqual({ + outcome: 'anchor', + reauthorize_reason: 'scope_not_granted' + }) + expect(browserEvents()).toEqual([{ reauthorize_reason: 'mint_scope_missing' }]) }) }) diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index c3b01bf62..01843e648 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -62,7 +62,7 @@ type WorkspaceSwitchOutcome = | 'retryable' | 'refused' -type BrowserReason = ReauthorizeReason | 'scope_not_granted' +type SwitchReason = ReauthorizeReason | 'scope_not_granted' type GrantRefresh = 'refreshed' | 'ended' | 'unavailable' @@ -93,15 +93,15 @@ function refreshFailureOutcome(refreshed: GrantRefresh): SettledMintOutcome { return refreshed === 'ended' ? { kind: 'reauthorize', reason: 'grant_ended' } : RETRYABLE } -function reportSwitch(outcome: WorkspaceSwitchOutcome, reason?: BrowserReason): void { +function reportSwitch(outcome: WorkspaceSwitchOutcome, reason?: SwitchReason): void { mainTelemetry.emit( WORKSPACE_SWITCH_EVENT, reason ? { outcome, reauthorize_reason: reason } : { outcome } ) } -function reportBrowser(outcome: WorkspaceSwitchOutcome, reason: BrowserReason): void { - reportSwitch(outcome, reason) +function reportBrowser(reason: ReauthorizeReason): void { + reportSwitch('browser', reason) mainTelemetry.emit(WORKSPACE_SWITCH_BROWSER_EVENT, { reauthorize_reason: reason }) } @@ -441,7 +441,7 @@ export class CloudSession { generation: number, reason: ReauthorizeReason ): Promise { - reportBrowser('browser', reason) + reportBrowser(reason) let tokens: AuthTokens try { ;({ tokens } = await signIn({ workspaceId })) @@ -453,7 +453,7 @@ export class CloudSession { const canMint = canMintWorkspaceTokens(tokens.accessToken) const isAnchor = workspaceId === workspaceIdOf(tokens.accessToken) - if (!canMint) reportBrowser(isAnchor ? 'anchor' : 'retryable', 'scope_not_granted') + if (!canMint) reportSwitch(isAnchor ? 'anchor' : 'retryable', 'scope_not_granted') if (isAnchor) { activateWorkspace(workspaceId) return this.afterConsent(this.status(), tokens) From 57123ae3c371b4d3082b25d01bda02db6bdaa7ea Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 23:41:28 -0500 Subject: [PATCH 30/75] fix(auth): never hand back a token after the account or workspace changed 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. --- src/main/cloud/session.test.ts | 112 +++++++++++++++++++++++++++++++++ src/main/cloud/session.ts | 33 +++++++--- 2 files changed, 137 insertions(+), 8 deletions(-) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index 2b956daea..b3c01233d 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -790,6 +790,118 @@ describe('CloudSession.switchWorkspace with no browser', () => { expect(mintRequests).toHaveLength(1) }) + describe('a token read pending while a consent changes the account in the same generation', () => { + async function readPendingWhileAccountChanges(lateReply: () => Response | Promise) { + saveGrant(grantOn('w1')) + const session = new CloudSession() + await session.switchWorkspace('w2') + saveWorkspaceToken('w2', { accessToken: mintedJwt('w2'), expiresAt: Date.now() + 30_000 }) + const late = deferred() + const pendingSignIn = deferred>>() + mocked(signIn).mockReturnValue(pendingSignIn.promise) + mintRequests = [] + mintReply = async ({ workspaceId }) => { + if (workspaceId === 'w3') return json(403, { code: 'sso_required' }) + await late.promise + return lateReply() + } + + const switching = session.switchWorkspace('w3') + await vi.waitFor(() => expect(signIn).toHaveBeenCalledOnce()) + const read = session.getAccessToken() + await vi.waitFor(() => expect(mintRequests).toHaveLength(2)) + pendingSignIn.resolve(signedInResult(grantOn('w3', { subject: 'user-2' }))) + await switching + late.resolve() + return { session, read } + } + + it.each<[string, () => Response]>([ + ['a 429', () => json(429, {})], + ['a 500', () => json(500, {})], + [ + 'a network failure', + () => { + throw new TypeError('offline') + } + ], + ['a refusal', () => json(404, {})], + ['a mint for the old account', () => minted('w2')] + ])('%s does not hand back the old account token', async (_name, reply) => { + const { session, read } = await readPendingWhileAccountChanges(reply) + + await expect(read).resolves.toBeNull() + + expect(session.currentSubject()).toBe('user-2') + expect(session.currentWorkspaceId()).toBe('w3') + }) + + it('a refresh landing after the account changed returns null from both token reads', async () => { + saveGrant(grantOn('w1', { expiresAt: Date.now() + 30_000 })) + const session = new CloudSession() + const rotation = deferred() + mocked(refresh).mockReturnValue(rotation.promise) + + const anchorRead = session.getAccessToken() + const grantRead = session.getGrantAccessToken() + saveGrant(grantOn('w3', { subject: 'user-2' })) + rotation.resolve(grantOn('w1', { revision: '-fresh' })) + + await expect(anchorRead).resolves.toBeNull() + await expect(grantRead).resolves.toBeNull() + }) + + it('a mint flight waiting on the policy never posts with the new account grant', async () => { + saveGrant(grantOn('w1')) + const session = new CloudSession() + await session.switchWorkspace('w2') + saveWorkspaceToken('w2', { accessToken: mintedJwt('w2'), expiresAt: PAST }) + const pendingSignIn = deferred>>() + mocked(signIn).mockReturnValue(pendingSignIn.promise) + mintRequests = [] + mintReply = ({ workspaceId }) => + workspaceId === 'w3' ? json(403, { code: 'sso_required' }) : minted(workspaceId) + const switching = session.switchWorkspace('w3') + await vi.waitFor(() => expect(signIn).toHaveBeenCalledOnce()) + const policy = deferred() + mocked(isWorkspaceMintSwitchEnabled).mockReturnValueOnce(policy.promise) + + const read = session.getAccessToken() + const newAccount = grantOn('w3', { subject: 'user-2' }) + pendingSignIn.resolve(signedInResult(newAccount)) + await switching + policy.resolve(true) + + await expect(read).resolves.toBeNull() + expect(mintRequests).not.toContainEqual({ + workspaceId: 'w2', + bearer: newAccount.accessToken + }) + }) + }) + + it('a token read does not return the old workspace token after the same account moved on', async () => { + saveGrant(grantOn('w1')) + const session = new CloudSession() + await session.switchWorkspace('w2') + saveWorkspaceToken('w2', { accessToken: mintedJwt('w2'), expiresAt: Date.now() + 30_000 }) + const slowB = deferred() + const slowC = deferred() + mintRequests = [] + mintReply = ({ workspaceId }) => (workspaceId === 'w2' ? slowB.promise : slowC.promise) + + const switching = session.switchWorkspace('w3') + await vi.waitFor(() => expect(mintRequests).toHaveLength(1)) + const read = session.getAccessToken() + await vi.waitFor(() => expect(mintRequests).toHaveLength(2)) + slowC.resolve(minted('w3')) + await switching + slowB.resolve(json(429, {})) + + await expect(read).resolves.toBeNull() + expect(session.currentWorkspaceId()).toBe('w3') + }) + it('rejects a minted token for another workspace or account', async () => { saveGrant(grantOn('w1')) mintReply = () => diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index 01843e648..ab2952a8f 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -207,8 +207,10 @@ export class CloudSession { async getGrantAccessToken(): Promise { const grant = loadGrant() if (!grant) return null - if (!isFresh(grant) && grant.refreshToken) await this.refreshGrant(grant) - return loadGrant()?.accessToken ?? null + if (isFresh(grant) || !grant.refreshToken) return grant.accessToken + const subject = subjectOf(grant.accessToken) + await this.refreshGrant(grant) + return this.currentSubject() === subject ? (loadGrant()?.accessToken ?? null) : null } /** The token for API calls in the active workspace, null when it cannot get one. @@ -217,11 +219,16 @@ export class CloudSession { const grant = loadGrant() if (!grant) return null const generation = this.authGeneration + const subject = subjectOf(grant.accessToken) const workspaceId = loadActiveWorkspaceId() + const unchanged = (): boolean => + generation === this.authGeneration && + subject === this.currentSubject() && + workspaceId === loadActiveWorkspaceId() if (!workspaceId || workspaceId === workspaceIdOf(grant.accessToken)) { if (isFresh(grant) || !grant.refreshToken) return grant.accessToken const refreshed = await this.refreshGrant(grant) - if (generation !== this.authGeneration) return null + if (!unchanged()) return null if (refreshed === 'unavailable' && isExpired(grant)) return null return loadGrant()?.accessToken ?? null } @@ -229,7 +236,7 @@ export class CloudSession { if (held && isFresh(held)) return held.accessToken const outcome = await this.mintForWorkspace(workspaceId, generation) - if (generation !== this.authGeneration) return null + if (!unchanged()) return null if (outcome.kind === 'minted') return outcome.token if (held && held.expiresAt > Date.now()) return held.accessToken if (outcome.kind !== 'retryable') this.returnToAnchor(workspaceId, outcome) @@ -306,6 +313,7 @@ export class CloudSession { workspaceId: string, generation: number ): Promise { + const subject = this.currentSubject() if (!(await this.isWorkspaceMintAllowed(workspaceId))) { return { kind: 'reauthorize', reason: 'mint_disabled' } } @@ -318,7 +326,7 @@ export class CloudSession { if (refreshed === 'ended' || (refreshed === 'unavailable' && isExpired(grant))) return refreshFailureOutcome(refreshed) } - const first = await this.postMint(workspaceId, generation) + const first = await this.postMint(workspaceId, generation, subject) if ( first.kind !== 'unauthorized' && !(first.kind === 'reauthorize' && first.reason === 'grant_ended') @@ -328,13 +336,22 @@ export class CloudSession { if (!current) return RETRYABLE const refreshed = await this.refreshGrant(current) if (refreshed !== 'refreshed') return refreshFailureOutcome(refreshed) - const second = await this.postMint(workspaceId, generation) + const second = await this.postMint(workspaceId, generation, subject) return second.kind === 'unauthorized' ? RETRYABLE : second } - private async postMint(workspaceId: string, generation: number): Promise { + private async postMint( + workspaceId: string, + generation: number, + subject: string | null + ): Promise { const grant = loadGrant() - if (!grant || generation !== this.authGeneration || Date.now() < this.mintBlockedUntil) + if ( + !grant || + generation !== this.authGeneration || + subject !== subjectOf(grant.accessToken) || + Date.now() < this.mintBlockedUntil + ) return RETRYABLE const outcome = classifyMint(await mintWorkspaceToken(grant.accessToken, workspaceId)) if ( From 9b43ff5bf510552b39ee3b37f7df15516570ffe8 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 23:42:22 -0500 Subject: [PATCH 31/75] fix(auth): report a browser trip when the browser opens, not before sign-in starts A loopback bind or startup failure rejects before the browser opens, yet counted as a trip. Emit from onAuthorizeUrl, which runs right before the browser opens. A sign-in that fails earlier reports retryable with its reason and no browser event. --- src/main/cloud/oauth.test.ts | 17 +++++ src/main/cloud/session.test.ts | 126 ++++++++++++++++++++++----------- src/main/cloud/session.ts | 11 ++- 3 files changed, 110 insertions(+), 44 deletions(-) diff --git a/src/main/cloud/oauth.test.ts b/src/main/cloud/oauth.test.ts index 557b0a97b..c1f51942e 100644 --- a/src/main/cloud/oauth.test.ts +++ b/src/main/cloud/oauth.test.ts @@ -2,9 +2,15 @@ import { afterEach, describe, expect, it, vi } from 'vitest' vi.mock('electron', () => ({ shell: { openExternal: vi.fn(async () => {}) } })) +vi.mock('./loopback', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, startLoopbackListener: vi.fn(actual.startLoopbackListener) } +}) import { get } from 'node:http' import { shell } from 'electron' +import { startLoopbackListener } from './loopback' +import type * as LoopbackModule from './loopback' import { refresh, signIn } from './oauth' function stub(status: number, body: unknown): void { @@ -127,6 +133,17 @@ describe('oauth.signIn', () => { resource: 'https://c/api' } + it('announces no authorize URL and opens no browser when the listener cannot start', async () => { + vi.mocked(startLoopbackListener).mockRejectedValueOnce(new Error('address in use')) + vi.mocked(shell.openExternal).mockClear() + const onAuthorizeUrl = vi.fn() + + await expect(signIn({ onAuthorizeUrl })).rejects.toThrow('address in use') + + expect(onAuthorizeUrl).not.toHaveBeenCalled() + expect(shell.openExternal).not.toHaveBeenCalled() + }) + it('completes the flow when the browser opens and calls back', async () => { stub(200, { access_token: 'tok', refresh_token: 'r1', expires_in: 3600 }) vi.mocked(shell.openExternal).mockImplementation(async (authorizeUrl: string) => { diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index b3c01233d..7ebccfa50 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -129,6 +129,20 @@ function signedInResult(tokens: AuthTokens): Awaited> return { tokens, status: statusFromAccessToken(tokens.accessToken) } } +function browserSignInReturns(result: Awaited>): void { + mocked(signIn).mockImplementation(async (options) => { + options?.onAuthorizeUrl?.('https://cloud.test/authorize') + return result + }) +} + +function browserSignInReturnsOnce(result: Awaited>): void { + mocked(signIn).mockImplementationOnce(async (options) => { + options?.onAuthorizeUrl?.('https://cloud.test/authorize') + return result + }) +} + function deferred() { let resolve: (value: T) => void = () => {} const promise = new Promise((r) => { @@ -458,7 +472,7 @@ describe('CloudSession browser sign-in', () => { it('moves to the consented workspace on a fresh login', async () => { saveGrant(grantOn('w1')) - mocked(signIn).mockResolvedValue(signedInResult(grantOn('w3'))) + browserSignInReturns(signedInResult(grantOn('w3'))) const session = new CloudSession() await session.switchWorkspace('w2') @@ -516,7 +530,7 @@ describe('CloudSession browser sign-in', () => { describe('CloudSession.switchWorkspace with no browser', () => { it('T-V1: A to B to C to A signs in once and each new workspace is one mint', async () => { - mocked(signIn).mockResolvedValue(signedInResult(grantOn('wA'))) + browserSignInReturns(signedInResult(grantOn('wA'))) const session = new CloudSession() await session.login() @@ -648,7 +662,7 @@ describe('CloudSession.switchWorkspace with no browser', () => { it('shares one flight between concurrent switches to the same workspace', async () => { saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) - mocked(signIn).mockResolvedValue(signedInResult(grantOn('w2'))) + browserSignInReturns(signedInResult(grantOn('w2'))) const session = new CloudSession() await Promise.all([session.switchWorkspace('w2'), session.switchWorkspace('w2')]) @@ -935,12 +949,12 @@ describe('CloudSession.switchWorkspace reauthorize', () => { saveGrant(grantOn('w1')) mintReply = () => json(403, { code: 'sso_required' }) const sso = grantOn('w2', { revision: '-sso' }) - mocked(signIn).mockResolvedValue(signedInResult(sso)) + browserSignInReturns(signedInResult(sso)) const session = new CloudSession() await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) - expect(signIn).toHaveBeenCalledExactlyOnceWith({ workspaceId: 'w2' }) + expect(signIn).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ workspaceId: 'w2' })) expect(vaultOnDisk().grant).toEqual(sso) expect(switchEvents()).toEqual([{ outcome: 'browser', reauthorize_reason: 'sso_required' }]) expect(browserEvents()).toEqual([{ reauthorize_reason: 'sso_required' }]) @@ -952,7 +966,7 @@ describe('CloudSession.switchWorkspace reauthorize', () => { mintReply = ({ workspaceId }) => replies++ === 0 ? json(403, { code: 'sso_required' }) : minted(workspaceId) const consented = grantOn('w3') - mocked(signIn).mockResolvedValue(signedInResult(consented)) + browserSignInReturns(signedInResult(consented)) const session = new CloudSession() await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) @@ -971,14 +985,14 @@ describe('CloudSession.switchWorkspace reauthorize', () => { ? json(401, { message: 'workspace membership not found' }) : minted(workspaceId) mocked(refresh).mockRejectedValue(refreshRefused('invalid_client')) - mocked(signIn).mockResolvedValue(signedInResult(grantOn('w3'))) + browserSignInReturns(signedInResult(grantOn('w3'))) const session = new CloudSession() await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) await expect(session.switchWorkspace('w4')).resolves.toMatchObject({ workspaceId: 'w4' }) expect(refresh).toHaveBeenCalledOnce() - expect(signIn).toHaveBeenCalledExactlyOnceWith({ workspaceId: 'w2' }) + expect(signIn).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ workspaceId: 'w2' })) expect(browserEvents()).toEqual([{ reauthorize_reason: 'grant_ended' }]) }) @@ -1001,7 +1015,7 @@ describe('CloudSession.switchWorkspace reauthorize', () => { saveGrant(grantOn('w1')) mintReply = () => json(401, { code: 'oauth_grant_ended' }) mocked(refresh).mockResolvedValue(grantOn('w1', { revision: '-fresh' })) - mocked(signIn).mockResolvedValue(signedInResult(grantOn('w2'))) + browserSignInReturns(signedInResult(grantOn('w2'))) await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' @@ -1058,13 +1072,13 @@ describe('CloudSession.switchWorkspace reauthorize', () => { async (oauthError) => { saveGrant(grantOn('w1', { expiresAt: PAST })) mocked(refresh).mockRejectedValue(refreshRefused(oauthError)) - mocked(signIn).mockResolvedValue(signedInResult(grantOn('w2'))) + browserSignInReturns(signedInResult(grantOn('w2'))) await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) - expect(signIn).toHaveBeenCalledExactlyOnceWith({ workspaceId: 'w2' }) + expect(signIn).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ workspaceId: 'w2' })) } ) @@ -1101,13 +1115,13 @@ describe('CloudSession.switchWorkspace reauthorize', () => { it('switching to the anchor with a refused refresh opens one browser', async () => { saveGrant(grantOn('w1', { expiresAt: PAST })) mocked(refresh).mockRejectedValue(refreshRefused()) - mocked(signIn).mockResolvedValue(signedInResult(grantOn('w1', { revision: '-new' }))) + browserSignInReturns(signedInResult(grantOn('w1', { revision: '-new' }))) await expect(new CloudSession().switchWorkspace('w1')).resolves.toMatchObject({ workspaceId: 'w1' }) - expect(signIn).toHaveBeenCalledExactlyOnceWith({ workspaceId: 'w1' }) + expect(signIn).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ workspaceId: 'w1' })) }) it('switching to an expired anchor during a refresh outage stays put and reports retryable', async () => { @@ -1157,7 +1171,7 @@ describe('CloudSession.switchWorkspace reauthorize', () => { it('a second refusal after the browser trip does not open another', async () => { saveGrant(grantOn('w1')) mintReply = () => json(403, { code: 'sso_required' }) - mocked(signIn).mockResolvedValue(signedInResult(grantOn('w3'))) + browserSignInReturns(signedInResult(grantOn('w3'))) await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ workspaceSwitchFailure: 'retryable' @@ -1170,13 +1184,41 @@ describe('CloudSession.switchWorkspace reauthorize', () => { saveGrant(grantOn('w1')) let replies = 0 mintReply = () => (replies++ === 0 ? json(403, { code: 'sso_required' }) : json(404, {})) - mocked(signIn).mockResolvedValue(signedInResult(grantOn('w3'))) + browserSignInReturns(signedInResult(grantOn('w3'))) await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ workspaceSwitchFailure: 'unavailable' }) }) + it('a sign-in that fails before the browser opens reports no browser trip', async () => { + saveGrant(grantOn('w1')) + mintReply = () => json(403, { code: 'sso_required' }) + mocked(signIn).mockRejectedValue(new SignInFailure('address in use', 'network')) + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w1', + workspaceSwitchFailure: 'retryable' + }) + + expect(browserEvents()).toEqual([]) + expect(switchEvents()).toEqual([{ outcome: 'retryable', reauthorize_reason: 'sso_required' }]) + }) + + it('a sign-in cancelled after the browser opened counts as one browser trip', async () => { + saveGrant(grantOn('w1')) + mintReply = () => json(403, { code: 'sso_required' }) + mocked(signIn).mockImplementation(async (options) => { + options?.onAuthorizeUrl?.('https://cloud.test/authorize') + throw new SignInFailure('access_denied', 'cancelled') + }) + + await new CloudSession().switchWorkspace('w2') + + expect(browserEvents()).toEqual([{ reauthorize_reason: 'sso_required' }]) + expect(switchEvents()).toEqual([{ outcome: 'browser', reauthorize_reason: 'sso_required' }]) + }) + it('a cancelled browser trip stays put and reports retryable', async () => { saveGrant(grantOn('w1')) mintReply = () => json(403, { code: 'sso_required' }) @@ -1194,7 +1236,7 @@ describe('CloudSession.switchWorkspace reauthorize', () => { await held.switchWorkspace('w2') mintRequests = [] mintReply = () => json(403, { code: 'sso_required' }) - mocked(signIn).mockResolvedValue(signedInResult(grantOn('w9', { subject: 'user-2' }))) + browserSignInReturns(signedInResult(grantOn('w9', { subject: 'user-2' }))) await held.switchWorkspace('w3') @@ -1209,12 +1251,12 @@ describe('CloudSession mint kill switches', () => { saveGrant(grantOn('w1')) mintReply = mintDisabled const consented = grantOn('w2') - mocked(signIn).mockResolvedValue(signedInResult(consented)) + browserSignInReturns(signedInResult(consented)) const session = new CloudSession() await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) - expect(signIn).toHaveBeenCalledExactlyOnceWith({ workspaceId: 'w2' }) + expect(signIn).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ workspaceId: 'w2' })) expect(mintRequests).toHaveLength(1) expect(vaultOnDisk().grant).toEqual(consented) expect(switchEvents()).toEqual([{ outcome: 'browser', reauthorize_reason: 'mint_disabled' }]) @@ -1237,7 +1279,7 @@ describe('CloudSession mint kill switches', () => { const original = grantOn('w1') saveGrant(original) mintReply = mintDisabled - mocked(signIn).mockResolvedValue(signedInResult(grantOn('w3'))) + browserSignInReturns(signedInResult(grantOn('w3'))) const session = new CloudSession() await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ @@ -1253,20 +1295,20 @@ describe('CloudSession mint kill switches', () => { it('the ops flag off skips the mint and opens one browser carrying B', async () => { saveGrant(grantOn('w1')) killMintSwitch() - mocked(signIn).mockResolvedValue(signedInResult(grantOn('w2'))) + browserSignInReturns(signedInResult(grantOn('w2'))) const session = new CloudSession() await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) expect(mintRequests).toEqual([]) - expect(signIn).toHaveBeenCalledExactlyOnceWith({ workspaceId: 'w2' }) + expect(signIn).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ workspaceId: 'w2' })) expect(browserEvents()).toEqual([{ reauthorize_reason: 'mint_disabled' }]) }) it('no loop: the ops flag off and consent on another workspace opens no second browser', async () => { saveGrant(grantOn('w1')) killMintSwitch() - mocked(signIn).mockResolvedValue(signedInResult(grantOn('w3'))) + browserSignInReturns(signedInResult(grantOn('w3'))) const session = new CloudSession() await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ @@ -1327,7 +1369,7 @@ describe('CloudSession regressions', () => { ) ) _resetForTest() - mocked(signIn).mockResolvedValue(signedInResult(grantOn('w3'))) + browserSignInReturns(signedInResult(grantOn('w3'))) const session = new CloudSession() expect(session.status()).toMatchObject({ signedIn: true, workspaceId: 'w1' }) @@ -1375,12 +1417,12 @@ describe('CloudSession regressions', () => { describe('CloudSession grants without the mint scope (T-V29)', () => { it('opens exactly one browser, asks Cloud nothing first, and then mints', async () => { saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) - mocked(signIn).mockResolvedValue(signedInResult(grantOn('w3'))) + browserSignInReturns(signedInResult(grantOn('w3'))) const session = new CloudSession() await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) - expect(signIn).toHaveBeenCalledExactlyOnceWith({ workspaceId: 'w2' }) + expect(signIn).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ workspaceId: 'w2' })) expect(mintRequests).toHaveLength(1) expect(browserEvents()).toEqual([{ reauthorize_reason: 'mint_scope_missing' }]) }) @@ -1397,7 +1439,7 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { it('cannot loop: a sign-in that returns no scope stays put, reports retryable and is telemetered', async () => { saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) - mocked(signIn).mockResolvedValue( + browserSignInReturns( signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) ) const session = new CloudSession() @@ -1418,7 +1460,7 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { it('a second and third switch after a scopeless sign-in stay put with no browser', async () => { saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) - mocked(signIn).mockResolvedValue( + browserSignInReturns( signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) ) const session = new CloudSession() @@ -1443,7 +1485,7 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { it('a scopeless grant on B reaches its anchor and asks no browser for the next workspace', async () => { saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) - mocked(signIn).mockResolvedValue(signedInResult(grantOn('w2', { scope: READ_ONLY_SCOPE }))) + browserSignInReturns(signedInResult(grantOn('w2', { scope: READ_ONLY_SCOPE }))) const session = new CloudSession() await session.switchWorkspace('w2') @@ -1457,12 +1499,12 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { it('an explicit sign-in with the scope lifts the hold and switching mints again', async () => { saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) - mocked(signIn).mockResolvedValueOnce( + browserSignInReturnsOnce( signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) ) const session = new CloudSession() await session.switchWorkspace('w2') - mocked(signIn).mockResolvedValueOnce(signedInResult(grantOn('w1', { revision: '-scoped' }))) + browserSignInReturnsOnce(signedInResult(grantOn('w1', { revision: '-scoped' }))) await session.login() await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) @@ -1473,12 +1515,12 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { it('a grant that can mint lifts the hold, so one that later narrows can ask again', async () => { saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) - mocked(signIn).mockResolvedValueOnce( + browserSignInReturnsOnce( signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) ) const session = new CloudSession() await session.switchWorkspace('w2') - mocked(signIn).mockResolvedValueOnce( + browserSignInReturnsOnce( signedInResult(grantOn('w1', { expiresAt: PAST, revision: '-scoped' })) ) await session.login() @@ -1487,7 +1529,7 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { ) mintReply = () => json(403, { code: 'insufficient_scope' }) await session.switchWorkspace('w2') - mocked(signIn).mockResolvedValueOnce(signedInResult(grantOn('w3'))) + browserSignInReturnsOnce(signedInResult(grantOn('w3'))) await expect(session.switchWorkspace('w3')).resolves.toMatchObject({ workspaceId: 'w3' }) @@ -1496,7 +1538,7 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { it('an explicit sign-in that also returns no scope keeps ordinary switches off the browser', async () => { saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) - mocked(signIn).mockResolvedValue( + browserSignInReturns( signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) ) const session = new CloudSession() @@ -1511,7 +1553,7 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { it('logout resets the hold', async () => { saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) - mocked(signIn).mockResolvedValue( + browserSignInReturns( signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) ) const session = new CloudSession() @@ -1526,7 +1568,7 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { it('a restart keeps the hold: no second browser across sessions', async () => { saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) - mocked(signIn).mockResolvedValue( + browserSignInReturns( signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) ) await new CloudSession().switchWorkspace('w2') @@ -1554,7 +1596,7 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { ) ) _resetForTest() - mocked(signIn).mockResolvedValue( + browserSignInReturns( signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) ) expect(vaultOnDisk().mintScopeWithheld).toBeUndefined() @@ -1569,12 +1611,12 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { it('a restart with a scoped sign-in in between mints: the grant that can mint cleared the hold', async () => { saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) - mocked(signIn).mockResolvedValueOnce( + browserSignInReturnsOnce( signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) ) const session = new CloudSession() await session.switchWorkspace('w2') - mocked(signIn).mockResolvedValueOnce(signedInResult(grantOn('w1', { revision: '-scoped' }))) + browserSignInReturnsOnce(signedInResult(grantOn('w1', { revision: '-scoped' }))) await session.login() _resetForTest() @@ -1588,7 +1630,7 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { it('an explicit sign-in can still try after a restart', async () => { saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) - mocked(signIn).mockResolvedValue( + browserSignInReturns( signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) ) await new CloudSession().switchWorkspace('w2') @@ -1602,7 +1644,7 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { it('reports scope_not_granted when an sso sign-in narrows a grant that could mint', async () => { saveGrant(grantOn('w1')) mintReply = () => json(403, { code: 'sso_required' }) - mocked(signIn).mockResolvedValue(signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE }))) + browserSignInReturns(signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE }))) await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ workspaceSwitchFailure: 'retryable' @@ -1618,7 +1660,7 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { it('a scopeless grant consented on B activates B, since an anchor needs no mint', async () => { saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) - mocked(signIn).mockResolvedValue(signedInResult(grantOn('w2', { scope: READ_ONLY_SCOPE }))) + browserSignInReturns(signedInResult(grantOn('w2', { scope: READ_ONLY_SCOPE }))) const reply = await new CloudSession().switchWorkspace('w2') diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index ab2952a8f..f34dfc967 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -458,11 +458,18 @@ export class CloudSession { generation: number, reason: ReauthorizeReason ): Promise { - reportBrowser(reason) + let browserOpened = false let tokens: AuthTokens try { - ;({ tokens } = await signIn({ workspaceId })) + ;({ tokens } = await signIn({ + workspaceId, + onAuthorizeUrl: () => { + browserOpened = true + reportBrowser(reason) + } + })) } catch { + if (!browserOpened) reportSwitch('retryable', reason) return generation === this.authGeneration ? this.stayed('retryable') : this.status() } if (generation !== this.authGeneration) return this.status() From 5378739cb69bfa4b9f7e0bb813f322190b72da12 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 23:43:38 -0500 Subject: [PATCH 32/75] feat(auth): mirror a sign-in that returned no mint scope to Datadog The browser-event dedupe removed Datadog's only view of this misconfiguration. Emit comfy.desktop.auth.mint_scope_not_granted once when a browser sign-in stores a grant without the mint scope. --- src/main/cloud/session.test.ts | 48 ++++++++++++++++++++++++ src/main/cloud/session.ts | 6 ++- src/shared/datadogMirroredEvents.test.ts | 1 + src/shared/datadogMirroredEvents.ts | 1 + 4 files changed, 55 insertions(+), 1 deletion(-) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index 7ebccfa50..b05da6898 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -45,6 +45,7 @@ import { CLOUD_CONFIG } from './config' import { openAuthorizePage, refresh, signIn } from './oauth' import { CloudSession, + MINT_SCOPE_NOT_GRANTED_EVENT, WORKSPACE_RETURNED_TO_ANCHOR_EVENT, WORKSPACE_SWITCH_BROWSER_EVENT, WORKSPACE_SWITCH_EVENT @@ -157,6 +158,12 @@ function switchEvents(): unknown[] { .map(([, context]) => context) } +function mintScopeNotGrantedEvents(): unknown[] { + return mocked(mainTelemetry.emit).mock.calls.filter( + ([event]) => event === MINT_SCOPE_NOT_GRANTED_EVENT + ) +} + function browserEvents(): unknown[] { return mocked(mainTelemetry.emit) .mock.calls.filter(([event]) => event === WORKSPACE_SWITCH_BROWSER_EVENT) @@ -1641,6 +1648,47 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { expect(signIn).toHaveBeenCalledTimes(2) }) + it('emits one mint_scope_not_granted for a switch sign-in, and none for the later held switches', async () => { + saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) + browserSignInReturns(signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-b' }))) + const session = new CloudSession() + + await session.switchWorkspace('w2') + await session.switchWorkspace('w3') + + expect(mintScopeNotGrantedEvents()).toHaveLength(1) + }) + + it('emits one mint_scope_not_granted for an explicit sign-in with no scope', async () => { + browserSignInReturns(signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE }))) + + await new CloudSession().login() + + expect(mintScopeNotGrantedEvents()).toHaveLength(1) + }) + + it('emits no mint_scope_not_granted when a sign-in returns the scope', async () => { + browserSignInReturns(signedInResult(grantOn('w1'))) + const session = new CloudSession() + + await session.login() + + expect(mintScopeNotGrantedEvents()).toEqual([]) + }) + + it('emits none for a scopeless sign-in dropped after logout', async () => { + const pending = deferred>>() + mocked(signIn).mockReturnValue(pending.promise) + const session = new CloudSession() + + const login = session.login() + session.logout() + pending.resolve(signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE }))) + await login + + expect(mintScopeNotGrantedEvents()).toEqual([]) + }) + it('reports scope_not_granted when an sso sign-in narrows a grant that could mint', async () => { saveGrant(grantOn('w1')) mintReply = () => json(403, { code: 'sso_required' }) diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index f34dfc967..2a8df81d0 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -45,6 +45,8 @@ const REFRESH_SKEW_MS = 60_000 export const WORKSPACE_SWITCH_EVENT = 'comfy.desktop.auth.workspace_switch' /** Mirrored to Datadog: every browser trip a workspace switch causes. */ export const WORKSPACE_SWITCH_BROWSER_EVENT = 'comfy.desktop.auth.workspace_switch_browser' +/** Mirrored to Datadog: a browser sign-in returned a grant without the mint scope. */ +export const MINT_SCOPE_NOT_GRANTED_EVENT = 'comfy.desktop.auth.mint_scope_not_granted' /** Mirrored to Datadog: a token read could not renew the active workspace, so it went back to the anchor. */ export const WORKSPACE_RETURNED_TO_ANCHOR_EVENT = 'comfy.desktop.auth.workspace_returned_to_anchor' @@ -162,7 +164,9 @@ export class CloudSession { private storeSignedInGrant(tokens: AuthTokens): void { this.mintBlockedUntil = 0 - saveGrant(tokens, { mintScopeWithheld: !canMintWorkspaceTokens(tokens.accessToken) }) + const mintScopeWithheld = !canMintWorkspaceTokens(tokens.accessToken) + saveGrant(tokens, { mintScopeWithheld }) + if (mintScopeWithheld) mainTelemetry.emit(MINT_SCOPE_NOT_GRANTED_EVENT) } private clearPendingLogin(): void { diff --git a/src/shared/datadogMirroredEvents.test.ts b/src/shared/datadogMirroredEvents.test.ts index 37d685ed0..7cc284e94 100644 --- a/src/shared/datadogMirroredEvents.test.ts +++ b/src/shared/datadogMirroredEvents.test.ts @@ -26,6 +26,7 @@ describe('isDatadogMirroredEvent', () => { it('mirrors workspace_switch_browser but not workspace_switch', () => { expect(isDatadogMirroredEvent('comfy.desktop.auth.workspace_switch_browser')).toBe(true) expect(isDatadogMirroredEvent('comfy.desktop.auth.workspace_returned_to_anchor')).toBe(true) + expect(isDatadogMirroredEvent('comfy.desktop.auth.mint_scope_not_granted')).toBe(true) expect(isDatadogMirroredEvent('comfy.desktop.auth.workspace_switch')).toBe(false) }) diff --git a/src/shared/datadogMirroredEvents.ts b/src/shared/datadogMirroredEvents.ts index d92a2d459..a469ea175 100644 --- a/src/shared/datadogMirroredEvents.ts +++ b/src/shared/datadogMirroredEvents.ts @@ -33,6 +33,7 @@ export const DATADOG_MIRRORED_EVENT_NAMES: ReadonlySet = new Set([ 'comfy.desktop.auth.view_token_mint_failed', 'comfy.desktop.auth.workspace_switch_browser', 'comfy.desktop.auth.workspace_returned_to_anchor', + 'comfy.desktop.auth.mint_scope_not_granted', // ComfyUI execution failures — alert on execution error rate per release // and per gpu_tier. 'comfy.desktop.execution.error', From fedf10074381d5e90319fba02485d1b498d1725d Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 8 Nov 2026 23:45:51 -0500 Subject: [PATCH 33/75] test(auth): pin the account re-check when the new account lands on the same workspace id A mutant removing the account comparison survived, because every earlier case also changed the active workspace. --- src/main/cloud/session.test.ts | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index b05da6898..92a5860dd 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -857,6 +857,37 @@ describe('CloudSession.switchWorkspace with no browser', () => { expect(session.currentWorkspaceId()).toBe('w3') }) + it('the new account landing on the same workspace id does not get the old account token', async () => { + saveGrant(grantOn('w1')) + const session = new CloudSession() + await session.switchWorkspace('w2') + saveWorkspaceToken('w2', { accessToken: mintedJwt('w2'), expiresAt: Date.now() + 30_000 }) + const late = deferred() + const pendingSignIn = deferred>>() + mocked(signIn).mockReturnValue(pendingSignIn.promise) + let w3Replies = 0 + mintRequests = [] + mintReply = async ({ workspaceId }) => { + if (workspaceId === 'w3') { + return w3Replies++ === 0 ? json(403, { code: 'sso_required' }) : json(404, {}) + } + await late.promise + return json(429, {}) + } + + const switching = session.switchWorkspace('w3') + await vi.waitFor(() => expect(signIn).toHaveBeenCalledOnce()) + const read = session.getAccessToken() + await vi.waitFor(() => expect(mintRequests).toHaveLength(2)) + pendingSignIn.resolve(signedInResult(grantOn('w2', { subject: 'user-2' }))) + await switching + late.resolve() + + await expect(read).resolves.toBeNull() + expect(session.currentSubject()).toBe('user-2') + expect(session.currentWorkspaceId()).toBe('w2') + }) + it('a refresh landing after the account changed returns null from both token reads', async () => { saveGrant(grantOn('w1', { expiresAt: Date.now() + 30_000 })) const session = new CloudSession() From b586ad203e15f3309dcfa4c95aa70ca74184e9b5 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 9 Nov 2026 00:21:29 -0500 Subject: [PATCH 34/75] test(auth): capture the authorize page in E2E runs and isolate userData on macOS recordShellOpenExternal had no callers, so getShellOpenExternalCalls was always empty and any test asserting on it passed vacuously. openAuthorizePage now records in an E2E run and opens no browser. The harness gains a userDataDir option, the only way to keep a macOS run off the developer's real Application Support and to relaunch the same profile there. --- e2e/support/electronHarness.ts | 7 +++++++ src/main/cloud/oauth.test.ts | 25 ++++++++++++++++++++++++- src/main/cloud/oauth.ts | 7 ++++++- 3 files changed, 37 insertions(+), 2 deletions(-) diff --git a/e2e/support/electronHarness.ts b/e2e/support/electronHarness.ts index 59cc0f31f..a473556d9 100644 --- a/e2e/support/electronHarness.ts +++ b/e2e/support/electronHarness.ts @@ -43,6 +43,9 @@ export interface SeedOptions { * while a process from the previous launch still holds the default: a child Desktop spawned * inherits Electron's listening socket, so an orphan outlives the app holding it. */ cdpPort?: number + /** Run against this Electron userData dir. The only way to keep a macOS run off the developer's + * real Application Support, and to relaunch the same profile there. The caller owns the dir. */ + userDataDir?: string } export interface SeedInstallation { @@ -248,6 +251,10 @@ export async function launchLauncherApp(options?: SeedOptions): Promise { resource: 'https://c/api' } + it('records the authorize page instead of opening a browser in an E2E run', async () => { + vi.stubEnv('E2E', '1') + resetShellOpenExternalCalls() + vi.mocked(shell.openExternal).mockClear() + + await openAuthorizePage('https://cloud.test/authorize') + + expect(getShellOpenExternalCalls()).toEqual(['https://cloud.test/authorize']) + expect(shell.openExternal).not.toHaveBeenCalled() + vi.unstubAllEnvs() + }) + + it('opens the system browser outside an E2E run', async () => { + vi.stubEnv('E2E', '') + vi.mocked(shell.openExternal).mockClear() + + await openAuthorizePage('https://cloud.test/authorize') + + expect(shell.openExternal).toHaveBeenCalledExactlyOnceWith('https://cloud.test/authorize') + vi.unstubAllEnvs() + }) + it('announces no authorize URL and opens no browser when the listener cannot start', async () => { vi.mocked(startLoopbackListener).mockRejectedValueOnce(new Error('address in use')) vi.mocked(shell.openExternal).mockClear() diff --git a/src/main/cloud/oauth.ts b/src/main/cloud/oauth.ts index 460e7acbd..786a092c4 100644 --- a/src/main/cloud/oauth.ts +++ b/src/main/cloud/oauth.ts @@ -5,6 +5,7 @@ */ import { shell } from 'electron' +import { recordShellOpenExternal } from '../lib/e2eOverrides' import { statusFromAccessToken } from './claims' import { CLOUD_CONFIG } from './config' import { startLoopbackListener } from './loopback' @@ -122,8 +123,12 @@ async function requestToken(tokenUrl: string, body: URLSearchParams): Promise { + if (process.env['E2E'] === '1') { + recordShellOpenExternal(authorizeUrl) + return Promise.resolve() + } return shell.openExternal(authorizeUrl) } From 9e18e3c095cefefc4d4969419bf5f52bfd70b0e6 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 9 Nov 2026 00:22:07 -0500 Subject: [PATCH 35/75] test(auth): drive workspace switching end to end through the real selector Runs the built app against a fake Cloud on 127.0.0.1. Covers one browser for A to B to C to A, a relaunch restoring B, a non-member 404, sso_required, the server kill and its no-loop guard, and a 500 and connection refused on mint. Restoring the browser fallback in session.ts fails the first test on the count. --- e2e/README.md | 1 + e2e/workspace-switch-no-browser.test.ts | 517 ++++++++++++++++++++++++ 2 files changed, 518 insertions(+) create mode 100644 e2e/workspace-switch-no-browser.test.ts diff --git a/e2e/README.md b/e2e/README.md index dc5b45774..55ae2058a 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -113,6 +113,7 @@ Snapshot of `e2e/` as of 2026-07. "Meets zero-mock bar" applies the policy above | `title-bar-hover-gate.test.ts` | platform | n/a | Hover-gate state machine. | | `update-pills.test.ts` | platform | n/a | Injects update states via `setAppUpdateState` / `setInstallUpdate`. | | `window-visible.spec.ts` | platform | n/a | Launch smoke test. | +| `workspace-switch-no-browser.test.ts` | `@macos` `@windows` | n/a | Real selector clicks against a fake Cloud on 127.0.0.1; a fake browser plays the authorize step from the openExternal hook; temporary userData with a mock keychain. | Thirteen specs formerly tagged `@lifecycle` were retagged to the platform projects: they inject synthetic runtime state or assert dispatch instead of real side effects, which diff --git a/e2e/workspace-switch-no-browser.test.ts b/e2e/workspace-switch-no-browser.test.ts new file mode 100644 index 000000000..c7110a075 --- /dev/null +++ b/e2e/workspace-switch-no-browser.test.ts @@ -0,0 +1,517 @@ +/** + * E2E: sign in once, then switch workspaces with no further browser, driven through the real + * workspace selector in the instance-selection window of the real built app. + * + * A fake Cloud on 127.0.0.1 stands in for the real one, so this is E2E rather than lifecycle. The + * fake browser plays the authorize step for every URL the app records through the openExternal + * hook: it requests the authorize page and follows the redirect to the app's loopback listener. + * + * Every launch runs on its own temporary Electron userData dir with a mock keychain. On macOS the + * harness's HOME override does not move userData, so without this the vault and settings would + * land in the developer's real profile. + * + * `E2E_SHOTS_DIR`, when set, receives a screenshot of each main state. + */ +import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http' +import type { AddressInfo } from 'node:net' +import { existsSync } from 'node:fs' +import { mkdir, mkdtemp, readFile, realpath, rm } from 'node:fs/promises' +import os from 'node:os' +import path from 'node:path' +import { expect, test } from '@playwright/test' +import en from '../locales/en.json' +import { launchApp, type AppContext } from './launchApp' +import { getShellOpenExternalCalls } from './support/devHooks' +import { captureHostWindow } from './support/windowCapture' + +const UNAVAILABLE_COPY = en.devPlatform.workspace.switchUnavailable +const RETRYABLE_COPY = en.devPlatform.workspace.switchRetryable +const FAILURE_CAPTION = '[data-testid="chooser-workspace-switch-failure"]' +const SELECTOR = '[data-testid="devplatform-workspace-selector"]' +const REFRESH = '[data-testid="chooser-workspace-refresh"]' +const SIGN_IN = '[data-testid="devplatform-account-signin"]' +const SETTLE_MS = 1_500 +const SUBJECT = 'user-e2e' +const WORKSPACES = ['A', 'B', 'C'] +const AUTH_VAULT = 'comfy-cloud-auth.bin' + +type MintBehavior = (workspaceId: string, bearerWorkspace: string) => FakeReply | undefined + +interface FakeReply { + status: number + body: unknown +} + +interface BearerClaims { + workspace_id?: string + scope?: string +} + +function jwt(claims: Record): string { + const b64 = (value: unknown): string => Buffer.from(JSON.stringify(value)).toString('base64url') + return `${b64({ alg: 'none' })}.${b64(claims)}.fake-signature` +} + +function claimsOf(req: IncomingMessage): BearerClaims { + const segment = req.headers.authorization?.replace('Bearer ', '').split('.')[1] + if (!segment) return {} + return JSON.parse(Buffer.from(segment, 'base64url').toString('utf-8')) as BearerClaims +} + +function tokenFor(workspaceId: string, lifetimeSeconds: number, scope?: string): string { + const iat = Math.floor(Date.now() / 1000) + return jwt({ + sub: SUBJECT, + email: 'e2e@example.com', + workspace_id: workspaceId, + workspace_type: 'team', + role: 'member', + ...(scope ? { scope } : {}), + iat, + exp: iat + lifetimeSeconds + }) +} + +function reply(res: ServerResponse, status: number, body: unknown): void { + res.writeHead(status, { 'content-type': 'application/json' }) + res.end(JSON.stringify(body)) +} + +async function bodyOf(req: IncomingMessage): Promise { + const chunks: Buffer[] = [] + for await (const chunk of req) chunks.push(chunk as Buffer) + return Buffer.concat(chunks).toString('utf-8') +} + +class FakeCloud { + readonly authorizeUrls: URL[] = [] + readonly mints: { workspaceId: string; bearerWorkspace: string }[] = [] + readonly builds: { workspace: string; canMint: boolean }[] = [] + readonly members: string[] = [] + mintBehavior: MintBehavior = () => undefined + /** Plays the workspace a person picks on the consent screen. */ + consentOverride: string | null = null + port = 0 + private server: Server | null = null + private readonly codes = new Map() + private nextId = 0 + + get url(): string { + return `http://127.0.0.1:${this.port}` + } + + async start(): Promise { + const server = createServer((req, res) => { + void this.route(req, res) + }) + this.server = server + await new Promise((resolve) => server.listen(this.port, '127.0.0.1', resolve)) + this.port = (server.address() as AddressInfo).port + } + + async stop(): Promise { + const server = this.server + if (!server) return + this.server = null + server.closeAllConnections() + await new Promise((resolve) => server.close(resolve)) + } + + private async route(req: IncomingMessage, res: ServerResponse): Promise { + const url = new URL(req.url ?? '/', this.url) + if (url.pathname === '/oauth/authorize') return this.authorize(url, res) + if (url.pathname === '/oauth/token') return this.token(req, res) + if (url.pathname === '/api/auth/token') return this.mint(req, res) + if (url.pathname === '/api/workspaces') { + return reply(res, 200, { + workspaces: WORKSPACES.map((id) => ({ + id, + name: `Workspace ${id}`, + type: 'team', + role: 'member' + })) + }) + } + if (url.pathname === '/api/workspace/members') { + this.members.push(claimsOf(req).workspace_id ?? '') + return reply(res, 200, { members: [], pagination: { has_more: false } }) + } + if (url.pathname === '/v1/builds') { + const claims = claimsOf(req) + this.builds.push({ + workspace: claims.workspace_id ?? '', + canMint: claims.scope !== undefined + }) + return reply(res, 200, { builds: [] }) + } + reply(res, 404, { code: 'NOT_FOUND' }) + } + + private authorize(url: URL, res: ServerResponse): void { + this.authorizeUrls.push(url) + const code = `code-${++this.nextId}` + this.codes.set(code, { + workspaceId: this.consentOverride ?? url.searchParams.get('workspace_id') ?? 'A', + scope: url.searchParams.get('scope') ?? '' + }) + const redirect = new URL(url.searchParams.get('redirect_uri') ?? '') + redirect.searchParams.set('code', code) + redirect.searchParams.set('state', url.searchParams.get('state') ?? '') + res.writeHead(302, { location: redirect.toString() }) + res.end() + } + + private async token(req: IncomingMessage, res: ServerResponse): Promise { + const form = new URLSearchParams(await bodyOf(req)) + const grant = this.codes.get(form.get('code') ?? form.get('refresh_token') ?? '') + if (!grant) return reply(res, 400, { error: 'invalid_grant' }) + const refreshToken = `refresh-${++this.nextId}` + this.codes.set(refreshToken, grant) + reply(res, 200, { + access_token: tokenFor(grant.workspaceId, 3600, grant.scope), + refresh_token: refreshToken, + expires_in: 3600 + }) + } + + private async mint(req: IncomingMessage, res: ServerResponse): Promise { + const workspaceId = (JSON.parse(await bodyOf(req)) as { workspace_id: string }).workspace_id + const bearerWorkspace = claimsOf(req).workspace_id ?? '' + this.mints.push({ workspaceId, bearerWorkspace }) + const scripted = this.mintBehavior(workspaceId, bearerWorkspace) + if (scripted) return reply(res, scripted.status, scripted.body) + reply(res, 200, { + token: tokenFor(workspaceId, 900), + expires_at: new Date(Date.now() + 900_000).toISOString() + }) + } +} + +let cloud: FakeCloud +let ctx: AppContext | null = null +let userDataDir: string +let browserOpens: string[] +let stopBrowser: () => Promise = async () => {} +let inheritedEnv: Record + +function panel(): AppContext['panel'] { + if (!ctx) throw new Error('app is not running') + return ctx.panel +} + +function playBrowser(app: AppContext['app']): () => Promise { + let handled = 0 + let stopped = false + const loop = (async () => { + while (!stopped) { + const calls = await getShellOpenExternalCalls(app).catch(() => [] as string[]) + for (const url of calls.slice(handled)) { + handled += 1 + browserOpens.push(url) + await fetch(url).catch(() => {}) + } + await new Promise((resolve) => setTimeout(resolve, 100)) + } + })() + return async () => { + stopped = true + await loop + } +} + +async function launch(settings: Record = { firstUseCompleted: true }) { + ctx = await launchApp({ userDataDir, settings }) + const actual = await ctx.app.evaluate(({ app }) => app.getPath('userData')) + expect(await realpath(actual), 'the run stays off the real profile').toBe(userDataDir) + stopBrowser = playBrowser(ctx.app) +} + +async function quit(): Promise { + await stopBrowser() + stopBrowser = async () => {} + await ctx?.cleanup() + ctx = null +} + +async function shot(name: string): Promise { + const dir = process.env['E2E_SHOTS_DIR'] + if (!dir || !ctx) return + await mkdir(dir, { recursive: true }) + await captureHostWindow(ctx.app, ctx.panel, path.join(dir, `${name}.png`)) +} + +function activeWorkspace(): Promise { + return panel().evaluate( + 'window.api.comfybuilder.getAuthStatus().then((status) => status.workspaceId)' + ) +} + +async function expectActive(workspaceId: string): Promise { + await expect.poll(activeWorkspace, { timeout: 15_000 }).toBe(workspaceId) +} + +async function expectSelected(workspaceId: string): Promise { + await expect + .poll(() => panel().textOf(`${SELECTOR} .workspace-selector__name`), { timeout: 15_000 }) + .toBe(`Workspace ${workspaceId}`) +} + +async function expectBuildsFrom(workspaceId: string): Promise { + await expect.poll(() => cloud.builds.at(-1)?.workspace, { timeout: 15_000 }).toBe(workspaceId) +} + +async function select(workspaceId: string): Promise { + const item = `[data-testid="devplatform-workspace-${workspaceId}"]` + await panel().waitForVisible(SELECTOR) + await panel().clickUntilVisible(SELECTOR, item) + expect(await panel().click(item), `selected ${workspaceId}`).toBe(true) +} + +async function expectCaption(copy: string): Promise { + await expect.poll(() => panel().textOf(FAILURE_CAPTION), { timeout: 15_000 }).toBe(copy) +} + +async function expectNoCaption(): Promise { + await expect.poll(() => panel().exists(FAILURE_CAPTION), { timeout: 15_000 }).toBe(false) +} + +async function settle(): Promise { + await new Promise((resolve) => setTimeout(resolve, SETTLE_MS)) +} + +async function signInOnFreshProfile(): Promise { + await launch() + await panel().waitForVisible(SIGN_IN) + expect(await panel().click(SIGN_IN), 'clicked sign in').toBe(true) + await expectActive('A') + await expectBuildsFrom('A') + await expectSelected('A') + expect(browserOpens).toHaveLength(1) +} + +function consecutive(values: T[]): T[] { + return values.filter((value, index) => value !== values[index - 1]) +} + +test.setTimeout(120_000) + +test.beforeAll(() => { + inheritedEnv = { + COMFY_CLOUD_ISSUER: process.env['COMFY_CLOUD_ISSUER'], + COMFY_BUILDER_BASE_URL: process.env['COMFY_BUILDER_BASE_URL'] + } +}) + +test.afterAll(() => { + for (const [key, value] of Object.entries(inheritedEnv)) { + if (value === undefined) delete process.env[key] + else process.env[key] = value + } +}) + +test.beforeEach(async () => { + cloud = new FakeCloud() + await cloud.start() + process.env['COMFY_CLOUD_ISSUER'] = cloud.url + process.env['COMFY_BUILDER_BASE_URL'] = cloud.url + userDataDir = await realpath(await mkdtemp(path.join(os.tmpdir(), 'comfy-workspace-switch-e2e-'))) + browserOpens = [] +}) + +test.afterEach(async () => { + await quit() + await cloud.stop() + await rm(userDataDir, { recursive: true, force: true }) +}) + +test('T-V1: sign in once, switch A to B to C to A with no further browser, and restore B after a relaunch @macos @windows', async () => { + await launch() + await panel().waitForVisible(SIGN_IN) + await shot('01-signed-out') + expect(await panel().click(SIGN_IN), 'clicked sign in').toBe(true) + await expectActive('A') + await expectBuildsFrom('A') + await expectSelected('A') + await shot('02-signed-in-on-A') + + await select('B') + await expectActive('B') + await expectBuildsFrom('B') + await expectSelected('B') + await shot('03-switched-to-B') + + await select('C') + await expectActive('C') + await expectBuildsFrom('C') + await expectSelected('C') + await shot('04-switched-to-C') + + await select('A') + await expectActive('A') + await expectBuildsFrom('A') + await expectSelected('A') + await settle() + await shot('05-back-on-A') + + expect(browserOpens, 'one browser for the whole session').toHaveLength(1) + expect(cloud.authorizeUrls, 'one consent for the whole session').toHaveLength(1) + expect(cloud.mints).toEqual([ + { workspaceId: 'B', bearerWorkspace: 'A' }, + { workspaceId: 'C', bearerWorkspace: 'A' } + ]) + expect(consecutive(cloud.builds.map(({ workspace }) => workspace))).toEqual(['A', 'B', 'C', 'A']) + expect( + cloud.builds.filter(({ workspace }) => workspace !== 'A').some(({ canMint }) => canMint), + 'B and C builds calls carried minted tokens, not the grant' + ).toBe(false) + + await select('B') + await expectActive('B') + const settingsPath = path.join(userDataDir, 'settings.json') + await expect + .poll(async () => { + const raw = await readFile(settingsPath, 'utf-8') + return (JSON.parse(raw) as { dashboardWorkspaceId?: string }).dashboardWorkspaceId + }) + .toBe('B') + await quit() + + const vault = path.join(userDataDir, AUTH_VAULT) + expect(existsSync(vault), 'the vault is on disk').toBe(true) + expect(await readFile(vault, 'utf-8'), 'the vault is encrypted').not.toContain('refresh-') + const mintsBefore = cloud.mints.length + const authorizeBefore = cloud.authorizeUrls.length + browserOpens = [] + cloud.builds.length = 0 + + await launch(JSON.parse(await readFile(settingsPath, 'utf-8')) as Record) + await expectActive('B') + await expectSelected('B') + await expectBuildsFrom('B') + await settle() + await shot('06-relaunched-on-B') + + expect(browserOpens, 'a relaunch opens no browser').toEqual([]) + expect(cloud.authorizeUrls).toHaveLength(authorizeBefore) + expect(cloud.mints).toHaveLength(mintsBefore) +}) + +test('T-V2: a non-member 404 opens no browser, shows the unavailable caption and stays put @macos @windows', async () => { + await signInOnFreshProfile() + cloud.mintBehavior = () => ({ status: 404, body: { code: 'NOT_FOUND' } }) + + await select('B') + await expectCaption(UNAVAILABLE_COPY) + await settle() + await shot('07-unavailable-caption') + + expect(await activeWorkspace()).toBe('A') + expect(browserOpens).toHaveLength(1) + expect(cloud.authorizeUrls).toHaveLength(1) + expect(cloud.mints).toEqual([{ workspaceId: 'B', bearerWorkspace: 'A' }]) +}) + +test('T-V4: sso_required opens exactly one more browser carrying B, then B is active @macos @windows', async () => { + await signInOnFreshProfile() + cloud.mintBehavior = (workspaceId, bearerWorkspace) => + workspaceId === bearerWorkspace ? undefined : { status: 403, body: { code: 'sso_required' } } + + await select('B') + await expectActive('B') + await expectBuildsFrom('B') + await settle() + await expectNoCaption() + await shot('08-sso-consent-on-B') + + expect(browserOpens).toHaveLength(2) + expect(cloud.authorizeUrls).toHaveLength(2) + expect(cloud.authorizeUrls[1]?.searchParams.get('workspace_id')).toBe('B') + expect(cloud.mints).toEqual([{ workspaceId: 'B', bearerWorkspace: 'A' }]) +}) + +const MINT_DISABLED: FakeReply = { + status: 503, + body: { code: 'oauth_workspace_mint_disabled' } +} + +test('server kill: each switch takes exactly one browser and the new anchor activates with no mint @macos @windows', async () => { + await signInOnFreshProfile() + cloud.mintBehavior = (workspaceId, bearerWorkspace) => + workspaceId === bearerWorkspace ? undefined : MINT_DISABLED + + await select('B') + await expectActive('B') + await expectBuildsFrom('B') + expect(browserOpens).toHaveLength(2) + expect(cloud.authorizeUrls[1]?.searchParams.get('workspace_id')).toBe('B') + + await select('C') + await expectActive('C') + await expectBuildsFrom('C') + await settle() + await shot('09-server-kill-degraded') + + expect(browserOpens, 'one browser per switch').toHaveLength(3) + expect(cloud.authorizeUrls[2]?.searchParams.get('workspace_id')).toBe('C') + expect(cloud.mints.map(({ workspaceId }) => workspaceId)).toEqual(['B', 'C']) +}) + +test('server kill: consent on another workspace does not loop: it stays put with one browser @macos @windows', async () => { + await signInOnFreshProfile() + cloud.mintBehavior = (workspaceId, bearerWorkspace) => + workspaceId === bearerWorkspace ? undefined : MINT_DISABLED + cloud.consentOverride = 'A' + + await select('B') + await expectCaption(RETRYABLE_COPY) + await settle() + await shot('10-server-kill-no-loop') + + expect(await activeWorkspace()).toBe('A') + expect(browserOpens, 'no second browser for the same switch').toHaveLength(2) + expect(cloud.mints.map(({ workspaceId }) => workspaceId)).toEqual(['B', 'B']) +}) + +test('a 500 on mint opens no browser, shows the retry caption and the app keeps working on A @macos @windows', async () => { + await signInOnFreshProfile() + cloud.mintBehavior = () => ({ status: 500, body: {} }) + + await select('B') + await expectCaption(RETRYABLE_COPY) + await settle() + await shot('11-retry-caption-500') + + expect(await activeWorkspace()).toBe('A') + expect(browserOpens).toHaveLength(1) + + cloud.builds.length = 0 + expect(await panel().click(REFRESH), 'clicked refresh').toBe(true) + await expectBuildsFrom('A') + await expectCaption(RETRYABLE_COPY) + + cloud.mintBehavior = () => undefined + await select('C') + await expectActive('C') + await expectNoCaption() + expect(browserOpens).toHaveLength(1) +}) + +test('connection refused on mint opens no browser, shows the retry caption, and Refresh recovers @macos @windows', async () => { + await signInOnFreshProfile() + await cloud.stop() + + await select('B') + await expectCaption(RETRYABLE_COPY) + await settle() + await shot('12-retry-caption-connection-refused') + + expect(await activeWorkspace()).toBe('A') + expect(browserOpens).toHaveLength(1) + + await cloud.start() + expect(await panel().click(REFRESH), 'clicked refresh').toBe(true) + await expectActive('B') + await expectNoCaption() + await shot('13-recovered-after-refresh') + expect(browserOpens).toHaveLength(1) +}) From 7bfc29590c7cf44e50265dc973e4840bade4ff3d Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 9 Nov 2026 01:59:44 -0500 Subject: [PATCH 36/75] fix(auth): keep the authorize capture out of packaged builds An inherited E2E=1 would stop a packaged app opening the browser at sign-in. The harness runs unpackaged, so only that case captures the URL. T-V1 also checks the browser count after returning to a cached workspace. --- e2e/workspace-switch-no-browser.test.ts | 2 ++ src/main/cloud/oauth.test.ts | 21 +++++++++++++++++++-- src/main/cloud/oauth.ts | 6 +++--- 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/e2e/workspace-switch-no-browser.test.ts b/e2e/workspace-switch-no-browser.test.ts index c7110a075..9c329e108 100644 --- a/e2e/workspace-switch-no-browser.test.ts +++ b/e2e/workspace-switch-no-browser.test.ts @@ -374,6 +374,8 @@ test('T-V1: sign in once, switch A to B to C to A with no further browser, and r return (JSON.parse(raw) as { dashboardWorkspaceId?: string }).dashboardWorkspaceId }) .toBe('B') + expect(browserOpens, 'returning to a cached workspace takes no browser').toHaveLength(1) + expect(cloud.authorizeUrls, 'returning to a cached workspace takes no consent').toHaveLength(1) await quit() const vault = path.join(userDataDir, AUTH_VAULT) diff --git a/src/main/cloud/oauth.test.ts b/src/main/cloud/oauth.test.ts index 7eedb7ff2..801b79d67 100644 --- a/src/main/cloud/oauth.test.ts +++ b/src/main/cloud/oauth.test.ts @@ -1,14 +1,17 @@ // @vitest-environment node import { afterEach, describe, expect, it, vi } from 'vitest' -vi.mock('electron', () => ({ shell: { openExternal: vi.fn(async () => {}) } })) +vi.mock('electron', () => ({ + app: { isPackaged: false }, + shell: { openExternal: vi.fn(async () => {}) } +})) vi.mock('./loopback', async (importOriginal) => { const actual = await importOriginal() return { ...actual, startLoopbackListener: vi.fn(actual.startLoopbackListener) } }) import { get } from 'node:http' -import { shell } from 'electron' +import { app, shell } from 'electron' import { startLoopbackListener } from './loopback' import type * as LoopbackModule from './loopback' import { getShellOpenExternalCalls, resetShellOpenExternalCalls } from '../lib/e2eOverrides' @@ -146,6 +149,20 @@ describe('oauth.signIn', () => { vi.unstubAllEnvs() }) + it('opens the system browser in a packaged app even with E2E set', async () => { + vi.stubEnv('E2E', '1') + resetShellOpenExternalCalls() + vi.mocked(shell.openExternal).mockClear() + Object.defineProperty(app, 'isPackaged', { value: true, configurable: true }) + + await openAuthorizePage('https://cloud.test/authorize') + + expect(shell.openExternal).toHaveBeenCalledExactlyOnceWith('https://cloud.test/authorize') + expect(getShellOpenExternalCalls()).toEqual([]) + Object.defineProperty(app, 'isPackaged', { value: false, configurable: true }) + vi.unstubAllEnvs() + }) + it('opens the system browser outside an E2E run', async () => { vi.stubEnv('E2E', '') vi.mocked(shell.openExternal).mockClear() diff --git a/src/main/cloud/oauth.ts b/src/main/cloud/oauth.ts index 786a092c4..e81f31042 100644 --- a/src/main/cloud/oauth.ts +++ b/src/main/cloud/oauth.ts @@ -3,7 +3,7 @@ * system browser at the authorize URL, wait for the callback code, exchange it * for tokens. `signIn` optionally pre-selects a workspace (the switch path). */ -import { shell } from 'electron' +import { app, shell } from 'electron' import { recordShellOpenExternal } from '../lib/e2eOverrides' import { statusFromAccessToken } from './claims' @@ -123,9 +123,9 @@ async function requestToken(tokenUrl: string, body: URLSearchParams): Promise { - if (process.env['E2E'] === '1') { + if (process.env['E2E'] === '1' && !app.isPackaged) { recordShellOpenExternal(authorizeUrl) return Promise.resolve() } From 44ef7df3eccc94dcc33aabe4e08b456e98cc851b Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 9 Nov 2026 02:20:45 -0500 Subject: [PATCH 37/75] fix(auth): open the browser only when a person asks for the workspace The chooser's watcher treated restoring a saved selection like choosing one, so a launch after a failed switch opened the browser with no click. The intent now comes from the selection event, not from the value changing. A restored switch stays put and shows the retry caption, and a person joining one in flight upgrades it, so their action is never dropped. --- e2e/workspace-switch-no-browser.test.ts | 31 +++++++ src/main/cloud/index.ts | 1 + src/main/cloud/session.test.ts | 65 ++++++++++++++ src/main/cloud/session.ts | 20 ++++- src/main/cloud/types.ts | 3 + .../ipc/registerDevPlatformHandlers.test.ts | 4 +- .../lib/ipc/registerDevPlatformHandlers.ts | 32 ++++--- src/preload/api.ts | 4 +- src/renderer/src/stores/authStore.ts | 22 +++-- src/renderer/src/views/ChooserView.test.ts | 90 ++++++++++++++++++- src/renderer/src/views/ChooserView.vue | 12 ++- .../src/views/InstallWizardModal.test.ts | 4 +- src/types/ipc.ts | 14 ++- 13 files changed, 272 insertions(+), 30 deletions(-) diff --git a/e2e/workspace-switch-no-browser.test.ts b/e2e/workspace-switch-no-browser.test.ts index 9c329e108..ea963ac0b 100644 --- a/e2e/workspace-switch-no-browser.test.ts +++ b/e2e/workspace-switch-no-browser.test.ts @@ -474,6 +474,37 @@ test('server kill: consent on another workspace does not loop: it stays put with expect(cloud.mints.map(({ workspaceId }) => workspaceId)).toEqual(['B', 'B']) }) +test('a relaunch after a failed switch opens no browser, and Refresh is what asks for one @macos @windows', async () => { + await signInOnFreshProfile() + cloud.mintBehavior = (workspaceId, bearerWorkspace) => + workspaceId === bearerWorkspace ? undefined : MINT_DISABLED + cloud.consentOverride = 'A' + + await select('B') + await expectCaption(RETRYABLE_COPY) + const settingsPath = path.join(userDataDir, 'settings.json') + await expect + .poll(async () => { + const raw = await readFile(settingsPath, 'utf-8') + return (JSON.parse(raw) as { dashboardWorkspaceId?: string }).dashboardWorkspaceId + }) + .toBe('B') + await quit() + browserOpens = [] + const authorizeBefore = cloud.authorizeUrls.length + + await launch(JSON.parse(await readFile(settingsPath, 'utf-8')) as Record) + await expectCaption(RETRYABLE_COPY) + await settle() + + expect(browserOpens, 'a launch opens no browser on its own').toEqual([]) + expect(cloud.authorizeUrls).toHaveLength(authorizeBefore) + expect(await activeWorkspace()).toBe('A') + + expect(await panel().click(REFRESH), 'clicked refresh').toBe(true) + await expect.poll(() => browserOpens.length).toBe(1) +}) + test('a 500 on mint opens no browser, shows the retry caption and the app keeps working on A @macos @windows', async () => { await signInOnFreshProfile() cloud.mintBehavior = () => ({ status: 500, body: {} }) diff --git a/src/main/cloud/index.ts b/src/main/cloud/index.ts index c0e254462..21906c792 100644 --- a/src/main/cloud/index.ts +++ b/src/main/cloud/index.ts @@ -30,5 +30,6 @@ export type { Workspace, WorkspaceMember, WorkspaceSwitchFailure, + WorkspaceSwitchIntent, WorkspaceSwitchStatus } from './types' diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index 92a5860dd..015e593b3 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -983,6 +983,71 @@ describe('CloudSession.switchWorkspace with no browser', () => { }) describe('CloudSession.switchWorkspace reauthorize', () => { + it.each<[string, () => void, string]>([ + ['the server kill switch', () => (mintReply = mintDisabled), 'mint_disabled'], + ['the Desktop ops flag', killMintSwitch, 'mint_disabled'], + [ + 'an SSO policy', + () => (mintReply = () => json(403, { code: 'sso_required' })), + 'sso_required' + ], + [ + 'an ended grant', + () => { + mintReply = () => json(401, { code: 'oauth_grant_ended' }) + mocked(refresh).mockRejectedValue(refreshRefused()) + }, + 'grant_ended' + ] + ])('a restored switch stays put for %s and opens no browser', async (_name, arrange, reason) => { + saveGrant(grantOn('w1')) + const session = new CloudSession() + arrange() + + const reply = await session.switchWorkspace('w2', 'restored') + + expect(signIn).not.toHaveBeenCalled() + expect(reply).toMatchObject({ workspaceId: 'w1', workspaceSwitchFailure: 'retryable' }) + expect(switchEvents()).toEqual([{ outcome: 'retryable', reauthorize_reason: reason }]) + expect(browserEvents()).toEqual([]) + }) + + it('a person joining a restored switch still gets the browser the switch needs', async () => { + saveGrant(grantOn('w1')) + const session = new CloudSession() + const late = deferred() + mintReply = () => late.promise + mocked(signIn).mockResolvedValue({ + tokens: grantOn('w2'), + status: { signedIn: true, workspaceId: 'w2' } + }) + + const restoring = session.switchWorkspace('w2', 'restored') + const joining = session.switchWorkspace('w2', 'chosen') + late.resolve(json(403, { code: 'sso_required' })) + await Promise.all([restoring, joining]) + + expect(signIn).toHaveBeenCalledOnce() + }) + + it('a person retrying after a restored switch reaches sign-in for a grant with no mint scope', async () => { + saveGrant(grantOn('w1', { scope: 'comfy-cloud:user:read' })) + const session = new CloudSession() + mocked(signIn).mockResolvedValue({ + tokens: grantOn('w2'), + status: { signedIn: true, workspaceId: 'w2' } + }) + + await expect(session.switchWorkspace('w2', 'restored')).resolves.toMatchObject({ + workspaceSwitchFailure: 'retryable' + }) + expect(signIn).not.toHaveBeenCalled() + + await session.switchWorkspace('w2', 'chosen') + + expect(signIn).toHaveBeenCalledOnce() + }) + it('T-V4: sso_required opens one browser carrying B and then succeeds', async () => { saveGrant(grantOn('w1')) mintReply = () => json(403, { code: 'sso_required' }) diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index 2a8df81d0..e8faf3c5e 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -32,6 +32,7 @@ import type { Workspace, WorkspaceMember, WorkspaceSwitchFailure, + WorkspaceSwitchIntent, WorkspaceSwitchStatus } from './types' import { classifyMint, mintWorkspaceToken } from './workspaceToken' @@ -111,6 +112,7 @@ export class CloudSession { private readonly refreshing = new Map>() private readonly minting = new Map>() private switching: { workspaceId: string; result: Promise } | null = null + private switchIntent: WorkspaceSwitchIntent = 'chosen' private mintBlockedUntil = 0 private loginInFlight: Promise | null = null private loginAuthorizeUrl: string | null = null @@ -386,10 +388,18 @@ export class CloudSession { } /** Activate `workspaceId`. Only a refused grant, an SSO policy, a missing mint scope or a - * mint kill switch opens the browser; every other failure stays put and says so. */ - switchWorkspace(workspaceId: string): Promise { - if (this.switching?.workspaceId === workspaceId) return this.switching.result + * mint kill switch opens the browser, and only for a `chosen` switch; every other failure + * stays put and says so. */ + switchWorkspace( + workspaceId: string, + intent: WorkspaceSwitchIntent = 'chosen' + ): Promise { + if (this.switching?.workspaceId === workspaceId) { + if (intent === 'chosen') this.switchIntent = 'chosen' + return this.switching.result + } this.clearPendingLogin() + this.switchIntent = intent const generation = ++this.authGeneration const result = this.runSwitch(workspaceId, generation).finally(() => { if (this.switching?.result === result) this.switching = null @@ -462,6 +472,10 @@ export class CloudSession { generation: number, reason: ReauthorizeReason ): Promise { + if (this.switchIntent === 'restored') { + reportSwitch('retryable', reason) + return this.stayed('retryable') + } let browserOpened = false let tokens: AuthTokens try { diff --git a/src/main/cloud/types.ts b/src/main/cloud/types.ts index 93cbe397d..537c8b598 100644 --- a/src/main/cloud/types.ts +++ b/src/main/cloud/types.ts @@ -28,6 +28,9 @@ export interface AuthStatus { export type WorkspaceSwitchFailure = 'unavailable' | 'retryable' +/** `chosen` is a person's selection or retry; `restored` brings back a saved selection and never opens the browser. */ +export type WorkspaceSwitchIntent = 'chosen' | 'restored' + /** The reply to a workspace switch: the resulting status, plus why it stayed put when it did. */ export interface WorkspaceSwitchStatus extends AuthStatus { workspaceSwitchFailure?: WorkspaceSwitchFailure diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts index 729d78460..025723fcb 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts @@ -507,7 +507,7 @@ describe('registerDevPlatformHandlers', () => { const status = await handler('comfybuilder:switchWorkspace')({}, 'w2') expect(mocks.allowDesktopWorkspace).toHaveBeenCalledWith('w2') - expect(mocks.switchWorkspace).toHaveBeenCalledWith('w2') + expect(mocks.switchWorkspace).toHaveBeenCalledWith('w2', 'chosen') expect(status).toMatchObject({ workspaceId: 'w2' }) expect(win.webContents.send).toHaveBeenCalledWith('comfybuilder:authChanged', status) }) @@ -1026,7 +1026,7 @@ describe('registerDevPlatformHandlers', () => { ok: true }) - expect(mocks.switchWorkspace).toHaveBeenCalledExactlyOnceWith('w2') + expect(mocks.switchWorkspace).toHaveBeenCalledExactlyOnceWith('w2', 'chosen') expect(mocks.createBuildDraft).toHaveBeenCalledOnce() expect(mocks.openExternal).toHaveBeenCalledExactlyOnceWith( 'https://platform.comfy.org/profile/builds/build-2/draft?workspace=w2' diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.ts b/src/main/lib/ipc/registerDevPlatformHandlers.ts index d7b833a1b..ca27f9474 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.ts @@ -34,7 +34,12 @@ import { } from '../../devplatform/builds' import type { BuildRow } from '../../devplatform/builds' import { clearVersionCache, getVersionCacheGeneration } from '../../devplatform/versionCache' -import type { AuthStatus, Workspace, WorkspaceSwitchStatus } from '../../cloud' +import type { + AuthStatus, + Workspace, + WorkspaceSwitchIntent, + WorkspaceSwitchStatus +} from '../../cloud' import { installations, defaultInstallDir, @@ -134,12 +139,13 @@ export async function signInToCloud(): Promise { } async function switchAndAnnounce( - workspaceId: string + workspaceId: string, + intent: WorkspaceSwitchIntent ): Promise<{ reply: WorkspaceSwitchStatus; superseded: boolean }> { const session = getCloudSession() const subjectBefore = session.currentSubject() clearVersionCache() - const switching = session.switchWorkspace(workspaceId) + const switching = session.switchWorkspace(workspaceId, intent) const generation = session.currentAuthGeneration() const { reachedThroughConsent, ...reply } = await switching clearVersionCache() @@ -160,8 +166,11 @@ async function switchAndAnnounce( * needed. A failure stays on this reply and off the broadcast. Shared by the chooser and the * hosted ComfyUI view. */ -export async function switchCloudWorkspace(workspaceId: string): Promise { - return (await switchAndAnnounce(workspaceId)).reply +export async function switchCloudWorkspace( + workspaceId: string, + intent: WorkspaceSwitchIntent = 'chosen' +): Promise { + return (await switchAndAnnounce(workspaceId, intent)).reply } /** @@ -277,10 +286,13 @@ export function registerDevPlatformHandlers(): void { } ) - ipcMain.handle(DEVPLATFORM_CHANNELS.switchWorkspace, (_event, workspaceId: string) => { - getViewWorkspaceGrants().allowDesktop(workspaceId) - return switchCloudWorkspace(workspaceId) - }) + ipcMain.handle( + DEVPLATFORM_CHANNELS.switchWorkspace, + (_event, workspaceId: string, intent?: WorkspaceSwitchIntent) => { + getViewWorkspaceGrants().allowDesktop(workspaceId) + return switchCloudWorkspace(workspaceId, intent === 'restored' ? 'restored' : 'chosen') + } + ) ipcMain.handle( DEVPLATFORM_CHANNELS.promoteLocalInstance, @@ -312,7 +324,7 @@ export function registerDevPlatformHandlers(): void { if (session.currentSubject() !== subject) { return { ok: false, message: 'Could not activate the instance workspace.' } } - const { reply: switched, superseded } = await switchAndAnnounce(workspaceId) + const { reply: switched, superseded } = await switchAndAnnounce(workspaceId, 'chosen') if (superseded || !switched.signedIn || switched.workspaceId !== workspaceId) { return { ok: false, message: 'Could not activate the instance workspace.' } } diff --git a/src/preload/api.ts b/src/preload/api.ts index c839090a7..bfdc4c035 100644 --- a/src/preload/api.ts +++ b/src/preload/api.ts @@ -259,8 +259,8 @@ export function buildElectronApi(): ElectronApi { return () => ipcRenderer.removeListener('comfybuilder:authChanged', handler) }, listWorkspaces: () => ipcRenderer.invoke('comfybuilder:listWorkspaces'), - switchWorkspace: (workspaceId) => - ipcRenderer.invoke('comfybuilder:switchWorkspace', workspaceId), + switchWorkspace: (workspaceId, intent) => + ipcRenderer.invoke('comfybuilder:switchWorkspace', workspaceId, intent), listBuilds: () => ipcRenderer.invoke('comfybuilder:listBuilds'), openBuildsPage: (workspaceId) => ipcRenderer.invoke('comfybuilder:openBuildsPage', workspaceId), diff --git a/src/renderer/src/stores/authStore.ts b/src/renderer/src/stores/authStore.ts index 17dc1902d..c8498640f 100644 --- a/src/renderer/src/stores/authStore.ts +++ b/src/renderer/src/stores/authStore.ts @@ -1,7 +1,13 @@ import { computed, onScopeDispose, ref } from 'vue' import { defineStore } from 'pinia' -import type { AuthStatus, ElectronApi, Workspace, WorkspaceSwitchFailure } from '../../../types/ipc' +import type { + AuthStatus, + ElectronApi, + Workspace, + WorkspaceSwitchFailure, + WorkspaceSwitchIntent +} from '../../../types/ipc' import { isPersonalWorkspace, PERSONAL_WORKSPACE_ID } from '../../../shared/workspaces' import type { Build } from '../devplatform/types' @@ -164,12 +170,18 @@ export const useAuthStore = defineStore('auth', () => { /** Activate the workspace for remote operations. Main mints its token with no * browser unless the server requires a new sign-in, and stays on the current - * workspace when it cannot; `workspaceSwitchFailure` then says why. */ - async function switchWorkspace(workspaceId: string): Promise { + * workspace when it cannot; `workspaceSwitchFailure` then says why. A `restored` + * switch never opens the browser. */ + async function switchWorkspace( + workspaceId: string, + intent: WorkspaceSwitchIntent = 'chosen' + ): Promise { const thisSwitch = ++latestSwitch workspaceSwitchFailure.value = undefined - const { workspaceSwitchFailure: failure, ...next } = - await comfybuilderApi.switchWorkspace(workspaceId) + const { workspaceSwitchFailure: failure, ...next } = await comfybuilderApi.switchWorkspace( + workspaceId, + intent + ) applyAuthoritativeStatus(next) if (thisSwitch === latestSwitch) workspaceSwitchFailure.value = failure return next diff --git a/src/renderer/src/views/ChooserView.test.ts b/src/renderer/src/views/ChooserView.test.ts index d9b01b60c..964b5b4d2 100644 --- a/src/renderer/src/views/ChooserView.test.ts +++ b/src/renderer/src/views/ChooserView.test.ts @@ -6,7 +6,9 @@ import { createPinia, setActivePinia } from 'pinia' import ChooserView from './ChooserView.vue' import WhyTryCloudModal from '../components/WhyTryCloudModal.vue' import { useSessionStore } from '../stores/sessionStore' +import { useAuthStore } from '../stores/authStore' import { useDashboardScopeStore } from '../stores/dashboardScopeStore' +import { PERSONAL_WORKSPACE_ID } from '../../../shared/workspaces' import { TID } from '../../../shared/testIds' import type { DevPlatformBuild, Installation } from '../types/ipc' @@ -865,7 +867,7 @@ describe('ChooserView', () => { await wrapper.get('[data-testid="devplatform-workspace-w2"]').trigger('click') await flushPromises() - expect(api.comfybuilder.switchWorkspace).toHaveBeenCalledExactlyOnceWith('w2') + expect(api.comfybuilder.switchWorkspace).toHaveBeenCalledExactlyOnceWith('w2', 'chosen') expect(api.comfybuilder.listBuilds).toHaveBeenCalledOnce() }) @@ -966,10 +968,94 @@ describe('ChooserView', () => { await flushPromises() expect(api.comfybuilder.switchWorkspace).toHaveBeenCalledTimes(2) - expect(api.comfybuilder.switchWorkspace).toHaveBeenLastCalledWith('w2') + expect(api.comfybuilder.switchWorkspace).toHaveBeenLastCalledWith('w2', 'chosen') expect(wrapper.find('[data-testid="chooser-workspace-switch-failure"]').exists()).toBe(false) }) + it('restores a saved selection that arrives after the default resolved', async () => { + const api = installMockApiSignedIn([], [], { id: 'p1', name: 'Personal' }) + api.comfybuilder.getAuthStatus.mockResolvedValue({ + signedIn: true, + workspaceType: 'personal', + workspaceId: 'p1' + }) + api.comfybuilder.listWorkspaces.mockResolvedValue([ + { id: 'p1', name: 'Personal', type: 'personal', role: 'owner' }, + { id: 'w2', name: 'Workspace B', type: 'team', role: 'admin' } + ]) + let resolveSaved: (workspaceId: string) => void = () => {} + const saved = new Promise((resolve) => (resolveSaved = resolve)) + api.getSetting.mockImplementation(async (key: string) => + key === 'dashboardWorkspaceId' ? saved : undefined + ) + api.comfybuilder.switchWorkspace.mockResolvedValue({ + signedIn: true, + workspaceType: 'personal', + workspaceId: 'p1', + workspaceSwitchFailure: 'retryable' + }) + mountChooser() + await flushPromises() + + resolveSaved('w2') + await flushPromises() + + expect(api.comfybuilder.switchWorkspace).toHaveBeenCalledExactlyOnceWith('w2', 'restored') + }) + + it('keeps a person choosing Personal as their choice while the catalog loads', async () => { + const api = installMockApiSignedIn([], [], { id: 'w1', name: 'Workspace A' }) + api.comfybuilder.listWorkspaces.mockResolvedValue([ + { id: 'w1', name: 'Workspace A', type: 'team', role: 'admin' } + ]) + const wrapper = mountChooser() + await flushPromises() + api.comfybuilder.switchWorkspace.mockResolvedValue({ + signedIn: true, + workspaceType: 'personal', + workspaceId: 'p1' + }) + api.comfybuilder.switchWorkspace.mockClear() + + await wrapper.get('[data-testid="devplatform-workspace-selector"]').trigger('click') + await wrapper + .get(`[data-testid="devplatform-workspace-${PERSONAL_WORKSPACE_ID}"]`) + .trigger('click') + await flushPromises() + expect(api.comfybuilder.switchWorkspace).not.toHaveBeenCalled() + + useAuthStore().workspaces = [ + { id: 'w1', name: 'Workspace A', type: 'team', role: 'admin' }, + { id: 'p1', name: 'Personal', type: 'personal', role: 'owner' } + ] + await flushPromises() + + expect(api.comfybuilder.switchWorkspace).toHaveBeenCalledExactlyOnceWith('p1', 'chosen') + }) + + it('restores a saved selection at launch without asking for a browser', async () => { + const api = installMockApiSignedIn([], [], { id: 'w1', name: 'Workspace A' }) + api.comfybuilder.listWorkspaces.mockResolvedValue([ + { id: 'w1', name: 'Workspace A', type: 'team', role: 'admin' }, + { id: 'w2', name: 'Workspace B', type: 'team', role: 'admin' } + ]) + api.getSetting.mockImplementation(async (key: string) => + key === 'dashboardWorkspaceId' ? 'w2' : undefined + ) + api.comfybuilder.switchWorkspace.mockResolvedValue({ + signedIn: true, + workspaceType: 'team', + workspaceId: 'w1', + workspaceSwitchFailure: 'retryable' + }) + + const relaunched = mountChooser() + await flushPromises() + + expect(api.comfybuilder.switchWorkspace).toHaveBeenCalledExactlyOnceWith('w2', 'restored') + expect(relaunched.find('[data-testid="chooser-workspace-switch-failure"]').exists()).toBe(true) + }) + it('refreshes workspace membership and Builds', async () => { const api = installMockApiSignedIn([], [], { id: 'w1', name: 'Comfy Design Team' }) const wrapper = mountChooser() diff --git a/src/renderer/src/views/ChooserView.vue b/src/renderer/src/views/ChooserView.vue index f069a8e67..1fb50e4c6 100644 --- a/src/renderer/src/views/ChooserView.vue +++ b/src/renderer/src/views/ChooserView.vue @@ -96,9 +96,14 @@ defineExpose({ activeFilter }) // --- Dashboard scope --- +let personChoseWorkspace = false + const selectedWorkspaceModel = computed({ get: () => dashboardScope.selectedWorkspaceId, - set: dashboardScope.selectWorkspace + set: (workspaceId: string) => { + personChoseWorkspace = workspaceId !== dashboardScope.selectedWorkspaceId + dashboardScope.selectWorkspace(workspaceId) + } }) /** Server workspace whose Builds belong to the selected dashboard scope. */ @@ -120,10 +125,13 @@ watch( [() => authStore.isSignedIn, selectedManagedWorkspaceId], async ([signedIn, workspaceId]) => { const generation = ++buildPrefetchGeneration + if (!signedIn) personChoseWorkspace = false if (!signedIn || !workspaceId) return + const intent = personChoseWorkspace ? 'chosen' : 'restored' + personChoseWorkspace = false try { if (authStore.status.workspaceId !== workspaceId) { - await authStore.switchWorkspace(workspaceId) + await authStore.switchWorkspace(workspaceId, intent) } if ( generation !== buildPrefetchGeneration || diff --git a/src/renderer/src/views/InstallWizardModal.test.ts b/src/renderer/src/views/InstallWizardModal.test.ts index cd6db41f3..550d3f53b 100644 --- a/src/renderer/src/views/InstallWizardModal.test.ts +++ b/src/renderer/src/views/InstallWizardModal.test.ts @@ -680,7 +680,7 @@ describe('InstallWizardModal workspace Builds', () => { ).open({ workspaceId: 'w2' }) await flushPromises() - expect(window.api.comfybuilder.switchWorkspace).toHaveBeenCalledExactlyOnceWith('w2') + expect(window.api.comfybuilder.switchWorkspace).toHaveBeenCalledExactlyOnceWith('w2', 'chosen') expect( (window.api.comfybuilder.switchWorkspace as ReturnType).mock .invocationCallOrder[0] @@ -733,7 +733,7 @@ describe('InstallWizardModal workspace Builds', () => { await wrapper.get('.workspace-build-refresh').trigger('click') await flushPromises() - expect(switchWorkspace).toHaveBeenCalledExactlyOnceWith('w2') + expect(switchWorkspace).toHaveBeenCalledExactlyOnceWith('w2', 'chosen') expect(listBuilds).toHaveBeenCalledOnce() expect(switchWorkspace.mock.invocationCallOrder[0]).toBeLessThan( listBuilds.mock.invocationCallOrder[0]! diff --git a/src/types/ipc.ts b/src/types/ipc.ts index efdbbdcb2..7218e533e 100644 --- a/src/types/ipc.ts +++ b/src/types/ipc.ts @@ -12,9 +12,16 @@ import type { AuthStatus, Workspace, WorkspaceSwitchFailure, + WorkspaceSwitchIntent, WorkspaceSwitchStatus } from '../main/cloud/types' -export type { AuthStatus, Workspace, WorkspaceSwitchFailure, WorkspaceSwitchStatus } +export type { + AuthStatus, + Workspace, + WorkspaceSwitchFailure, + WorkspaceSwitchIntent, + WorkspaceSwitchStatus +} // One Core beta activation card, as main resolves it for the title bar. Re-exported from its // producer rather than restated here: this file's header forbids duplicating types, and an @@ -1723,7 +1730,10 @@ export interface ElectronApi { getAuthStatus(): Promise onAuthChanged(callback: (status: AuthStatus) => void): Unsubscribe listWorkspaces(): Promise - switchWorkspace(workspaceId: string): Promise + switchWorkspace( + workspaceId: string, + intent?: WorkspaceSwitchIntent + ): Promise listBuilds(): Promise openBuildsPage(workspaceId: string): Promise installBuild(request: InstallBuildRequest): Promise From d9424e8ec5ff92eeace4b1e7c5e18cc081a9a8fb Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 9 Nov 2026 02:31:46 -0500 Subject: [PATCH 38/75] fix(auth): hold a person's workspace pick in the dashboard scope store The chooser's own flag could go unconsumed and then authorize a later automatic selection, and it missed picks made in other surfaces. The store is where every pick and every automatic change already meet, so it now holds the pick and drops it when something else replaces the selection. --- .../src/stores/dashboardScopeStore.test.ts | 66 +++++++++++++++++++ .../src/stores/dashboardScopeStore.ts | 17 ++++- src/renderer/src/views/ChooserView.test.ts | 22 +++++++ src/renderer/src/views/ChooserView.vue | 11 +--- 4 files changed, 105 insertions(+), 11 deletions(-) diff --git a/src/renderer/src/stores/dashboardScopeStore.test.ts b/src/renderer/src/stores/dashboardScopeStore.test.ts index b736f9af6..eb56e49d0 100644 --- a/src/renderer/src/stores/dashboardScopeStore.test.ts +++ b/src/renderer/src/stores/dashboardScopeStore.test.ts @@ -221,4 +221,70 @@ describe('useDashboardScopeStore', () => { await flushPromises() expect(scope.selectedWorkspaceId).toBe('w1') }) + + describe('takeChosenSelection', () => { + let settingsChanged: (change: { key: string }) => void + + async function readyStore() { + api.onSettingsChanged.mockImplementation((callback) => { + settingsChanged = callback + return () => {} + }) + api.comfybuilder.getAuthStatus.mockResolvedValue(signedIn) + api.comfybuilder.listWorkspaces.mockResolvedValue(workspaces) + const store = useDashboardScopeStore() + await store.initialize() + await flushPromises() + return store + } + + it('answers once for a person picking a workspace', async () => { + const store = await readyStore() + + store.selectWorkspace('w2') + + expect(store.takeChosenSelection()).toBe(true) + expect(store.takeChosenSelection()).toBe(false) + }) + + it('does not count a restored selection', async () => { + api.getSetting.mockResolvedValue('w2') + const store = await readyStore() + + expect(store.selectedWorkspaceId).toBe('w2') + expect(store.takeChosenSelection()).toBe(false) + }) + + it('does not count picking what is already selected', async () => { + const store = await readyStore() + + store.selectWorkspace(store.selectedWorkspaceId) + + expect(store.takeChosenSelection()).toBe(false) + }) + + it('drops a pick another window has replaced', async () => { + const store = await readyStore() + store.selectWorkspace('w2') + api.setSetting.mockResolvedValue(undefined) + await flushPromises() + + api.getSetting.mockResolvedValue('w1') + settingsChanged({ key: 'dashboardWorkspaceId' }) + await flushPromises() + + expect(store.selectedWorkspaceId).toBe('w1') + expect(store.takeChosenSelection()).toBe(false) + }) + + it('keeps a pick that the membership check confirms', async () => { + const store = await readyStore() + store.selectWorkspace('w2') + + await useAuthStore().fetchWorkspaces() + await flushPromises() + + expect(store.takeChosenSelection()).toBe(true) + }) + }) }) diff --git a/src/renderer/src/stores/dashboardScopeStore.ts b/src/renderer/src/stores/dashboardScopeStore.ts index 3bcf71c02..7e4f967b7 100644 --- a/src/renderer/src/stores/dashboardScopeStore.ts +++ b/src/renderer/src/stores/dashboardScopeStore.ts @@ -21,6 +21,7 @@ export const useDashboardScopeStore = defineStore('dashboardScope', () => { let preferenceRevision = 0 let pendingWrite: { workspaceId: string } | undefined let disposed = false + let chosenWorkspaceId: string | undefined const membershipKnown = computed( () => authStore.workspacesLoaded && !authStore.loadingWorkspaces && !authStore.workspacesError @@ -42,6 +43,7 @@ export const useDashboardScopeStore = defineStore('dashboardScope', () => { } function applySelection(workspaceId: string): void { + if (workspaceId !== chosenWorkspaceId) chosenWorkspaceId = undefined selectedWorkspaceId.value = workspaceId if ( !initialized.value || @@ -71,7 +73,9 @@ export const useDashboardScopeStore = defineStore('dashboardScope', () => { function selectWorkspace(workspaceId: string): void { selectionChanged = true preferenceRevision += 1 - applySelection(resolveWorkspaceId(workspaceId)) + const resolved = resolveWorkspaceId(workspaceId) + if (resolved !== selectedWorkspaceId.value) chosenWorkspaceId = resolved + applySelection(resolved) } function savedWorkspaceId(): string | undefined { @@ -141,6 +145,7 @@ export const useDashboardScopeStore = defineStore('dashboardScope', () => { (next, previous) => { if (!initialized.value || !next.loaded) return if (!next.signedIn) { + chosenWorkspaceId = undefined applySelection(PERSONAL_WORKSPACE_ID) return } @@ -168,5 +173,13 @@ export const useDashboardScopeStore = defineStore('dashboardScope', () => { } }) - return { selectedWorkspaceId, initialized, initialize, selectWorkspace } + /** Whether a person picked the current selection since the last call, rather than a launch, + * another window or a membership check setting it. */ + function takeChosenSelection(): boolean { + const chosen = chosenWorkspaceId === selectedWorkspaceId.value + chosenWorkspaceId = undefined + return chosen + } + + return { selectedWorkspaceId, initialized, initialize, selectWorkspace, takeChosenSelection } }) diff --git a/src/renderer/src/views/ChooserView.test.ts b/src/renderer/src/views/ChooserView.test.ts index 964b5b4d2..33e7c6f04 100644 --- a/src/renderer/src/views/ChooserView.test.ts +++ b/src/renderer/src/views/ChooserView.test.ts @@ -1033,6 +1033,28 @@ describe('ChooserView', () => { expect(api.comfybuilder.switchWorkspace).toHaveBeenCalledExactlyOnceWith('p1', 'chosen') }) + it('counts a pick made in another surface as a person choosing it', async () => { + const api = installMockApiSignedIn([], [], { id: 'w1', name: 'Workspace A' }) + api.comfybuilder.listWorkspaces.mockResolvedValue([ + { id: 'w1', name: 'Workspace A', type: 'team', role: 'admin' }, + { id: 'w2', name: 'Workspace B', type: 'team', role: 'admin' } + ]) + api.comfybuilder.switchWorkspace.mockResolvedValue({ + signedIn: true, + workspaceType: 'team', + workspaceId: 'w2' + }) + const wrapper = mountChooser() + await flushPromises() + wrapper.unmount() + useDashboardScopeStore().selectWorkspace('w2') + + mount(ChooserView, { global: { plugins: [createTestI18n()] } }) + await flushPromises() + + expect(api.comfybuilder.switchWorkspace).toHaveBeenCalledExactlyOnceWith('w2', 'chosen') + }) + it('restores a saved selection at launch without asking for a browser', async () => { const api = installMockApiSignedIn([], [], { id: 'w1', name: 'Workspace A' }) api.comfybuilder.listWorkspaces.mockResolvedValue([ diff --git a/src/renderer/src/views/ChooserView.vue b/src/renderer/src/views/ChooserView.vue index 1fb50e4c6..178571af6 100644 --- a/src/renderer/src/views/ChooserView.vue +++ b/src/renderer/src/views/ChooserView.vue @@ -96,14 +96,9 @@ defineExpose({ activeFilter }) // --- Dashboard scope --- -let personChoseWorkspace = false - const selectedWorkspaceModel = computed({ get: () => dashboardScope.selectedWorkspaceId, - set: (workspaceId: string) => { - personChoseWorkspace = workspaceId !== dashboardScope.selectedWorkspaceId - dashboardScope.selectWorkspace(workspaceId) - } + set: dashboardScope.selectWorkspace }) /** Server workspace whose Builds belong to the selected dashboard scope. */ @@ -125,10 +120,8 @@ watch( [() => authStore.isSignedIn, selectedManagedWorkspaceId], async ([signedIn, workspaceId]) => { const generation = ++buildPrefetchGeneration - if (!signedIn) personChoseWorkspace = false if (!signedIn || !workspaceId) return - const intent = personChoseWorkspace ? 'chosen' : 'restored' - personChoseWorkspace = false + const intent = dashboardScope.takeChosenSelection() ? 'chosen' : 'restored' try { if (authStore.status.workspaceId !== workspaceId) { await authStore.switchWorkspace(workspaceId, intent) From 4098de9ff514ccea966aa5d4d8666b4f22899b9d Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 9 Nov 2026 02:39:46 -0500 Subject: [PATCH 39/75] fix(auth): retire a workspace pick once the wizard attempts the switch A pick made in another surface stayed pending through the wizard's own attempt, so cancelling that sign-in opened the browser again on returning to the chooser. --- .../src/stores/dashboardScopeStore.test.ts | 16 +++++++++++++ .../src/views/InstallWizardModal.test.ts | 24 +++++++++++++++++++ src/renderer/src/views/InstallWizardModal.vue | 2 ++ 3 files changed, 42 insertions(+) diff --git a/src/renderer/src/stores/dashboardScopeStore.test.ts b/src/renderer/src/stores/dashboardScopeStore.test.ts index eb56e49d0..71ddeee88 100644 --- a/src/renderer/src/stores/dashboardScopeStore.test.ts +++ b/src/renderer/src/stores/dashboardScopeStore.test.ts @@ -277,6 +277,22 @@ describe('useDashboardScopeStore', () => { expect(store.takeChosenSelection()).toBe(false) }) + it('does not count a selection another window brought back to the old pick', async () => { + const store = await readyStore() + store.selectWorkspace('w2') + await flushPromises() + + api.getSetting.mockResolvedValue('w1') + settingsChanged({ key: 'dashboardWorkspaceId' }) + await flushPromises() + api.getSetting.mockResolvedValue('w2') + settingsChanged({ key: 'dashboardWorkspaceId' }) + await flushPromises() + + expect(store.selectedWorkspaceId).toBe('w2') + expect(store.takeChosenSelection()).toBe(false) + }) + it('keeps a pick that the membership check confirms', async () => { const store = await readyStore() store.selectWorkspace('w2') diff --git a/src/renderer/src/views/InstallWizardModal.test.ts b/src/renderer/src/views/InstallWizardModal.test.ts index 550d3f53b..e0571caff 100644 --- a/src/renderer/src/views/InstallWizardModal.test.ts +++ b/src/renderer/src/views/InstallWizardModal.test.ts @@ -10,6 +10,7 @@ import BrandVariantList from '../components/BrandVariantList.vue' import PathDiskInfo from '../components/PathDiskInfo.vue' import { useModal } from '../composables/useModal' import { useAuthStore } from '../stores/authStore' +import { useDashboardScopeStore } from '../stores/dashboardScopeStore' function makeI18n() { return createI18n({ legacy: false, locale: 'en', messages: { en } }) @@ -41,6 +42,7 @@ beforeEach(() => { getFieldOptions: vi.fn().mockResolvedValue([]), validateHardware: vi.fn().mockResolvedValue({ supported: true }), getSetting: vi.fn().mockResolvedValue(false), + onSettingsChanged: vi.fn(() => () => {}), getInstallationsSummary: vi.fn().mockResolvedValue({ localCount: 0 }), getUniqueName: vi.fn().mockResolvedValue('ComfyUI'), getDiskSpace: vi.fn().mockResolvedValue(null), @@ -662,6 +664,28 @@ describe('InstallWizardModal workspace Builds', () => { ).toBe('true') }) + it('retires a pending workspace pick once it attempts the switch itself', async () => { + signInToWorkspace([]) + ;(window.api.comfybuilder.switchWorkspace as ReturnType).mockResolvedValue({ + signedIn: true, + workspaceId: 'w1', + workspaceType: 'team', + workspaceSwitchFailure: 'retryable' + }) + const wrapper = mountModal() + await flushPromises() + const scope = useDashboardScopeStore() + scope.selectWorkspace('w2') + + await ( + wrapper.vm as unknown as { open: (opts: { workspaceId: string }) => Promise } + ).open({ workspaceId: 'w2' }) + await flushPromises() + + expect(window.api.comfybuilder.switchWorkspace).toHaveBeenCalledWith('w2', 'chosen') + expect(scope.takeChosenSelection()).toBe(false) + }) + it('activates the selected workspace before loading its Builds', async () => { signInToWorkspace([]) ;(window.api.comfybuilder.switchWorkspace as ReturnType).mockResolvedValue({ diff --git a/src/renderer/src/views/InstallWizardModal.vue b/src/renderer/src/views/InstallWizardModal.vue index 933d92b87..e1212b28b 100644 --- a/src/renderer/src/views/InstallWizardModal.vue +++ b/src/renderer/src/views/InstallWizardModal.vue @@ -4,6 +4,7 @@ import { useI18n } from 'vue-i18n' import { HardDrive, CircleAlert, RefreshCw } from 'lucide-vue-next' import { useModal } from '../composables/useModal' import { useAuthStore } from '../stores/authStore' +import { useDashboardScopeStore } from '../stores/dashboardScopeStore' import type { InstallBuildResult, @@ -686,6 +687,7 @@ async function initializeManagedBuilds(gen: number, refreshBuilds: boolean): Pro let status = authStore.status if (status.workspaceId !== targetWorkspaceId) { authorizingWorkspace.value = true + useDashboardScopeStore().takeChosenSelection() try { status = await authStore.switchWorkspace(targetWorkspaceId) } finally { From c64c3fd01c8091ff51a5aea2159c7f64c405bb6d Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 9 Nov 2026 02:57:39 -0500 Subject: [PATCH 40/75] chore(bridge): bump the bridge types for the switchWorkspace doc change --- packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts | 4 ++-- packages/comfyui-desktop-bridge-types/package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts b/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts index ac6c9fd02..d53a6c7f0 100644 --- a/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts +++ b/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts @@ -135,8 +135,8 @@ export interface ComfyDesktop2AuthBridge { /** Signs Desktop out of its account (every view follows) and resolves with * the resulting state; Desktop may keep the session if an install needs it. */ signOut(): Promise - /** Re-scopes Desktop's session to `workspaceId` (browser consent the first - * time) and resolves with the resulting state; every view follows. */ + /** Re-scopes Desktop's session to `workspaceId` (no browser unless the server + * requires a new sign-in) and resolves with the resulting state; every view follows. */ switchWorkspace(workspaceId: string): Promise /** Fires when Desktop signs in, signs out or switches workspace. */ onChanged(callback: (state: ComfyDesktop2AuthState) => void): () => void diff --git a/packages/comfyui-desktop-bridge-types/package.json b/packages/comfyui-desktop-bridge-types/package.json index 93c5e1d04..79cc36c65 100644 --- a/packages/comfyui-desktop-bridge-types/package.json +++ b/packages/comfyui-desktop-bridge-types/package.json @@ -1,6 +1,6 @@ { "name": "@comfyorg/comfyui-desktop-bridge-types", - "version": "0.6.0", + "version": "0.6.1", "description": "TypeScript definitions for the Comfy Desktop hosted frontend bridge", "type": "module", "main": "./index.js", From 5d639ea1d650f3479f25b60af7a8a7ed22f1df5e Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 9 Nov 2026 19:07:45 -0500 Subject: [PATCH 41/75] feat(auth): local views get a partner-node token minted by Desktop Desktop's sign-in now asks for comfy-cloud:jobs:write, which Cloud requires before a grant can mint a partner-node token. Main mints that token for the local view's current workspace, renews it in its session once it has under an hour left, and starts a new session when renewal is refused or the session nears its 7-day end. The view gets only the current token, over a new Auth.getPartnerNodeToken, under the workspace token's rules: a trusted view, Desktop's current workspace, that view's allowlist, and no reply that lands after a switch, a sign-in or a sign-out. A grant from before jobs:write gets null without a Cloud call, and any refusal gets null, so the view keeps the workspace token. Neither opens the browser. Failed mints and renewals wait 60 seconds, or Retry-After when longer, before Cloud is asked again. The partner-node cache and the reply fence carry the grant's refresh family (fam), so a same-account sign-in that replaces the grant does not reuse or accept the old grant's session. The embedded-session flag read moved inside the fence for both token kinds. The 60-minute renewal threshold matches the frontend's own reuse threshold for partner-node tokens, so a queued prompt starts with at least an hour. --- .../comfyDesktopBridge.d.ts | 4 + .../comfyui-desktop-bridge-types/package.json | 2 +- src/main/cloud/claims.test.ts | 18 +- src/main/cloud/claims.ts | 20 +- src/main/cloud/config.ts | 5 +- src/main/cloud/oauth.test.ts | 24 + src/main/cloud/session.ts | 8 +- src/main/cloud/workspaceToken.test.ts | 52 +- src/main/cloud/workspaceToken.ts | 49 +- src/main/lib/embeddedSession.test.ts | 73 ++- src/main/lib/embeddedSession.ts | 27 +- .../ipc/registerDevPlatformHandlers.test.ts | 3 + .../registerEmbeddedSessionHandlers.test.ts | 2 + .../ipc/registerEmbeddedSessionHandlers.ts | 5 + .../lib/viewWorkspaceGrants.session.test.ts | 31 + src/main/lib/viewWorkspaceGrants.test.ts | 537 +++++++++++++++++- src/main/lib/viewWorkspaceGrants.ts | 182 +++++- src/preload/comfyPreload.test.ts | 2 + src/preload/comfyPreload.ts | 2 + src/types/comfyDesktopBridge.ts | 4 + 20 files changed, 1006 insertions(+), 44 deletions(-) diff --git a/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts b/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts index d53a6c7f0..391babae1 100644 --- a/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts +++ b/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts @@ -130,6 +130,10 @@ export interface ComfyDesktop2AuthBridge { * is scoped to; null when signed out, disabled, or the scope is missing, * malformed or different. The refresh token never leaves Desktop. */ getWorkspaceToken(workspaceId: string): Promise + /** The partner-node token for prompts in `workspaceId`, under the same rules + * as `getWorkspaceToken`. Desktop mints and renews it; null means use the + * workspace token. Absent on Desktop builds before it. */ + getPartnerNodeToken?(workspaceId: string): Promise /** Runs Desktop's browser sign-in and resolves with the resulting state. */ requestSignIn(): Promise /** Signs Desktop out of its account (every view follows) and resolves with diff --git a/packages/comfyui-desktop-bridge-types/package.json b/packages/comfyui-desktop-bridge-types/package.json index 79cc36c65..ad59ecade 100644 --- a/packages/comfyui-desktop-bridge-types/package.json +++ b/packages/comfyui-desktop-bridge-types/package.json @@ -1,6 +1,6 @@ { "name": "@comfyorg/comfyui-desktop-bridge-types", - "version": "0.6.1", + "version": "0.7.0", "description": "TypeScript definitions for the Comfy Desktop hosted frontend bridge", "type": "module", "main": "./index.js", diff --git a/src/main/cloud/claims.test.ts b/src/main/cloud/claims.test.ts index 8be805baf..d5cedf78e 100644 --- a/src/main/cloud/claims.test.ts +++ b/src/main/cloud/claims.test.ts @@ -1,6 +1,13 @@ // @vitest-environment node import { describe, expect, it } from 'vitest' -import { identityOf, statusFromAccessToken, subjectOf, workspaceIdOf } from './claims' +import { + canMintPartnerNodeTokens, + identityOf, + statusFromAccessToken, + subjectOf, + workspaceIdOf +} from './claims' +import { CLOUD_CONFIG, WORKSPACE_MINT_SCOPE } from './config' function jwt(payload: Record): string { const b64 = (o: unknown): string => Buffer.from(JSON.stringify(o)).toString('base64url') @@ -51,4 +58,13 @@ describe('claims', () => { expect(identityOf(jwt({ email: 'a@b.co' }))).toBeNull() expect(identityOf('not-a-jwt')).toBeNull() }) + + it.each([ + ['a grant from a sign-in Desktop requests today', CLOUD_CONFIG.scope, true], + ['a grant from before jobs:write', `comfy-cloud:user:read ${WORKSPACE_MINT_SCOPE}`, false], + ['a grant without the mint scope', 'comfy-cloud:user:read comfy-cloud:jobs:write', false], + ['a token with no scope', undefined, false] + ])('canMintPartnerNodeTokens for %s', (_name, scope, expected) => { + expect(canMintPartnerNodeTokens(jwt({ sub: 'u', ...(scope ? { scope } : {}) }))).toBe(expected) + }) }) diff --git a/src/main/cloud/claims.ts b/src/main/cloud/claims.ts index 1cc59aa2b..8d234ddaa 100644 --- a/src/main/cloud/claims.ts +++ b/src/main/cloud/claims.ts @@ -1,6 +1,6 @@ import { Buffer } from 'node:buffer' -import { WORKSPACE_MINT_SCOPE } from './config' +import { PARTNER_NODE_MINT_SCOPE, WORKSPACE_MINT_SCOPE } from './config' import type { AuthStatus } from './types' /** Claims read (never verified here; the server does that) from the access-token JWT. */ @@ -11,6 +11,7 @@ interface AccessTokenClaims { workspace_type?: string role?: string scope?: string + fam?: unknown iat?: unknown exp?: unknown } @@ -54,8 +55,17 @@ export function workspaceIdOf(accessToken: string): string | null { /** The grant behind this token can mint workspace tokens; false for grants from before the mint scope. */ export function canMintWorkspaceTokens(accessToken: string): boolean { + return hasScope(accessToken, WORKSPACE_MINT_SCOPE) +} + +/** The grant can mint partner-node tokens for any workspace it can mint for; false for grants from before `jobs:write`. */ +export function canMintPartnerNodeTokens(accessToken: string): boolean { + return canMintWorkspaceTokens(accessToken) && hasScope(accessToken, PARTNER_NODE_MINT_SCOPE) +} + +function hasScope(accessToken: string, wanted: string): boolean { const scope = decodeJwtPayload(accessToken)?.scope - return typeof scope === 'string' && scope.split(' ').includes(WORKSPACE_MINT_SCOPE) + return typeof scope === 'string' && scope.split(' ').includes(wanted) } /** How long a token was issued for, in seconds, independent of any clock; null without usable claims. */ @@ -66,6 +76,12 @@ export function lifetimeSecondsOf(accessToken: string): number | null { return Number.isFinite(lifetime) ? lifetime : null } +/** The refresh family (`fam`) behind an access token: the same across refreshes, new at every sign-in. */ +export function grantFamilyOf(accessToken: string): string | null { + const fam = decodeJwtPayload(accessToken)?.fam + return typeof fam === 'string' ? fam : null +} + /** The account subject a token belongs to, or null for malformed/legacy tokens. */ export function subjectOf(accessToken: string): string | null { return decodeJwtPayload(accessToken)?.sub ?? null diff --git a/src/main/cloud/config.ts b/src/main/cloud/config.ts index 0dde318ce..7f742aab9 100644 --- a/src/main/cloud/config.ts +++ b/src/main/cloud/config.ts @@ -9,6 +9,9 @@ const DEFAULT_CLIENT_ID = 'comfy-desktop' /** Lets a grant mint workspace tokens at `POST /api/auth/token`. Placeholder until Cloud names it. */ export const WORKSPACE_MINT_SCOPE = 'comfy-cloud:workspace-token:mint' +/** Lets a grant mint partner-node tokens, which spend the workspace's credits on partner nodes. */ +export const PARTNER_NODE_MINT_SCOPE = 'comfy-cloud:jobs:write' + export const CLOUD_ISSUER = process.env.COMFY_CLOUD_ISSUER || DEFAULT_ISSUER export const CLOUD_CONFIG = { @@ -19,7 +22,7 @@ export const CLOUD_CONFIG = { /** Workspace REST base (same host as the issuer). */ apiBase: `${CLOUD_ISSUER}/api`, clientId: process.env.COMFY_CLOUD_CLIENT_ID || DEFAULT_CLIENT_ID, - scope: `comfy-cloud:user:read ${WORKSPACE_MINT_SCOPE}`, + scope: `comfy-cloud:user:read ${PARTNER_NODE_MINT_SCOPE} ${WORKSPACE_MINT_SCOPE}`, resource: `${CLOUD_ISSUER}/api`, audience: 'comfy-cloud' } as const diff --git a/src/main/cloud/oauth.test.ts b/src/main/cloud/oauth.test.ts index 801b79d67..ee668a866 100644 --- a/src/main/cloud/oauth.test.ts +++ b/src/main/cloud/oauth.test.ts @@ -199,6 +199,30 @@ describe('oauth.signIn', () => { expect(status.signedIn).toBe(true) }) + it('asks for the partner-node and workspace mint scopes by default', async () => { + stub(200, { access_token: 'tok', refresh_token: 'r1', expires_in: 3600 }) + let requested: string[] = [] + vi.mocked(shell.openExternal).mockImplementation(async (authorizeUrl: string) => { + const u = new URL(authorizeUrl) + requested = (u.searchParams.get('scope') ?? '').split(' ') + get( + `${u.searchParams.get('redirect_uri')}?code=abc&state=${u.searchParams.get('state')}`, + (res) => res.resume() + ) + }) + const { scope: _scope, ...defaults } = opts + + await signIn({ ...defaults, timeoutMs: 5000 }) + + expect(requested).toEqual( + expect.arrayContaining([ + 'comfy-cloud:user:read', + 'comfy-cloud:jobs:write', + 'comfy-cloud:workspace-token:mint' + ]) + ) + }) + it('rejects on the callback timeout even when openExternal never settles', async () => { // A wedged OS shell handler must not strand the sign-in (and with it the // single-flight login promise) forever. diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index e8faf3c5e..5626d03b6 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -9,7 +9,7 @@ import type { TokenProvider } from '../comfybuilder' import * as mainTelemetry from '../lib/telemetry' import { isWorkspaceMintSwitchEnabled } from '../lib/workspaceMintSwitchFlag' -import { canMintWorkspaceTokens, subjectOf, workspaceIdOf } from './claims' +import { canMintWorkspaceTokens, grantFamilyOf, subjectOf, workspaceIdOf } from './claims' import { openAuthorizePage, refresh, signIn } from './oauth' import { SignInFailure } from './signInFailure' import { @@ -204,6 +204,12 @@ export class CloudSession { return grant ? subjectOf(grant.accessToken) : null } + /** The grant's refresh family, which a new sign-in replaces even for the same account. */ + currentGrantFamily(): string | null { + const grant = loadGrant() + return grant ? grantFamilyOf(grant.accessToken) : null + } + /** The active workspace, or null when signed out. */ currentWorkspaceId(): string | null { return loadActiveWorkspaceId() diff --git a/src/main/cloud/workspaceToken.test.ts b/src/main/cloud/workspaceToken.test.ts index d1b7b8665..721380a8a 100644 --- a/src/main/cloud/workspaceToken.test.ts +++ b/src/main/cloud/workspaceToken.test.ts @@ -1,7 +1,12 @@ // @vitest-environment node import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { classifyMint, mintWorkspaceToken } from './workspaceToken' +import { + classifyMint, + mintPartnerNodeToken, + mintWorkspaceToken, + renewPartnerNodeToken +} from './workspaceToken' import type { WorkspaceTokenMint } from './workspaceToken' function respond(status: number, body: unknown, headers: Record = {}): void { @@ -99,6 +104,51 @@ describe('mintWorkspaceToken', () => { }) }) +describe('partner-node tokens', () => { + it('mints with the access token, naming the workspace and the partner-node resource', async () => { + const expiresAt = new Date(Date.now() + 90 * 60_000).toISOString() + respond(200, { token: 'partner-jwt', expires_at: expiresAt }) + + await expect( + mintPartnerNodeToken('oauth-access', 'ws-2', { apiBase: 'https://cloud.test/api' }) + ).resolves.toEqual({ kind: 'minted', token: 'partner-jwt', expiresAt: Date.parse(expiresAt) }) + expect(fetch).toHaveBeenCalledWith( + 'https://cloud.test/api/auth/token', + expect.objectContaining({ + method: 'POST', + headers: expect.objectContaining({ Authorization: 'Bearer oauth-access' }), + body: JSON.stringify({ workspace_id: 'ws-2', resource: 'partner-node' }) + }) + ) + }) + + it('renews with the partner-node token as Bearer and no body', async () => { + const expiresAt = new Date(Date.now() + 90 * 60_000).toISOString() + respond(200, { token: 'renewed-jwt', expires_at: expiresAt }) + + await expect( + renewPartnerNodeToken('partner-jwt', { apiBase: 'https://cloud.test/api' }) + ).resolves.toEqual({ kind: 'minted', token: 'renewed-jwt', expiresAt: Date.parse(expiresAt) }) + const [url, init] = vi.mocked(fetch).mock.calls[0] ?? [] + expect(url).toBe('https://cloud.test/api/auth/partner-node/renew') + expect(init).toMatchObject({ + method: 'POST', + headers: { Authorization: 'Bearer partner-jwt' } + }) + expect(init?.body).toBeUndefined() + }) + + it('carries a refused renewal code', async () => { + respond(403, { code: 'partner_node_session_ended', message: 'ended' }) + + await expect(renewPartnerNodeToken('partner-jwt')).resolves.toEqual({ + kind: 'failed', + status: 403, + code: 'partner_node_session_ended' + }) + }) +}) + describe('mintWorkspaceToken and the local clock', () => { const SERVER_NOW_MS = Date.parse('2026-11-08T12:00:00Z') const SERVER_NOW = SERVER_NOW_MS / 1000 diff --git a/src/main/cloud/workspaceToken.ts b/src/main/cloud/workspaceToken.ts index 913dff513..d13aea9a1 100644 --- a/src/main/cloud/workspaceToken.ts +++ b/src/main/cloud/workspaceToken.ts @@ -1,4 +1,4 @@ -/** Mints a workspace token at `POST {apiBase}/auth/token` with Desktop's OAuth access token. */ +/** Mints workspace and partner-node tokens at `POST {apiBase}/auth/token` with Desktop's OAuth access token. */ import { lifetimeSecondsOf } from './claims' import { CLOUD_CONFIG } from './config' @@ -82,31 +82,62 @@ function mintedFrom(body: unknown, requestedAt: number): WorkspaceTokenMint | nu return expiresAtMs > Date.now() ? { kind: 'minted', token, expiresAt: expiresAtMs } : null } -export async function mintWorkspaceToken( +export function mintWorkspaceToken( accessToken: string, workspaceId: string, options: MintWorkspaceTokenOptions = {} +): Promise { + return postForToken('/auth/token', accessToken, { workspace_id: workspaceId }, options) +} + +/** Mints a partner-node token, which starts a renewable partner-node session, at `POST {apiBase}/auth/token`. */ +export function mintPartnerNodeToken( + accessToken: string, + workspaceId: string, + options: MintWorkspaceTokenOptions = {} +): Promise { + return postForToken( + '/auth/token', + accessToken, + { workspace_id: workspaceId, resource: 'partner-node' }, + options + ) +} + +/** Renews a partner-node token in its session at `POST {apiBase}/auth/partner-node/renew`. */ +export function renewPartnerNodeToken( + partnerNodeToken: string, + options: MintWorkspaceTokenOptions = {} +): Promise { + return postForToken('/auth/partner-node/renew', partnerNodeToken, undefined, options) +} + +async function postForToken( + route: string, + bearer: string, + body: Record | undefined, + options: MintWorkspaceTokenOptions ): Promise { const base = (options.apiBase ?? CLOUD_CONFIG.apiBase).replace(/\/+$/, '') const requestedAt = Date.now() let res: Response try { - res = await fetch(`${base}/auth/token`, { + res = await fetch(`${base}${route}`, { method: 'POST', headers: { Accept: 'application/json', - 'Content-Type': 'application/json', - Authorization: `Bearer ${accessToken}` + ...(body ? { 'Content-Type': 'application/json' } : {}), + Authorization: `Bearer ${bearer}` }, - body: JSON.stringify({ workspace_id: workspaceId }), + ...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS) }) } catch { return { kind: 'failed', status: null } } - const body: unknown = await res.json().catch(() => null) - if (res.ok) return mintedFrom(body, requestedAt) ?? { kind: 'failed', status: res.status } - const code = errorCodeOf(body) + const reply: unknown = await res.json().catch(() => null) + if (res.ok) return mintedFrom(reply, requestedAt) ?? { kind: 'failed', status: res.status } + const code = errorCodeOf(reply) const retryAfterSeconds = retryAfterSecondsOf(res) return { kind: 'failed', diff --git a/src/main/lib/embeddedSession.test.ts b/src/main/lib/embeddedSession.test.ts index 2246a993e..e912d4851 100644 --- a/src/main/lib/embeddedSession.test.ts +++ b/src/main/lib/embeddedSession.test.ts @@ -3,26 +3,32 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const mocks = vi.hoisted(() => ({ enabled: true, + generation: 0, + flagRead: null as Promise | null, getGrantAccessToken: vi.fn<() => Promise>(), mint: vi.fn(), + partnerMint: vi.fn(), current: 'ws-1', entries: [] as unknown[] })) vi.mock('./embeddedSessionFlag', () => ({ - isEmbeddedSessionEnabled: async () => mocks.enabled + isEmbeddedSessionEnabled: async () => (mocks.flagRead ? mocks.flagRead : mocks.enabled) })) vi.mock('../devplatform/session', () => ({ getCloudSession: () => ({ getGrantAccessToken: mocks.getGrantAccessToken, currentWorkspaceId: () => mocks.current, currentSubject: () => (mocks.current ? 'user-1' : null), - currentAuthGeneration: () => 0, + currentGrantFamily: () => null, + currentAuthGeneration: () => mocks.generation, isWorkspaceMintAllowed: async () => true }) })) vi.mock('../cloud/workspaceToken', () => ({ - mintWorkspaceToken: mocks.mint + mintWorkspaceToken: mocks.mint, + mintPartnerNodeToken: mocks.partnerMint, + renewPartnerNodeToken: vi.fn() })) vi.mock('../host/registry', () => ({ get comfyWindows() { @@ -36,6 +42,7 @@ vi.mock('../host/registry', () => ({ import { EMBEDDED_SESSION_CHANNELS, + partnerNodeTokenForSender, workspaceTokenForSender, broadcastEmbeddedSessionChanged, stateForSender, @@ -57,6 +64,10 @@ function mintedFor(workspaceId: string): string { const MINTED = mintedFor('ws-1') +function partnerNodeFor(workspaceId: string): string { + return jwt({ sub: 'user-1', workspace_id: workspaceId, aud: 'comfy-partner-node', sid: 's-1' }) +} + interface ViewOptions { frameUrl?: string installationId?: string | null @@ -84,6 +95,8 @@ function view(comfyUrl: string, options: ViewOptions = {}) { beforeEach(() => { mocks.enabled = true + mocks.generation = 0 + mocks.flagRead = null mocks.entries = [] mocks.getGrantAccessToken.mockReset().mockResolvedValue(ACCESS) mocks.mint.mockReset().mockImplementation(async (_grant: string, workspaceId: string) => ({ @@ -91,6 +104,11 @@ beforeEach(() => { token: mintedFor(workspaceId), expiresAt: Date.now() + 900_000 })) + mocks.partnerMint.mockReset().mockImplementation(async (_grant: string, workspaceId: string) => ({ + kind: 'minted', + token: partnerNodeFor(workspaceId), + expiresAt: Date.now() + 90 * 60_000 + })) mocks.current = 'ws-1' resetViewGrants() }) @@ -110,6 +128,7 @@ describe('embeddedSession', () => { workspaceId: 'ws-1' }) await expect(workspaceTokenForSender(event, 'ws-1')).resolves.toBe(MINTED) + await expect(partnerNodeTokenForSender(event, 'ws-1')).resolves.toBe(partnerNodeFor('ws-1')) }) it.each([ @@ -123,9 +142,56 @@ describe('embeddedSession', () => { await expect(stateForSender(event)).resolves.toEqual({ status: 'disabled' }) await expect(workspaceTokenForSender(event, 'ws-1')).resolves.toBeNull() + await expect(partnerNodeTokenForSender(event, 'ws-1')).resolves.toBeNull() expect(mocks.getGrantAccessToken).not.toHaveBeenCalled() }) + it.each([ + ['its own workspace', 'ws-1', partnerNodeFor('ws-1')], + ['no workspace', undefined, null], + ['an empty workspace', '', null], + ['another workspace', 'ws-2', null], + ['a non-string workspace', 42, null] + ])( + 'releases the partner-node token for %s only on an exact match', + async (_name, workspaceId, expected) => { + const { event } = view('http://127.0.0.1:8000') + + await expect(partnerNodeTokenForSender(event, workspaceId)).resolves.toBe(expected) + } + ) + + it.each([ + ['workspace', workspaceTokenForSender], + ['partner-node', partnerNodeTokenForSender] + ])('drops a %s token request whose flag read spans a sign-in', async (_name, tokenForSender) => { + let release: (enabled: boolean) => void = () => {} + mocks.flagRead = new Promise((resolve) => { + release = resolve + }) + const { event } = view('http://127.0.0.1:8000') + const pending = tokenForSender(event, 'ws-1') + mocks.generation += 1 + release(true) + + await expect(pending).resolves.toBeNull() + expect(mocks.getGrantAccessToken).not.toHaveBeenCalled() + }) + + it('T-V6: hands a view switched to B a partner-node token for B, and a bystander none', async () => { + const switcher = view('http://127.0.0.1:8000') + const bystander = view('http://127.0.0.1:8001') + await switchWorkspaceForSender(switcher.event, 'ws-2', async () => { + mocks.current = 'ws-2' + }) + + await expect(partnerNodeTokenForSender(switcher.event, 'ws-2')).resolves.toBe( + partnerNodeFor('ws-2') + ) + await expect(partnerNodeTokenForSender(bystander.event, 'ws-2')).resolves.toBeNull() + expect(mocks.partnerMint).toHaveBeenCalledExactlyOnceWith(ACCESS, 'ws-2') + }) + it.each([ ['its own workspace', 'ws-1', MINTED], ['no workspace', undefined, null], @@ -213,6 +279,7 @@ describe('embeddedSession', () => { await expect(stateForSender(event)).resolves.toEqual({ status: 'disabled' }) await expect(workspaceTokenForSender(event, 'ws-1')).resolves.toBeNull() + await expect(partnerNodeTokenForSender(event, 'ws-1')).resolves.toBeNull() expect(mocks.getGrantAccessToken).not.toHaveBeenCalled() }) diff --git a/src/main/lib/embeddedSession.ts b/src/main/lib/embeddedSession.ts index c45a13d29..099465704 100644 --- a/src/main/lib/embeddedSession.ts +++ b/src/main/lib/embeddedSession.ts @@ -3,8 +3,8 @@ * local ComfyUI view, so an SSO user (who has no Firebase account) can sign in * there and run partner nodes. * - * Only a workspace token minted for the view's allowed workspace and the - * identity read from Desktop's grant cross to the renderer; the OAuth + * Only workspace and partner-node tokens minted for the view's allowed + * workspace and the identity read from Desktop's grant cross to the renderer; the OAuth * grant stays in main. Only the main frame of a * registered comfyView, still on the loopback ComfyUI Desktop loaded into it, * is served. Remote and LAN servers never receive the token. @@ -22,6 +22,7 @@ import { getViewWorkspaceGrants } from './viewWorkspaceGrants' export const EMBEDDED_SESSION_CHANNELS = { getState: 'desktop2-auth:get-state', getWorkspaceToken: 'desktop2-auth:get-workspace-token', + getPartnerNodeToken: 'desktop2-auth:get-partner-node-token', requestSignIn: 'desktop2-auth:request-sign-in', signOut: 'desktop2-auth:sign-out', switchWorkspace: 'desktop2-auth:switch-workspace', @@ -104,8 +105,26 @@ export async function workspaceTokenForSender( workspaceId: unknown ): Promise { if (typeof workspaceId !== 'string' || workspaceId === '') return null - if (!isTrustedSender(event) || !(await isEmbeddedSessionEnabled())) return null - return getViewWorkspaceGrants().tokenFor(event.sender, workspaceId) + if (!isTrustedSender(event)) return null + return getViewWorkspaceGrants().tokenFor(event.sender, workspaceId, isEmbeddedSessionEnabled) +} + +/** + * The partner-node token for a trusted view, under the same rules as + * {@link workspaceTokenForSender}. Main mints and renews it; the view only + * ever gets the current token. + */ +export async function partnerNodeTokenForSender( + event: EmbeddedSessionSender, + workspaceId: unknown +): Promise { + if (typeof workspaceId !== 'string' || workspaceId === '') return null + if (!isTrustedSender(event)) return null + return getViewWorkspaceGrants().partnerNodeTokenFor( + event.sender, + workspaceId, + isEmbeddedSessionEnabled + ) } /** diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts index 025723fcb..3150a073e 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts @@ -571,6 +571,7 @@ describe('registerDevPlatformHandlers', () => { { currentWorkspaceId: active, currentSubject: () => 'user-1', + currentGrantFamily: () => null, currentAuthGeneration: () => 1, getGrantAccessToken: async () => jwt({ sub: 'user-1', workspace_id: 'w1', scope: CLOUD_CONFIG.scope }), @@ -665,6 +666,7 @@ describe('registerDevPlatformHandlers', () => { { currentWorkspaceId: () => auth.active, currentSubject: () => auth.subject, + currentGrantFamily: () => null, currentAuthGeneration: () => auth.generation, getGrantAccessToken: async () => auth.subject @@ -845,6 +847,7 @@ describe('registerDevPlatformHandlers', () => { { currentWorkspaceId: () => active, currentSubject: () => subject, + currentGrantFamily: () => null, currentAuthGeneration: () => generation, getGrantAccessToken: async () => jwt({ sub: subject, workspace_id: 'home', scope: CLOUD_CONFIG.scope }), diff --git a/src/main/lib/ipc/registerEmbeddedSessionHandlers.test.ts b/src/main/lib/ipc/registerEmbeddedSessionHandlers.test.ts index f3524bd27..8d7f9cd5c 100644 --- a/src/main/lib/ipc/registerEmbeddedSessionHandlers.test.ts +++ b/src/main/lib/ipc/registerEmbeddedSessionHandlers.test.ts @@ -20,10 +20,12 @@ vi.mock('../embeddedSession', () => ({ EMBEDDED_SESSION_CHANNELS: { getState: 'desktop2-auth:get-state', getWorkspaceToken: 'desktop2-auth:get-workspace-token', + getPartnerNodeToken: 'desktop2-auth:get-partner-node-token', requestSignIn: 'desktop2-auth:request-sign-in', signOut: 'desktop2-auth:sign-out', switchWorkspace: 'desktop2-auth:switch-workspace' }, + partnerNodeTokenForSender: vi.fn(), stateForSender: mocks.stateForSender, switchWorkspaceForSender: vi.fn(), workspaceTokenForSender: vi.fn() diff --git a/src/main/lib/ipc/registerEmbeddedSessionHandlers.ts b/src/main/lib/ipc/registerEmbeddedSessionHandlers.ts index b1a401489..d340e6717 100644 --- a/src/main/lib/ipc/registerEmbeddedSessionHandlers.ts +++ b/src/main/lib/ipc/registerEmbeddedSessionHandlers.ts @@ -8,6 +8,7 @@ import { findEntryByComfySender } from '../../host/registry' import type { ComfyDesktop2AuthState } from '../../../types/comfyDesktopBridge' import { EMBEDDED_SESSION_CHANNELS, + partnerNodeTokenForSender, stateForSender, switchWorkspaceForSender, workspaceTokenForSender @@ -22,6 +23,10 @@ export function registerEmbeddedSessionHandlers(): void { workspaceTokenForSender(event, workspaceId) ) + ipcMain.handle(EMBEDDED_SESSION_CHANNELS.getPartnerNodeToken, (event, workspaceId: unknown) => + partnerNodeTokenForSender(event, workspaceId) + ) + ipcMain.handle( EMBEDDED_SESSION_CHANNELS.requestSignIn, async (event): Promise => { diff --git a/src/main/lib/viewWorkspaceGrants.session.test.ts b/src/main/lib/viewWorkspaceGrants.session.test.ts index 5ec3e41d6..060338827 100644 --- a/src/main/lib/viewWorkspaceGrants.session.test.ts +++ b/src/main/lib/viewWorkspaceGrants.session.test.ts @@ -240,4 +240,35 @@ describe('view token path through a real session', () => { await expect(pending).resolves.toBeNull() expect(mintRequests).toEqual([]) }) + + it('keeps the partner-node session across a refresh and starts a new one after a new sign-in', async () => { + const grantIn = (family: string): AuthTokens => ({ + ...GRANT, + accessToken: jwt({ + sub: 'user-1', + workspace_id: 'w1', + scope: CLOUD_CONFIG.scope, + fam: family + }) + }) + mintReply = (workspaceId) => + new Response( + JSON.stringify({ + token: mintedJwt(workspaceId), + expires_at: new Date(Date.now() + 90 * 60_000).toISOString() + }), + { status: 200 } + ) + saveGrant(grantIn('fam-1')) + await grants.partnerNodeTokenFor(view, 'w1') + saveGrant({ ...grantIn('fam-1'), refreshToken: 'refreshed' }) + await grants.partnerNodeTokenFor(view, 'w1') + expect(mintRequests).toEqual(['w1']) + + saveGrant(grantIn('fam-2')) + + await expect(grants.partnerNodeTokenFor(view, 'w1')).resolves.toBe(mintedJwt('w1')) + expect(mintRequests).toEqual(['w1', 'w1']) + expect(session.currentGrantFamily()).toBe('fam-2') + }) }) diff --git a/src/main/lib/viewWorkspaceGrants.test.ts b/src/main/lib/viewWorkspaceGrants.test.ts index a12197596..fbc8aafc0 100644 --- a/src/main/lib/viewWorkspaceGrants.test.ts +++ b/src/main/lib/viewWorkspaceGrants.test.ts @@ -2,12 +2,12 @@ import { Buffer } from 'node:buffer' import type { WebContents } from 'electron' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' vi.mock('../devplatform/session', () => ({ getCloudSession: () => ({}) })) vi.mock('./telemetry', () => ({ emit: vi.fn() })) -import { CLOUD_CONFIG } from '../cloud/config' +import { CLOUD_CONFIG, WORKSPACE_MINT_SCOPE } from '../cloud/config' import type { WorkspaceTokenMint } from '../cloud/workspaceToken' import * as mainTelemetry from './telemetry' import { @@ -71,6 +71,7 @@ function grantSession( return { currentWorkspaceId: () => current, currentSubject: () => (current ? user : null), + currentGrantFamily: () => null, currentAuthGeneration: () => generation, getGrantAccessToken, isWorkspaceMintAllowed: async () => true @@ -314,6 +315,7 @@ describe('ViewWorkspaceGrants', () => { ) const stale = grants.tokenFor(viewA, 'ws-1') const firstUserToken = accessToken('ws-1') + await vi.waitFor(() => expect(reads).toBe(1)) grants.endAll() grants.allowDesktop('ws-1') user = 'user-2' @@ -355,3 +357,534 @@ describe('ViewWorkspaceGrants', () => { expect(mint).toHaveBeenCalledOnce() }) }) + +describe('ViewWorkspaceGrants partner-node tokens', () => { + let partnerMint: ReturnType< + typeof vi.fn<(token: string, workspaceId: string) => Promise> + > + let partnerRenew: ReturnType Promise>> + let mintScopeAllowed: boolean + + function partnerToken(workspaceId: string, session = 'sid-1', round = 0): string { + return jwt({ + sub: user, + workspace_id: workspaceId, + aud: 'comfy-partner-node', + sid: session, + round + }) + } + + function partnerMinted(token: string, lifetimeMs = 90 * 60_000): WorkspaceTokenMint { + return { kind: 'minted', token, expiresAt: Date.now() + lifetimeMs } + } + + function build(scope: string = CLOUD_CONFIG.scope): ViewWorkspaceGrants { + return new ViewWorkspaceGrants( + { + ...grantSession(async () => (current ? accessToken('ws-1', scope) : null)), + isWorkspaceMintAllowed: async () => mintScopeAllowed + }, + mint, + { mint: partnerMint, renew: partnerRenew } + ) + } + + beforeEach(() => { + mintScopeAllowed = true + partnerMint = vi.fn(async (_token: string, workspaceId: string) => + partnerMinted(partnerToken(workspaceId)) + ) + partnerRenew = vi.fn(async () => partnerMinted(partnerToken('ws-1', 'sid-1', 1))) + grants = build() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('T-V7: hands the view a partner-node token minted from the grant, never the grant or the workspace token', async () => { + const token = await grants.partnerNodeTokenFor(viewA, 'ws-1') + + expect(token).toBe(partnerToken('ws-1')) + expect(token).not.toBe(accessToken('ws-1')) + expect(token).not.toBe(mintedToken('ws-1')) + expect(partnerMint).toHaveBeenCalledExactlyOnceWith(accessToken('ws-1'), 'ws-1') + expect(mint).not.toHaveBeenCalled() + }) + + it('T-V6: a view switched to B gets a partner-node token for B, and a view that did not switch gets none', async () => { + await grants.partnerNodeTokenFor(viewA, 'ws-1') + grants.allowView(viewA, 'ws-2') + signInAt('ws-2') + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-2')).resolves.toBe(partnerToken('ws-2')) + await expect(grants.partnerNodeTokenFor(viewB, 'ws-2')).resolves.toBeNull() + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() + expect(partnerMint).toHaveBeenLastCalledWith(accessToken('ws-1'), 'ws-2') + }) + + it('mints once for concurrent requests and reuses the token while it has over an hour left', async () => { + await Promise.all([ + grants.partnerNodeTokenFor(viewA, 'ws-1'), + grants.partnerNodeTokenFor(viewB, 'ws-1') + ]) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + + expect(partnerMint).toHaveBeenCalledOnce() + expect(partnerRenew).not.toHaveBeenCalled() + }) + + it('renews in the same session before expiry and hands the view only the renewed token', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe( + partnerToken('ws-1', 'sid-1', 1) + ) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + + expect(partnerRenew).toHaveBeenCalledExactlyOnceWith(partnerToken('ws-1')) + expect(partnerMint).toHaveBeenCalledOnce() + }) + + it.each<[string, () => WorkspaceTokenMint]>([ + [ + 'a session that ended', + () => ({ kind: 'failed', status: 403, code: 'partner_node_session_ended' }) + ], + [ + 'a revoked session', + () => ({ kind: 'failed', status: 403, code: 'partner_node_session_revoked' }) + ], + ['an unknown session', () => ({ kind: 'failed', status: 401 })], + [ + 'a session in its last hour', + () => partnerMinted(partnerToken('ws-1', 'sid-1', 1), 20 * 60_000) + ] + ])('starts a new session after %s', async (_name, renewal) => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + partnerRenew.mockResolvedValueOnce(renewal()) + partnerMint.mockResolvedValueOnce(partnerMinted(partnerToken('ws-1', 'sid-2'))) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe( + partnerToken('ws-1', 'sid-2') + ) + expect(partnerMint).toHaveBeenCalledTimes(2) + }) + + it('drops the held token when its session was refused and no new session could start', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + partnerRenew.mockResolvedValueOnce({ + kind: 'failed', + status: 403, + code: 'partner_node_session_ended' + }) + partnerMint.mockResolvedValueOnce({ kind: 'failed', status: 401, code: 'oauth_grant_ended' }) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() + }) + + it.each<[string, number | null]>([ + ['a network error', null], + ['a rate limit', 429], + ['a server error', 503] + ])( + 'hands out nothing when the session was refused and the new mint met %s', + async (_name, status) => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + partnerRenew.mockResolvedValueOnce({ + kind: 'failed', + status: 403, + code: 'partner_node_session_revoked' + }) + partnerMint.mockResolvedValueOnce({ kind: 'failed', status }) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() + } + ) + + it.each<[string, number | null]>([ + ['a rate limit', 429], + ['a server error', 500], + ['a network error', null] + ])('keeps handing out the current token after %s on renewal', async (_name, status) => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + partnerRenew.mockResolvedValueOnce({ kind: 'failed', status }) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe(partnerToken('ws-1')) + expect(partnerMint).toHaveBeenCalledOnce() + }) + + it.each<[string, WorkspaceTokenMint]>([ + ['the mint switched off', { kind: 'failed', status: 503, code: 'partner_node_token_disabled' }], + ['a client not allowed', { kind: 'failed', status: 403, code: 'oauth_token_mint_refused' }], + ['a grant without jobs:write', { kind: 'failed', status: 403, code: 'insufficient_scope' }], + ['a network error', { kind: 'failed', status: null }] + ])( + 'hands out nothing after %s, so the view keeps the workspace token', + async (_name, refusal) => { + partnerMint.mockResolvedValueOnce(refusal) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe(mintedToken('ws-1')) + } + ) + + it('hands out nothing, and does not ask Cloud, for a grant from before jobs:write', async () => { + grants = build(`comfy-cloud:user:read ${WORKSPACE_MINT_SCOPE}`) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe(mintedToken('ws-1')) + expect(partnerMint).not.toHaveBeenCalled() + }) + + it('hands out nothing for another workspace while the mint switch is off', async () => { + mintScopeAllowed = false + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() + expect(partnerMint).not.toHaveBeenCalled() + }) + + it.each<[string, () => string]>([ + ['another workspace', () => partnerToken('ws-9')], + ['another account', () => jwt({ sub: 'user-9', workspace_id: 'ws-1', sid: 'sid-1' })] + ])('refuses a partner-node token minted for %s', async (_name, token) => { + partnerMint.mockResolvedValueOnce(partnerMinted(token())) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() + }) + + it('T-V27: drops a mint reply that lands after a switch to B', async () => { + const reply = deferred() + partnerMint.mockReturnValueOnce(reply.promise) + const pending = grants.partnerNodeTokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(partnerMint).toHaveBeenCalledOnce()) + grants.allowView(viewA, 'ws-2') + signInAt('ws-2') + reply.resolve(partnerMinted(partnerToken('ws-1'))) + + await expect(pending).resolves.toBeNull() + }) + + it('T-V27: drops a mint reply that lands after sign-out, and does not keep its token', async () => { + const reply = deferred() + partnerMint.mockReturnValueOnce(reply.promise) + const pending = grants.partnerNodeTokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(partnerMint).toHaveBeenCalledOnce()) + signInAt(null) + grants.endAll() + reply.resolve(partnerMinted(partnerToken('ws-1', 'stale'))) + + await expect(pending).resolves.toBeNull() + signInAt('ws-1') + grants.allowDesktop('ws-1') + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe(partnerToken('ws-1')) + expect(partnerMint).toHaveBeenCalledTimes(2) + }) + + it('T-V28: drops a renewal that lands after sign-out, and does not renew a token from before it', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + const renewal = deferred() + partnerRenew.mockReturnValueOnce(renewal.promise) + const pending = grants.partnerNodeTokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(partnerRenew).toHaveBeenCalledOnce()) + signInAt(null) + grants.endAll() + renewal.resolve(partnerMinted(partnerToken('ws-1', 'sid-1', 1))) + + await expect(pending).resolves.toBeNull() + signInAt('ws-1') + grants.allowDesktop('ws-1') + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe(partnerToken('ws-1')) + expect(partnerRenew).toHaveBeenCalledOnce() + }) + + it('does not ask Cloud again until Retry-After passes after a rate-limited renewal', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + partnerRenew.mockResolvedValueOnce({ kind: 'failed', status: 429, retryAfterSeconds: 120 }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 90_000) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe(partnerToken('ws-1')) + expect(partnerRenew).toHaveBeenCalledOnce() + + vi.setSystemTime(Date.now() + 31_000) + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe( + partnerToken('ws-1', 'sid-1', 1) + ) + expect(partnerRenew).toHaveBeenCalledTimes(2) + }) + + it('does not ask Cloud again for a minute after a refused mint', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + partnerMint.mockResolvedValueOnce({ + kind: 'failed', + status: 503, + code: 'partner_node_token_disabled' + }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() + expect(partnerMint).toHaveBeenCalledOnce() + + vi.setSystemTime(Date.now() + 61_000) + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe(partnerToken('ws-1')) + expect(partnerMint).toHaveBeenCalledTimes(2) + }) + + it.each<[string, WorkspaceTokenMint, string | null]>([ + ['refused', { kind: 'failed', status: 403, code: 'oauth_token_mint_refused' }, null], + ['switched off', { kind: 'failed', status: 503, code: 'partner_node_token_disabled' }, null], + ['unreachable', { kind: 'failed', status: null }, 'held'] + ])( + 'does not hand out a last-hour renewal when the new session is %s', + async (_name, refusal, expected) => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + partnerRenew.mockResolvedValueOnce( + partnerMinted(partnerToken('ws-1', 'sid-1', 1), 20 * 60_000) + ) + partnerMint.mockResolvedValueOnce(refusal) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe( + expected === 'held' ? partnerToken('ws-1') : null + ) + } + ) + + it('does not start a new session for a renewal refused after sign-out', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + const renewal = deferred() + partnerRenew.mockReturnValueOnce(renewal.promise) + const pending = grants.partnerNodeTokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(partnerRenew).toHaveBeenCalledOnce()) + signInAt(null) + grants.endAll() + renewal.resolve({ kind: 'failed', status: 403, code: 'partner_node_session_revoked' }) + + await expect(pending).resolves.toBeNull() + expect(partnerMint).toHaveBeenCalledOnce() + }) + + it('starts a new session when a renewal comes back already expired', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + const renewal = deferred() + partnerRenew.mockReturnValueOnce(renewal.promise) + partnerMint.mockImplementationOnce(async () => partnerMinted(partnerToken('ws-1', 'sid-2'))) + const pending = grants.partnerNodeTokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(partnerRenew).toHaveBeenCalledOnce()) + const renewed = partnerMinted(partnerToken('ws-1', 'sid-1', 1), 70 * 60_000) + vi.setSystemTime(Date.now() + 2 * 60 * 60_000) + renewal.resolve(renewed) + + await expect(pending).resolves.toBe(partnerToken('ws-1', 'sid-2')) + }) + + it('renews a token for A again after A to B to A, and gives B its own session', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + grants.allowView(viewA, 'ws-2') + await grants.partnerNodeTokenFor(viewA, 'ws-1') + signInAt('ws-2') + await expect(grants.partnerNodeTokenFor(viewA, 'ws-2')).resolves.toBe(partnerToken('ws-2')) + signInAt('ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe( + partnerToken('ws-1', 'sid-1', 1) + ) + expect(partnerRenew).toHaveBeenCalledExactlyOnceWith(partnerToken('ws-1')) + expect(partnerMint.mock.calls.map(([, workspaceId]) => workspaceId)).toEqual(['ws-1', 'ws-2']) + }) + + it('starts over after the same account signs in again', async () => { + await grants.partnerNodeTokenFor(viewA, 'ws-1') + grants.endAll() + signInAt('ws-1') + grants.allowDesktop('ws-1') + partnerMint.mockResolvedValueOnce(partnerMinted(partnerToken('ws-1', 'sid-2'))) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe( + partnerToken('ws-1', 'sid-2') + ) + expect(partnerRenew).not.toHaveBeenCalled() + }) + + describe('when a new sign-in replaces the grant for the same account', () => { + let family: string + + beforeEach(() => { + family = 'fam-1' + grants = new ViewWorkspaceGrants( + { + ...grantSession(async () => + jwt({ sub: user, workspace_id: 'ws-1', scope: CLOUD_CONFIG.scope, fam: family }) + ), + currentGrantFamily: () => family + }, + mint, + { mint: partnerMint, renew: partnerRenew } + ) + }) + + it('starts a new session instead of reusing the old grant one', async () => { + await grants.partnerNodeTokenFor(viewA, 'ws-1') + family = 'fam-2' + partnerMint.mockResolvedValueOnce(partnerMinted(partnerToken('ws-1', 'sid-2'))) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe( + partnerToken('ws-1', 'sid-2') + ) + expect(partnerMint).toHaveBeenCalledTimes(2) + }) + + it('drops a mint reply from the old grant that lands after the new sign-in', async () => { + const reply = deferred() + partnerMint.mockReturnValueOnce(reply.promise) + const pending = grants.partnerNodeTokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(partnerMint).toHaveBeenCalledOnce()) + family = 'fam-2' + reply.resolve(partnerMinted(partnerToken('ws-1', 'old-grant'))) + + await expect(pending).resolves.toBeNull() + }) + + it('drops a workspace token reply from the old grant that lands after the new sign-in', async () => { + const reply = deferred() + mint.mockReturnValueOnce(reply.promise) + const pending = grants.tokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(mint).toHaveBeenCalledOnce()) + family = 'fam-2' + reply.resolve({ kind: 'minted', token: staleToken('ws-1'), expiresAt: Date.now() + 900_000 }) + + await expect(pending).resolves.toBeNull() + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe(mintedToken('ws-1')) + }) + }) + + it('forgets a token whose renewal was refused after a switch, so A to B to A does not hand it out', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + grants.allowView(viewA, 'ws-2') + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + const renewal = deferred() + partnerRenew.mockReturnValueOnce(renewal.promise) + const pending = grants.partnerNodeTokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(partnerRenew).toHaveBeenCalledOnce()) + signInAt('ws-2') + renewal.resolve({ kind: 'failed', status: 403, code: 'partner_node_session_revoked' }) + await expect(pending).resolves.toBeNull() + signInAt('ws-1') + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() + expect(partnerRenew).toHaveBeenCalledOnce() + expect(partnerMint).toHaveBeenCalledOnce() + }) + + it('keeps the Retry-After of a renewal that lands after a switch, once back on A', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + grants.allowView(viewA, 'ws-2') + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + const renewal = deferred() + partnerRenew.mockReturnValueOnce(renewal.promise) + const pending = grants.partnerNodeTokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(partnerRenew).toHaveBeenCalledOnce()) + signInAt('ws-2') + renewal.resolve({ kind: 'failed', status: 429, retryAfterSeconds: 120 }) + await expect(pending).resolves.toBeNull() + signInAt('ws-1') + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe(partnerToken('ws-1')) + expect(partnerRenew).toHaveBeenCalledOnce() + }) + + it('forgets the held token when a new session is refused after a switch, once back on A', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + grants.allowView(viewA, 'ws-2') + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + partnerRenew.mockResolvedValueOnce(partnerMinted(partnerToken('ws-1', 'sid-1', 1), 20 * 60_000)) + const reply = deferred() + partnerMint.mockReturnValueOnce(reply.promise) + const pending = grants.partnerNodeTokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(partnerMint).toHaveBeenCalledTimes(2)) + signInAt('ws-2') + reply.resolve({ kind: 'failed', status: 503, code: 'partner_node_token_disabled' }) + await expect(pending).resolves.toBeNull() + signInAt('ws-1') + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() + }) + + it('keeps the longer of two retry deadlines when a shorter failure lands later', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + const older = deferred() + partnerMint.mockReturnValueOnce(older.promise) + grants.allowView(viewA, 'ws-2') + const stale = grants.partnerNodeTokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(partnerMint).toHaveBeenCalledOnce()) + signInAt('ws-2') + signInAt('ws-1') + partnerMint.mockResolvedValueOnce({ kind: 'failed', status: 429, retryAfterSeconds: 3600 }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + older.resolve({ kind: 'failed', status: 503 }) + await stale + vi.setSystemTime(Date.now() + 61_000) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() + expect(partnerMint).toHaveBeenCalledTimes(2) + }) + + it('keeps the held token when a renewal reply could not be read', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + partnerRenew.mockResolvedValueOnce({ kind: 'failed', status: 200 }) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe(partnerToken('ws-1')) + expect(partnerMint).toHaveBeenCalledOnce() + }) + + it('keeps a newer token when a refusal for the older one lands late', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + grants.allowView(viewA, 'ws-2') + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + const late = deferred() + partnerRenew.mockReturnValueOnce(late.promise) + const stale = grants.partnerNodeTokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(partnerRenew).toHaveBeenCalledOnce()) + signInAt('ws-2') + signInAt('ws-1') + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe( + partnerToken('ws-1', 'sid-1', 1) + ) + late.resolve({ kind: 'failed', status: 403, code: 'partner_node_session_revoked' }) + await expect(stale).resolves.toBeNull() + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe( + partnerToken('ws-1', 'sid-1', 1) + ) + expect(partnerRenew).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/main/lib/viewWorkspaceGrants.ts b/src/main/lib/viewWorkspaceGrants.ts index 69f8be0b9..c1d4e7c2e 100644 --- a/src/main/lib/viewWorkspaceGrants.ts +++ b/src/main/lib/viewWorkspaceGrants.ts @@ -1,12 +1,26 @@ import type { WebContents } from 'electron' -import { canMintWorkspaceTokens, subjectOf, workspaceIdOf } from '../cloud/claims' -import { mintWorkspaceToken } from '../cloud/workspaceToken' +import { + canMintPartnerNodeTokens, + canMintWorkspaceTokens, + grantFamilyOf, + subjectOf, + workspaceIdOf +} from '../cloud/claims' +import { + mintPartnerNodeToken, + mintWorkspaceToken, + renewPartnerNodeToken +} from '../cloud/workspaceToken' import type { WorkspaceTokenMint } from '../cloud/workspaceToken' import { getCloudSession } from '../devplatform/session' import * as mainTelemetry from './telemetry' const MINT_REFRESH_SKEW_MS = 60_000 +/** A partner-node token is renewed once it has less than this left, so a queued prompt still has an hour. */ +const PARTNER_NODE_RENEW_BEFORE_MS = 60 * 60_000 +/** After a failed partner-node mint or renewal, Cloud is not asked again for this long unless `Retry-After` says longer. */ +const PARTNER_NODE_RETRY_MS = 60_000 export const VIEW_TOKEN_MINTED_EVENT = 'comfy.desktop.auth.view_token_minted' export const VIEW_TOKEN_MINT_FAILED_EVENT = 'comfy.desktop.auth.view_token_mint_failed' @@ -25,6 +39,7 @@ function reportMint(result: WorkspaceTokenMint): void { export interface GrantSession { currentWorkspaceId(): string | null currentSubject(): string | null + currentGrantFamily(): string | null currentAuthGeneration(): number getGrantAccessToken(): Promise isWorkspaceMintAllowed(workspaceId: string): Promise @@ -35,13 +50,38 @@ export type MintWorkspaceToken = ( workspaceId: string ) => Promise +export interface PartnerNodeTokenCalls { + mint: MintWorkspaceToken + renew(partnerNodeToken: string): Promise +} + +const PARTNER_NODE_TOKEN_CALLS: PartnerNodeTokenCalls = { + mint: (accessToken, workspaceId) => mintPartnerNodeToken(accessToken, workspaceId), + renew: (partnerNodeToken) => renewPartnerNodeToken(partnerNodeToken) +} + +const PARTNER_NODE_MINT_DISABLED_CODE = 'partner_node_token_disabled' + +function isRetryableFailure(result: WorkspaceTokenMint): boolean { + return ( + result.kind === 'failed' && + result.code !== PARTNER_NODE_MINT_DISABLED_CODE && + (result.status === null || result.status === 429 || result.status >= 500 || result.status < 300) + ) +} + function mintKey(subject: string, workspaceId: string): string { return JSON.stringify([subject, workspaceId]) } +type Gate = () => Promise + +const OPEN: Gate = async () => true + interface MintFence { epoch: number generation: number + family: string | null } interface HeldToken { @@ -60,11 +100,14 @@ export class ViewWorkspaceGrants { private desktopAllowed = new Set() private viewAllowed = new WeakMap>() private minted = new Map() + private partnerNodeMinted = new Map() + private partnerNodeRetryAt = new Map() private minting = new Map>() constructor( private readonly session: GrantSession, - private readonly mint: MintWorkspaceToken = mintWorkspaceToken + private readonly mint: MintWorkspaceToken = mintWorkspaceToken, + private readonly partnerNode: PartnerNodeTokenCalls = PARTNER_NODE_TOKEN_CALLS ) {} /** Desktop UI (sign-in, dashboard) chose `workspaceId`: every view may hold it. */ @@ -88,23 +131,55 @@ export class ViewWorkspaceGrants { this.desktopAllowed = new Set() this.viewAllowed = new WeakMap() this.minted = new Map() + this.partnerNodeMinted = new Map() + this.partnerNodeRetryAt = new Map() this.minting = new Map() } - async tokenFor(view: WebContents, workspaceId: string): Promise { + /** `gate` is awaited inside the reply fence, so a sign-in or switch during it drops the reply. */ + tokenFor(view: WebContents, workspaceId: string, gate: Gate = OPEN): Promise { + return this.handOut(view, workspaceId, gate, (fence) => this.workspaceToken(workspaceId, fence)) + } + + /** The current partner-node token of Desktop's session for `workspaceId`, under the same rules as {@link tokenFor}. */ + partnerNodeTokenFor( + view: WebContents, + workspaceId: string, + gate: Gate = OPEN + ): Promise { + return this.handOut(view, workspaceId, gate, (fence) => + this.partnerNodeToken(workspaceId, fence) + ) + } + + private async handOut( + view: WebContents, + workspaceId: string, + gate: Gate, + read: (fence: MintFence) => Promise + ): Promise { if (!this.mayHold(view, workspaceId)) return null const fence = this.currentFence() - const held = await this.workspaceToken(workspaceId, fence) + if (!(await gate()) || !this.isCurrent(fence)) return null + const held = await read(fence) if (!held || !this.isCurrent(fence) || !this.mayHold(view, workspaceId)) return null return this.session.currentSubject() === held.subject ? held.token : null } private currentFence(): MintFence { - return { epoch: this.epoch, generation: this.session.currentAuthGeneration() } + return { + epoch: this.epoch, + generation: this.session.currentAuthGeneration(), + family: this.session.currentGrantFamily() + } } private isCurrent(fence: MintFence): boolean { - return fence.epoch === this.epoch && fence.generation === this.session.currentAuthGeneration() + return ( + fence.epoch === this.epoch && + fence.generation === this.session.currentAuthGeneration() && + fence.family === this.session.currentGrantFamily() + ) } private seed(): void { @@ -134,7 +209,12 @@ export class ViewWorkspaceGrants { const allowed = await this.session.isWorkspaceMintAllowed(workspaceId) if (!allowed || !this.isCurrent(fence)) return null - const result = await this.mintOnce(accessToken, key, workspaceId, fence) + const result = await this.once(['workspace', key], fence, () => + this.mint(accessToken, workspaceId).then((minted) => { + reportMint(minted) + return minted + }) + ) if (!this.isCurrent(fence) || this.session.currentSubject() !== subject) return null if (result.kind !== 'minted') return null if (workspaceIdOf(result.token) !== workspaceId || subjectOf(result.token) !== subject) @@ -143,24 +223,88 @@ export class ViewWorkspaceGrants { return { token: result.token, subject } } - private mintOnce( - accessToken: string, + private async partnerNodeToken(workspaceId: string, fence: MintFence): Promise { + const accessToken = await this.session.getGrantAccessToken() + if (!this.isCurrent(fence) || !accessToken || !canMintPartnerNodeTokens(accessToken)) + return null + const subject = subjectOf(accessToken) + if (!subject) return null + const key = JSON.stringify([subject, grantFamilyOf(accessToken), workspaceId]) + const cached = this.partnerNodeMinted.get(key) + if (cached && cached.expiresAt - PARTNER_NODE_RENEW_BEFORE_MS > Date.now()) + return { token: cached.token, subject } + if (Date.now() < (this.partnerNodeRetryAt.get(key) ?? 0)) return this.stillHeld(key, subject) + + const allowed = await this.session.isWorkspaceMintAllowed(workspaceId) + if (!allowed || !this.isCurrent(fence)) return null + const result = await this.once(['partner-node', key], fence, () => + cached + ? this.renewOrMint(key, cached.token, accessToken, workspaceId, fence) + : this.partnerNode.mint(accessToken, workspaceId) + ) + const usable = + result.kind === 'minted' && + workspaceIdOf(result.token) === workspaceId && + subjectOf(result.token) === subject && + result.expiresAt - MINT_REFRESH_SKEW_MS > Date.now() + if (!usable && fence.epoch === this.epoch) { + const retryAfterMs = + result.kind === 'failed' && result.retryAfterSeconds !== undefined + ? result.retryAfterSeconds * 1000 + : 0 + const retryAt = Date.now() + Math.max(PARTNER_NODE_RETRY_MS, retryAfterMs) + this.partnerNodeRetryAt.set(key, Math.max(retryAt, this.partnerNodeRetryAt.get(key) ?? 0)) + if (cached && !isRetryableFailure(result)) this.forgetPartnerNodeToken(key, cached.token) + } + if (!this.isCurrent(fence) || this.session.currentSubject() !== subject) return null + if (usable) { + this.partnerNodeRetryAt.delete(key) + this.partnerNodeMinted.set(key, { token: result.token, expiresAt: result.expiresAt }) + return { token: result.token, subject } + } + return this.stillHeld(key, subject) + } + + private stillHeld(key: string, subject: string): HeldToken | null { + const held = this.partnerNodeMinted.get(key) + return held && held.expiresAt - MINT_REFRESH_SKEW_MS > Date.now() + ? { token: held.token, subject } + : null + } + + /** Renew in the same session; a session that ended, was refused or nears its end gets a new one. */ + private async renewOrMint( key: string, + partnerNodeToken: string, + accessToken: string, workspaceId: string, fence: MintFence ): Promise { - const flight = JSON.stringify([fence.generation, key]) + const renewed = await this.partnerNode.renew(partnerNodeToken) + if (renewed.kind === 'minted' && renewed.expiresAt - PARTNER_NODE_RENEW_BEFORE_MS > Date.now()) + return renewed + if (renewed.kind === 'failed' && !isRetryableFailure(renewed)) + this.forgetPartnerNodeToken(key, partnerNodeToken) + if (isRetryableFailure(renewed) || !this.isCurrent(fence)) return renewed + return this.partnerNode.mint(accessToken, workspaceId) + } + + private forgetPartnerNodeToken(key: string, token: string): void { + if (this.partnerNodeMinted.get(key)?.token === token) this.partnerNodeMinted.delete(key) + } + + private once( + key: readonly string[], + fence: MintFence, + start: () => Promise + ): Promise { + const flight = JSON.stringify([fence.generation, fence.family, ...key]) const inFlight = this.minting.get(flight) if (inFlight) return inFlight const minting = this.minting - const pending = this.mint(accessToken, workspaceId) - .then((result) => { - reportMint(result) - return result - }) - .finally(() => { - if (minting.get(flight) === pending) minting.delete(flight) - }) + const pending = start().finally(() => { + if (minting.get(flight) === pending) minting.delete(flight) + }) minting.set(flight, pending) return pending } diff --git a/src/preload/comfyPreload.test.ts b/src/preload/comfyPreload.test.ts index 9fc33f096..9796bf9fa 100644 --- a/src/preload/comfyPreload.test.ts +++ b/src/preload/comfyPreload.test.ts @@ -389,6 +389,7 @@ describe('comfyPreload auth bridge', () => { await Auth.getState() await Auth.getWorkspaceToken('ws-1') + await Auth.getPartnerNodeToken?.('ws-1') await Auth.requestSignIn() await Auth.signOut() await Auth.switchWorkspace('ws-2') @@ -396,6 +397,7 @@ describe('comfyPreload auth bridge', () => { expect(mocks.invoke.mock.calls).toEqual([ ['desktop2-auth:get-state'], ['desktop2-auth:get-workspace-token', 'ws-1'], + ['desktop2-auth:get-partner-node-token', 'ws-1'], ['desktop2-auth:request-sign-in'], ['desktop2-auth:sign-out'], ['desktop2-auth:switch-workspace', 'ws-2'] diff --git a/src/preload/comfyPreload.ts b/src/preload/comfyPreload.ts index cbd3612e0..e919383a5 100644 --- a/src/preload/comfyPreload.ts +++ b/src/preload/comfyPreload.ts @@ -306,6 +306,8 @@ const Auth: ComfyDesktop2AuthBridge = { getState: () => ipcRenderer.invoke('desktop2-auth:get-state'), getWorkspaceToken: (workspaceId) => ipcRenderer.invoke('desktop2-auth:get-workspace-token', workspaceId), + getPartnerNodeToken: (workspaceId) => + ipcRenderer.invoke('desktop2-auth:get-partner-node-token', workspaceId), requestSignIn: () => ipcRenderer.invoke('desktop2-auth:request-sign-in'), signOut: () => ipcRenderer.invoke('desktop2-auth:sign-out'), switchWorkspace: (workspaceId) => diff --git a/src/types/comfyDesktopBridge.ts b/src/types/comfyDesktopBridge.ts index ff0f5724e..0df2ff003 100644 --- a/src/types/comfyDesktopBridge.ts +++ b/src/types/comfyDesktopBridge.ts @@ -129,6 +129,10 @@ export interface ComfyDesktop2AuthBridge { * is scoped to; null when signed out, disabled, or the scope is missing, * malformed or different. The refresh token never leaves Desktop. */ getWorkspaceToken(workspaceId: string): Promise + /** The partner-node token for prompts in `workspaceId`, under the same rules + * as `getWorkspaceToken`. Desktop mints and renews it; null means use the + * workspace token. Absent on Desktop builds before it. */ + getPartnerNodeToken?(workspaceId: string): Promise /** Runs Desktop's browser sign-in and resolves with the resulting state. */ requestSignIn(): Promise /** Signs Desktop out of its account (every view follows) and resolves with From bcc8cb6bba37f8541f8a651b00a734b3a94a2a87 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 9 Nov 2026 19:12:13 -0500 Subject: [PATCH 42/75] feat(auth): sign-out revokes this device's Cloud grant, retrying until Cloud confirms Logout clears local tokens at once and queues the grant's refresh token for POST /oauth/revoke (RFC 7009). The queue keeps one safeStorage-encrypted file per token, so no write can touch another entry, and holds entries it cannot save in memory. A worker retries network errors and transient answers with backoff capped at 15 minutes, drops an entry on 200 or a permanent OAuth error, resumes at app start, and sends each token only to the Cloud recorded as its issuer. A refresh that lands after logout is revoked too. The vault now records the issuing Cloud and client at sign-in and refresh. A vault from an older build has no record and is revoked only after a refresh proves its Cloud. --- src/main/cloud/config.ts | 5 + src/main/cloud/oauth.ts | 36 +++ src/main/cloud/revocation.test.ts | 378 ++++++++++++++++++++++++++++++ src/main/cloud/revocation.ts | 73 ++++++ src/main/cloud/session.test.ts | 199 +++++++++++++++- src/main/cloud/session.ts | 30 ++- src/main/cloud/tokenStore.test.ts | 76 ++++++ src/main/cloud/tokenStore.ts | 133 ++++++++++- src/main/index.ts | 3 + 9 files changed, 927 insertions(+), 6 deletions(-) create mode 100644 src/main/cloud/revocation.test.ts create mode 100644 src/main/cloud/revocation.ts diff --git a/src/main/cloud/config.ts b/src/main/cloud/config.ts index 0dde318ce..cef58391d 100644 --- a/src/main/cloud/config.ts +++ b/src/main/cloud/config.ts @@ -11,10 +11,15 @@ export const WORKSPACE_MINT_SCOPE = 'comfy-cloud:workspace-token:mint' export const CLOUD_ISSUER = process.env.COMFY_CLOUD_ISSUER || DEFAULT_ISSUER +export function revokeUrlOf(issuer: string): string { + return `${issuer}/oauth/revoke` +} + export const CLOUD_CONFIG = { issuer: CLOUD_ISSUER, authorizeUrl: `${CLOUD_ISSUER}/oauth/authorize`, tokenUrl: `${CLOUD_ISSUER}/oauth/token`, + revokeUrl: revokeUrlOf(CLOUD_ISSUER), jwksUrl: `${CLOUD_ISSUER}/.well-known/jwks.json`, /** Workspace REST base (same host as the issuer). */ apiBase: `${CLOUD_ISSUER}/api`, diff --git a/src/main/cloud/oauth.ts b/src/main/cloud/oauth.ts index e81f31042..926407228 100644 --- a/src/main/cloud/oauth.ts +++ b/src/main/cloud/oauth.ts @@ -22,6 +22,14 @@ import type { AuthStatus, AuthTokens } from './types' const DEFAULT_SIGN_IN_TIMEOUT_MS = 600_000 const TOKEN_REQUEST_TIMEOUT_MS = 15_000 +/** RFC 7009 / 6749 errors that no retry of the same revocation can fix. */ +const PERMANENT_REVOKE_ERRORS: ReadonlySet = new Set([ + 'invalid_request', + 'invalid_client', + 'unauthorized_client', + 'unsupported_token_type' +]) + export interface OAuthOptions { authorizeUrl?: string tokenUrl?: string @@ -207,3 +215,31 @@ export async function refresh( ) return toTokens(r, refreshToken) } + +/** RFC 7009 revocation of one refresh token. `settled` on 200, or a refusal no retry can fix; + * `retry` on network failure, timeout or any other answer. */ +export async function revoke( + refreshToken: string, + clientId: string, + revokeUrl: string = CLOUD_CONFIG.revokeUrl +): Promise<'settled' | 'retry'> { + const controller = new AbortController() + const timer = setTimeout(() => controller.abort(), TOKEN_REQUEST_TIMEOUT_MS) + try { + const resp = await fetch(revokeUrl, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ token: refreshToken, client_id: clientId }).toString(), + redirect: 'manual', + signal: controller.signal + }) + const detail = await resp.text().catch(() => '') + if (resp.status === 200) return 'settled' + if (resp.status !== 400 && resp.status !== 401) return 'retry' + return PERMANENT_REVOKE_ERRORS.has(oauthErrorOf(detail) ?? '') ? 'settled' : 'retry' + } catch { + return 'retry' + } finally { + clearTimeout(timer) + } +} diff --git a/src/main/cloud/revocation.test.ts b/src/main/cloud/revocation.test.ts new file mode 100644 index 000000000..e6c0c4e96 --- /dev/null +++ b/src/main/cloud/revocation.test.ts @@ -0,0 +1,378 @@ +// @vitest-environment node +import * as fs from 'fs' +import type * as FsModule from 'fs' +import * as os from 'node:os' +import * as path from 'node:path' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const electronState = vi.hoisted(() => ({ userData: '' })) + +vi.mock('fs', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, rmSync: vi.fn(actual.rmSync), renameSync: vi.fn(actual.renameSync) } +}) + +vi.mock('electron', () => ({ + app: { getPath: vi.fn(() => electronState.userData), isPackaged: false }, + safeStorage: { + isEncryptionAvailable: vi.fn(() => true), + encryptString: vi.fn((value: string) => + Buffer.from(`enc:${Buffer.from(value, 'utf-8').toString('base64')}`, 'utf-8') + ), + decryptString: vi.fn((value: Buffer) => { + const text = value.toString('utf-8') + if (!text.startsWith('enc:')) throw new Error('not encrypted') + return Buffer.from(text.slice(4), 'base64').toString('utf-8') + }) + }, + shell: { openExternal: vi.fn(() => Promise.resolve()) } +})) + +import { safeStorage } from 'electron' + +import { CLOUD_CONFIG } from './config' +import { Revocations } from './revocation' +import { _resetForTest, addPendingRevocation, loadPendingRevocations } from './tokenStore' +import type { PendingRevocation } from './tokenStore' + +interface RevokeRequest { + url: string + token: string | null + clientId: string | null + redirect: RequestRedirect | undefined +} + +const MAX_WAIT_MS = 60 * 60_000 + +type Reply = () => Response | Promise + +let replies: Reply[] +let replyFor: Record +let requests: RevokeRequest[] + +const ok: Reply = () => new Response(null, { status: 200 }) +const offline: Reply = () => Promise.reject(new TypeError('fetch failed')) + +function status(code: number, body: unknown = {}): Reply { + return () => new Response(JSON.stringify(body), { status: code }) +} + +function revocation(refreshToken: string): PendingRevocation { + return { issuer: CLOUD_CONFIG.issuer, clientId: CLOUD_CONFIG.clientId, refreshToken } +} + +function queuedTokens(): string[] { + _resetForTest() + return loadPendingRevocations() + .pending.map((entry) => entry.refreshToken) + .sort() +} + +beforeEach(() => { + electronState.userData = fs.mkdtempSync(path.join(os.tmpdir(), 'comfy-cloud-revocation-')) + _resetForTest() + requests = [] + replies = [] + replyFor = {} + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string, init: RequestInit) => { + const body = new URLSearchParams(String(init.body)) + requests.push({ + url, + token: body.get('token'), + clientId: body.get('client_id'), + redirect: init.redirect + }) + return (replyFor[body.get('token') ?? ''] ?? replies.shift() ?? ok)() + }) + ) +}) + +afterEach(() => { + vi.useRealTimers() + _resetForTest() + fs.rmSync(electronState.userData, { recursive: true, force: true }) + vi.unstubAllGlobals() +}) + +describe('Revocations', () => { + it('revokes the token at the Cloud that issued it and forgets it once Cloud confirms', async () => { + const revocations = new Revocations() + + revocations.add(revocation('refresh-1')) + await revocations.drain() + + expect(requests).toEqual([ + { + url: CLOUD_CONFIG.revokeUrl, + token: 'refresh-1', + clientId: CLOUD_CONFIG.clientId, + redirect: 'manual' + } + ]) + expect(queuedTokens()).toEqual([]) + }) + + it('keeps the token on disk before the first attempt answers', async () => { + let answer: (response: Response) => void = () => {} + replies = [() => new Promise((resolve) => (answer = resolve))] + const revocations = new Revocations() + + revocations.add(revocation('refresh-1')) + expect(queuedTokens()).toEqual(['refresh-1']) + + answer(new Response(null, { status: 200 })) + await revocations.drain() + expect(queuedTokens()).toEqual([]) + }) + + it.each<[string, Reply]>([ + ['offline', offline], + ['a 500', status(500)], + ['a 503', status(503)], + ['a 429', status(429)], + ['a 404 before Cloud serves the endpoint', status(404)], + ['a 400 without an OAuth error', status(400, { message: 'bad gateway page' })], + ['a 400 with a transient OAuth error', status(400, { error: 'temporarily_unavailable' })], + ['a 202', status(202)], + ['a redirect', () => new Response(null, { status: 307, headers: { location: 'https://x' } })] + ])('keeps the token after %s and revokes it once Cloud is reachable', async (_name, failure) => { + vi.useFakeTimers() + replies = [failure, ok] + const revocations = new Revocations() + + revocations.add(revocation('refresh-1')) + await revocations.drain() + expect(queuedTokens()).toEqual(['refresh-1']) + + await vi.advanceTimersByTimeAsync(5_000) + + expect(requests.map((request) => request.token)).toEqual(['refresh-1', 'refresh-1']) + expect(queuedTokens()).toEqual([]) + }) + + it('backs off between attempts while Cloud stays unreachable', async () => { + vi.useFakeTimers() + replies = [offline, offline, offline] + const revocations = new Revocations() + + revocations.add(revocation('refresh-1')) + await revocations.drain() + await vi.advanceTimersByTimeAsync(5_000) + expect(requests).toHaveLength(2) + await vi.advanceTimersByTimeAsync(9_999) + expect(requests).toHaveLength(2) + await vi.advanceTimersByTimeAsync(1) + + expect(requests).toHaveLength(3) + }) + + it('keeps one backoff when a drain is started again during a backoff', async () => { + vi.useFakeTimers() + replies = [offline, offline, ok] + const revocations = new Revocations() + revocations.add(revocation('refresh-1')) + await revocations.drain() + + await revocations.drain() + expect(requests).toHaveLength(2) + await vi.advanceTimersByTimeAsync(9_999) + expect(requests).toHaveLength(2) + await vi.advanceTimersByTimeAsync(1) + + expect(requests).toHaveLength(3) + await vi.advanceTimersByTimeAsync(MAX_WAIT_MS) + expect(requests).toHaveLength(3) + expect(queuedTokens()).toEqual([]) + }) + + it.each<[string, number, string]>([ + ['invalid_client', 400, 'invalid_client'], + ['invalid_request', 400, 'invalid_request'], + ['invalid_client on 401', 401, 'invalid_client'] + ])('drops the token when Cloud refuses it with %s', async (_name, code, error) => { + vi.useFakeTimers() + replies = [status(code, { error })] + const revocations = new Revocations() + + revocations.add(revocation('refresh-1')) + await revocations.drain() + await vi.advanceTimersByTimeAsync(MAX_WAIT_MS) + + expect(requests).toHaveLength(1) + expect(queuedTokens()).toEqual([]) + }) + + it('revokes a token queued before a relaunch', async () => { + vi.useFakeTimers() + replies = [offline] + const before = new Revocations() + before.add(revocation('refresh-1')) + await before.drain() + expect(requests).toHaveLength(1) + + _resetForTest() + const relaunched = new Revocations() + await relaunched.drain() + + expect(requests.map((request) => request.token)).toEqual(['refresh-1', 'refresh-1']) + expect(queuedTokens()).toEqual([]) + }) + + it('sends every queued token, including one queued while another is in flight', async () => { + let answer: (response: Response) => void = () => {} + replies = [() => new Promise((resolve) => (answer = resolve))] + const revocations = new Revocations() + + revocations.add(revocation('refresh-1')) + revocations.add(revocation('refresh-2')) + answer(new Response(null, { status: 200 })) + await vi.waitFor(() => expect(requests).toHaveLength(2)) + await revocations.drain() + + expect(requests.map((request) => request.token)).toEqual(['refresh-1', 'refresh-2']) + expect(queuedTokens()).toEqual([]) + }) + + it('holds a token queued during a backoff until the backoff ends', async () => { + vi.useFakeTimers() + replies = [offline] + const revocations = new Revocations() + revocations.add(revocation('refresh-1')) + await revocations.drain() + + revocations.add(revocation('refresh-2')) + await vi.advanceTimersByTimeAsync(4_999) + expect(requests).toHaveLength(1) + await vi.advanceTimersByTimeAsync(1) + + expect(requests[0]?.token).toBe('refresh-1') + expect(requests.map((request) => request.token).sort()).toEqual([ + 'refresh-1', + 'refresh-1', + 'refresh-2' + ]) + expect(queuedTokens()).toEqual([]) + }) + + it('sends a token queued while another attempt fails, then retries only the failed one', async () => { + vi.useFakeTimers() + let fail: (error: Error) => void = () => {} + replies = [() => new Promise((_resolve, reject) => (fail = reject))] + const revocations = new Revocations() + revocations.add(revocation('refresh-1')) + revocations.add(revocation('refresh-2')) + + fail(new TypeError('fetch failed')) + await vi.advanceTimersByTimeAsync(4_999) + expect(requests.map((request) => request.token)).toEqual(['refresh-1', 'refresh-2']) + await vi.advanceTimersByTimeAsync(1) + + expect(requests.map((request) => request.token)).toEqual([ + 'refresh-1', + 'refresh-2', + 'refresh-1' + ]) + expect(queuedTokens()).toEqual([]) + }) + + it('keeps revoking other tokens while one keeps failing', async () => { + vi.useFakeTimers() + addPendingRevocation(revocation('refresh-1')) + addPendingRevocation(revocation('refresh-2')) + replyFor = { 'refresh-1': status(500) } + const revocations = new Revocations() + + await revocations.drain() + await vi.advanceTimersByTimeAsync(5_000) + + expect(queuedTokens()).toEqual(['refresh-1']) + expect(requests.filter((request) => request.token === 'refresh-2')).toHaveLength(1) + expect(requests.filter((request) => request.token === 'refresh-1')).toHaveLength(2) + }) + + it('does not resend a confirmed token whose saved copy cannot be deleted, and deletes it later', async () => { + vi.useFakeTimers() + const dir = path.join(electronState.userData, 'comfy-cloud-revocations') + addPendingRevocation(revocation('refresh-1')) + const revocations = new Revocations() + vi.mocked(fs.rmSync).mockImplementation(() => { + throw Object.assign(new Error('locked'), { code: 'EPERM' }) + }) + + try { + await revocations.drain() + await vi.advanceTimersByTimeAsync(5_000) + expect(fs.readdirSync(dir)).toHaveLength(1) + } finally { + vi.mocked(fs.rmSync).mockReset() + } + await vi.advanceTimersByTimeAsync(10_000) + + expect(requests.map((request) => request.token)).toEqual(['refresh-1']) + expect(fs.readdirSync(dir)).toEqual([]) + }) + + it('keeps a token it could not save in memory and leaves no partial file', async () => { + vi.useFakeTimers() + replies = [offline] + vi.mocked(fs.renameSync).mockImplementation(() => { + throw Object.assign(new Error('disk full'), { code: 'ENOSPC' }) + }) + const revocations = new Revocations() + + try { + revocations.add(revocation('refresh-1')) + await revocations.drain() + expect(fs.readdirSync(path.join(electronState.userData, 'comfy-cloud-revocations'))).toEqual( + [] + ) + expect(loadPendingRevocations().pending.map((entry) => entry.refreshToken)).toEqual([ + 'refresh-1' + ]) + } finally { + vi.mocked(fs.renameSync).mockReset() + } + }) + + it('reads a saved token again later when it could not be read at start', async () => { + vi.useFakeTimers() + addPendingRevocation(revocation('refresh-2')) + _resetForTest() + vi.mocked(safeStorage.isEncryptionAvailable).mockReturnValueOnce(false) + + const relaunched = new Revocations() + await relaunched.drain() + expect(requests).toEqual([]) + + await vi.advanceTimersByTimeAsync(5_000) + expect(requests.map((request) => request.token)).toEqual(['refresh-2']) + expect(queuedTokens()).toEqual([]) + }) + + it('sends each token only to the Cloud that issued it', async () => { + addPendingRevocation({ + issuer: 'https://other-cloud.example', + clientId: 'other-client', + refreshToken: 'refresh-elsewhere' + }) + addPendingRevocation(revocation('refresh-1')) + + await new Revocations().drain() + + expect(requests.map(({ url, token, clientId }) => ({ url, token, clientId }))).toEqual( + expect.arrayContaining([ + { + url: 'https://other-cloud.example/oauth/revoke', + token: 'refresh-elsewhere', + clientId: 'other-client' + }, + { url: CLOUD_CONFIG.revokeUrl, token: 'refresh-1', clientId: CLOUD_CONFIG.clientId } + ]) + ) + expect(requests).toHaveLength(2) + expect(queuedTokens()).toEqual([]) + }) +}) diff --git a/src/main/cloud/revocation.ts b/src/main/cloud/revocation.ts new file mode 100644 index 000000000..1ec2107e7 --- /dev/null +++ b/src/main/cloud/revocation.ts @@ -0,0 +1,73 @@ +/** + * Durable this-device sign-out: a signed-out grant's refresh token waits in an encrypted queue + * until the Cloud that issued it, and only that Cloud, confirms `POST /oauth/revoke`. + */ +import { revokeUrlOf } from './config' +import { revoke } from './oauth' +import { addPendingRevocation, loadPendingRevocations, removePendingRevocation } from './tokenStore' +import type { PendingRevocation } from './tokenStore' + +const FIRST_RETRY_MS = 5_000 +const MAX_RETRY_MS = 15 * 60_000 + +export class Revocations { + private draining: Promise | null = null + private drainAgain = false + private failures = 0 + private retryTimer: ReturnType | null = null + private readonly settledButSaved = new Set() + + /** Persist a revocation, then send it unless an earlier attempt is still running or backing off. */ + add(revocation: PendingRevocation): void { + addPendingRevocation(revocation) + if (this.draining) this.drainAgain = true + else if (!this.retryTimer) void this.drain() + } + + /** Send every queued revocation, each to the Cloud that issued it; resolves when this pass ends. */ + drain(): Promise { + if (this.draining) return this.draining + if (this.retryTimer) clearTimeout(this.retryTimer) + this.retryTimer = null + const draining = this.sendPending().finally(() => { + this.draining = null + const again = this.drainAgain && !this.retryTimer + this.drainAgain = false + if (again) void this.drain() + }) + this.draining = draining + return draining + } + + private async sendPending(): Promise { + for (const refreshToken of this.settledButSaved) { + if (removePendingRevocation(refreshToken)) this.settledButSaved.delete(refreshToken) + } + const failed = new Set() + for (;;) { + const { pending, complete } = loadPendingRevocations() + const next = pending.find( + (entry) => !failed.has(entry.refreshToken) && !this.settledButSaved.has(entry.refreshToken) + ) + if (!next) { + if (complete && failed.size === 0 && this.settledButSaved.size === 0) this.failures = 0 + else this.scheduleRetry() + return + } + if ((await revoke(next.refreshToken, next.clientId, revokeUrlOf(next.issuer))) === 'retry') { + failed.add(next.refreshToken) + } else if (!removePendingRevocation(next.refreshToken)) { + this.settledButSaved.add(next.refreshToken) + } + } + } + + private scheduleRetry(): void { + const delay = Math.min(FIRST_RETRY_MS * 2 ** this.failures, MAX_RETRY_MS) + this.failures += 1 + this.retryTimer = setTimeout(() => { + this.retryTimer = null + void this.drain() + }, delay) + } +} diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index 015e593b3..dc216ad56 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -22,7 +22,8 @@ vi.mock('electron', () => ({ }, shell: { openExternal: vi.fn(() => Promise.resolve()) } })) -vi.mock('./oauth', () => ({ +vi.mock('./oauth', async (importOriginal) => ({ + revoke: (await importOriginal()).revoke, signIn: vi.fn(), refresh: vi.fn(), openAuthorizePage: vi.fn(() => Promise.resolve()) @@ -43,6 +44,7 @@ import { isWorkspaceMintSwitchEnabled } from '../lib/workspaceMintSwitchFlag' import { statusFromAccessToken } from './claims' import { CLOUD_CONFIG } from './config' import { openAuthorizePage, refresh, signIn } from './oauth' +import type * as OAuthModule from './oauth' import { CloudSession, MINT_SCOPE_NOT_GRANTED_EVENT, @@ -51,7 +53,13 @@ import { WORKSPACE_SWITCH_EVENT } from './session' import { SignInFailure } from './signInFailure' -import { _resetForTest, clearTokens, saveGrant, saveWorkspaceToken } from './tokenStore' +import { + _resetForTest, + clearTokens, + loadPendingRevocations, + saveGrant, + saveWorkspaceToken +} from './tokenStore' import type { AuthTokens } from './types' import { listWorkspaceMembers, listWorkspaces } from './workspaces' @@ -125,6 +133,9 @@ type MintReply = (request: MintRequest) => Response | Promise let mintReply: MintReply let mintRequests: MintRequest[] +let revokeReply: () => Response | Promise +let revokedTokens: (string | null)[] +let revokeUrls: string[] function signedInResult(tokens: AuthTokens): Awaited> { return { tokens, status: statusFromAccessToken(tokens.accessToken) } @@ -202,10 +213,18 @@ beforeEach(() => { _resetForTest() mintRequests = [] mintReply = ({ workspaceId }) => minted(workspaceId) + revokedTokens = [] + revokeUrls = [] + revokeReply = () => new Response(null, { status: 200 }) mocked(isWorkspaceMintSwitchEnabled).mockResolvedValue(true) vi.stubGlobal( 'fetch', - vi.fn(async (_url: string, init: RequestInit) => { + vi.fn(async (url: string, init: RequestInit) => { + if (url.endsWith('/oauth/revoke')) { + revokeUrls.push(url) + revokedTokens.push(new URLSearchParams(String(init.body)).get('token')) + return revokeReply() + } const request = { workspaceId: (JSON.parse(String(init.body)) as { workspace_id: string }).workspace_id, bearer: new Headers(init.headers).get('Authorization')?.replace('Bearer ', '') ?? '' @@ -1998,3 +2017,177 @@ describe('CloudSession token provider', () => { expect(onSignedOut).not.toHaveBeenCalled() }) }) + +describe('CloudSession logout revokes this device on Cloud (T-V8, T-V18)', () => { + function pendingRevocations(): string[] { + _resetForTest() + return loadPendingRevocations() + .pending.map((entry) => entry.refreshToken) + .sort() + } + + it('signs out at once and queues the grant before Cloud answers', async () => { + const grant = grantOn('w1') + saveGrant(grant) + const answer = deferred() + revokeReply = () => answer.promise + const session = new CloudSession() + + session.logout() + + expect(session.isSignedIn()).toBe(false) + expect(revokedTokens).toEqual([grant.refreshToken]) + expect(pendingRevocations()).toEqual([grant.refreshToken]) + answer.resolve(new Response(null, { status: 200 })) + await vi.waitFor(() => expect(pendingRevocations()).toEqual([])) + }) + + it('forgets the queued grant once Cloud confirms', async () => { + const grant = grantOn('w1') + saveGrant(grant) + const session = new CloudSession() + + session.logout() + + await vi.waitFor(() => expect(pendingRevocations()).toEqual([])) + expect(revokedTokens).toEqual([grant.refreshToken]) + }) + + it('revokes the grant after the app comes back online', async () => { + vi.useFakeTimers() + const grant = grantOn('w1') + saveGrant(grant) + revokeReply = () => Promise.reject(new TypeError('fetch failed')) + const session = new CloudSession() + + session.logout() + await vi.advanceTimersByTimeAsync(0) + expect(pendingRevocations()).toEqual([grant.refreshToken]) + + revokeReply = () => new Response(null, { status: 200 }) + await vi.advanceTimersByTimeAsync(5_000) + + expect(revokedTokens).toEqual([grant.refreshToken, grant.refreshToken]) + expect(pendingRevocations()).toEqual([]) + }) + + it('revokes, after a relaunch, a grant whose sign-out never reached Cloud', async () => { + vi.useFakeTimers() + const grant = grantOn('w1') + saveGrant(grant) + revokeReply = () => Promise.reject(new TypeError('fetch failed')) + new CloudSession().logout() + await vi.waitFor(() => expect(revokedTokens).toHaveLength(1)) + + _resetForTest() + revokeReply = () => new Response(null, { status: 200 }) + new CloudSession().resumeRevocations() + + await vi.waitFor(() => expect(pendingRevocations()).toEqual([])) + expect(revokedTokens).toEqual([grant.refreshToken, grant.refreshToken]) + }) + + it('revokes only the signed-out grant, never minted tokens or a later grant', async () => { + const first = grantOn('w1') + saveGrant(first) + saveWorkspaceToken('w2', { accessToken: mintedJwt('w2'), expiresAt: FUTURE }) + const answer = deferred() + revokeReply = () => answer.promise + const session = new CloudSession() + + session.logout() + saveGrant(grantOn('w1', { revision: '-next' })) + session.resumeRevocations() + await session.switchWorkspace('w2') + answer.resolve(new Response(null, { status: 200 })) + await vi.waitFor(() => expect(pendingRevocations()).toEqual([])) + session.resumeRevocations() + + expect(revokedTokens).toEqual([first.refreshToken]) + expect(session.isSignedIn()).toBe(true) + }) + + it('also revokes a rotation that lands after logout', async () => { + const stale = grantOn('w1', { expiresAt: PAST }) + const rotated = grantOn('w1', { revision: '-fresh' }) + saveGrant(stale) + const rotation = deferred() + mocked(refresh).mockReturnValue(rotation.promise) + const session = new CloudSession() + + const request = session.getAccessToken() + session.logout() + rotation.resolve(rotated) + await request + + await vi.waitFor(() => + expect(revokedTokens).toEqual([stale.refreshToken, rotated.refreshToken]) + ) + await vi.waitFor(() => expect(pendingRevocations()).toEqual([])) + }) + + it('sends the grant only to the Cloud that issued it', async () => { + saveGrant(grantOn('w1')) + const vaultPath = path.join(electronState.userData, 'comfy-cloud-auth.bin') + fs.writeFileSync( + vaultPath, + safeStorage.encryptString(JSON.stringify({ ...vaultOnDisk(), issuer: 'https://other.test' })) + ) + _resetForTest() + + new CloudSession().logout() + + await vi.waitFor(() => expect(pendingRevocations()).toEqual([])) + expect(revokeUrls).toEqual(['https://other.test/oauth/revoke']) + expect(revokedTokens).toEqual(['refresh-w1']) + }) + + it('does not revoke a grant whose refresh lands after another account signed in and out', async () => { + const first = grantOn('w1', { expiresAt: PAST }) + saveGrant(first) + const rotation = deferred() + mocked(refresh).mockReturnValue(rotation.promise) + const session = new CloudSession() + const request = session.getAccessToken() + + const second = grantOn('w2', { subject: 'user-2' }) + browserSignInReturnsOnce(signedInResult(second)) + await session.login() + session.logout() + rotation.resolve(grantOn('w1', { revision: '-fresh' })) + await request + + await vi.waitFor(() => expect(pendingRevocations()).toEqual([])) + expect(revokedTokens).toEqual([second.refreshToken]) + }) + + it('revokes nothing for a grant from an older build until a refresh proves its Cloud', async () => { + const stale = grantOn('w1', { expiresAt: PAST }) + saveGrant(stale) + const vaultPath = path.join(electronState.userData, 'comfy-cloud-auth.bin') + const { issuer: _issuer, clientId: _clientId, ...older } = vaultOnDisk() + fs.writeFileSync(vaultPath, safeStorage.encryptString(JSON.stringify(older))) + _resetForTest() + const session = new CloudSession() + + session.logout() + expect(revokedTokens).toEqual([]) + + saveGrant(stale) + fs.writeFileSync(vaultPath, safeStorage.encryptString(JSON.stringify(older))) + _resetForTest() + const rotated = grantOn('w1', { revision: '-fresh' }) + mocked(refresh).mockResolvedValue(rotated) + await session.getAccessToken() + session.logout() + + await vi.waitFor(() => expect(revokedTokens).toEqual([rotated.refreshToken])) + }) + + it('revokes nothing when no one is signed in', () => { + new CloudSession().logout() + + expect(revokedTokens).toEqual([]) + expect(pendingRevocations()).toEqual([]) + }) +}) diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index e8faf3c5e..c594dfdb0 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -10,7 +10,9 @@ import type { TokenProvider } from '../comfybuilder' import * as mainTelemetry from '../lib/telemetry' import { isWorkspaceMintSwitchEnabled } from '../lib/workspaceMintSwitchFlag' import { canMintWorkspaceTokens, subjectOf, workspaceIdOf } from './claims' +import { CLOUD_CONFIG } from './config' import { openAuthorizePage, refresh, signIn } from './oauth' +import { Revocations } from './revocation' import { SignInFailure } from './signInFailure' import { activateWorkspace, @@ -20,6 +22,7 @@ import { isMintScopeWithheld, loadActiveWorkspaceId, loadGrant, + loadGrantOrigin, loadWorkspaceToken, replaceGrant, saveGrant, @@ -117,6 +120,8 @@ export class CloudSession { private loginInFlight: Promise | null = null private loginAuthorizeUrl: string | null = null private returnedToAnchorHandler: (() => void) | null = null + private readonly revocations = new Revocations() + private readonly signedOutRefreshTokens = new Set() /** Latest auth intent. Older flows may finish, but cannot change what a newer * login, workspace switch, or logout chose. */ @@ -176,15 +181,25 @@ export class CloudSession { this.loginAuthorizeUrl = null } - /** Forget tokens. Installed environments are untouched. */ + /** Forget tokens at once; revoke this grant on Cloud in the background. Installs are untouched. */ logout(): void { + const refreshToken = loadGrant()?.refreshToken + const origin = loadGrantOrigin() this.authGeneration += 1 this.switching = null this.mintBlockedUntil = 0 this.clearPendingLogin() + if (refreshToken && this.refreshing.has(refreshToken)) + this.signedOutRefreshTokens.add(refreshToken) + if (refreshToken && origin) this.revocations.add({ ...origin, refreshToken }) clearTokens() } + /** Resume revocations a previous run queued and Cloud has not confirmed. */ + resumeRevocations(): void { + void this.revocations.drain() + } + status(): AuthStatus { return getAuthStatus() } @@ -277,10 +292,21 @@ export class CloudSession { private async rotateGrant(grant: AuthTokens, refreshToken: string): Promise { try { - replaceGrant(grant.accessToken, refreshToken, await refresh(refreshToken)) + const rotated = await refresh(refreshToken) + const stored = replaceGrant(grant.accessToken, refreshToken, rotated) + const next = rotated.refreshToken + if (!stored && this.signedOutRefreshTokens.has(refreshToken) && next) { + this.revocations.add({ + issuer: CLOUD_CONFIG.issuer, + clientId: CLOUD_CONFIG.clientId, + refreshToken: next + }) + } return 'refreshed' } catch (error) { return isDefinitiveRefreshRefusal(error) ? 'ended' : 'unavailable' + } finally { + this.signedOutRefreshTokens.delete(refreshToken) } } diff --git a/src/main/cloud/tokenStore.test.ts b/src/main/cloud/tokenStore.test.ts index 05d19b58d..93afc7372 100644 --- a/src/main/cloud/tokenStore.test.ts +++ b/src/main/cloud/tokenStore.test.ts @@ -27,6 +27,7 @@ import { CLOUD_CONFIG } from './config' import { _resetForTest, activateWorkspace, + addPendingRevocation, clearTokens, dropWorkspaceToken, getAuthStatus, @@ -34,7 +35,10 @@ import { isMintScopeWithheld, loadActiveWorkspaceId, loadGrant, + loadGrantOrigin, + loadPendingRevocations, loadWorkspaceToken, + removePendingRevocation, replaceGrant, saveGrant, saveWorkspaceNames, @@ -109,6 +113,8 @@ describe('grant vault', () => { expect(readVault()).toEqual({ version: 2, + issuer: CLOUD_CONFIG.issuer, + clientId: CLOUD_CONFIG.clientId, subject: 'user-1', grant, activeWorkspaceId: 'w2', @@ -360,6 +366,76 @@ describe('grant vault', () => { expect(fs.existsSync(vaultPath())).toBe(false) }) + it('records the Cloud a grant came from at sign-in and at each refresh, and nothing for an older vault', () => { + const grant = tokens('user-1', 'w1') + saveGrant(grant) + expect(loadGrantOrigin()).toEqual({ + issuer: CLOUD_CONFIG.issuer, + clientId: CLOUD_CONFIG.clientId + }) + + const { issuer: _issuer, clientId: _clientId, ...older } = readVault() + writeVault(older) + _resetForTest() + expect(loadGrantOrigin()).toBeNull() + + replaceGrant(grant.accessToken, grant.refreshToken ?? '', tokens('user-1', 'w1', '-next')) + expect(loadGrantOrigin()).toEqual({ + issuer: CLOUD_CONFIG.issuer, + clientId: CLOUD_CONFIG.clientId + }) + }) + + it('keeps queued revocations encrypted, outside the vault, one file each', () => { + const first = { issuer: 'https://cloud.test', clientId: 'cid', refreshToken: 'refresh-1' } + const second = { ...first, refreshToken: 'refresh-2' } + saveGrant(tokens('user-1', 'w1')) + + addPendingRevocation(first) + addPendingRevocation(second) + clearTokens() + _resetForTest() + + expect(loadPendingRevocations()).toEqual({ + pending: expect.arrayContaining([first, second]), + complete: true + }) + const dir = path.join(electronState.userData, 'comfy-cloud-revocations') + const files = fs.readdirSync(dir) + expect(files).toHaveLength(2) + for (const file of files) { + expect(fs.readFileSync(path.join(dir, file), 'utf-8')).not.toMatch(/refresh-/) + } + }) + + it('never loses a queued revocation to an unreadable sibling entry', () => { + const first = { issuer: 'https://cloud.test', clientId: 'cid', refreshToken: 'refresh-1' } + addPendingRevocation(first) + const dir = path.join(electronState.userData, 'comfy-cloud-revocations') + fs.writeFileSync(path.join(dir, 'unreadable.bin'), 'garbage') + + addPendingRevocation({ ...first, refreshToken: 'refresh-2' }) + removePendingRevocation('refresh-2') + + expect(loadPendingRevocations()).toEqual({ pending: [first], complete: false }) + expect(fs.readFileSync(path.join(dir, 'unreadable.bin'), 'utf-8')).toBe('garbage') + }) + + it('keeps a revocation in memory while it cannot be saved, and saves it once storage works', () => { + const revocation = { issuer: 'https://cloud.test', clientId: 'cid', refreshToken: 'refresh-1' } + electronState.encryptionAvailable = false + + addPendingRevocation(revocation) + + expect(loadPendingRevocations().pending).toEqual([revocation]) + expect(fs.existsSync(path.join(electronState.userData, 'comfy-cloud-revocations'))).toBe(false) + + electronState.encryptionAvailable = true + expect(loadPendingRevocations().pending).toEqual([revocation]) + _resetForTest() + expect(loadPendingRevocations()).toEqual({ pending: [revocation], complete: true }) + }) + it('migrates a version 1 vault: the active bundle becomes the grant, others are dropped', () => { const active = tokens('user-1', 'w2') writeVault({ diff --git a/src/main/cloud/tokenStore.ts b/src/main/cloud/tokenStore.ts index cf6d0b876..bb1e8f4f2 100644 --- a/src/main/cloud/tokenStore.ts +++ b/src/main/cloud/tokenStore.ts @@ -4,18 +4,29 @@ * renderer, logs, or disk in plaintext. When the OS secure-storage backend is * unavailable, tokens are kept in memory for the process lifetime only. */ +import { createHash } from 'crypto' import { app, safeStorage } from 'electron' import * as fs from 'fs' import * as path from 'path' import { canMintWorkspaceTokens, statusFromAccessToken, subjectOf, workspaceIdOf } from './claims' +import { CLOUD_CONFIG } from './config' import type { AuthStatus, AuthTokens, Workspace } from './types' const AUTH_FILENAME = 'comfy-cloud-auth.bin' +const REVOCATIONS_DIRNAME = 'comfy-cloud-revocations' const VAULT_VERSION = 2 +/** The Cloud and OAuth client a grant was issued by. */ +export interface GrantOrigin { + issuer: string + clientId: string +} + interface TokenVault { version: typeof VAULT_VERSION + issuer?: string + clientId?: string subject?: string grant: AuthTokens mintScopeWithheld?: true @@ -32,7 +43,13 @@ interface LegacyVault { workspaceNames?: Record } +/** A signed-out grant's refresh token, kept until the Cloud that issued it confirms revocation. */ +export interface PendingRevocation extends GrantOrigin { + refreshToken: string +} + let cachedVault: TokenVault | null = null +const unsavedRevocations = new Map() let authFilePath: string | null = null let secureStorageUnavailable = false @@ -86,6 +103,8 @@ function isVault(v: unknown): v is TokenVault { (v.mintScopeWithheld === undefined || v.mintScopeWithheld === true) && (v.activeWorkspaceId === null || typeof v.activeWorkspaceId === 'string') && (v.subject === undefined || typeof v.subject === 'string') && + (v.issuer === undefined || typeof v.issuer === 'string') && + (v.clientId === undefined || typeof v.clientId === 'string') && isRecord(v.workspaceTokens) && Object.values(v.workspaceTokens).every(isTokens) && isWorkspaceNames(v.workspaceNames) @@ -178,7 +197,7 @@ export function saveGrant(grant: AuthTokens, options: { mintScopeWithheld?: bool const current = loadVault() const subject = subjectOf(grant.accessToken) if (!current || !subject || current.subject !== subject) { - persistVault({ ...vaultFor(grant), ...withheld }) + persistVault({ ...vaultFor(grant), ...configuredOrigin(), ...withheld }) return } delete current.mintScopeWithheld @@ -196,6 +215,7 @@ export function saveGrant(grant: AuthTokens, options: { mintScopeWithheld?: bool } } current.grant = grant + Object.assign(current, configuredOrigin()) if (!holdsToken(current, current.activeWorkspaceId)) current.activeWorkspaceId = workspaceIdOf(grant.accessToken) persistVault(current) @@ -211,6 +231,18 @@ export function loadGrant(): AuthTokens | null { return loadVault()?.grant ?? null } +function configuredOrigin(): GrantOrigin { + return { issuer: CLOUD_CONFIG.issuer, clientId: CLOUD_CONFIG.clientId } +} + +/** Where the stored grant came from: its browser sign-in or its last refresh. Null when unknown, + * as for a vault written before this was recorded and not refreshed since. */ +export function loadGrantOrigin(): GrantOrigin | null { + const vault = loadVault() + if (!vault?.issuer || !vault.clientId) return null + return { issuer: vault.issuer, clientId: vault.clientId } +} + /** The workspace API calls act in, or null when signed out or the grant has no workspace claim. */ export function loadActiveWorkspaceId(): string | null { return loadVault()?.activeWorkspaceId ?? null @@ -284,6 +316,7 @@ export function replaceGrant( return false } vault.grant = grant + Object.assign(vault, configuredOrigin()) if (canMintWorkspaceTokens(grant.accessToken)) delete vault.mintScopeWithheld persistVault(vault) return true @@ -298,6 +331,103 @@ export function clearTokens(): void { } } +function revocationsDir(): string { + return path.join(app.getPath('userData'), REVOCATIONS_DIRNAME) +} + +function revocationPath(refreshToken: string): string { + const name = createHash('sha256').update(refreshToken).digest('hex') + return path.join(revocationsDir(), `${name}.bin`) +} + +function isPendingRevocation(v: unknown): v is PendingRevocation { + return ( + isRecord(v) && + typeof v.issuer === 'string' && + typeof v.clientId === 'string' && + typeof v.refreshToken === 'string' + ) +} + +function writeRevocation(revocation: PendingRevocation): boolean { + if (!encryptionAvailable()) return false + const target = revocationPath(revocation.refreshToken) + try { + fs.mkdirSync(revocationsDir(), { recursive: true }) + fs.writeFileSync(`${target}.tmp`, safeStorage.encryptString(JSON.stringify(revocation))) + fs.renameSync(`${target}.tmp`, target) + return true + } catch { + removeQuietly(`${target}.tmp`) + return false + } +} + +/** The revocations still waiting for Cloud; `complete` is false when a saved one could not be read yet. */ +export interface PendingRevocations { + pending: PendingRevocation[] + complete: boolean +} + +function readSavedRevocations(): PendingRevocations { + let names: string[] + try { + names = fs.readdirSync(revocationsDir()).filter((name) => name.endsWith('.bin')) + } catch (error) { + return { pending: [], complete: (error as NodeJS.ErrnoException).code === 'ENOENT' } + } + if (names.length > 0 && !encryptionAvailable()) return { pending: [], complete: false } + const pending = names.flatMap((name) => { + try { + const parsed: unknown = JSON.parse( + safeStorage.decryptString(fs.readFileSync(path.join(revocationsDir(), name))) + ) + return isPendingRevocation(parsed) ? [parsed] : [] + } catch { + return [] + } + }) + return { pending, complete: pending.length === names.length } +} + +/** One encrypted file per revocation, so no write can touch another. An entry that could not be + * saved stays in memory, and saving it is retried on every read. */ +export function loadPendingRevocations(): PendingRevocations { + for (const [refreshToken, revocation] of unsavedRevocations) { + if (writeRevocation(revocation)) unsavedRevocations.delete(refreshToken) + } + const saved = readSavedRevocations() + const savedTokens = new Set(saved.pending.map((entry) => entry.refreshToken)) + const unsaved = [...unsavedRevocations.values()].filter( + (entry) => !savedTokens.has(entry.refreshToken) + ) + return { pending: [...saved.pending, ...unsaved], complete: saved.complete } +} + +export function addPendingRevocation(revocation: PendingRevocation): void { + if (!writeRevocation(revocation)) unsavedRevocations.set(revocation.refreshToken, revocation) +} + +/** False when the saved entry could not be deleted. */ +export function removePendingRevocation(refreshToken: string): boolean { + unsavedRevocations.delete(refreshToken) + removeQuietly(`${revocationPath(refreshToken)}.tmp`) + try { + fs.rmSync(revocationPath(refreshToken), { force: true }) + return true + } catch { + return false + } +} + +function removeQuietly(file: string): void { + try { + fs.rmSync(file, { force: true }) + } catch { + // Retried with the entry's next removal. + } +} + function activeToken(vault: TokenVault): string | null { const active = vault.activeWorkspaceId if (active === workspaceIdOf(vault.grant.accessToken)) return vault.grant.accessToken @@ -322,6 +452,7 @@ export function getAuthStatus(): AuthStatus { /** @internal reset module state between unit tests. */ export function _resetForTest(): void { cachedVault = null + unsavedRevocations.clear() authFilePath = null secureStorageUnavailable = false } diff --git a/src/main/index.ts b/src/main/index.ts index 017266f69..f72ccd6bc 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -124,6 +124,7 @@ import { initCloudFreeRuns } from './lib/cloudFreeRuns' import { initCoreBetaFlags, refreshCoreBetaFlags } from './lib/coreBetaCampaignFlags' import { initEmbeddedSessionFlag } from './lib/embeddedSessionFlag' import { initWorkspaceMintSwitchFlag } from './lib/workspaceMintSwitchFlag' +import { getCloudSession } from './devplatform/session' import { initStaffFlagTargeting } from './lib/staffFlagTargeting' import { initUserTier } from './lib/userTier' import { readSmartAppControlState } from './lib/smartAppControl' @@ -1555,6 +1556,8 @@ if (app.isPackaged && !app.requestSingleInstanceLock()) { void initWorkspaceMintSwitchFlag({ distinctId: installationId }) + getCloudSession().resumeRevocations() + const locale = (settings.get('language') as string | undefined) || app.getLocale().split('-')[0] i18n.init(locale) From 30c0a7ca4abac29fd9496fb0bdd3ec5d6e500995 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 9 Nov 2026 19:42:36 -0500 Subject: [PATCH 43/75] fix(auth): views may hold the workspace a local-instance promotion switched to --- .../ipc/registerDevPlatformHandlers.test.ts | 23 +++++++++++++++++++ .../lib/ipc/registerDevPlatformHandlers.ts | 3 +++ 2 files changed, 26 insertions(+) diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts index d71ba3b85..c503748f7 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts @@ -608,12 +608,35 @@ describe('registerDevPlatformHandlers', () => { }) expect(mocks.switchWorkspace).toHaveBeenCalledExactlyOnceWith('w2') + expect(mocks.allowDesktopWorkspace).toHaveBeenCalledExactlyOnceWith('w2') expect(mocks.createBuildDraft).toHaveBeenCalledOnce() expect(mocks.openExternal).toHaveBeenCalledExactlyOnceWith( 'https://platform.comfy.org/profile/builds/build-2/draft?workspace=w2' ) }) + it('does not let views hold a workspace the promotion failed to activate', async () => { + mocks.get.mockResolvedValue({ + id: 'local-1', + name: 'Workspace Instance', + sourceId: 'comfybuilder', + workspaceId: 'w2', + status: 'installed', + installPath: '/installs/local-1' + }) + mocks.switchWorkspace.mockResolvedValueOnce({ + signedIn: true, + workspaceId: 'w1', + workspaceType: 'team' + }) + + await expect(handler('comfybuilder:promoteLocalInstance')({}, 'local-1')).resolves.toEqual({ + ok: false, + message: 'Could not activate the instance workspace.' + }) + expect(mocks.allowDesktopWorkspace).not.toHaveBeenCalled() + }) + it('does not upload if the active workspace changes during capture', async () => { const inst = { id: 'local-1', diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.ts b/src/main/lib/ipc/registerDevPlatformHandlers.ts index df3e877c4..08eedfd5d 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.ts @@ -288,6 +288,9 @@ export function registerDevPlatformHandlers(): void { clearVersionCache() const switched = await session.switchWorkspace(workspaceId) clearVersionCache() + if (switched.signedIn && switched.workspaceId === workspaceId) { + getViewWorkspaceGrants().allowDesktop(workspaceId) + } broadcastAuthChanged(switched) if (!switched.signedIn || switched.workspaceId !== workspaceId) { return { ok: false, message: 'Could not activate the instance workspace.' } From 27380552e621dd9c175316bec3e9465b9c223cd3 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 9 Nov 2026 19:51:57 -0500 Subject: [PATCH 44/75] fix(auth): a dashboard switch lets views hold a workspace only once it is active --- src/main/lib/ipc/registerDevPlatformHandlers.test.ts | 11 +++++++++++ src/main/lib/ipc/registerDevPlatformHandlers.ts | 9 ++++++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts index c503748f7..298fc0250 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts @@ -499,6 +499,17 @@ describe('registerDevPlatformHandlers', () => { expect(win.webContents.send).toHaveBeenCalledWith('comfybuilder:authChanged', status) }) + it.for([ + ['signed out', { signedIn: false }], + ['still on another workspace', { signedIn: true, workspaceId: 'w1', workspaceType: 'team' }] + ] as const)('a dashboard switch that ends %s lets no view hold the target', async ([, reply]) => { + mocks.switchWorkspace.mockResolvedValue(reply) + + await handler('comfybuilder:switchWorkspace')({}, 'w2') + + expect(mocks.allowDesktopWorkspace).not.toHaveBeenCalled() + }) + it('captures fresh state, creates a draft, and opens the validated Platform URL', async () => { const result = await handler('comfybuilder:promoteLocalInstance')({}, 'local-1') diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.ts b/src/main/lib/ipc/registerDevPlatformHandlers.ts index 08eedfd5d..4219a8638 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.ts @@ -254,9 +254,12 @@ export function registerDevPlatformHandlers(): void { } ) - ipcMain.handle(DEVPLATFORM_CHANNELS.switchWorkspace, (_event, workspaceId: string) => { - getViewWorkspaceGrants().allowDesktop(workspaceId) - return switchCloudWorkspace(workspaceId) + ipcMain.handle(DEVPLATFORM_CHANNELS.switchWorkspace, async (_event, workspaceId: string) => { + const status = await switchCloudWorkspace(workspaceId) + if (status.signedIn && status.workspaceId === workspaceId) { + getViewWorkspaceGrants().allowDesktop(workspaceId) + } + return status }) ipcMain.handle( From 45b36d70f1c6913b11a748efd3cb60edfdd0f5fd Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 9 Nov 2026 19:56:25 -0500 Subject: [PATCH 45/75] fix(auth): an ended grant goes straight to sign-in without a refresh A mint answering 401 oauth_grant_ended means Cloud already revoked the grant (logout elsewhere, sign out of all devices, SSO). Refreshing it anyway is refresh-token reuse to Cloud: it answers 400, fires the oauth.refresh.reuse_detected theft metric and rewrites the family's revocation reason. Desktop now drops the ended grant's refresh token and takes the existing one-sign-in recovery directly; a plain 401 still refreshes once. Restored switches and token reads still never open a browser. --- src/main/cloud/session.test.ts | 45 +++++++++++++++++++++++++++------- src/main/cloud/session.ts | 10 ++++---- src/main/cloud/tokenStore.ts | 9 +++++++ 3 files changed, 50 insertions(+), 14 deletions(-) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index 015e593b3..57b756759 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -392,6 +392,7 @@ describe('CloudSession background token reads never open the browser', () => { await expect(session.getAccessToken()).resolves.toBeNull() + expect(refresh).not.toHaveBeenCalled() expect(signIn).not.toHaveBeenCalled() expect(onReturned).toHaveBeenCalledOnce() expect(session.currentWorkspaceId()).toBe('w1') @@ -1116,7 +1117,8 @@ describe('CloudSession.switchWorkspace reauthorize', () => { it('a second oauth_grant_ended 401 after a good refresh is reauthorize', async () => { saveGrant(grantOn('w1')) - mintReply = () => json(401, { code: 'oauth_grant_ended' }) + let replies = 0 + mintReply = () => (replies++ === 0 ? json(401, {}) : json(401, { code: 'oauth_grant_ended' })) mocked(refresh).mockResolvedValue(grantOn('w1', { revision: '-fresh' })) browserSignInReturns(signedInResult(grantOn('w2'))) @@ -1200,18 +1202,43 @@ describe('CloudSession.switchWorkspace reauthorize', () => { expect(signIn).not.toHaveBeenCalled() }) - it('a first oauth_grant_ended 401 still refreshes once before deciding', async () => { - saveGrant(grantOn('w1')) - let replies = 0 - mintReply = ({ workspaceId }) => - replies++ === 0 ? json(401, { code: 'oauth_grant_ended' }) : minted(workspaceId) + it('an oauth_grant_ended 401 asks for one sign-in without refreshing the ended grant', async () => { + const ended = grantOn('w1') + saveGrant(ended) + mintReply = ({ workspaceId, bearer }) => + bearer === ended.accessToken ? json(401, { code: 'oauth_grant_ended' }) : minted(workspaceId) mocked(refresh).mockResolvedValue(grantOn('w1', { revision: '-fresh' })) + browserSignInReturns(signedInResult(grantOn('w3'))) + const session = new CloudSession() - await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ - workspaceId: 'w2' + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) + await expect(session.switchWorkspace('w4')).resolves.toMatchObject({ workspaceId: 'w4' }) + + expect(refresh).not.toHaveBeenCalled() + expect(signIn).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ workspaceId: 'w2' })) + expect(browserEvents()).toEqual([{ reauthorize_reason: 'grant_ended' }]) + }) + + it('an oauth_grant_ended 401 leaves no refresh token, so the ended grant is never refreshed', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + const ended = grantOn('w1') + saveGrant(ended) + mintReply = () => json(401, { code: 'oauth_grant_ended' }) + mocked(refresh).mockResolvedValue(grantOn('w1', { revision: '-fresh' })) + const session = new CloudSession() + + await expect(session.switchWorkspace('w2', 'restored')).resolves.toMatchObject({ + workspaceId: 'w1', + workspaceSwitchFailure: 'retryable' }) + vi.setSystemTime(ended.expiresAt + 1) - expect(refresh).toHaveBeenCalledOnce() + await expect(session.getAccessToken()).resolves.toBe(ended.accessToken) + await expect(session.switchWorkspace('w1', 'restored')).resolves.toMatchObject({ + workspaceSwitchFailure: 'retryable' + }) + expect(refresh).not.toHaveBeenCalled() + expect(vaultOnDisk().grant).not.toHaveProperty('refreshToken') expect(signIn).not.toHaveBeenCalled() }) diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index e8faf3c5e..483b85035 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -16,6 +16,7 @@ import { activateWorkspace, clearTokens, dropWorkspaceToken, + endGrant, getAuthStatus, isMintScopeWithheld, loadActiveWorkspaceId, @@ -333,11 +334,7 @@ export class CloudSession { return refreshFailureOutcome(refreshed) } const first = await this.postMint(workspaceId, generation, subject) - if ( - first.kind !== 'unauthorized' && - !(first.kind === 'reauthorize' && first.reason === 'grant_ended') - ) - return first + if (first.kind !== 'unauthorized') return first const current = loadGrant() if (!current) return RETRYABLE const refreshed = await this.refreshGrant(current) @@ -360,6 +357,9 @@ export class CloudSession { ) return RETRYABLE const outcome = classifyMint(await mintWorkspaceToken(grant.accessToken, workspaceId)) + if (outcome.kind === 'reauthorize' && outcome.reason === 'grant_ended') { + endGrant(grant.accessToken) + } if ( outcome.kind === 'retryable' && outcome.retryAfterSeconds !== undefined && diff --git a/src/main/cloud/tokenStore.ts b/src/main/cloud/tokenStore.ts index cf6d0b876..ce5c2c7cd 100644 --- a/src/main/cloud/tokenStore.ts +++ b/src/main/cloud/tokenStore.ts @@ -289,6 +289,15 @@ export function replaceGrant( return true } +/** Drop the refresh token of a grant Cloud reported as ended, so it is never refreshed again. */ +export function endGrant(expectedAccessToken: string): void { + const vault = loadVault() + if (!vault || vault.grant.accessToken !== expectedAccessToken) return + const { refreshToken: _ended, ...grant } = vault.grant + vault.grant = grant + persistVault(vault) +} + export function clearTokens(): void { cachedVault = null try { From 1b187e474904da2a7d0cb53f006d9edd9f91da67 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 9 Nov 2026 19:58:42 -0500 Subject: [PATCH 46/75] fix(auth): revoke the grant a fresh sign-in replaces A switch that needs a sign-in (server kill switch, ops flag off, sso_required, ended grant) and a new sign-in both overwrote the stored grant without revoking it, so its refresh family stayed live on Cloud. The replaced grant's refresh token now goes into the durable revoke queue with its recorded issuer and client, under the same rules as sign-out, including a rotation of it still in flight. A grant Cloud already ended holds no refresh token, so nothing is queued for it. --- src/main/cloud/session.test.ts | 54 ++++++++++++++++++++++++++++++++-- src/main/cloud/session.ts | 21 +++++++++---- 2 files changed, 66 insertions(+), 9 deletions(-) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index 1243c346b..d59973c66 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -2169,7 +2169,7 @@ describe('CloudSession logout revokes this device on Cloud (T-V8, T-V18)', () => expect(revokedTokens).toEqual(['refresh-w1']) }) - it('does not revoke a grant whose refresh lands after another account signed in and out', async () => { + it('revokes a grant another account replaced, its late rotation, and the signed-out grant', async () => { const first = grantOn('w1', { expiresAt: PAST }) saveGrant(first) const rotation = deferred() @@ -2181,11 +2181,59 @@ describe('CloudSession logout revokes this device on Cloud (T-V8, T-V18)', () => browserSignInReturnsOnce(signedInResult(second)) await session.login() session.logout() - rotation.resolve(grantOn('w1', { revision: '-fresh' })) + const rotated = grantOn('w1', { revision: '-fresh' }) + rotation.resolve(rotated) await request await vi.waitFor(() => expect(pendingRevocations()).toEqual([])) - expect(revokedTokens).toEqual([second.refreshToken]) + expect([...revokedTokens].sort()).toEqual( + [first.refreshToken, rotated.refreshToken, second.refreshToken].sort() + ) + }) + + it.each<[string, AuthTokens]>([ + ['the same account', grantOn('w1', { revision: '-again' })], + ['another account', grantOn('w2', { subject: 'user-2' })] + ])('revokes the grant a new sign-in as %s replaces', async (_name, next) => { + const replaced = grantOn('w1') + saveGrant(replaced) + browserSignInReturns(signedInResult(next)) + + await new CloudSession().login() + + await vi.waitFor(() => expect(pendingRevocations()).toEqual([])) + expect(revokedTokens).toEqual([replaced.refreshToken]) + }) + + it.each<[string, () => void]>([ + ['the server kill switch', () => (mintReply = mintDisabled)], + ['the Desktop ops flag', killMintSwitch], + ['an SSO policy', () => (mintReply = () => json(403, { code: 'sso_required' }))] + ])('revokes the grant a switch replaces with a sign-in for %s', async (_name, arrange) => { + const replaced = grantOn('w1') + saveGrant(replaced) + arrange() + browserSignInReturns(signedInResult(grantOn('w2', { revision: '-consented' }))) + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w2' + }) + + await vi.waitFor(() => expect(pendingRevocations()).toEqual([])) + expect(revokedTokens).toEqual([replaced.refreshToken]) + }) + + it('revokes nothing for a grant Cloud reported ended when a sign-in replaces it', async () => { + saveGrant(grantOn('w1')) + mintReply = () => json(401, { code: 'oauth_grant_ended' }) + browserSignInReturns(signedInResult(grantOn('w2', { revision: '-consented' }))) + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w2' + }) + + expect(pendingRevocations()).toEqual([]) + expect(revokedTokens).toEqual([]) }) it('revokes nothing for a grant from an older build until a refresh proves its Cloud', async () => { diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index 1aa248974..9af0a2d6e 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -30,6 +30,7 @@ import { saveWorkspaceNames, saveWorkspaceToken } from './tokenStore' +import type { GrantOrigin } from './tokenStore' import type { AuthStatus, AuthTokens, @@ -122,7 +123,7 @@ export class CloudSession { private loginAuthorizeUrl: string | null = null private returnedToAnchorHandler: (() => void) | null = null private readonly revocations = new Revocations() - private readonly signedOutRefreshTokens = new Set() + private readonly retiredRefreshTokens = new Set() /** Latest auth intent. Older flows may finish, but cannot change what a newer * login, workspace switch, or logout chose. */ @@ -171,9 +172,12 @@ export class CloudSession { } private storeSignedInGrant(tokens: AuthTokens): void { + const replaced = loadGrant()?.refreshToken + const origin = loadGrantOrigin() this.mintBlockedUntil = 0 const mintScopeWithheld = !canMintWorkspaceTokens(tokens.accessToken) saveGrant(tokens, { mintScopeWithheld }) + if (replaced !== tokens.refreshToken) this.retireGrant(replaced, origin) if (mintScopeWithheld) mainTelemetry.emit(MINT_SCOPE_NOT_GRANTED_EVENT) } @@ -190,12 +194,17 @@ export class CloudSession { this.switching = null this.mintBlockedUntil = 0 this.clearPendingLogin() - if (refreshToken && this.refreshing.has(refreshToken)) - this.signedOutRefreshTokens.add(refreshToken) - if (refreshToken && origin) this.revocations.add({ ...origin, refreshToken }) + this.retireGrant(refreshToken, origin) clearTokens() } + /** Revoke a grant Desktop no longer holds, and any rotation of it still in flight. */ + private retireGrant(refreshToken: string | undefined, origin: GrantOrigin | null): void { + if (!refreshToken) return + if (this.refreshing.has(refreshToken)) this.retiredRefreshTokens.add(refreshToken) + if (origin) this.revocations.add({ ...origin, refreshToken }) + } + /** Resume revocations a previous run queued and Cloud has not confirmed. */ resumeRevocations(): void { void this.revocations.drain() @@ -296,7 +305,7 @@ export class CloudSession { const rotated = await refresh(refreshToken) const stored = replaceGrant(grant.accessToken, refreshToken, rotated) const next = rotated.refreshToken - if (!stored && this.signedOutRefreshTokens.has(refreshToken) && next) { + if (!stored && this.retiredRefreshTokens.has(refreshToken) && next) { this.revocations.add({ issuer: CLOUD_CONFIG.issuer, clientId: CLOUD_CONFIG.clientId, @@ -307,7 +316,7 @@ export class CloudSession { } catch (error) { return isDefinitiveRefreshRefusal(error) ? 'ended' : 'unavailable' } finally { - this.signedOutRefreshTokens.delete(refreshToken) + this.retiredRefreshTokens.delete(refreshToken) } } From 1882926e75db58dd06f494834fefdb08c0392b66 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 9 Nov 2026 20:07:50 -0500 Subject: [PATCH 47/75] fix(auth): an ended grant also ends a rotation of it stored meanwhile A token read can rotate the grant while a mint that used the previous access token is still out. When that mint answers oauth_grant_ended, the stored rotation belongs to the same ended family; dropping only an exact access-token match left its refresh token behind for a later refresh. The session now follows the rotations it stored from the bearer the mint used. --- src/main/cloud/session.test.ts | 23 +++++++++++++++++++++++ src/main/cloud/session.ts | 14 ++++++++++++-- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index 57b756759..19beff82b 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -1219,6 +1219,29 @@ describe('CloudSession.switchWorkspace reauthorize', () => { expect(browserEvents()).toEqual([{ reauthorize_reason: 'grant_ended' }]) }) + it('an oauth_grant_ended 401 also ends a rotation of the grant stored while the mint was out', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + const ended = grantOn('w1') + const rotated = grantOn('w1', { revision: '-fresh', expiresAt: ended.expiresAt + 3_600_000 }) + saveGrant(ended) + const late = deferred() + mintReply = () => late.promise + mocked(refresh).mockResolvedValue(rotated) + const session = new CloudSession() + + const switching = session.switchWorkspace('w2', 'restored') + await vi.waitFor(() => expect(mintRequests).toHaveLength(1)) + vi.setSystemTime(ended.expiresAt + 1) + await expect(session.getAccessToken()).resolves.toBe(rotated.accessToken) + late.resolve(json(401, { code: 'oauth_grant_ended' })) + await switching + vi.setSystemTime(rotated.expiresAt + 1) + + await expect(session.getAccessToken()).resolves.toBe(rotated.accessToken) + expect(refresh).toHaveBeenCalledExactlyOnceWith(ended.refreshToken) + expect(vaultOnDisk().grant).not.toHaveProperty('refreshToken') + }) + it('an oauth_grant_ended 401 leaves no refresh token, so the ended grant is never refreshed', async () => { vi.useFakeTimers({ toFake: ['Date'] }) const ended = grantOn('w1') diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index 483b85035..5463e5aa8 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -111,6 +111,7 @@ function reportBrowser(reason: ReauthorizeReason): void { export class CloudSession { private readonly refreshing = new Map>() + private readonly rotatedTo = new Map() private readonly minting = new Map>() private switching: { workspaceId: string; result: Promise } | null = null private switchIntent: WorkspaceSwitchIntent = 'chosen' @@ -278,7 +279,9 @@ export class CloudSession { private async rotateGrant(grant: AuthTokens, refreshToken: string): Promise { try { - replaceGrant(grant.accessToken, refreshToken, await refresh(refreshToken)) + const rotated = await refresh(refreshToken) + if (replaceGrant(grant.accessToken, refreshToken, rotated)) + this.rotatedTo.set(grant.accessToken, rotated.accessToken) return 'refreshed' } catch (error) { return isDefinitiveRefreshRefusal(error) ? 'ended' : 'unavailable' @@ -358,7 +361,7 @@ export class CloudSession { return RETRYABLE const outcome = classifyMint(await mintWorkspaceToken(grant.accessToken, workspaceId)) if (outcome.kind === 'reauthorize' && outcome.reason === 'grant_ended') { - endGrant(grant.accessToken) + this.endGrantFamily(grant.accessToken) } if ( outcome.kind === 'retryable' && @@ -371,6 +374,13 @@ export class CloudSession { return outcome } + /** End the stored grant if it is `accessToken` or a rotation of it. */ + private endGrantFamily(accessToken: string): void { + for (let token: string | undefined = accessToken; token; token = this.rotatedTo.get(token)) { + endGrant(token) + } + } + /** The signed-in user's workspaces; unavailable catalogs reject rather than imply removal. */ async listWorkspaces(): Promise { const token = await this.getGrantAccessToken() From 7180ad5a6801d4bf6ed829a0b2fa3ac835f31765 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 9 Nov 2026 20:09:31 -0500 Subject: [PATCH 48/75] test(auth): stub revoke where a switch now revokes the replaced grant --- src/main/lib/ipc/switchCloudWorkspace.session.test.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/main/lib/ipc/switchCloudWorkspace.session.test.ts b/src/main/lib/ipc/switchCloudWorkspace.session.test.ts index 74cf98df3..4284b8c6e 100644 --- a/src/main/lib/ipc/switchCloudWorkspace.session.test.ts +++ b/src/main/lib/ipc/switchCloudWorkspace.session.test.ts @@ -26,6 +26,7 @@ vi.mock('electron', () => ({ vi.mock('../../cloud/oauth', () => ({ signIn: vi.fn(), refresh: vi.fn(), + revoke: vi.fn(async () => 'settled'), openAuthorizePage: vi.fn(async () => {}) })) vi.mock('../../devplatform/session', () => ({ @@ -61,7 +62,7 @@ vi.mock('../embeddedSessionFlag', () => ({ isEmbeddedSessionEnabled: async () => vi.mock('../workspaceMintSwitchFlag', () => ({ isWorkspaceMintSwitchEnabled: async () => true })) import { CLOUD_CONFIG } from '../../cloud/config' -import { refresh, signIn } from '../../cloud/oauth' +import { refresh, revoke, signIn } from '../../cloud/oauth' import { CloudSession } from '../../cloud/session' import { SignInFailure } from '../../cloud/signInFailure' import { _resetForTest, clearTokens, saveGrant } from '../../cloud/tokenStore' @@ -164,6 +165,11 @@ describe('switchCloudWorkspace with a real session, vault and view grants', () = mintReply = minted await expect(getViewWorkspaceGrants().tokenFor(otherView, 'X')).resolves.toBe(mintedJwt('X')) + expect(revoke).toHaveBeenCalledExactlyOnceWith( + grantOn('A').refreshToken, + CLOUD_CONFIG.clientId, + expect.any(String) + ) }) it('a view switch that mints stays isolated to that view', async () => { From 4718e7065ca199edfa3e3a8c2a2e27c6158af198 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 9 Nov 2026 20:11:25 -0500 Subject: [PATCH 49/75] fix(auth): revoke a replaced grant only once the new one is saved If the vault write for the new sign-in fails, the previous grant is still the one on disk and a relaunch reads it back. Revoking it then would leave Desktop starting on a revoked grant whose next refresh Cloud treats as reuse. saveGrant now reports whether the vault reached disk, and the replaced grant is retired only when it did. --- src/main/cloud/session.test.ts | 21 ++++++++++++++++++++- src/main/cloud/session.ts | 4 ++-- src/main/cloud/tokenStore.ts | 19 ++++++++++++------- 3 files changed, 34 insertions(+), 10 deletions(-) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index b58c3d121..615fb0387 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -3,7 +3,7 @@ import * as fs from 'node:fs' import * as os from 'node:os' import * as path from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' const electronState = vi.hoisted(() => ({ userData: '' })) @@ -2246,6 +2246,25 @@ describe('CloudSession logout revokes this device on Cloud (T-V8, T-V18)', () => expect(revokedTokens).toEqual([replaced.refreshToken]) }) + it('keeps the replaced grant when the new one could not be saved, since a relaunch reads it back', async () => { + const replaced = grantOn('w1') + saveGrant(replaced) + browserSignInReturns(signedInResult(grantOn('w1', { revision: '-again' }))) + const encrypt = mocked(safeStorage.encryptString).getMockImplementation() + onTestFinished(() => { + mocked(safeStorage.encryptString).mockImplementation(encrypt!) + }) + mocked(safeStorage.encryptString).mockImplementation(() => { + throw new Error('disk full') + }) + + await new CloudSession().login() + + expect(pendingRevocations()).toEqual([]) + expect(revokedTokens).toEqual([]) + expect(vaultOnDisk().grant).toEqual(replaced) + }) + it('revokes nothing for a grant Cloud reported ended when a sign-in replaces it', async () => { saveGrant(grantOn('w1')) mintReply = () => json(401, { code: 'oauth_grant_ended' }) diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index 19dc06817..14d2b658d 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -177,8 +177,8 @@ export class CloudSession { const origin = loadGrantOrigin() this.mintBlockedUntil = 0 const mintScopeWithheld = !canMintWorkspaceTokens(tokens.accessToken) - saveGrant(tokens, { mintScopeWithheld }) - if (replaced !== tokens.refreshToken) this.retireGrant(replaced, origin) + const saved = saveGrant(tokens, { mintScopeWithheld }) + if (saved && replaced !== tokens.refreshToken) this.retireGrant(replaced, origin) if (mintScopeWithheld) mainTelemetry.emit(MINT_SCOPE_NOT_GRANTED_EVENT) } diff --git a/src/main/cloud/tokenStore.ts b/src/main/cloud/tokenStore.ts index 5c4752143..ec9ab9d2d 100644 --- a/src/main/cloud/tokenStore.ts +++ b/src/main/cloud/tokenStore.ts @@ -142,23 +142,26 @@ function migratedVault(legacy: LegacyVault): TokenVault | null { } } -function persistVault(vault: TokenVault): void { +/** False when an older vault may still be on disk for the next launch to read. */ +function persistVault(vault: TokenVault): boolean { cachedVault = vault if (!encryptionAvailable()) { // No secure backend: never write plaintext, and drop any prior encrypted // file so a later run can't read stale tokens back as current. try { fs.rmSync(filePath(), { force: true }) + return true } catch { - /* nothing to remove */ + return false } - return } try { fs.writeFileSync(filePath(), safeStorage.encryptString(JSON.stringify(vault))) + return true } catch { // A failed persist must not fail the sign-in the user just completed; the // in-memory cache still holds the tokens for this session. + return false } } @@ -192,13 +195,15 @@ function holdsToken(vault: TokenVault, workspaceId: string | null): boolean { /** Store the grant from a browser sign-in. A changed account replaces the vault. The old access * token stays held for its old anchor; an active workspace with no held token moves to the new one. */ -export function saveGrant(grant: AuthTokens, options: { mintScopeWithheld?: boolean } = {}): void { +export function saveGrant( + grant: AuthTokens, + options: { mintScopeWithheld?: boolean } = {} +): boolean { const withheld = options.mintScopeWithheld ? ({ mintScopeWithheld: true } as const) : {} const current = loadVault() const subject = subjectOf(grant.accessToken) if (!current || !subject || current.subject !== subject) { - persistVault({ ...vaultFor(grant), ...configuredOrigin(), ...withheld }) - return + return persistVault({ ...vaultFor(grant), ...configuredOrigin(), ...withheld }) } delete current.mintScopeWithheld Object.assign(current, withheld) @@ -218,7 +223,7 @@ export function saveGrant(grant: AuthTokens, options: { mintScopeWithheld?: bool Object.assign(current, configuredOrigin()) if (!holdsToken(current, current.activeWorkspaceId)) current.activeWorkspaceId = workspaceIdOf(grant.accessToken) - persistVault(current) + return persistVault(current) } /** A browser sign-in returned this grant without the mint scope, so another trip would not help. */ From 9f520cc3996eb7803f129001e3206af03f43214d Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 9 Nov 2026 20:19:09 -0500 Subject: [PATCH 50/75] fix(auth): a view mint told the grant ended also stops its refresh Embedded views mint workspace tokens through their own path, which returned null on 401 oauth_grant_ended but left the grant's refresh token stored, so the next token read in the refresh window refreshed a family Cloud had already revoked. The view path now ends the grant through the session the same way the session's own mint does. --- src/main/cloud/session.ts | 4 ++-- src/main/lib/embeddedSession.test.ts | 8 ++++++-- .../lib/ipc/registerDevPlatformHandlers.test.ts | 9 ++++++--- src/main/lib/viewWorkspaceGrants.session.test.ts | 15 ++++++++++++++- src/main/lib/viewWorkspaceGrants.test.ts | 3 ++- src/main/lib/viewWorkspaceGrants.ts | 6 +++++- 6 files changed, 35 insertions(+), 10 deletions(-) diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index 5463e5aa8..3d238c227 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -374,8 +374,8 @@ export class CloudSession { return outcome } - /** End the stored grant if it is `accessToken` or a rotation of it. */ - private endGrantFamily(accessToken: string): void { + /** Cloud ended the grant `accessToken` came from: drop its refresh token, and that of any rotation of it. */ + endGrantFamily(accessToken: string): void { for (let token: string | undefined = accessToken; token; token = this.rotatedTo.get(token)) { endGrant(token) } diff --git a/src/main/lib/embeddedSession.test.ts b/src/main/lib/embeddedSession.test.ts index 2246a993e..da31de098 100644 --- a/src/main/lib/embeddedSession.test.ts +++ b/src/main/lib/embeddedSession.test.ts @@ -1,6 +1,8 @@ // @vitest-environment node import { beforeEach, describe, expect, it, vi } from 'vitest' +import type * as WorkspaceTokenModule from '../cloud/workspaceToken' + const mocks = vi.hoisted(() => ({ enabled: true, getGrantAccessToken: vi.fn<() => Promise>(), @@ -18,10 +20,12 @@ vi.mock('../devplatform/session', () => ({ currentWorkspaceId: () => mocks.current, currentSubject: () => (mocks.current ? 'user-1' : null), currentAuthGeneration: () => 0, - isWorkspaceMintAllowed: async () => true + isWorkspaceMintAllowed: async () => true, + endGrantFamily: () => {} }) })) -vi.mock('../cloud/workspaceToken', () => ({ +vi.mock('../cloud/workspaceToken', async (importOriginal) => ({ + ...(await importOriginal()), mintWorkspaceToken: mocks.mint })) vi.mock('../host/registry', () => ({ diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts index 2da098bfd..4f1ae1ef3 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts @@ -574,7 +574,8 @@ describe('registerDevPlatformHandlers', () => { currentAuthGeneration: () => 1, getGrantAccessToken: async () => jwt({ sub: 'user-1', workspace_id: 'w1', scope: CLOUD_CONFIG.scope }), - isWorkspaceMintAllowed: async () => true + isWorkspaceMintAllowed: async () => true, + endGrantFamily: () => {} }, async (_grant, workspaceId) => ({ kind: 'minted', @@ -670,7 +671,8 @@ describe('registerDevPlatformHandlers', () => { auth.subject ? jwt({ sub: auth.subject, workspace_id: 'home', scope: CLOUD_CONFIG.scope }) : null, - isWorkspaceMintAllowed: async () => true + isWorkspaceMintAllowed: async () => true, + endGrantFamily: () => {} }, async (_grant, workspaceId) => ({ kind: 'minted', @@ -848,7 +850,8 @@ describe('registerDevPlatformHandlers', () => { currentAuthGeneration: () => generation, getGrantAccessToken: async () => jwt({ sub: subject, workspace_id: 'home', scope: CLOUD_CONFIG.scope }), - isWorkspaceMintAllowed: async () => true + isWorkspaceMintAllowed: async () => true, + endGrantFamily: () => {} }, async (_grant, workspaceId) => ({ kind: 'minted', diff --git a/src/main/lib/viewWorkspaceGrants.session.test.ts b/src/main/lib/viewWorkspaceGrants.session.test.ts index 5ec3e41d6..6cc629eba 100644 --- a/src/main/lib/viewWorkspaceGrants.session.test.ts +++ b/src/main/lib/viewWorkspaceGrants.session.test.ts @@ -29,7 +29,7 @@ vi.mock('./workspaceMintSwitchFlag', () => ({ })) import { CLOUD_CONFIG } from '../cloud/config' -import { openAuthorizePage, signIn } from '../cloud/oauth' +import { openAuthorizePage, refresh, signIn } from '../cloud/oauth' import { CloudSession } from '../cloud/session' import { _resetForTest, clearTokens, saveGrant } from '../cloud/tokenStore' import type { AuthTokens } from '../cloud/types' @@ -213,6 +213,19 @@ describe('view token path through a real session', () => { expect(mintRequests).toEqual([]) }) + it('a view mint told the grant ended never lets the grant be refreshed', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + mintReply = () => new Response(JSON.stringify({ code: 'oauth_grant_ended' }), { status: 401 }) + + await expect(grants.tokenFor(view, 'w1')).resolves.toBeNull() + vi.setSystemTime(GRANT.expiresAt + 1) + await expect(grants.tokenFor(view, 'w1')).resolves.toBeNull() + + expect(refresh).not.toHaveBeenCalled() + expect(signIn).not.toHaveBeenCalled() + expect(openAuthorizePage).not.toHaveBeenCalled() + }) + it('a server kill refuses a view mint with no browser', async () => { await activeOnW2() mintReply = () => diff --git a/src/main/lib/viewWorkspaceGrants.test.ts b/src/main/lib/viewWorkspaceGrants.test.ts index a12197596..d6f2f114c 100644 --- a/src/main/lib/viewWorkspaceGrants.test.ts +++ b/src/main/lib/viewWorkspaceGrants.test.ts @@ -73,7 +73,8 @@ function grantSession( currentSubject: () => (current ? user : null), currentAuthGeneration: () => generation, getGrantAccessToken, - isWorkspaceMintAllowed: async () => true + isWorkspaceMintAllowed: async () => true, + endGrantFamily: () => {} } } diff --git a/src/main/lib/viewWorkspaceGrants.ts b/src/main/lib/viewWorkspaceGrants.ts index 69f8be0b9..356919a64 100644 --- a/src/main/lib/viewWorkspaceGrants.ts +++ b/src/main/lib/viewWorkspaceGrants.ts @@ -1,7 +1,7 @@ import type { WebContents } from 'electron' import { canMintWorkspaceTokens, subjectOf, workspaceIdOf } from '../cloud/claims' -import { mintWorkspaceToken } from '../cloud/workspaceToken' +import { classifyMint, mintWorkspaceToken } from '../cloud/workspaceToken' import type { WorkspaceTokenMint } from '../cloud/workspaceToken' import { getCloudSession } from '../devplatform/session' import * as mainTelemetry from './telemetry' @@ -28,6 +28,7 @@ export interface GrantSession { currentAuthGeneration(): number getGrantAccessToken(): Promise isWorkspaceMintAllowed(workspaceId: string): Promise + endGrantFamily(accessToken: string): void } export type MintWorkspaceToken = ( @@ -156,6 +157,9 @@ export class ViewWorkspaceGrants { const pending = this.mint(accessToken, workspaceId) .then((result) => { reportMint(result) + const outcome = classifyMint(result) + if (outcome.kind === 'reauthorize' && outcome.reason === 'grant_ended') + this.session.endGrantFamily(accessToken) return result }) .finally(() => { From d42a61f326727f31f9f13ec4b75b2c04b46a4ae2 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 9 Nov 2026 23:04:02 -0500 Subject: [PATCH 51/75] fix(auth): settle a revocation on any 2xx from /oauth/revoke --- src/main/cloud/oauth.ts | 4 ++-- src/main/cloud/revocation.test.ts | 13 ++++++++++++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/main/cloud/oauth.ts b/src/main/cloud/oauth.ts index 510040e66..9f88a610c 100644 --- a/src/main/cloud/oauth.ts +++ b/src/main/cloud/oauth.ts @@ -210,9 +210,9 @@ export async function revoke( redirect: 'manual', signal: controller.signal }) - const detail = await resp.text().catch(() => '') - if (resp.status === 200) return 'settled' + if (resp.ok) return 'settled' if (resp.status !== 400 && resp.status !== 401) return 'retry' + const detail = await resp.text().catch(() => '') return PERMANENT_REVOKE_ERRORS.has(oauthErrorOf(detail) ?? '') ? 'settled' : 'retry' } catch { return 'retry' diff --git a/src/main/cloud/revocation.test.ts b/src/main/cloud/revocation.test.ts index e6c0c4e96..b0ab6862a 100644 --- a/src/main/cloud/revocation.test.ts +++ b/src/main/cloud/revocation.test.ts @@ -128,6 +128,17 @@ describe('Revocations', () => { expect(queuedTokens()).toEqual([]) }) + it.each([200, 202, 204])('drops the token once Cloud answers %i', async (code) => { + replies = [() => new Response(null, { status: code })] + const revocations = new Revocations() + + revocations.add(revocation('refresh-1')) + await revocations.drain() + + expect(requests).toHaveLength(1) + expect(queuedTokens()).toEqual([]) + }) + it.each<[string, Reply]>([ ['offline', offline], ['a 500', status(500)], @@ -136,7 +147,7 @@ describe('Revocations', () => { ['a 404 before Cloud serves the endpoint', status(404)], ['a 400 without an OAuth error', status(400, { message: 'bad gateway page' })], ['a 400 with a transient OAuth error', status(400, { error: 'temporarily_unavailable' })], - ['a 202', status(202)], + ['a 502', status(502)], ['a redirect', () => new Response(null, { status: 307, headers: { location: 'https://x' } })] ])('keeps the token after %s and revokes it once Cloud is reachable', async (_name, failure) => { vi.useFakeTimers() From 84cf2270af2a601f1a0c65ec1120042762ddda4d Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 9 Nov 2026 23:14:37 -0500 Subject: [PATCH 52/75] fix(auth): send a newly queued revocation without waiting out another token's backoff --- src/main/cloud/revocation.test.ts | 23 +++++++++++------------ src/main/cloud/revocation.ts | 2 +- 2 files changed, 12 insertions(+), 13 deletions(-) diff --git a/src/main/cloud/revocation.test.ts b/src/main/cloud/revocation.test.ts index b0ab6862a..97061e248 100644 --- a/src/main/cloud/revocation.test.ts +++ b/src/main/cloud/revocation.test.ts @@ -247,25 +247,24 @@ describe('Revocations', () => { expect(queuedTokens()).toEqual([]) }) - it('holds a token queued during a backoff until the backoff ends', async () => { + it('sends a token queued during a backoff right away while the failing one keeps backing off', async () => { vi.useFakeTimers() - replies = [offline] + replyFor = { 'refresh-1': offline } const revocations = new Revocations() revocations.add(revocation('refresh-1')) await revocations.drain() revocations.add(revocation('refresh-2')) - await vi.advanceTimersByTimeAsync(4_999) - expect(requests).toHaveLength(1) - await vi.advanceTimersByTimeAsync(1) + await vi.advanceTimersByTimeAsync(0) - expect(requests[0]?.token).toBe('refresh-1') - expect(requests.map((request) => request.token).sort()).toEqual([ - 'refresh-1', - 'refresh-1', - 'refresh-2' - ]) - expect(queuedTokens()).toEqual([]) + expect(requests.map((request) => request.token)).toContain('refresh-2') + expect(queuedTokens()).toEqual(['refresh-1']) + const attempts = requests.length + await vi.advanceTimersByTimeAsync(9_999) + expect(requests).toHaveLength(attempts) + await vi.advanceTimersByTimeAsync(1) + expect(requests).toHaveLength(attempts + 1) + expect(requests.at(-1)?.token).toBe('refresh-1') }) it('sends a token queued while another attempt fails, then retries only the failed one', async () => { diff --git a/src/main/cloud/revocation.ts b/src/main/cloud/revocation.ts index e7edffe19..b0e8899cf 100644 --- a/src/main/cloud/revocation.ts +++ b/src/main/cloud/revocation.ts @@ -16,7 +16,7 @@ export class Revocations { add(revocation: PendingRevocation): void { addPendingRevocation(revocation) if (this.draining) this.drainAgain = true - else if (!this.retryTimer) void this.drain() + else void this.drain() } drain(): Promise { From 9494b028b6afd69038a78573394df547af2c5f46 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 9 Nov 2026 23:18:06 -0500 Subject: [PATCH 53/75] fix(auth): let a view hold a workspace only after its own switch reaches it A failed or superseded view switch used to leave the workspace on the view's allowlist, so a later Desktop switch to that workspace let the view mint its token. Grant after the switch, only when no newer auth operation ran and the switch returned signed in on that workspace. Seed the Desktop allowlist before switching so the destination is not seeded as Desktop-chosen. --- src/main/lib/embeddedSession.test.ts | 52 +++++++++++++++++++++++----- src/main/lib/embeddedSession.ts | 16 +++++++-- src/main/lib/viewWorkspaceGrants.ts | 2 +- 3 files changed, 58 insertions(+), 12 deletions(-) diff --git a/src/main/lib/embeddedSession.test.ts b/src/main/lib/embeddedSession.test.ts index c1a80afef..6496c1f65 100644 --- a/src/main/lib/embeddedSession.test.ts +++ b/src/main/lib/embeddedSession.test.ts @@ -5,6 +5,7 @@ const mocks = vi.hoisted(() => ({ getAccessToken: vi.fn<() => Promise>(), mint: vi.fn(), current: 'ws-1', + generation: 0, entries: [] as unknown[] })) @@ -15,7 +16,8 @@ vi.mock('../devplatform/session', () => ({ getCloudSession: () => ({ getAccessToken: mocks.getAccessToken, currentWorkspaceId: () => mocks.current, - currentSubject: () => (mocks.current ? 'user-1' : null) + currentSubject: () => (mocks.current ? 'user-1' : null), + currentAuthGeneration: () => mocks.generation }) })) vi.mock('../cloud/workspaceToken', () => ({ @@ -134,10 +136,12 @@ describe('embeddedSession', () => { it('switches a signed-in view to the workspace it names and returns the new state', async () => { const { event } = view('http://127.0.0.1:8000') - const switchWorkspace = vi.fn(async () => { + const switchWorkspace = vi.fn(async (workspaceId: string) => { + mocks.generation += 1 mocks.getAccessToken.mockResolvedValue( - jwt({ sub: 'user-1', email: 'a@example.com', workspace_id: 'ws-2' }) + jwt({ sub: 'user-1', email: 'a@example.com', workspace_id: workspaceId }) ) + return { signedIn: true, workspaceId } }) await expect(switchWorkspaceForSender(event, 'ws-2', switchWorkspace)).resolves.toEqual({ @@ -152,9 +156,11 @@ describe('embeddedSession', () => { it('releases the workspace a view switched to only to that view', async () => { const switcher = view('http://127.0.0.1:8000') const bystander = view('http://127.0.0.1:8001') - const switchWorkspace = vi.fn(async () => { - mocks.current = 'ws-2' - mocks.getAccessToken.mockResolvedValue(jwt({ sub: 'user-1', workspace_id: 'ws-2' })) + const switchWorkspace = vi.fn(async (workspaceId: string) => { + mocks.generation += 1 + mocks.current = workspaceId + mocks.getAccessToken.mockResolvedValue(jwt({ sub: 'user-1', workspace_id: workspaceId })) + return { signedIn: true, workspaceId } }) await switchWorkspaceForSender(switcher.event, 'ws-2', switchWorkspace) @@ -163,6 +169,36 @@ describe('embeddedSession', () => { await expect(workspaceTokenForSender(bystander.event, 'ws-2')).resolves.toBeNull() }) + it('does not let a view hold a workspace its switch failed to reach, even once the session is on it', async () => { + const switcher = view('http://127.0.0.1:8000') + const failingSwitch = vi.fn(async () => { + mocks.generation += 1 + return { signedIn: true, workspaceId: 'ws-1' } + }) + + await switchWorkspaceForSender(switcher.event, 'ws-2', failingSwitch) + mocks.current = 'ws-2' + mocks.getAccessToken.mockResolvedValue(jwt({ sub: 'user-1', workspace_id: 'ws-2' })) + + await expect(workspaceTokenForSender(switcher.event, 'ws-2')).resolves.toBeNull() + }) + + it('does not let a view hold a workspace when a newer switch superseded its own', async () => { + const switcher = view('http://127.0.0.1:8000') + const supersededSwitch = vi.fn(async () => { + mocks.generation += 1 + await Promise.resolve() + mocks.generation += 1 + mocks.current = 'ws-2' + mocks.getAccessToken.mockResolvedValue(jwt({ sub: 'user-1', workspace_id: 'ws-2' })) + return { signedIn: true, workspaceId: 'ws-2' } + }) + + await switchWorkspaceForSender(switcher.event, 'ws-2', supersededSwitch) + + await expect(workspaceTokenForSender(switcher.event, 'ws-2')).resolves.toBeNull() + }) + it.each([ ['a remote view', 'http://192.168.1.20:8188', 'ws-2', ACCESS, { status: 'disabled' }], ['a signed-out session', 'http://127.0.0.1:8000', 'ws-2', null, { status: 'signed_out' }], @@ -171,7 +207,7 @@ describe('embeddedSession', () => { ])('does not switch for %s', async (_name, comfyUrl, workspaceId, token, expected) => { mocks.getAccessToken.mockResolvedValue(token) const { event } = view(comfyUrl) - const switchWorkspace = vi.fn(async () => undefined) + const switchWorkspace = vi.fn(async () => ({ signedIn: true })) const state = await switchWorkspaceForSender(event, workspaceId, switchWorkspace) @@ -183,7 +219,7 @@ describe('embeddedSession', () => { it('does not switch while the ops flag is off', async () => { mocks.enabled = false const { event } = view('http://127.0.0.1:8000') - const switchWorkspace = vi.fn(async () => undefined) + const switchWorkspace = vi.fn(async () => ({ signedIn: true })) await expect(switchWorkspaceForSender(event, 'ws-2', switchWorkspace)).resolves.toEqual({ status: 'disabled' diff --git a/src/main/lib/embeddedSession.ts b/src/main/lib/embeddedSession.ts index d175eb2e8..a42da4730 100644 --- a/src/main/lib/embeddedSession.ts +++ b/src/main/lib/embeddedSession.ts @@ -4,6 +4,7 @@ import { canMintWorkspaceTokens, identityOf } from '../cloud/claims' import { getCloudSession } from '../devplatform/session' import { comfyWindows, findEntryByComfySender } from '../host/registry' import type { ComfyWindowEntry } from '../host/registry' +import type { AuthStatus } from '../cloud/types' import type { ComfyDesktop2AuthState } from '../../types/comfyDesktopBridge' import { isEmbeddedSessionEnabled } from './embeddedSessionFlag' import { getViewWorkspaceGrants } from './viewWorkspaceGrants' @@ -85,13 +86,22 @@ export async function workspaceTokenForSender( export async function switchWorkspaceForSender( event: EmbeddedSessionSender, workspaceId: unknown, - switchWorkspace: (workspaceId: string) => Promise + switchWorkspace: (workspaceId: string) => Promise ): Promise { const state = await stateForSender(event) if (state.status !== 'signed_in' || typeof workspaceId !== 'string' || workspaceId === '') return state - getViewWorkspaceGrants().allowView(event.sender, workspaceId) - await switchWorkspace(workspaceId) + const session = getCloudSession() + const grants = getViewWorkspaceGrants() + grants.seed() + const switching = switchWorkspace(workspaceId) + const generation = session.currentAuthGeneration() + const status = await switching + const ownSwitchReached = + session.currentAuthGeneration() === generation && + status.signedIn && + status.workspaceId === workspaceId + if (ownSwitchReached) grants.allowView(event.sender, workspaceId) return stateForSender(event) } diff --git a/src/main/lib/viewWorkspaceGrants.ts b/src/main/lib/viewWorkspaceGrants.ts index 8091464d1..0934be67f 100644 --- a/src/main/lib/viewWorkspaceGrants.ts +++ b/src/main/lib/viewWorkspaceGrants.ts @@ -89,7 +89,7 @@ export class ViewWorkspaceGrants { return this.session.currentSubject() === held.subject ? held.token : null } - private seed(): void { + seed(): void { if (this.seeded) return this.seeded = true const current = this.session.currentWorkspaceId() From 0c71d166439f4ba1c5cdab68b095cc566b0bd987 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 9 Nov 2026 23:27:34 -0500 Subject: [PATCH 54/75] fix(auth): cap the mint block, gate dashboard grants on supersession, lock wizard refresh Cap a Retry-After mint block at five minutes so one oversized header cannot stall every non-anchor switch until restart. The dashboard switch handler lets views hold the target only when its own switch was not superseded, as the promotion path already does. Disable the wizard's Builds Refresh and Retry while it re-establishes its target workspace, so a second click cannot start a parallel switch. --- src/main/cloud/session.test.ts | 21 ++++++++++++++++++- src/main/cloud/session.ts | 4 +++- .../ipc/registerDevPlatformHandlers.test.ts | 10 +++++++++ .../lib/ipc/registerDevPlatformHandlers.ts | 4 ++-- .../src/views/InstallWizardModal.test.ts | 20 ++++++++++++++++++ src/renderer/src/views/InstallWizardModal.vue | 4 ++-- 6 files changed, 57 insertions(+), 6 deletions(-) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index bd985e521..b9614e38e 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -2,7 +2,7 @@ import * as fs from 'node:fs' import * as os from 'node:os' import * as path from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' const electronState = vi.hoisted(() => ({ userData: '' })) @@ -747,6 +747,25 @@ describe('CloudSession.switchWorkspace with no browser', () => { expect(mintRequests).toHaveLength(1) }) + it('caps a huge Retry-After at five minutes', async () => { + saveGrant(grantOn('w1')) + mintReply = () => json(429, {}, { 'Retry-After': '1000000000' }) + const session = new CloudSession() + const start = Date.now() + const now = vi.spyOn(Date, 'now').mockReturnValue(start) + onTestFinished(() => now.mockRestore()) + + await session.switchWorkspace('w2') + now.mockReturnValue(start + 5 * 60_000 - 1) + await session.switchWorkspace('w3') + expect(mintRequests).toHaveLength(1) + + now.mockReturnValue(start + 5 * 60_000) + mintReply = ({ workspaceId }) => minted(workspaceId, start + 60 * 60_000) + await expect(session.switchWorkspace('w4')).resolves.toMatchObject({ workspaceId: 'w4' }) + expect(mintRequests).toHaveLength(2) + }) + it('a late 429 from before logout does not throttle the next account', async () => { saveGrant(grantOn('w1')) const late = deferred() diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index 7aace80ec..2a33aab68 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -33,6 +33,7 @@ import type { ReauthorizeReason, WorkspaceMintOutcome } from './workspaceToken' import { listWorkspaceMembers, listWorkspaces } from './workspaces' const REFRESH_SKEW_MS = 60_000 +const MAX_MINT_BLOCK_MS = 5 * 60_000 export const WORKSPACE_SWITCH_EVENT = 'comfy.desktop.auth.workspace_switch' export const WORKSPACE_SWITCH_BROWSER_EVENT = 'comfy.desktop.auth.workspace_switch_browser' @@ -341,7 +342,8 @@ export class CloudSession { generation === this.authGeneration && subjectOf(grant.accessToken) === this.currentSubject() ) { - this.mintBlockedUntil = Date.now() + outcome.retryAfterSeconds * 1000 + this.mintBlockedUntil = + Date.now() + Math.min(outcome.retryAfterSeconds * 1000, MAX_MINT_BLOCK_MS) } return outcome } diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts index 3951d4c2e..56dc056ca 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts @@ -504,6 +504,16 @@ describe('registerDevPlatformHandlers', () => { expect(win.webContents.send).toHaveBeenCalledWith('comfybuilder:authChanged', status) }) + it('lets no view hold the target when a newer auth operation superseded the dashboard switch', async () => { + mocks.currentAuthGeneration.mockReturnValueOnce(1).mockReturnValueOnce(2) + mocks.switchWorkspace.mockResolvedValue({ signedIn: true, workspaceId: 'w2' }) + mocks.allowDesktopWorkspace.mockClear() + + await handler('comfybuilder:switchWorkspace')({}, 'w2') + + expect(mocks.allowDesktopWorkspace).not.toHaveBeenCalled() + }) + it('forgets view allowlists when a switch signs in as a different account', async () => { mocks.currentSubject.mockReturnValueOnce('user-1').mockReturnValueOnce('user-2') mocks.switchWorkspace.mockResolvedValue({ signedIn: true, workspaceId: 'w9' }) diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.ts b/src/main/lib/ipc/registerDevPlatformHandlers.ts index f0e4ba38e..164d12dae 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.ts @@ -230,11 +230,11 @@ export function registerDevPlatformHandlers(): void { ipcMain.handle( DEVPLATFORM_CHANNELS.switchWorkspace, async (_event, workspaceId: string, intent?: WorkspaceSwitchIntent) => { - const status = await switchCloudWorkspace( + const { reply: status, superseded } = await switchAndAnnounce( workspaceId, intent === 'restored' ? 'restored' : 'chosen' ) - if (status.signedIn && status.workspaceId === workspaceId) { + if (!superseded && status.signedIn && status.workspaceId === workspaceId) { getViewWorkspaceGrants().allowDesktop(workspaceId) } return status diff --git a/src/renderer/src/views/InstallWizardModal.test.ts b/src/renderer/src/views/InstallWizardModal.test.ts index 5ce35270e..fe291f8c7 100644 --- a/src/renderer/src/views/InstallWizardModal.test.ts +++ b/src/renderer/src/views/InstallWizardModal.test.ts @@ -759,6 +759,26 @@ describe('InstallWizardModal workspace Builds', () => { ]) }) + it.each(['.workspace-build-refresh', '.wizard-build-retry'])( + '%s is disabled while the target workspace is being re-established', + async (button) => { + const { wrapper, switchWorkspace } = await openOnW2ThenReturnToAnchor() + useAuthStore().buildsError = true + await flushPromises() + let finish: (status: unknown) => void = () => {} + switchWorkspace.mockReturnValue(new Promise((resolve) => (finish = resolve))) + + await wrapper.get(button).trigger('click') + await flushPromises() + expect(wrapper.get(button).attributes('disabled')).toBeDefined() + await wrapper.get(button).trigger('click') + + finish({ signedIn: true, workspaceId: 'w2', workspaceType: 'team' }) + await flushPromises() + expect(switchWorkspace).toHaveBeenCalledOnce() + } + ) + it('Refresh fetches nothing for the anchor when the target cannot be re-established', async () => { const { wrapper, switchWorkspace, listBuilds } = await openOnW2ThenReturnToAnchor() switchWorkspace.mockResolvedValue({ diff --git a/src/renderer/src/views/InstallWizardModal.vue b/src/renderer/src/views/InstallWizardModal.vue index 55d0d0325..2260d8db5 100644 --- a/src/renderer/src/views/InstallWizardModal.vue +++ b/src/renderer/src/views/InstallWizardModal.vue @@ -1288,7 +1288,7 @@ defineExpose({ open }) class="workspace-build-refresh" :title="$t('newInstall.refreshWorkspaceBuilds')" :aria-label="$t('newInstall.refreshWorkspaceBuilds')" - :disabled="authStore.loadingBuilds" + :disabled="authStore.loadingBuilds || authorizingWorkspace" @click="refreshManagedBuilds" > {{ $t('devPlatform.build.loadError') }} From 83b8a9199d399ff5efcb04225fd5babb141f4d23 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 9 Nov 2026 23:28:14 -0500 Subject: [PATCH 55/75] fix(auth): return an explicit reached outcome from a workspace switch A switch whose browser sign-in picked another workspace returned the current status. When that status already named the requested workspace, for example an expired active token, callers read it as success and granted the workspace. switchWorkspace now returns { status, reached }, reached only when this switch activated or authorized the workspace, and the dashboard switch, promotion and view switch grant only on reached. --- src/main/cloud/index.ts | 8 +- src/main/cloud/session.test.ts | 76 ++++++++++++++++--- src/main/cloud/session.ts | 29 ++++--- src/main/cloud/types.ts | 5 ++ src/main/lib/embeddedSession.test.ts | 45 ++++------- src/main/lib/embeddedSession.ts | 15 +--- .../ipc/registerDevPlatformHandlers.test.ts | 28 +++---- .../lib/ipc/registerDevPlatformHandlers.ts | 24 +++--- 8 files changed, 141 insertions(+), 89 deletions(-) diff --git a/src/main/cloud/index.ts b/src/main/cloud/index.ts index 9b260fbf6..314edaac2 100644 --- a/src/main/cloud/index.ts +++ b/src/main/cloud/index.ts @@ -4,4 +4,10 @@ export { listWorkspaceMembers, listWorkspaces } from './workspaces' export { getAuthStatus, clearTokens } from './tokenStore' export { statusFromAccessToken, workspaceIdOf } from './claims' export { CLOUD_CONFIG, CLOUD_ISSUER } from './config' -export type { AuthStatus, AuthTokens, Workspace, WorkspaceMember } from './types' +export type { + AuthStatus, + AuthTokens, + Workspace, + WorkspaceMember, + WorkspaceSwitchOutcome +} from './types' diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index bc2513d1d..819bfc61b 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -163,7 +163,7 @@ describe('CloudSession access tokens', () => { const switching = session.switchWorkspace('w2') expect(refresh).toHaveBeenCalledTimes(2) refreshes.get(staleTwo.refreshToken!)!(freshTwo) - await expect(switching).resolves.toMatchObject({ workspaceId: 'w2' }) + await expect(switching).resolves.toMatchObject({ status: { workspaceId: 'w2' }, reached: true }) refreshes.get(staleOne.refreshToken!)!(freshOne) await expect(oldRequest).resolves.toBeNull() @@ -273,8 +273,14 @@ describe('CloudSession workspaces', () => { cache(workspaceTwo) const session = new CloudSession() - await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) - await expect(session.switchWorkspace('w1')).resolves.toMatchObject({ workspaceId: 'w1' }) + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ + status: { workspaceId: 'w2' }, + reached: true + }) + await expect(session.switchWorkspace('w1')).resolves.toMatchObject({ + status: { workspaceId: 'w1' }, + reached: true + }) expect(activateWorkspace).toHaveBeenNthCalledWith(1, 'w2') expect(activateWorkspace).toHaveBeenNthCalledWith(2, 'w1') @@ -290,7 +296,8 @@ describe('CloudSession workspaces', () => { mocked(refresh).mockResolvedValue(freshTwo) await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ - workspaceId: 'w2' + status: { workspaceId: 'w2' }, + reached: true }) expect(refresh).toHaveBeenCalledExactlyOnceWith(staleTwo.refreshToken) @@ -309,7 +316,8 @@ describe('CloudSession workspaces', () => { }) await expect(new CloudSession().switchWorkspace('w1')).resolves.toMatchObject({ - workspaceId: 'w1' + status: { workspaceId: 'w1' }, + reached: true }) expect(refresh).toHaveBeenCalledExactlyOnceWith(stale.refreshToken) @@ -326,13 +334,54 @@ describe('CloudSession workspaces', () => { }) await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ - workspaceId: 'w1' + status: { workspaceId: 'w1' }, + reached: false }) expect(signIn).toHaveBeenCalledExactlyOnceWith({ workspaceId: 'w2' }) expect(saveTokens).not.toHaveBeenCalled() }) + it('reports a switch superseded during its refresh as unreached', async () => { + const workspaceOne = makeTokens('w1') + const staleTwo = makeTokens('w2', past) + const freshTwo = makeTokens('w2', future, '-fresh') + cache(workspaceOne, true) + cache(staleTwo) + let finishRefresh: (tokens: typeof freshTwo) => void = () => {} + mocked(refresh).mockImplementation( + () => + new Promise((resolve) => { + finishRefresh = resolve + }) + ) + const session = new CloudSession() + + const superseded = session.switchWorkspace('w2') + const newer = session.switchWorkspace('w1') + finishRefresh(freshTwo) + + await expect(superseded).resolves.toMatchObject({ reached: false }) + await expect(newer).resolves.toMatchObject({ status: { workspaceId: 'w1' }, reached: true }) + }) + + it('reports an unreached switch when browser auth for the expired active workspace picks another', async () => { + const stale = makeTokens('w1', past) + const other = makeTokens('w2') + cache(stale, true) + mocked(refresh).mockRejectedValue(new Error('revoked')) + mocked(signIn).mockResolvedValue({ + tokens: other, + status: statusFromAccessToken(other.accessToken) + }) + + await expect(new CloudSession().switchWorkspace('w1')).resolves.toMatchObject({ + status: { workspaceId: 'w1' }, + reached: false + }) + expect(saveTokens).not.toHaveBeenCalled() + }) + it('stores first-time workspace authorization for later silent activation', async () => { const workspaceOne = makeTokens('w1') const workspaceTwo = makeTokens('w2') @@ -343,9 +392,18 @@ describe('CloudSession workspaces', () => { }) const session = new CloudSession() - await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) - await expect(session.switchWorkspace('w1')).resolves.toMatchObject({ workspaceId: 'w1' }) - await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ + status: { workspaceId: 'w2' }, + reached: true + }) + await expect(session.switchWorkspace('w1')).resolves.toMatchObject({ + status: { workspaceId: 'w1' }, + reached: true + }) + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ + status: { workspaceId: 'w2' }, + reached: true + }) expect(signIn).toHaveBeenCalledOnce() expect(saveTokens).toHaveBeenCalledExactlyOnceWith(workspaceTwo) diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index a2e94631e..424c2db65 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -12,7 +12,13 @@ import { saveTokens, saveWorkspaceNames } from './tokenStore' -import type { AuthStatus, AuthTokens, Workspace, WorkspaceMember } from './types' +import type { + AuthStatus, + AuthTokens, + Workspace, + WorkspaceMember, + WorkspaceSwitchOutcome +} from './types' import { listWorkspaceMembers, listWorkspaces } from './workspaces' const REFRESH_SKEW_MS = 60_000 @@ -34,9 +40,11 @@ export class CloudSession { onAuthorizeUrl: (url) => { if (generation === this.authGeneration) this.loginAuthorizeUrl = url } - }).finally(() => { - if (this.loginInFlight === login) this.clearPendingLogin() }) + .then(({ status }) => status) + .finally(() => { + if (this.loginInFlight === login) this.clearPendingLogin() + }) this.loginInFlight = login return login } @@ -132,7 +140,7 @@ export class CloudSession { return listWorkspaceMembers(token) } - async switchWorkspace(workspaceId: string): Promise { + async switchWorkspace(workspaceId: string): Promise { this.clearPendingLogin() const generation = ++this.authGeneration const current = loadTokens() @@ -143,10 +151,10 @@ export class CloudSession { if (cached?.refreshToken && cached.expiresAt - REFRESH_SKEW_MS <= Date.now()) { cached = await this.refreshWorkspaceTokens(workspaceId, cached) } - if (generation !== this.authGeneration) return this.status() + if (generation !== this.authGeneration) return { status: this.status(), reached: false } if (cached && cached.expiresAt > Date.now()) { if (cached !== current) activateWorkspace(workspaceId) - return this.status() + return { status: this.status(), reached: true } } return this.authenticateAtGeneration(generation, { workspaceId }) } @@ -154,13 +162,14 @@ export class CloudSession { private async authenticateAtGeneration( generation: number, options: OAuthOptions - ): Promise { + ): Promise { const { workspaceId } = options const { tokens, status } = await signIn(options) - if (generation !== this.authGeneration) return this.status() - if (workspaceId && status.workspaceId !== workspaceId) return this.status() + if (generation !== this.authGeneration) return { status: this.status(), reached: false } + if (workspaceId && status.workspaceId !== workspaceId) + return { status: this.status(), reached: false } saveTokens(tokens) - return status + return { status, reached: true } } asTokenProvider(onSignedOut?: () => void): TokenProvider { diff --git a/src/main/cloud/types.ts b/src/main/cloud/types.ts index 637854aed..f6afe4f5f 100644 --- a/src/main/cloud/types.ts +++ b/src/main/cloud/types.ts @@ -13,6 +13,11 @@ export interface AuthStatus { role?: string } +export interface WorkspaceSwitchOutcome { + status: AuthStatus + reached: boolean +} + export interface Workspace { id: string name: string diff --git a/src/main/lib/embeddedSession.test.ts b/src/main/lib/embeddedSession.test.ts index 6496c1f65..c6e2d8803 100644 --- a/src/main/lib/embeddedSession.test.ts +++ b/src/main/lib/embeddedSession.test.ts @@ -5,7 +5,6 @@ const mocks = vi.hoisted(() => ({ getAccessToken: vi.fn<() => Promise>(), mint: vi.fn(), current: 'ws-1', - generation: 0, entries: [] as unknown[] })) @@ -16,8 +15,7 @@ vi.mock('../devplatform/session', () => ({ getCloudSession: () => ({ getAccessToken: mocks.getAccessToken, currentWorkspaceId: () => mocks.current, - currentSubject: () => (mocks.current ? 'user-1' : null), - currentAuthGeneration: () => mocks.generation + currentSubject: () => (mocks.current ? 'user-1' : null) }) })) vi.mock('../cloud/workspaceToken', () => ({ @@ -137,11 +135,10 @@ describe('embeddedSession', () => { it('switches a signed-in view to the workspace it names and returns the new state', async () => { const { event } = view('http://127.0.0.1:8000') const switchWorkspace = vi.fn(async (workspaceId: string) => { - mocks.generation += 1 mocks.getAccessToken.mockResolvedValue( jwt({ sub: 'user-1', email: 'a@example.com', workspace_id: workspaceId }) ) - return { signedIn: true, workspaceId } + return { status: { signedIn: true, workspaceId }, reached: true } }) await expect(switchWorkspaceForSender(event, 'ws-2', switchWorkspace)).resolves.toEqual({ @@ -157,10 +154,9 @@ describe('embeddedSession', () => { const switcher = view('http://127.0.0.1:8000') const bystander = view('http://127.0.0.1:8001') const switchWorkspace = vi.fn(async (workspaceId: string) => { - mocks.generation += 1 mocks.current = workspaceId mocks.getAccessToken.mockResolvedValue(jwt({ sub: 'user-1', workspace_id: workspaceId })) - return { signedIn: true, workspaceId } + return { status: { signedIn: true, workspaceId }, reached: true } }) await switchWorkspaceForSender(switcher.event, 'ws-2', switchWorkspace) @@ -169,36 +165,23 @@ describe('embeddedSession', () => { await expect(workspaceTokenForSender(bystander.event, 'ws-2')).resolves.toBeNull() }) - it('does not let a view hold a workspace its switch failed to reach, even once the session is on it', async () => { + it.each([ + ['failed', 'ws-1'], + ['did not reach although the session already names', 'ws-2'] + ])('does not let a view hold a workspace its switch %s it', async (_name, reportedWorkspace) => { const switcher = view('http://127.0.0.1:8000') - const failingSwitch = vi.fn(async () => { - mocks.generation += 1 - return { signedIn: true, workspaceId: 'ws-1' } - }) + const unreachedSwitch = vi.fn(async () => ({ + status: { signedIn: true, workspaceId: reportedWorkspace }, + reached: false + })) - await switchWorkspaceForSender(switcher.event, 'ws-2', failingSwitch) + await switchWorkspaceForSender(switcher.event, 'ws-2', unreachedSwitch) mocks.current = 'ws-2' mocks.getAccessToken.mockResolvedValue(jwt({ sub: 'user-1', workspace_id: 'ws-2' })) await expect(workspaceTokenForSender(switcher.event, 'ws-2')).resolves.toBeNull() }) - it('does not let a view hold a workspace when a newer switch superseded its own', async () => { - const switcher = view('http://127.0.0.1:8000') - const supersededSwitch = vi.fn(async () => { - mocks.generation += 1 - await Promise.resolve() - mocks.generation += 1 - mocks.current = 'ws-2' - mocks.getAccessToken.mockResolvedValue(jwt({ sub: 'user-1', workspace_id: 'ws-2' })) - return { signedIn: true, workspaceId: 'ws-2' } - }) - - await switchWorkspaceForSender(switcher.event, 'ws-2', supersededSwitch) - - await expect(workspaceTokenForSender(switcher.event, 'ws-2')).resolves.toBeNull() - }) - it.each([ ['a remote view', 'http://192.168.1.20:8188', 'ws-2', ACCESS, { status: 'disabled' }], ['a signed-out session', 'http://127.0.0.1:8000', 'ws-2', null, { status: 'signed_out' }], @@ -207,7 +190,7 @@ describe('embeddedSession', () => { ])('does not switch for %s', async (_name, comfyUrl, workspaceId, token, expected) => { mocks.getAccessToken.mockResolvedValue(token) const { event } = view(comfyUrl) - const switchWorkspace = vi.fn(async () => ({ signedIn: true })) + const switchWorkspace = vi.fn(async () => ({ status: { signedIn: true }, reached: true })) const state = await switchWorkspaceForSender(event, workspaceId, switchWorkspace) @@ -219,7 +202,7 @@ describe('embeddedSession', () => { it('does not switch while the ops flag is off', async () => { mocks.enabled = false const { event } = view('http://127.0.0.1:8000') - const switchWorkspace = vi.fn(async () => ({ signedIn: true })) + const switchWorkspace = vi.fn(async () => ({ status: { signedIn: true }, reached: true })) await expect(switchWorkspaceForSender(event, 'ws-2', switchWorkspace)).resolves.toEqual({ status: 'disabled' diff --git a/src/main/lib/embeddedSession.ts b/src/main/lib/embeddedSession.ts index a42da4730..89599c9d1 100644 --- a/src/main/lib/embeddedSession.ts +++ b/src/main/lib/embeddedSession.ts @@ -4,7 +4,7 @@ import { canMintWorkspaceTokens, identityOf } from '../cloud/claims' import { getCloudSession } from '../devplatform/session' import { comfyWindows, findEntryByComfySender } from '../host/registry' import type { ComfyWindowEntry } from '../host/registry' -import type { AuthStatus } from '../cloud/types' +import type { WorkspaceSwitchOutcome } from '../cloud/types' import type { ComfyDesktop2AuthState } from '../../types/comfyDesktopBridge' import { isEmbeddedSessionEnabled } from './embeddedSessionFlag' import { getViewWorkspaceGrants } from './viewWorkspaceGrants' @@ -86,22 +86,15 @@ export async function workspaceTokenForSender( export async function switchWorkspaceForSender( event: EmbeddedSessionSender, workspaceId: unknown, - switchWorkspace: (workspaceId: string) => Promise + switchWorkspace: (workspaceId: string) => Promise ): Promise { const state = await stateForSender(event) if (state.status !== 'signed_in' || typeof workspaceId !== 'string' || workspaceId === '') return state - const session = getCloudSession() const grants = getViewWorkspaceGrants() grants.seed() - const switching = switchWorkspace(workspaceId) - const generation = session.currentAuthGeneration() - const status = await switching - const ownSwitchReached = - session.currentAuthGeneration() === generation && - status.signedIn && - status.workspaceId === workspaceId - if (ownSwitchReached) grants.allowView(event.sender, workspaceId) + const { reached } = await switchWorkspace(workspaceId) + if (reached) grants.allowView(event.sender, workspaceId) return stateForSender(event) } diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts index 487c46f85..6f1d8465d 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts @@ -479,9 +479,8 @@ describe('registerDevPlatformHandlers', () => { const win = { webContents: { isDestroyed: () => false, send: vi.fn() } } mocks.getAllWindows.mockReturnValue([win]) mocks.switchWorkspace.mockResolvedValue({ - signedIn: true, - workspaceId: 'w2', - workspaceType: 'team' + status: { signedIn: true, workspaceId: 'w2', workspaceType: 'team' }, + reached: true }) const status = await handler('comfybuilder:switchWorkspace')({}, 'w2') @@ -493,14 +492,18 @@ describe('registerDevPlatformHandlers', () => { it.for([ ['signed out', { signedIn: false }], - ['still on another workspace', { signedIn: true, workspaceId: 'w1', workspaceType: 'team' }] - ] as const)('a dashboard switch that ends %s lets no view hold the target', async ([, reply]) => { - mocks.switchWorkspace.mockResolvedValue(reply) + ['still on another workspace', { signedIn: true, workspaceId: 'w1', workspaceType: 'team' }], + ['unreached on a session that names the target', { signedIn: true, workspaceId: 'w2' }] + ] as const)( + 'a dashboard switch that ends %s lets no view hold the target', + async ([, status]) => { + mocks.switchWorkspace.mockResolvedValue({ status, reached: false }) - await handler('comfybuilder:switchWorkspace')({}, 'w2') + await handler('comfybuilder:switchWorkspace')({}, 'w2') - expect(mocks.allowDesktopWorkspace).not.toHaveBeenCalled() - }) + expect(mocks.allowDesktopWorkspace).not.toHaveBeenCalled() + } + ) it('captures fresh state, creates a draft, and opens the validated Platform URL', async () => { const result = await handler('comfybuilder:promoteLocalInstance')({}, 'local-1') @@ -598,7 +601,7 @@ describe('registerDevPlatformHandlers', () => { mocks.switchWorkspace.mockImplementationOnce(async () => { const status = { signedIn: true, workspaceId: 'w2', workspaceType: 'team' } mocks.status.mockReturnValue(status) - return status + return { status, reached: true } }) mocks.createBuildDraft.mockResolvedValue({ buildId: 'build-2', @@ -628,9 +631,8 @@ describe('registerDevPlatformHandlers', () => { installPath: '/installs/local-1' }) mocks.switchWorkspace.mockResolvedValueOnce({ - signedIn: true, - workspaceId: 'w1', - workspaceType: 'team' + status: { signedIn: true, workspaceId: 'w1', workspaceType: 'team' }, + reached: false }) await expect(handler('comfybuilder:promoteLocalInstance')({}, 'local-1')).resolves.toEqual({ diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.ts b/src/main/lib/ipc/registerDevPlatformHandlers.ts index 320f9fac7..91ff61b4d 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.ts @@ -20,7 +20,7 @@ import { } from '../../devplatform/builds' import type { BuildRow } from '../../devplatform/builds' import { clearVersionCache, getVersionCacheGeneration } from '../../devplatform/versionCache' -import type { AuthStatus, Workspace } from '../../cloud' +import type { AuthStatus, Workspace, WorkspaceSwitchOutcome } from '../../cloud' import { installations, defaultInstallDir, @@ -102,12 +102,12 @@ export async function signInToCloud(): Promise { return status } -export async function switchCloudWorkspace(workspaceId: string): Promise { +export async function switchCloudWorkspace(workspaceId: string): Promise { clearVersionCache() - const status = await getCloudSession().switchWorkspace(workspaceId) + const outcome = await getCloudSession().switchWorkspace(workspaceId) clearVersionCache() - broadcastAuthChanged(status) - return status + broadcastAuthChanged(outcome.status) + return outcome } export async function signOutOfCloud(host: ComfyWindowEntry | undefined): Promise { @@ -195,10 +195,8 @@ export function registerDevPlatformHandlers(): void { ) ipcMain.handle(DEVPLATFORM_CHANNELS.switchWorkspace, async (_event, workspaceId: string) => { - const status = await switchCloudWorkspace(workspaceId) - if (status.signedIn && status.workspaceId === workspaceId) { - getViewWorkspaceGrants().allowDesktop(workspaceId) - } + const { status, reached } = await switchCloudWorkspace(workspaceId) + if (reached) getViewWorkspaceGrants().allowDesktop(workspaceId) return status }) @@ -229,13 +227,11 @@ export function registerDevPlatformHandlers(): void { if (!workspaceId) return { ok: false, message: 'No active workspace.' } if (status.workspaceId !== workspaceId) { clearVersionCache() - const switched = await session.switchWorkspace(workspaceId) + const { status: switched, reached } = await session.switchWorkspace(workspaceId) clearVersionCache() - if (switched.signedIn && switched.workspaceId === workspaceId) { - getViewWorkspaceGrants().allowDesktop(workspaceId) - } + if (reached) getViewWorkspaceGrants().allowDesktop(workspaceId) broadcastAuthChanged(switched) - if (!switched.signedIn || switched.workspaceId !== workspaceId) { + if (!reached) { return { ok: false, message: 'Could not activate the instance workspace.' } } } From 19b0872dac67589491d7c0a172efdb11f233710a Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 10 Nov 2026 13:05:11 -0500 Subject: [PATCH 56/75] fix(auth): bound revocation retries and revoke dropped sign-ins - Stamp each queued revocation and drop it once Cloud's 30 day refresh token lifetime has passed, so a revoke Cloud never confirms stops retrying and leaves the disk. Entries from earlier builds are dated by their file. - Revoke a grant saved by an older build at the configured Cloud instead of skipping it until the next refresh. - Revoke the tokens of a sign-in or switch consent that finishes after sign-out or a newer switch, never the stored grant itself. --- src/main/cloud/revocation.test.ts | 49 +++++++++++++++++++++++-- src/main/cloud/revocation.ts | 11 ++++-- src/main/cloud/session.test.ts | 60 +++++++++++++++++++++++++------ src/main/cloud/session.ts | 28 ++++++++++----- src/main/cloud/tokenStore.test.ts | 28 ++++++++++++--- src/main/cloud/tokenStore.ts | 19 ++++++---- 6 files changed, 159 insertions(+), 36 deletions(-) diff --git a/src/main/cloud/revocation.test.ts b/src/main/cloud/revocation.test.ts index 97061e248..bdfe641da 100644 --- a/src/main/cloud/revocation.test.ts +++ b/src/main/cloud/revocation.test.ts @@ -50,6 +50,7 @@ type Reply = () => Response | Promise let replies: Reply[] let replyFor: Record let requests: RevokeRequest[] +const written = new Set() const ok: Reply = () => new Response(null, { status: 200 }) const offline: Reply = () => Promise.reject(new TypeError('fetch failed')) @@ -59,7 +60,12 @@ function status(code: number, body: unknown = {}): Reply { } function revocation(refreshToken: string): PendingRevocation { - return { issuer: CLOUD_CONFIG.issuer, clientId: CLOUD_CONFIG.clientId, refreshToken } + return { + issuer: CLOUD_CONFIG.issuer, + clientId: CLOUD_CONFIG.clientId, + refreshToken, + queuedAt: Date.now() + } } function queuedTokens(): string[] { @@ -73,6 +79,7 @@ beforeEach(() => { electronState.userData = fs.mkdtempSync(path.join(os.tmpdir(), 'comfy-cloud-revocation-')) _resetForTest() requests = [] + written.clear() replies = [] replyFor = {} vi.stubGlobal( @@ -347,6 +354,24 @@ describe('Revocations', () => { } }) + it('revokes a token queued by an earlier build, dating it by its file', async () => { + const dir = path.join(electronState.userData, 'comfy-cloud-revocations') + const monthAgo = new Date(Date.now() - 31 * 24 * 3_600_000) + for (const token of ['refresh-recent', 'refresh-month-old']) { + addPendingRevocation(revocation(token)) + const file = fs.readdirSync(dir).find((name) => !written.has(name)) ?? '' + written.add(file) + const { queuedAt: _queuedAt, ...older } = revocation(token) + fs.writeFileSync(path.join(dir, file), safeStorage.encryptString(JSON.stringify(older))) + if (token === 'refresh-month-old') fs.utimesSync(path.join(dir, file), monthAgo, monthAgo) + } + + await new Revocations().drain() + + expect(requests.map((request) => request.token)).toEqual(['refresh-recent']) + expect(queuedTokens()).toEqual([]) + }) + it('reads a saved token again later when it could not be read at start', async () => { vi.useFakeTimers() addPendingRevocation(revocation('refresh-2')) @@ -362,11 +387,31 @@ describe('Revocations', () => { expect(queuedTokens()).toEqual([]) }) + it('gives up on a token once it has outlived its 30 day lifetime on Cloud', async () => { + vi.useFakeTimers() + replies = [status(503), status(503)] + const revocations = new Revocations() + revocations.add(revocation('refresh-1')) + await revocations.drain() + addPendingRevocation({ ...revocation('refresh-old'), queuedAt: Date.now() - 720 * 3_600_000 }) + + await vi.advanceTimersByTimeAsync(5_000) + expect(requests.map((request) => request.token)).toEqual(['refresh-1', 'refresh-1']) + expect(queuedTokens()).toEqual(['refresh-1']) + + vi.setSystemTime(Date.now() + 720 * 3_600_000) + await vi.advanceTimersByTimeAsync(MAX_WAIT_MS) + + expect(requests).toHaveLength(2) + expect(queuedTokens()).toEqual([]) + }) + it('sends each token only to the Cloud that issued it', async () => { addPendingRevocation({ issuer: 'https://other-cloud.example', clientId: 'other-client', - refreshToken: 'refresh-elsewhere' + refreshToken: 'refresh-elsewhere', + queuedAt: Date.now() }) addPendingRevocation(revocation('refresh-1')) diff --git a/src/main/cloud/revocation.ts b/src/main/cloud/revocation.ts index b0e8899cf..c6f1a04da 100644 --- a/src/main/cloud/revocation.ts +++ b/src/main/cloud/revocation.ts @@ -5,6 +5,7 @@ import type { PendingRevocation } from './tokenStore' const FIRST_RETRY_MS = 5_000 const MAX_RETRY_MS = 15 * 60_000 +const CLOUD_REFRESH_TOKEN_LIFETIME_MS = 720 * 60 * 60_000 export class Revocations { private draining: Promise | null = null @@ -13,8 +14,8 @@ export class Revocations { private retryTimer: ReturnType | null = null private readonly settledButSaved = new Set() - add(revocation: PendingRevocation): void { - addPendingRevocation(revocation) + add(revocation: Omit): void { + addPendingRevocation({ ...revocation, queuedAt: Date.now() }) if (this.draining) this.drainAgain = true else void this.drain() } @@ -48,7 +49,11 @@ export class Revocations { else this.scheduleRetry() return } - if ((await revoke(next.refreshToken, next.clientId, revokeUrlOf(next.issuer))) === 'retry') { + const expired = next.queuedAt + CLOUD_REFRESH_TOKEN_LIFETIME_MS <= Date.now() + if ( + !expired && + (await revoke(next.refreshToken, next.clientId, revokeUrlOf(next.issuer))) === 'retry' + ) { failed.add(next.refreshToken) } else if (!removePendingRevocation(next.refreshToken)) { this.settledButSaved.add(next.refreshToken) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index 6a304ff5c..436fbaf09 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -2352,27 +2352,67 @@ describe('CloudSession logout revokes this device on Cloud (T-V8, T-V18)', () => expect(revokedTokens).toEqual([]) }) - it('revokes nothing for a grant from an older build until a refresh proves its Cloud', async () => { - const stale = grantOn('w1', { expiresAt: PAST }) - saveGrant(stale) + it('revokes a grant from an older build at the configured Cloud', async () => { + const grant = grantOn('w1') + saveGrant(grant) const vaultPath = path.join(electronState.userData, 'comfy-cloud-auth.bin') const { issuer: _issuer, clientId: _clientId, ...older } = vaultOnDisk() fs.writeFileSync(vaultPath, safeStorage.encryptString(JSON.stringify(older))) _resetForTest() + + new CloudSession().logout() + + await vi.waitFor(() => expect(revokedTokens).toEqual([grant.refreshToken])) + }) + + it('revokes a sign-in that finishes after logout', async () => { + const pending = deferred>>() + mocked(signIn).mockReturnValue(pending.promise) const session = new CloudSession() + const late = grantOn('w1', { revision: '-late' }) + const login = session.login() session.logout() + pending.resolve(signedInResult(late)) + await login + + await vi.waitFor(() => expect(revokedTokens).toEqual([late.refreshToken])) + expect(session.isSignedIn()).toBe(false) + }) + + it('never revokes the stored grant when a superseded sign-in returns it', async () => { + const grant = grantOn('w1') + saveGrant(grant) + const pending = deferred>>() + mocked(signIn).mockReturnValue(pending.promise) + const session = new CloudSession() + + const login = session.login() + await session.switchWorkspace('w1') + pending.resolve(signedInResult(grant)) + await login + session.resumeRevocations() + expect(revokedTokens).toEqual([]) + expect(vaultOnDisk().grant).toEqual(grant) + }) - saveGrant(stale) - fs.writeFileSync(vaultPath, safeStorage.encryptString(JSON.stringify(older))) - _resetForTest() - const rotated = grantOn('w1', { revision: '-fresh' }) - mocked(refresh).mockResolvedValue(rotated) - await session.getAccessToken() + it('revokes a switch consent that finishes after logout', async () => { + const grant = grantOn('w1') + saveGrant(grant) + mintReply = () => json(403, { code: 'sso_required' }) + const pending = deferred>>() + mocked(signIn).mockReturnValue(pending.promise) + const session = new CloudSession() + const late = grantOn('w2', { revision: '-late' }) + + const switching = session.switchWorkspace('w2') + await vi.waitFor(() => expect(signIn).toHaveBeenCalledOnce()) session.logout() + pending.resolve(signedInResult(late)) + await switching - await vi.waitFor(() => expect(revokedTokens).toEqual([rotated.refreshToken])) + await vi.waitFor(() => expect(revokedTokens).toEqual([grant.refreshToken, late.refreshToken])) }) it('revokes nothing when no one is signed in', () => { diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index d57552c59..0c3dd8333 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -146,7 +146,10 @@ export class CloudSession { if (generation === this.authGeneration) this.loginAuthorizeUrl = url } }) - if (generation !== this.authGeneration) return this.status() + if (generation !== this.authGeneration) { + this.revokeUnstored(tokens.refreshToken) + return this.status() + } this.storeSignedInGrant(tokens) const anchor = workspaceIdOf(tokens.accessToken) if (anchor) activateWorkspace(anchor) @@ -185,6 +188,15 @@ export class CloudSession { if (origin) this.revocations.add({ ...origin, refreshToken }) } + private revokeUnstored(refreshToken: string | undefined): void { + if (!refreshToken || refreshToken === loadGrant()?.refreshToken) return + this.revocations.add({ + issuer: CLOUD_CONFIG.issuer, + clientId: CLOUD_CONFIG.clientId, + refreshToken + }) + } + resumeRevocations(): void { void this.revocations.drain() } @@ -278,13 +290,8 @@ export class CloudSession { const rotated = await refresh(refreshToken) const stored = replaceGrant(grant.accessToken, refreshToken, rotated) if (stored) this.rotatedTo.set(grant.accessToken, rotated.accessToken) - const next = rotated.refreshToken - if (!stored && this.retiredRefreshTokens.has(refreshToken) && next) { - this.revocations.add({ - issuer: CLOUD_CONFIG.issuer, - clientId: CLOUD_CONFIG.clientId, - refreshToken: next - }) + if (!stored && this.retiredRefreshTokens.has(refreshToken)) { + this.revokeUnstored(rotated.refreshToken) } return 'refreshed' } catch (error) { @@ -505,7 +512,10 @@ export class CloudSession { if (!browserOpened) reportSwitch('retryable', reason) return generation === this.authGeneration ? this.stayed('retryable') : this.unreached() } - if (generation !== this.authGeneration) return this.unreached() + if (generation !== this.authGeneration) { + this.revokeUnstored(tokens.refreshToken) + return this.unreached() + } this.storeSignedInGrant(tokens) const canMint = canMintWorkspaceTokens(tokens.accessToken) diff --git a/src/main/cloud/tokenStore.test.ts b/src/main/cloud/tokenStore.test.ts index c4b26751b..5d69e5d3a 100644 --- a/src/main/cloud/tokenStore.test.ts +++ b/src/main/cloud/tokenStore.test.ts @@ -365,7 +365,7 @@ describe('grant vault', () => { expect(fs.existsSync(vaultPath())).toBe(false) }) - it('records the Cloud a grant came from at sign-in and at each refresh, and nothing for an older vault', () => { + it('records the Cloud a grant came from at sign-in and at each refresh, and assumes the configured Cloud for an older vault', () => { const grant = tokens('user-1', 'w1') saveGrant(grant) expect(loadGrantOrigin()).toEqual({ @@ -376,7 +376,10 @@ describe('grant vault', () => { const { issuer: _issuer, clientId: _clientId, ...older } = readVault() writeVault(older) _resetForTest() - expect(loadGrantOrigin()).toBeNull() + expect(loadGrantOrigin()).toEqual({ + issuer: CLOUD_CONFIG.issuer, + clientId: CLOUD_CONFIG.clientId + }) replaceGrant(grant.accessToken, grant.refreshToken ?? '', tokens('user-1', 'w1', '-next')) expect(loadGrantOrigin()).toEqual({ @@ -386,7 +389,12 @@ describe('grant vault', () => { }) it('keeps queued revocations encrypted, outside the vault, one file each', () => { - const first = { issuer: 'https://cloud.test', clientId: 'cid', refreshToken: 'refresh-1' } + const first = { + issuer: 'https://cloud.test', + clientId: 'cid', + refreshToken: 'refresh-1', + queuedAt: 1 + } const second = { ...first, refreshToken: 'refresh-2' } saveGrant(tokens('user-1', 'w1')) @@ -408,7 +416,12 @@ describe('grant vault', () => { }) it('never loses a queued revocation to an unreadable sibling entry', () => { - const first = { issuer: 'https://cloud.test', clientId: 'cid', refreshToken: 'refresh-1' } + const first = { + issuer: 'https://cloud.test', + clientId: 'cid', + refreshToken: 'refresh-1', + queuedAt: 1 + } addPendingRevocation(first) const dir = path.join(electronState.userData, 'comfy-cloud-revocations') fs.writeFileSync(path.join(dir, 'unreadable.bin'), 'garbage') @@ -421,7 +434,12 @@ describe('grant vault', () => { }) it('keeps a revocation in memory while it cannot be saved, and saves it once storage works', () => { - const revocation = { issuer: 'https://cloud.test', clientId: 'cid', refreshToken: 'refresh-1' } + const revocation = { + issuer: 'https://cloud.test', + clientId: 'cid', + refreshToken: 'refresh-1', + queuedAt: 1 + } electronState.encryptionAvailable = false addPendingRevocation(revocation) diff --git a/src/main/cloud/tokenStore.ts b/src/main/cloud/tokenStore.ts index b661a2859..2166d0ade 100644 --- a/src/main/cloud/tokenStore.ts +++ b/src/main/cloud/tokenStore.ts @@ -38,6 +38,7 @@ interface LegacyVault { export interface PendingRevocation extends GrantOrigin { refreshToken: string + queuedAt: number } let cachedVault: TokenVault | null = null @@ -221,7 +222,8 @@ function configuredOrigin(): GrantOrigin { export function loadGrantOrigin(): GrantOrigin | null { const vault = loadVault() - if (!vault?.issuer || !vault.clientId) return null + if (!vault) return null + if (!vault.issuer || !vault.clientId) return configuredOrigin() return { issuer: vault.issuer, clientId: vault.clientId } } @@ -320,12 +322,15 @@ function revocationPath(refreshToken: string): string { return path.join(revocationsDir(), `${name}.bin`) } -function isPendingRevocation(v: unknown): v is PendingRevocation { +function isSavedRevocation( + v: unknown +): v is Omit & { queuedAt?: number } { return ( isRecord(v) && typeof v.issuer === 'string' && typeof v.clientId === 'string' && - typeof v.refreshToken === 'string' + typeof v.refreshToken === 'string' && + (v.queuedAt === undefined || typeof v.queuedAt === 'number') ) } @@ -358,10 +363,10 @@ function readSavedRevocations(): PendingRevocations { if (names.length > 0 && !encryptionAvailable()) return { pending: [], complete: false } const pending = names.flatMap((name) => { try { - const parsed: unknown = JSON.parse( - safeStorage.decryptString(fs.readFileSync(path.join(revocationsDir(), name))) - ) - return isPendingRevocation(parsed) ? [parsed] : [] + const file = path.join(revocationsDir(), name) + const parsed: unknown = JSON.parse(safeStorage.decryptString(fs.readFileSync(file))) + if (!isSavedRevocation(parsed)) return [] + return [{ ...parsed, queuedAt: parsed.queuedAt ?? fs.statSync(file).mtimeMs }] } catch { return [] } From 97c765e2f42015bb8ac4d327ac4a03e1bc428b2d Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 10 Nov 2026 13:11:03 -0500 Subject: [PATCH 57/75] fix(auth): sign views out on a rejected mint, keep them signed in without the scope - A 401 from the view token mint now goes through the token provider's unauthorized path, so Desktop signs out and every view follows instead of staying signed in with no token. - A grant Cloud issued without the mint scope keeps the view signed in on the grant itself, as before this change. That grant cannot mint, so no mint-capable token reaches a renderer, and a Cloud without the scope migration no longer leaves the view in a sign-in loop. --- src/main/devplatform/session.ts | 16 ++++++++------ src/main/lib/embeddedSession.test.ts | 14 ++++++------ src/main/lib/embeddedSession.ts | 4 ++-- src/main/lib/viewWorkspaceGrants.test.ts | 27 ++++++++++++++++++++---- src/main/lib/viewWorkspaceGrants.ts | 11 ++++++---- 5 files changed, 49 insertions(+), 23 deletions(-) diff --git a/src/main/devplatform/session.ts b/src/main/devplatform/session.ts index 922bb65b3..4aee51a20 100644 --- a/src/main/devplatform/session.ts +++ b/src/main/devplatform/session.ts @@ -1,6 +1,7 @@ import { BUILDER_BASE_URL } from './config' import { CloudSession } from '../cloud' import { ComfyBuilderClient } from '../comfybuilder' +import type { TokenProvider } from '../comfybuilder' let session: CloudSession | null = null let client: ComfyBuilderClient | null = null @@ -11,16 +12,19 @@ export function getCloudSession(): CloudSession { return session } +function tokenProvider(): TokenProvider { + return getCloudSession().asTokenProvider(() => unauthorizedHandler?.()) +} + export function getBuilderClient(): ComfyBuilderClient { - if (!client) { - client = new ComfyBuilderClient({ - baseUrl: BUILDER_BASE_URL, - auth: getCloudSession().asTokenProvider(() => unauthorizedHandler?.()) - }) - } + if (!client) client = new ComfyBuilderClient({ baseUrl: BUILDER_BASE_URL, auth: tokenProvider() }) return client } +export function rejectAccessToken(accessToken: string): void { + tokenProvider().onUnauthorized?.(accessToken) +} + export function setUnauthorizedHandler(handler: () => void): void { unauthorizedHandler = handler } diff --git a/src/main/lib/embeddedSession.test.ts b/src/main/lib/embeddedSession.test.ts index c6e2d8803..a74591dfb 100644 --- a/src/main/lib/embeddedSession.test.ts +++ b/src/main/lib/embeddedSession.test.ts @@ -16,7 +16,8 @@ vi.mock('../devplatform/session', () => ({ getAccessToken: mocks.getAccessToken, currentWorkspaceId: () => mocks.current, currentSubject: () => (mocks.current ? 'user-1' : null) - }) + }), + rejectAccessToken: vi.fn() })) vi.mock('../cloud/workspaceToken', () => ({ mintWorkspaceToken: mocks.mint @@ -229,14 +230,13 @@ describe('embeddedSession', () => { expect(mocks.getAccessToken).not.toHaveBeenCalled() }) - it('asks a view to sign in again, and hands it nothing, while the grant predates the mint scope', async () => { - mocks.getAccessToken.mockResolvedValue( - jwt({ sub: 'user-1', workspace_id: 'ws-1', scope: 'comfy-cloud:user:read' }) - ) + it('keeps a view signed in on the grant itself when Cloud did not grant the mint scope', async () => { + const grant = jwt({ sub: 'user-1', workspace_id: 'ws-1', scope: 'comfy-cloud:user:read' }) + mocks.getAccessToken.mockResolvedValue(grant) const { event } = view('http://127.0.0.1:8000') - await expect(stateForSender(event)).resolves.toEqual({ status: 'signed_out' }) - await expect(workspaceTokenForSender(event, 'ws-1')).resolves.toBeNull() + await expect(stateForSender(event)).resolves.toMatchObject({ status: 'signed_in' }) + await expect(workspaceTokenForSender(event, 'ws-1')).resolves.toBe(grant) expect(mocks.mint).not.toHaveBeenCalled() }) diff --git a/src/main/lib/embeddedSession.ts b/src/main/lib/embeddedSession.ts index 89599c9d1..27a910b12 100644 --- a/src/main/lib/embeddedSession.ts +++ b/src/main/lib/embeddedSession.ts @@ -1,6 +1,6 @@ import type { WebContents, WebFrameMain } from 'electron' -import { canMintWorkspaceTokens, identityOf } from '../cloud/claims' +import { identityOf } from '../cloud/claims' import { getCloudSession } from '../devplatform/session' import { comfyWindows, findEntryByComfySender } from '../host/registry' import type { ComfyWindowEntry } from '../host/registry' @@ -64,7 +64,7 @@ export function isTrustedSender({ sender, senderFrame }: EmbeddedSessionSender): async function sessionState(): Promise { if (!(await isEmbeddedSessionEnabled())) return DISABLED const token = await getCloudSession().getAccessToken() - const identity = token && canMintWorkspaceTokens(token) ? identityOf(token) : null + const identity = token ? identityOf(token) : null return identity ? { status: 'signed_in', ...identity } : { status: 'signed_out' } } diff --git a/src/main/lib/viewWorkspaceGrants.test.ts b/src/main/lib/viewWorkspaceGrants.test.ts index f86d7c752..880d0944b 100644 --- a/src/main/lib/viewWorkspaceGrants.test.ts +++ b/src/main/lib/viewWorkspaceGrants.test.ts @@ -4,7 +4,10 @@ import { Buffer } from 'node:buffer' import type { WebContents } from 'electron' import { beforeEach, describe, expect, it, vi } from 'vitest' -vi.mock('../devplatform/session', () => ({ getCloudSession: () => ({}) })) +vi.mock('../devplatform/session', () => ({ + getCloudSession: () => ({}), + rejectAccessToken: vi.fn() +})) vi.mock('./telemetry', () => ({ emit: vi.fn() })) import { CLOUD_CONFIG } from '../cloud/config' @@ -50,6 +53,7 @@ let mint: ReturnType< typeof vi.fn<(token: string, workspaceId: string) => Promise> > let grants: ViewWorkspaceGrants +let rejected: string[] function signInAt(workspaceId: string | null): void { current = workspaceId @@ -60,13 +64,15 @@ beforeEach(() => { user = 'user-1' signInAt('ws-1') mint = vi.fn(async (_token: string, workspaceId: string) => minted(workspaceId)) + rejected = [] grants = new ViewWorkspaceGrants( { currentWorkspaceId: () => current, currentSubject: () => (current ? user : null), getAccessToken: async () => (current ? accessToken(current) : null) }, - mint + mint, + (token) => rejected.push(token) ) }) @@ -96,6 +102,17 @@ describe('ViewWorkspaceGrants', () => { expect(mint).toHaveBeenCalledWith(accessToken('ws-1'), 'ws-1') }) + it('signs Desktop out when Cloud rejects the grant at the mint, and not for other failures', async () => { + mint.mockResolvedValueOnce({ kind: 'failed', status: 403 }) + await grants.tokenFor(viewA, 'ws-1') + expect(rejected).toEqual([]) + + mint.mockResolvedValueOnce({ kind: 'failed', status: 401 }) + expect(await grants.tokenFor(viewA, 'ws-1')).toBeNull() + + expect(rejected).toEqual([accessToken('ws-1')]) + }) + it('reuses a minted token until it nears expiry', async () => { await grants.tokenFor(viewA, 'ws-1') await grants.tokenFor(viewB, 'ws-1') @@ -192,7 +209,7 @@ describe('ViewWorkspaceGrants', () => { await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBeNull() }) - it('hands out nothing, and does not ask Cloud, for a grant without the mint scope', async () => { + it('hands out the grant itself, without asking Cloud, when it cannot mint', async () => { grants = new ViewWorkspaceGrants( { currentWorkspaceId: () => 'ws-1', @@ -202,7 +219,9 @@ describe('ViewWorkspaceGrants', () => { mint ) - await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBeNull() + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe( + accessToken('ws-1', 'comfy-cloud:user:read') + ) expect(mint).not.toHaveBeenCalled() }) diff --git a/src/main/lib/viewWorkspaceGrants.ts b/src/main/lib/viewWorkspaceGrants.ts index 0934be67f..69f09afca 100644 --- a/src/main/lib/viewWorkspaceGrants.ts +++ b/src/main/lib/viewWorkspaceGrants.ts @@ -3,7 +3,7 @@ import type { WebContents } from 'electron' import { canMintWorkspaceTokens, subjectOf, workspaceIdOf } from '../cloud/claims' import { mintWorkspaceToken } from '../cloud/workspaceToken' import type { WorkspaceTokenMint } from '../cloud/workspaceToken' -import { getCloudSession } from '../devplatform/session' +import { getCloudSession, rejectAccessToken } from '../devplatform/session' import * as mainTelemetry from './telemetry' const MINT_REFRESH_SKEW_MS = 60_000 @@ -57,7 +57,8 @@ export class ViewWorkspaceGrants { constructor( private readonly session: GrantSession, - private readonly mint: MintWorkspaceToken = mintWorkspaceToken + private readonly mint: MintWorkspaceToken = mintWorkspaceToken, + private readonly onUnauthorized: (accessToken: string) => void = () => {} ) {} allowDesktop(workspaceId: string | undefined): void { @@ -108,9 +109,9 @@ export class ViewWorkspaceGrants { const accessToken = await this.session.getAccessToken() if (epoch !== this.epoch) return null if (!accessToken || workspaceIdOf(accessToken) !== workspaceId) return null - if (!canMintWorkspaceTokens(accessToken)) return null const subject = subjectOf(accessToken) if (!subject) return null + if (!canMintWorkspaceTokens(accessToken)) return { token: accessToken, subject } const key = mintKey(subject, workspaceId) const cached = this.minted.get(key) if (cached && cached.expiresAt - MINT_REFRESH_SKEW_MS > Date.now()) @@ -134,6 +135,7 @@ export class ViewWorkspaceGrants { const pending = this.mint(accessToken, workspaceId) .then((result) => { reportMint(result) + if (result.kind === 'failed' && result.status === 401) this.onUnauthorized(accessToken) return result }) .finally(() => { @@ -147,7 +149,8 @@ export class ViewWorkspaceGrants { let grants: ViewWorkspaceGrants | null = null export function getViewWorkspaceGrants(): ViewWorkspaceGrants { - if (!grants) grants = new ViewWorkspaceGrants(getCloudSession()) + if (!grants) + grants = new ViewWorkspaceGrants(getCloudSession(), mintWorkspaceToken, rejectAccessToken) return grants } From b27f32fc9e76749c3b9f069b114c9fee1541ba41 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 10 Nov 2026 13:12:37 -0500 Subject: [PATCH 58/75] fix(auth): keep view-requested switches visible and fall back to the browser - A switch a local ComfyUI view requests no longer mints silently. It reaches the anchor or a workspace Desktop already holds without a browser, and any other workspace through browser consent, as before this change. Desktop's own selector still switches without a browser. - A chosen switch on a grant Cloud issued without the mint scope falls back to browser consent instead of staying put with a connection caption. The persisted scope hold is gone; a restored switch still never opens a browser. - 403 oauth_token_mint_refused falls back to browser consent with its own reauthorize reason, like the kill switch, instead of reading as an unavailable workspace. --- src/main/cloud/session.test.ts | 155 ++++++++---------- src/main/cloud/session.ts | 14 +- src/main/cloud/tokenStore.test.ts | 65 -------- src/main/cloud/tokenStore.ts | 16 +- src/main/cloud/types.ts | 2 +- src/main/cloud/workspaceToken.test.ts | 6 +- src/main/cloud/workspaceToken.ts | 5 + .../ipc/registerEmbeddedSessionHandlers.ts | 2 +- 8 files changed, 87 insertions(+), 178 deletions(-) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index cbc5ce435..96c3dd2a2 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -1641,6 +1641,51 @@ describe('CloudSession regressions', () => { }) }) +describe('CloudSession switches a local ComfyUI view requests', () => { + it('asks the browser for a new workspace instead of minting silently', async () => { + saveGrant(grantOn('w1')) + browserSignInReturns(signedInResult(grantOn('w2'))) + + await expect(new CloudSession().switchWorkspace('w2', 'requested')).resolves.toMatchObject({ + workspaceId: 'w2' + }) + + expect(signIn).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ workspaceId: 'w2' })) + expect(mintRequests).toEqual([]) + expect(browserEvents()).toEqual([{ reauthorize_reason: 'view_requested' }]) + }) + + it('moves without a browser to the anchor or a workspace Desktop already holds', async () => { + saveGrant(grantOn('w1')) + const session = new CloudSession() + await session.switchWorkspace('w2') + + await expect(session.switchWorkspace('w1', 'requested')).resolves.toMatchObject({ + workspaceId: 'w1' + }) + await expect(session.switchWorkspace('w2', 'requested')).resolves.toMatchObject({ + workspaceId: 'w2' + }) + + expect(signIn).not.toHaveBeenCalled() + expect(mintRequests).toHaveLength(1) + }) +}) + +describe('CloudSession when Cloud refuses this client a mint', () => { + it('falls back to browser consent, as with the kill switch', async () => { + saveGrant(grantOn('w1')) + mintReply = () => json(403, { code: 'oauth_token_mint_refused' }) + browserSignInReturns(signedInResult(grantOn('w2'))) + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w2' + }) + + expect(browserEvents()).toEqual([{ reauthorize_reason: 'mint_refused' }]) + }) +}) + describe('CloudSession grants without the mint scope (T-V29)', () => { it('opens exactly one browser, asks Cloud nothing first, and then mints', async () => { saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) @@ -1685,32 +1730,36 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { expect(browserEvents()).toEqual([{ reauthorize_reason: 'mint_scope_missing' }]) }) - it('a second and third switch after a scopeless sign-in stay put with no browser', async () => { + it('keeps asking the browser on each chosen switch while Cloud withholds the scope', async () => { saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) browserSignInReturns( signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) ) const session = new CloudSession() - await session.switchWorkspace('w2') - const browserTrips = browserEvents().length - for (const workspaceId of ['w2', 'w3']) { + for (const workspaceId of ['w2', 'w2', 'w3']) { await expect(session.switchWorkspace(workspaceId)).resolves.toMatchObject({ workspaceId: 'w1', workspaceSwitchFailure: 'retryable' }) } - expect(signIn).toHaveBeenCalledOnce() - expect(browserEvents()).toHaveLength(browserTrips) + expect(signIn).toHaveBeenCalledTimes(3) expect(mintRequests).toEqual([]) - expect(switchEvents().at(-1)).toEqual({ - outcome: 'retryable', - reauthorize_reason: 'scope_not_granted' + }) + + it('never opens a browser for a restored switch while Cloud withholds the scope', async () => { + saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) + + await expect(new CloudSession().switchWorkspace('w2', 'restored')).resolves.toMatchObject({ + workspaceId: 'w1', + workspaceSwitchFailure: 'retryable' }) + + expect(signIn).not.toHaveBeenCalled() }) - it('a scopeless grant on B reaches its anchor and asks no browser for the next workspace', async () => { + it('a scopeless grant on B reaches its anchor and asks the browser for the next workspace', async () => { saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) browserSignInReturns(signedInResult(grantOn('w2', { scope: READ_ONLY_SCOPE }))) const session = new CloudSession() @@ -1721,10 +1770,10 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { workspaceSwitchFailure: 'retryable' }) - expect(signIn).toHaveBeenCalledOnce() + expect(signIn).toHaveBeenCalledTimes(2) }) - it('an explicit sign-in with the scope lifts the hold and switching mints again', async () => { + it('an explicit sign-in with the scope lets switching mint again', async () => { saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) browserSignInReturnsOnce( signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) @@ -1740,7 +1789,7 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { expect(mintRequests).toHaveLength(1) }) - it('a grant that can mint lifts the hold, so one that later narrows can ask again', async () => { + it('a grant that later narrows asks the browser again', async () => { saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) browserSignInReturnsOnce( signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) @@ -1763,7 +1812,7 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { expect(signIn).toHaveBeenCalledTimes(3) }) - it('an explicit sign-in that also returns no scope keeps ordinary switches off the browser', async () => { + it('a switch after an explicit sign-in that returned no scope asks the browser again', async () => { saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) browserSignInReturns( signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) @@ -1775,68 +1824,10 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { workspaceSwitchFailure: 'retryable' }) - expect(signIn).toHaveBeenCalledOnce() - }) - - it('logout resets the hold', async () => { - saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) - browserSignInReturns( - signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) - ) - const session = new CloudSession() - await session.switchWorkspace('w2') - - session.logout() - saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) - await session.switchWorkspace('w2') - expect(signIn).toHaveBeenCalledTimes(2) }) - it('a restart keeps the hold: no second browser across sessions', async () => { - saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) - browserSignInReturns( - signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) - ) - await new CloudSession().switchWorkspace('w2') - _resetForTest() - - await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ - workspaceId: 'w1', - workspaceSwitchFailure: 'retryable' - }) - - expect(signIn).toHaveBeenCalledOnce() - expect(vaultOnDisk().mintScopeWithheld).toBe(true) - }) - - it('a pre-upgrade grant gets its one trip on first launch, then the hold survives restarts', async () => { - fs.writeFileSync( - path.join(electronState.userData, 'comfy-cloud-auth.bin'), - safeStorage.encryptString( - JSON.stringify({ - version: 1, - activeKey: 'workspace:w1', - subject: 'user-1', - bundles: { 'workspace:w1': grantOn('w1', { scope: READ_ONLY_SCOPE }) } - }) - ) - ) - _resetForTest() - browserSignInReturns( - signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) - ) - expect(vaultOnDisk().mintScopeWithheld).toBeUndefined() - - await new CloudSession().switchWorkspace('w2') - expect(signIn).toHaveBeenCalledOnce() - _resetForTest() - await new CloudSession().switchWorkspace('w2') - - expect(signIn).toHaveBeenCalledOnce() - }) - - it('a restart with a scoped sign-in in between mints: the grant that can mint cleared the hold', async () => { + it('a restart after a scoped sign-in mints', async () => { saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) browserSignInReturnsOnce( signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) @@ -1851,24 +1842,10 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { workspaceId: 'w2' }) - expect(signIn).toHaveBeenCalledTimes(2) - expect(vaultOnDisk()).not.toHaveProperty('mintScopeWithheld') - }) - - it('an explicit sign-in can still try after a restart', async () => { - saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) - browserSignInReturns( - signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-again' })) - ) - await new CloudSession().switchWorkspace('w2') - _resetForTest() - - await new CloudSession().login() - expect(signIn).toHaveBeenCalledTimes(2) }) - it('emits one mint_scope_not_granted for a switch sign-in, and none for the later held switches', async () => { + it('emits mint_scope_not_granted for each switch sign-in that returns no scope', async () => { saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) browserSignInReturns(signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE, revision: '-b' }))) const session = new CloudSession() @@ -1876,7 +1853,7 @@ describe('CloudSession grants without the mint scope (T-V29)', () => { await session.switchWorkspace('w2') await session.switchWorkspace('w3') - expect(mintScopeNotGrantedEvents()).toHaveLength(1) + expect(mintScopeNotGrantedEvents()).toHaveLength(2) }) it('emits one mint_scope_not_granted for an explicit sign-in with no scope', async () => { diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index 292539d59..9812f86a3 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -10,7 +10,6 @@ import { dropWorkspaceToken, endGrant, getAuthStatus, - isMintScopeWithheld, loadActiveWorkspaceId, loadGrant, loadWorkspaceToken, @@ -149,9 +148,9 @@ export class CloudSession { private storeSignedInGrant(tokens: AuthTokens): void { this.mintBlockedUntil = 0 - const mintScopeWithheld = !canMintWorkspaceTokens(tokens.accessToken) - saveGrant(tokens, { mintScopeWithheld }) - if (mintScopeWithheld) mainTelemetry.emit(MINT_SCOPE_NOT_GRANTED_EVENT) + saveGrant(tokens) + if (!canMintWorkspaceTokens(tokens.accessToken)) + mainTelemetry.emit(MINT_SCOPE_NOT_GRANTED_EVENT) } private clearPendingLogin(): void { @@ -395,6 +394,9 @@ export class CloudSession { } const held = loadWorkspaceToken(workspaceId) if (held && held.expiresAt > Date.now()) return this.activated(workspaceId, 'cached') + if (this.switchIntent === 'requested') { + return this.reauthorize(workspaceId, generation, 'view_requested') + } const outcome = await this.mintForWorkspace(workspaceId, generation) if (generation !== this.authGeneration) return this.unreached() @@ -411,10 +413,6 @@ export class CloudSession { reportSwitch('retryable') return this.stayed('retryable') case 'reauthorize': - if (outcome.reason === 'mint_scope_missing' && isMintScopeWithheld()) { - reportSwitch('retryable', 'scope_not_granted') - return this.stayed('retryable') - } return this.reauthorize(workspaceId, generation, outcome.reason) } } diff --git a/src/main/cloud/tokenStore.test.ts b/src/main/cloud/tokenStore.test.ts index 74e91307d..f0f94145d 100644 --- a/src/main/cloud/tokenStore.test.ts +++ b/src/main/cloud/tokenStore.test.ts @@ -22,7 +22,6 @@ vi.mock('electron', () => ({ import { safeStorage } from 'electron' -import { CLOUD_CONFIG } from './config' import { _resetForTest, activateWorkspace, @@ -30,7 +29,6 @@ import { dropWorkspaceToken, getAuthStatus, getCachedWorkspaceName, - isMintScopeWithheld, loadActiveWorkspaceId, loadGrant, loadWorkspaceToken, @@ -47,12 +45,6 @@ function jwt(subject: string, workspaceId: string): string { return `${b64({ alg: 'RS256' })}.${b64({ sub: subject, workspace_id: workspaceId })}.sig` } -function jwtWithScope(subject: string, workspaceId: string, scope: string): string { - const b64 = (value: unknown): string => - Buffer.from(JSON.stringify(value), 'utf-8').toString('base64url') - return `${b64({ alg: 'RS256' })}.${b64({ sub: subject, workspace_id: workspaceId, scope })}.sig` -} - function tokenWithoutSubject(workspaceId: string): string { const b64 = (value: unknown): string => Buffer.from(JSON.stringify(value), 'utf-8').toString('base64url') @@ -150,53 +142,6 @@ describe('grant vault', () => { expect(getAuthStatus()).toEqual({ signedIn: false }) }) - it('persists a withheld mint scope on the grant and clears it with a grant that can mint', () => { - saveGrant(tokens('user-1', 'w1'), { mintScopeWithheld: true }) - _resetForTest() - expect(isMintScopeWithheld()).toBe(true) - - saveGrant(tokens('user-1', 'w1', '-next')) - _resetForTest() - expect(isMintScopeWithheld()).toBe(false) - expect(readVault()).not.toHaveProperty('mintScopeWithheld') - }) - - it('forgets a withheld mint scope on logout and on a changed account', () => { - saveGrant(tokens('user-1', 'w1'), { mintScopeWithheld: true }) - saveGrant(tokens('user-2', 'w1')) - expect(isMintScopeWithheld()).toBe(false) - - saveGrant(tokens('user-2', 'w1'), { mintScopeWithheld: true }) - clearTokens() - expect(isMintScopeWithheld()).toBe(false) - }) - - it('a rotation that can mint clears a withheld scope and one that cannot keeps it', () => { - const scopeless = tokens('user-1', 'w1') - saveGrant(scopeless, { mintScopeWithheld: true }) - const rotated = tokens('user-1', 'w1', '-rotated') - replaceGrant(scopeless.accessToken, scopeless.refreshToken!, rotated) - expect(isMintScopeWithheld()).toBe(true) - - const scoped = { - accessToken: jwtWithScope('user-1', 'w1', CLOUD_CONFIG.scope), - refreshToken: 'refresh-scoped', - expiresAt: Date.now() + 3_600_000 - } - replaceGrant(rotated.accessToken, rotated.refreshToken!, scoped) - expect(isMintScopeWithheld()).toBe(false) - }) - - it('never sets a withheld scope when migrating a version 1 vault', () => { - writeVault({ - version: 1, - activeKey: 'workspace:w1', - bundles: { 'workspace:w1': tokens('user-1', 'w1') } - }) - - expect(isMintScopeWithheld()).toBe(false) - }) - it('activates only the anchor or a workspace with a held token', () => { saveGrant(tokens('user-1', 'w1')) saveWorkspaceToken('w2', mintedToken('user-1', 'w2')) @@ -393,16 +338,6 @@ describe('grant vault', () => { }) it.each<[string, unknown]>([ - [ - 'a version 2 vault with a malformed scope hold', - { - version: 2, - grant: tokens('user-1', 'w1'), - activeWorkspaceId: 'w1', - workspaceTokens: {}, - mintScopeWithheld: 'yes' - } - ], ['an unknown version', { version: 3, grant: tokens('user-1', 'w1') }], [ 'a version 2 vault with no grant', diff --git a/src/main/cloud/tokenStore.ts b/src/main/cloud/tokenStore.ts index 2af1af251..e89f7d875 100644 --- a/src/main/cloud/tokenStore.ts +++ b/src/main/cloud/tokenStore.ts @@ -2,7 +2,7 @@ import { app, safeStorage } from 'electron' import * as fs from 'fs' import * as path from 'path' -import { canMintWorkspaceTokens, statusFromAccessToken, subjectOf, workspaceIdOf } from './claims' +import { statusFromAccessToken, subjectOf, workspaceIdOf } from './claims' import type { AuthStatus, AuthTokens, Workspace } from './types' const AUTH_FILENAME = 'comfy-cloud-auth.bin' @@ -12,7 +12,6 @@ interface TokenVault { version: typeof VAULT_VERSION subject?: string grant: AuthTokens - mintScopeWithheld?: true activeWorkspaceId: string | null workspaceTokens: Record workspaceNames?: Record @@ -73,7 +72,6 @@ function isVault(v: unknown): v is TokenVault { if (!isRecord(v) || v.version !== VAULT_VERSION) return false return ( isTokens(v.grant) && - (v.mintScopeWithheld === undefined || v.mintScopeWithheld === true) && (v.activeWorkspaceId === null || typeof v.activeWorkspaceId === 'string') && (v.subject === undefined || typeof v.subject === 'string') && isRecord(v.workspaceTokens) && @@ -154,16 +152,13 @@ function holdsToken(vault: TokenVault, workspaceId: string | null): boolean { ) } -export function saveGrant(grant: AuthTokens, options: { mintScopeWithheld?: boolean } = {}): void { - const withheld = options.mintScopeWithheld ? ({ mintScopeWithheld: true } as const) : {} +export function saveGrant(grant: AuthTokens): void { const current = loadVault() const subject = subjectOf(grant.accessToken) if (!current || !subject || current.subject !== subject) { - persistVault({ ...vaultFor(grant), ...withheld }) + persistVault(vaultFor(grant)) return } - delete current.mintScopeWithheld - Object.assign(current, withheld) const previous = current.grant const previousAnchor = workspaceIdOf(previous.accessToken) if ( @@ -182,10 +177,6 @@ export function saveGrant(grant: AuthTokens, options: { mintScopeWithheld?: bool persistVault(current) } -export function isMintScopeWithheld(): boolean { - return loadVault()?.mintScopeWithheld === true -} - export function loadGrant(): AuthTokens | null { return loadVault()?.grant ?? null } @@ -255,7 +246,6 @@ export function replaceGrant( return false } vault.grant = grant - if (canMintWorkspaceTokens(grant.accessToken)) delete vault.mintScopeWithheld persistVault(vault) return true } diff --git a/src/main/cloud/types.ts b/src/main/cloud/types.ts index 688493de5..ea8e97ec4 100644 --- a/src/main/cloud/types.ts +++ b/src/main/cloud/types.ts @@ -15,7 +15,7 @@ export interface AuthStatus { export type WorkspaceSwitchFailure = 'unavailable' | 'retryable' -export type WorkspaceSwitchIntent = 'chosen' | 'restored' +export type WorkspaceSwitchIntent = 'chosen' | 'restored' | 'requested' export interface WorkspaceSwitchStatus extends AuthStatus { workspaceSwitchFailure?: WorkspaceSwitchFailure diff --git a/src/main/cloud/workspaceToken.test.ts b/src/main/cloud/workspaceToken.test.ts index d1b7b8665..0260fc2fe 100644 --- a/src/main/cloud/workspaceToken.test.ts +++ b/src/main/cloud/workspaceToken.test.ts @@ -290,7 +290,11 @@ describe('classifyMint', () => { { kind: 'refused' } ], ['403 workspace_access_denied', failed(403, 'workspace_access_denied'), { kind: 'refused' }], - ['403 oauth_token_mint_refused', failed(403, 'oauth_token_mint_refused'), { kind: 'refused' }], + [ + '403 oauth_token_mint_refused', + failed(403, 'oauth_token_mint_refused'), + { kind: 'reauthorize', reason: 'mint_refused' } + ], ['403 insufficient_scope', failed(403, 'insufficient_scope'), { kind: 'refused' }], [ '403 oauth_derived_mint_refused', diff --git a/src/main/cloud/workspaceToken.ts b/src/main/cloud/workspaceToken.ts index afa930a46..ebfc6890a 100644 --- a/src/main/cloud/workspaceToken.ts +++ b/src/main/cloud/workspaceToken.ts @@ -13,9 +13,12 @@ export type ReauthorizeReason = | 'grant_ended' | 'mint_scope_missing' | 'mint_disabled' + | 'mint_refused' + | 'view_requested' const MINT_DISABLED_CODE = 'oauth_workspace_mint_disabled' const GRANT_ENDED_CODE = 'oauth_grant_ended' +const MINT_REFUSED_CODE = 'oauth_token_mint_refused' export type WorkspaceMintOutcome = | { kind: 'minted'; token: string; expiresAt: number } @@ -43,6 +46,8 @@ export function classifyMint(mint: WorkspaceTokenMint): WorkspaceMintOutcome { if (status === 404) return { kind: 'unavailable' } if (status === 403 && code === 'sso_required') return { kind: 'reauthorize', reason: 'sso_required' } + if (status === 403 && code === MINT_REFUSED_CODE) + return { kind: 'reauthorize', reason: 'mint_refused' } return { kind: 'refused' } } diff --git a/src/main/lib/ipc/registerEmbeddedSessionHandlers.ts b/src/main/lib/ipc/registerEmbeddedSessionHandlers.ts index 1e70f8383..e6d09f60f 100644 --- a/src/main/lib/ipc/registerEmbeddedSessionHandlers.ts +++ b/src/main/lib/ipc/registerEmbeddedSessionHandlers.ts @@ -39,6 +39,6 @@ export function registerEmbeddedSessionHandlers(): void { ) ipcMain.handle(EMBEDDED_SESSION_CHANNELS.switchWorkspace, (event, workspaceId: unknown) => - switchWorkspaceForSender(event, workspaceId, switchCloudWorkspace) + switchWorkspaceForSender(event, workspaceId, (id) => switchCloudWorkspace(id, 'requested')) ) } From 13fe2d12ba89115bb0e918171e5809358462e5b0 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 10 Nov 2026 13:25:08 -0500 Subject: [PATCH 59/75] fix(auth): keep views on the held token without the scope, let a view request open consent - A view whose grant cannot mint now gets the token Desktop holds for its current workspace, when that token cannot mint either. Switching back to a workspace reached through two scopeless consents no longer leaves the view signed in with no token. - A view request joining an in-flight restored switch upgrades it, so an sso_required answer still opens browser consent. --- src/main/cloud/session.test.ts | 17 +++++++++++ src/main/cloud/session.ts | 2 +- src/main/lib/embeddedSession.test.ts | 1 + .../ipc/registerDevPlatformHandlers.test.ts | 3 ++ src/main/lib/viewWorkspaceGrants.test.ts | 30 ++++++++++++++++++- src/main/lib/viewWorkspaceGrants.ts | 16 ++++++++-- 6 files changed, 64 insertions(+), 5 deletions(-) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index 96c3dd2a2..e29cf7c24 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -1655,6 +1655,23 @@ describe('CloudSession switches a local ComfyUI view requests', () => { expect(browserEvents()).toEqual([{ reauthorize_reason: 'view_requested' }]) }) + it('lets a view request joining a restored switch still ask the browser', async () => { + saveGrant(grantOn('w1')) + const slow = deferred() + mintReply = () => slow.promise + browserSignInReturns(signedInResult(grantOn('w2'))) + const session = new CloudSession() + + const restored = session.switchWorkspace('w2', 'restored') + await vi.waitFor(() => expect(mintRequests).toHaveLength(1)) + const requested = session.switchWorkspace('w2', 'requested') + slow.resolve(json(403, { code: 'sso_required' })) + + await expect(requested).resolves.toMatchObject({ workspaceId: 'w2' }) + await restored + expect(signIn).toHaveBeenCalledOnce() + }) + it('moves without a browser to the anchor or a workspace Desktop already holds', async () => { saveGrant(grantOn('w1')) const session = new CloudSession() diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index 9812f86a3..991ed9d32 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -373,7 +373,7 @@ export class CloudSession { intent: WorkspaceSwitchIntent = 'chosen' ): Promise { if (this.switching?.workspaceId === workspaceId) { - if (intent === 'chosen') this.switchIntent = 'chosen' + if (intent === 'chosen' || this.switchIntent === 'restored') this.switchIntent = intent return this.switching.result } this.clearPendingLogin() diff --git a/src/main/lib/embeddedSession.test.ts b/src/main/lib/embeddedSession.test.ts index c7fd5ca39..afbc72798 100644 --- a/src/main/lib/embeddedSession.test.ts +++ b/src/main/lib/embeddedSession.test.ts @@ -16,6 +16,7 @@ vi.mock('./embeddedSessionFlag', () => ({ vi.mock('../devplatform/session', () => ({ getCloudSession: () => ({ getGrantAccessToken: mocks.getGrantAccessToken, + getAccessToken: mocks.getGrantAccessToken, currentWorkspaceId: () => mocks.current, currentSubject: () => (mocks.current ? 'user-1' : null), currentAuthGeneration: () => 0, diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts index 664dfab60..546b23080 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts @@ -578,6 +578,7 @@ describe('registerDevPlatformHandlers', () => { getGrantAccessToken: async () => jwt({ sub: 'user-1', workspace_id: 'w1', scope: CLOUD_CONFIG.scope }), isWorkspaceMintAllowed: async () => true, + getAccessToken: async () => null, endGrantFamily: () => {} }, async (_grant, workspaceId) => ({ @@ -675,6 +676,7 @@ describe('registerDevPlatformHandlers', () => { ? jwt({ sub: auth.subject, workspace_id: 'home', scope: CLOUD_CONFIG.scope }) : null, isWorkspaceMintAllowed: async () => true, + getAccessToken: async () => null, endGrantFamily: () => {} }, async (_grant, workspaceId) => ({ @@ -854,6 +856,7 @@ describe('registerDevPlatformHandlers', () => { getGrantAccessToken: async () => jwt({ sub: subject, workspace_id: 'home', scope: CLOUD_CONFIG.scope }), isWorkspaceMintAllowed: async () => true, + getAccessToken: async () => null, endGrantFamily: () => {} }, async (_grant, workspaceId) => ({ diff --git a/src/main/lib/viewWorkspaceGrants.test.ts b/src/main/lib/viewWorkspaceGrants.test.ts index 18972f1f3..7043de377 100644 --- a/src/main/lib/viewWorkspaceGrants.test.ts +++ b/src/main/lib/viewWorkspaceGrants.test.ts @@ -70,13 +70,15 @@ function signInAt(workspaceId: string | null): void { } function grantSession( - getGrantAccessToken: () => Promise + getGrantAccessToken: () => Promise, + getAccessToken: () => Promise = getGrantAccessToken ): ConstructorParameters[0] { return { currentWorkspaceId: () => current, currentSubject: () => (current ? user : null), currentAuthGeneration: () => generation, getGrantAccessToken, + getAccessToken, isWorkspaceMintAllowed: async () => true, endGrantFamily: () => {} } @@ -316,6 +318,32 @@ describe('ViewWorkspaceGrants', () => { expect(mint).not.toHaveBeenCalled() }) + it('hands a view the token Desktop holds for a workspace it reached without the mint scope', async () => { + const held = accessToken('ws-1', 'comfy-cloud:user:read') + grants = new ViewWorkspaceGrants( + grantSession( + async () => accessToken('ws-2', 'comfy-cloud:user:read'), + async () => held + ), + mint + ) + + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe(held) + expect(mint).not.toHaveBeenCalled() + }) + + it('never hands out a token that can mint, even one Desktop holds for the workspace', async () => { + grants = new ViewWorkspaceGrants( + grantSession( + async () => accessToken('ws-2', 'comfy-cloud:user:read'), + async () => accessToken('ws-1') + ), + mint + ) + + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBeNull() + }) + it('never hands one account a token minted for another account in the same workspace', async () => { await grants.tokenFor(viewA, 'ws-1') user = 'user-2' diff --git a/src/main/lib/viewWorkspaceGrants.ts b/src/main/lib/viewWorkspaceGrants.ts index 603f5f8e1..c603f9fa2 100644 --- a/src/main/lib/viewWorkspaceGrants.ts +++ b/src/main/lib/viewWorkspaceGrants.ts @@ -27,6 +27,7 @@ export interface GrantSession { currentSubject(): string | null currentAuthGeneration(): number getGrantAccessToken(): Promise + getAccessToken(): Promise isWorkspaceMintAllowed(workspaceId: string): Promise endGrantFamily(accessToken: string): void } @@ -121,14 +122,23 @@ export class ViewWorkspaceGrants { ) } + private async unmintable( + workspaceId: string, + subject: string, + fence: MintFence + ): Promise { + const token = await this.session.getAccessToken() + if (!this.isCurrent(fence) || !token || canMintWorkspaceTokens(token)) return null + if (workspaceIdOf(token) !== workspaceId || subjectOf(token) !== subject) return null + return { token, subject } + } + private async workspaceToken(workspaceId: string, fence: MintFence): Promise { const accessToken = await this.session.getGrantAccessToken() if (!this.isCurrent(fence) || !accessToken) return null const subject = subjectOf(accessToken) if (!subject) return null - if (!canMintWorkspaceTokens(accessToken)) { - return workspaceIdOf(accessToken) === workspaceId ? { token: accessToken, subject } : null - } + if (!canMintWorkspaceTokens(accessToken)) return this.unmintable(workspaceId, subject, fence) const key = mintKey(subject, workspaceId) const cached = this.minted.get(key) if (cached && cached.expiresAt - MINT_REFRESH_SKEW_MS > Date.now()) From fb46c20c78828f9cb6d67a559bd2ac68fb71fb56 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 10 Nov 2026 13:31:34 -0500 Subject: [PATCH 60/75] fix(auth): read a view's held token without side effects The scopeless view path called session.getAccessToken(), which can mint or return Desktop to its anchor workspace. It now reads the grant for its own workspace, or the held token for another, through a read-only heldWorkspaceToken(), so a view's token request never moves Desktop. --- src/main/cloud/session.test.ts | 18 ++++++++++++++++++ src/main/cloud/session.ts | 5 +++++ src/main/lib/embeddedSession.test.ts | 2 +- .../ipc/registerDevPlatformHandlers.test.ts | 6 +++--- src/main/lib/viewWorkspaceGrants.test.ts | 8 ++++---- src/main/lib/viewWorkspaceGrants.ts | 16 +++++++--------- 6 files changed, 38 insertions(+), 17 deletions(-) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index e29cf7c24..16db7c393 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -1641,6 +1641,24 @@ describe('CloudSession regressions', () => { }) }) +describe('CloudSession.heldWorkspaceToken', () => { + it('reads a held token without minting, refreshing or moving Desktop', async () => { + saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) + saveWorkspaceToken('w2', { accessToken: mintedJwt('w2'), expiresAt: FUTURE }) + saveWorkspaceToken('w3', { accessToken: mintedJwt('w3'), expiresAt: PAST }) + const session = new CloudSession() + await session.switchWorkspace('w3', 'restored') + const active = session.currentWorkspaceId() + + expect(session.heldWorkspaceToken('w2')).toBe(mintedJwt('w2')) + expect(session.heldWorkspaceToken('w3')).toBeNull() + + expect(session.currentWorkspaceId()).toBe(active) + expect(mintRequests).toEqual([]) + expect(signIn).not.toHaveBeenCalled() + }) +}) + describe('CloudSession switches a local ComfyUI view requests', () => { it('asks the browser for a new workspace instead of minting silently', async () => { saveGrant(grantOn('w1')) diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index 991ed9d32..1401ef014 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -187,6 +187,11 @@ export class CloudSession { return loadActiveWorkspaceId() } + heldWorkspaceToken(workspaceId: string): string | null { + const held = loadWorkspaceToken(workspaceId) + return held && held.expiresAt > Date.now() ? held.accessToken : null + } + async getGrantAccessToken(): Promise { const grant = loadGrant() if (!grant) return null diff --git a/src/main/lib/embeddedSession.test.ts b/src/main/lib/embeddedSession.test.ts index afbc72798..871f46626 100644 --- a/src/main/lib/embeddedSession.test.ts +++ b/src/main/lib/embeddedSession.test.ts @@ -16,7 +16,7 @@ vi.mock('./embeddedSessionFlag', () => ({ vi.mock('../devplatform/session', () => ({ getCloudSession: () => ({ getGrantAccessToken: mocks.getGrantAccessToken, - getAccessToken: mocks.getGrantAccessToken, + heldWorkspaceToken: () => null, currentWorkspaceId: () => mocks.current, currentSubject: () => (mocks.current ? 'user-1' : null), currentAuthGeneration: () => 0, diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts index 546b23080..3bbac5350 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts @@ -578,7 +578,7 @@ describe('registerDevPlatformHandlers', () => { getGrantAccessToken: async () => jwt({ sub: 'user-1', workspace_id: 'w1', scope: CLOUD_CONFIG.scope }), isWorkspaceMintAllowed: async () => true, - getAccessToken: async () => null, + heldWorkspaceToken: () => null, endGrantFamily: () => {} }, async (_grant, workspaceId) => ({ @@ -676,7 +676,7 @@ describe('registerDevPlatformHandlers', () => { ? jwt({ sub: auth.subject, workspace_id: 'home', scope: CLOUD_CONFIG.scope }) : null, isWorkspaceMintAllowed: async () => true, - getAccessToken: async () => null, + heldWorkspaceToken: () => null, endGrantFamily: () => {} }, async (_grant, workspaceId) => ({ @@ -856,7 +856,7 @@ describe('registerDevPlatformHandlers', () => { getGrantAccessToken: async () => jwt({ sub: subject, workspace_id: 'home', scope: CLOUD_CONFIG.scope }), isWorkspaceMintAllowed: async () => true, - getAccessToken: async () => null, + heldWorkspaceToken: () => null, endGrantFamily: () => {} }, async (_grant, workspaceId) => ({ diff --git a/src/main/lib/viewWorkspaceGrants.test.ts b/src/main/lib/viewWorkspaceGrants.test.ts index 7043de377..84edd8233 100644 --- a/src/main/lib/viewWorkspaceGrants.test.ts +++ b/src/main/lib/viewWorkspaceGrants.test.ts @@ -71,14 +71,14 @@ function signInAt(workspaceId: string | null): void { function grantSession( getGrantAccessToken: () => Promise, - getAccessToken: () => Promise = getGrantAccessToken + heldWorkspaceToken: (workspaceId: string) => string | null = () => null ): ConstructorParameters[0] { return { currentWorkspaceId: () => current, currentSubject: () => (current ? user : null), currentAuthGeneration: () => generation, getGrantAccessToken, - getAccessToken, + heldWorkspaceToken, isWorkspaceMintAllowed: async () => true, endGrantFamily: () => {} } @@ -323,7 +323,7 @@ describe('ViewWorkspaceGrants', () => { grants = new ViewWorkspaceGrants( grantSession( async () => accessToken('ws-2', 'comfy-cloud:user:read'), - async () => held + () => held ), mint ) @@ -336,7 +336,7 @@ describe('ViewWorkspaceGrants', () => { grants = new ViewWorkspaceGrants( grantSession( async () => accessToken('ws-2', 'comfy-cloud:user:read'), - async () => accessToken('ws-1') + () => accessToken('ws-1') ), mint ) diff --git a/src/main/lib/viewWorkspaceGrants.ts b/src/main/lib/viewWorkspaceGrants.ts index c603f9fa2..39585842b 100644 --- a/src/main/lib/viewWorkspaceGrants.ts +++ b/src/main/lib/viewWorkspaceGrants.ts @@ -27,7 +27,7 @@ export interface GrantSession { currentSubject(): string | null currentAuthGeneration(): number getGrantAccessToken(): Promise - getAccessToken(): Promise + heldWorkspaceToken(workspaceId: string): string | null isWorkspaceMintAllowed(workspaceId: string): Promise endGrantFamily(accessToken: string): void } @@ -122,13 +122,10 @@ export class ViewWorkspaceGrants { ) } - private async unmintable( - workspaceId: string, - subject: string, - fence: MintFence - ): Promise { - const token = await this.session.getAccessToken() - if (!this.isCurrent(fence) || !token || canMintWorkspaceTokens(token)) return null + private unmintable(grant: string, workspaceId: string, subject: string): HeldToken | null { + const token = + workspaceIdOf(grant) === workspaceId ? grant : this.session.heldWorkspaceToken(workspaceId) + if (!token || canMintWorkspaceTokens(token)) return null if (workspaceIdOf(token) !== workspaceId || subjectOf(token) !== subject) return null return { token, subject } } @@ -138,7 +135,8 @@ export class ViewWorkspaceGrants { if (!this.isCurrent(fence) || !accessToken) return null const subject = subjectOf(accessToken) if (!subject) return null - if (!canMintWorkspaceTokens(accessToken)) return this.unmintable(workspaceId, subject, fence) + if (!canMintWorkspaceTokens(accessToken)) + return this.unmintable(accessToken, workspaceId, subject) const key = mintKey(subject, workspaceId) const cached = this.minted.get(key) if (cached && cached.expiresAt - MINT_REFRESH_SKEW_MS > Date.now()) From 1006a9e37078896a9ed057e38bd834db04fc6e26 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 10 Nov 2026 13:37:38 -0500 Subject: [PATCH 61/75] fix(auth): never hand a view a minted token that can mint A minted workspace token is checked for workspace and subject before a view gets it. It is now also refused when it carries the mint scope, so the guarantee that no mint-capable token reaches a renderer no longer rests on Cloud's response alone. --- src/main/lib/embeddedSession.test.ts | 2 +- src/main/lib/viewWorkspaceGrants.test.ts | 1 + src/main/lib/viewWorkspaceGrants.ts | 6 +++++- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/main/lib/embeddedSession.test.ts b/src/main/lib/embeddedSession.test.ts index 871f46626..569d226d9 100644 --- a/src/main/lib/embeddedSession.test.ts +++ b/src/main/lib/embeddedSession.test.ts @@ -57,7 +57,7 @@ function jwt(claims: Record): string { const ACCESS = jwt({ sub: 'user-1', email: 'a@example.com', workspace_id: 'ws-1' }) function mintedFor(workspaceId: string): string { - return jwt({ sub: 'user-1', workspace_id: workspaceId, auth_method: 'cloud' }) + return jwt({ sub: 'user-1', workspace_id: workspaceId, auth_method: 'cloud', scope: undefined }) } const MINTED = mintedFor('ws-1') diff --git a/src/main/lib/viewWorkspaceGrants.test.ts b/src/main/lib/viewWorkspaceGrants.test.ts index 84edd8233..ae816d1ac 100644 --- a/src/main/lib/viewWorkspaceGrants.test.ts +++ b/src/main/lib/viewWorkspaceGrants.test.ts @@ -135,6 +135,7 @@ describe('ViewWorkspaceGrants', () => { it.each<[string, () => string]>([ ['another workspace', () => jwt({ sub: user, workspace_id: 'ws-9' })], ['another account', () => jwt({ sub: 'user-9', workspace_id: 'ws-1' })], + ['a token that can mint', () => accessToken('ws-1')], ['a token with no claims', () => 'opaque-token'] ])('refuses and does not cache a minted token for %s', async (_name, token) => { mint.mockResolvedValueOnce({ kind: 'minted', token: token(), expiresAt: Date.now() + 900_000 }) diff --git a/src/main/lib/viewWorkspaceGrants.ts b/src/main/lib/viewWorkspaceGrants.ts index 39585842b..c13998263 100644 --- a/src/main/lib/viewWorkspaceGrants.ts +++ b/src/main/lib/viewWorkspaceGrants.ts @@ -147,7 +147,11 @@ export class ViewWorkspaceGrants { const result = await this.mintOnce(accessToken, key, workspaceId, fence) if (!this.isCurrent(fence) || this.session.currentSubject() !== subject) return null if (result.kind !== 'minted') return null - if (workspaceIdOf(result.token) !== workspaceId || subjectOf(result.token) !== subject) + if ( + workspaceIdOf(result.token) !== workspaceId || + subjectOf(result.token) !== subject || + canMintWorkspaceTokens(result.token) + ) return null this.minted.set(key, { token: result.token, expiresAt: result.expiresAt }) return { token: result.token, subject } From 79ba148ad14cb5c67d34986778de383cd068defd Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 10 Nov 2026 13:54:15 -0500 Subject: [PATCH 62/75] docs(auth): describe when a view's switchWorkspace opens consent --- src/types/comfyDesktopBridge.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/types/comfyDesktopBridge.ts b/src/types/comfyDesktopBridge.ts index ff0f5724e..9c11358c3 100644 --- a/src/types/comfyDesktopBridge.ts +++ b/src/types/comfyDesktopBridge.ts @@ -134,8 +134,9 @@ export interface ComfyDesktop2AuthBridge { /** Signs Desktop out of its account (every view follows) and resolves with * the resulting state; Desktop may keep the session if an install needs it. */ signOut(): Promise - /** Re-scopes Desktop's session to `workspaceId` (no browser unless the server - * requires a new sign-in) and resolves with the resulting state; every view follows. */ + /** Re-scopes Desktop's session to `workspaceId` and resolves with the resulting + * state; every view follows. No browser for the grant's own workspace or one + * Desktop already holds; any other workspace opens browser consent. */ switchWorkspace(workspaceId: string): Promise /** Fires when Desktop signs in, signs out or switches workspace. */ onChanged(callback: (state: ComfyDesktop2AuthState) => void): () => void From 4daa5bccf63a7334c03668a223155121698d7c5e Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 10 Nov 2026 13:57:51 -0500 Subject: [PATCH 63/75] fix(auth): drop an unreadable revocation file once its token has expired A queue file that cannot be decrypted or parsed kept the queue incomplete, so the retry timer ran for as long as the app was open and again on every launch. A recent one is still kept, since a locked keychain looks the same, but one older than the 30 day refresh token lifetime is deleted: its token is dead on Cloud. --- src/main/cloud/config.ts | 2 ++ src/main/cloud/revocation.ts | 3 +-- src/main/cloud/tokenStore.test.ts | 20 ++++++++++++++++++++ src/main/cloud/tokenStore.ts | 27 +++++++++++++++++++-------- 4 files changed, 42 insertions(+), 10 deletions(-) diff --git a/src/main/cloud/config.ts b/src/main/cloud/config.ts index f6d5b8774..9a587a1a0 100644 --- a/src/main/cloud/config.ts +++ b/src/main/cloud/config.ts @@ -1,6 +1,8 @@ const DEFAULT_ISSUER = 'https://cloud.comfy.org' const DEFAULT_CLIENT_ID = 'comfy-desktop' +export const CLOUD_REFRESH_TOKEN_LIFETIME_MS = 720 * 60 * 60_000 + export const WORKSPACE_MINT_SCOPE = 'comfy-cloud:workspace-token:mint' export const CLOUD_ISSUER = process.env.COMFY_CLOUD_ISSUER || DEFAULT_ISSUER diff --git a/src/main/cloud/revocation.ts b/src/main/cloud/revocation.ts index c6f1a04da..f2539e8b8 100644 --- a/src/main/cloud/revocation.ts +++ b/src/main/cloud/revocation.ts @@ -1,11 +1,10 @@ -import { revokeUrlOf } from './config' +import { CLOUD_REFRESH_TOKEN_LIFETIME_MS, revokeUrlOf } from './config' import { revoke } from './oauth' import { addPendingRevocation, loadPendingRevocations, removePendingRevocation } from './tokenStore' import type { PendingRevocation } from './tokenStore' const FIRST_RETRY_MS = 5_000 const MAX_RETRY_MS = 15 * 60_000 -const CLOUD_REFRESH_TOKEN_LIFETIME_MS = 720 * 60 * 60_000 export class Revocations { private draining: Promise | null = null diff --git a/src/main/cloud/tokenStore.test.ts b/src/main/cloud/tokenStore.test.ts index 5f46c0a63..8d05ead58 100644 --- a/src/main/cloud/tokenStore.test.ts +++ b/src/main/cloud/tokenStore.test.ts @@ -361,6 +361,26 @@ describe('grant vault', () => { } }) + it('drops an unreadable queue file once it has outlived the refresh token, and only then', () => { + const revocation = { + issuer: 'https://cloud.test', + clientId: 'cid', + refreshToken: 'refresh-1', + queuedAt: 1 + } + addPendingRevocation(revocation) + const dir = path.join(electronState.userData, 'comfy-cloud-revocations') + const unreadable = path.join(dir, 'unreadable.bin') + fs.writeFileSync(unreadable, 'garbage') + expect(loadPendingRevocations()).toEqual({ pending: [revocation], complete: false }) + + const monthAgo = new Date(Date.now() - 31 * 24 * 3_600_000) + fs.utimesSync(unreadable, monthAgo, monthAgo) + + expect(loadPendingRevocations()).toEqual({ pending: [revocation], complete: true }) + expect(fs.existsSync(unreadable)).toBe(false) + }) + it('never loses a queued revocation to an unreadable sibling entry', () => { const first = { issuer: 'https://cloud.test', diff --git a/src/main/cloud/tokenStore.ts b/src/main/cloud/tokenStore.ts index cc9af7c37..fbb221f32 100644 --- a/src/main/cloud/tokenStore.ts +++ b/src/main/cloud/tokenStore.ts @@ -4,7 +4,7 @@ import * as fs from 'fs' import * as path from 'path' import { statusFromAccessToken, subjectOf, workspaceIdOf } from './claims' -import { CLOUD_CONFIG } from './config' +import { CLOUD_CONFIG, CLOUD_REFRESH_TOKEN_LIFETIME_MS } from './config' import type { AuthStatus, AuthTokens, Workspace } from './types' const AUTH_FILENAME = 'comfy-cloud-auth.bin' @@ -340,6 +340,16 @@ export interface PendingRevocations { complete: boolean } +function dropIfOutlived(file: string): boolean { + try { + if (fs.statSync(file).mtimeMs + CLOUD_REFRESH_TOKEN_LIFETIME_MS > Date.now()) return false + fs.rmSync(file, { force: true }) + return true + } catch { + return false + } +} + function readSavedRevocations(): PendingRevocations { let names: string[] try { @@ -348,17 +358,18 @@ function readSavedRevocations(): PendingRevocations { return { pending: [], complete: (error as NodeJS.ErrnoException).code === 'ENOENT' } } if (names.length > 0 && !encryptionAvailable()) return { pending: [], complete: false } + let unreadable = 0 const pending = names.flatMap((name) => { + const file = path.join(revocationsDir(), name) try { - const file = path.join(revocationsDir(), name) const parsed: unknown = JSON.parse(safeStorage.decryptString(fs.readFileSync(file))) - if (!isSavedRevocation(parsed)) return [] - return [{ ...parsed, queuedAt: parsed.queuedAt ?? fs.statSync(file).mtimeMs }] - } catch { - return [] - } + if (isSavedRevocation(parsed)) + return [{ ...parsed, queuedAt: parsed.queuedAt ?? fs.statSync(file).mtimeMs }] + } catch {} + if (!dropIfOutlived(file)) unreadable += 1 + return [] }) - return { pending, complete: pending.length === names.length } + return { pending, complete: unreadable === 0 } } export function loadPendingRevocations(): PendingRevocations { From dc2501065e9a43fcc6808dcc98f74291886602d0 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 10 Nov 2026 14:01:02 -0500 Subject: [PATCH 64/75] chore(types): regenerate bridge declarations --- .../comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts b/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts index d53a6c7f0..b3c4e4485 100644 --- a/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts +++ b/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts @@ -135,8 +135,9 @@ export interface ComfyDesktop2AuthBridge { /** Signs Desktop out of its account (every view follows) and resolves with * the resulting state; Desktop may keep the session if an install needs it. */ signOut(): Promise - /** Re-scopes Desktop's session to `workspaceId` (no browser unless the server - * requires a new sign-in) and resolves with the resulting state; every view follows. */ + /** Re-scopes Desktop's session to `workspaceId` and resolves with the resulting + * state; every view follows. No browser for the grant's own workspace or one + * Desktop already holds; any other workspace opens browser consent. */ switchWorkspace(workspaceId: string): Promise /** Fires when Desktop signs in, signs out or switches workspace. */ onChanged(callback: (state: ComfyDesktop2AuthState) => void): () => void From 320e160799b3b1297ce0b6bff1e71f7fc7f1cc80 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 10 Nov 2026 14:07:11 -0500 Subject: [PATCH 65/75] fix(auth): a partner-node mint told the grant ended also stops its refresh The base ends the grant's refresh family when a view's workspace token mint answers 401 oauth_grant_ended, so Desktop stops refreshing a grant Cloud already ended. A partner-node mint goes to the same route with the same grant and can get the same answer, and left the family refreshable. The mint that starts a session and the one that replaces a refused session now end the family the same way. A partner-node 401 does not go to the unauthorized path: that path signs Desktop out, and this read only ever returns null to the view. --- .../lib/viewWorkspaceGrants.session.test.ts | 13 +++++++++++ src/main/lib/viewWorkspaceGrants.ts | 23 +++++++++++++++---- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/src/main/lib/viewWorkspaceGrants.session.test.ts b/src/main/lib/viewWorkspaceGrants.session.test.ts index a7910ab0f..80c6fd862 100644 --- a/src/main/lib/viewWorkspaceGrants.session.test.ts +++ b/src/main/lib/viewWorkspaceGrants.session.test.ts @@ -226,6 +226,19 @@ describe('view token path through a real session', () => { expect(openAuthorizePage).not.toHaveBeenCalled() }) + it('a partner-node mint told the grant ended never lets the grant be refreshed', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + mintReply = () => new Response(JSON.stringify({ code: 'oauth_grant_ended' }), { status: 401 }) + + await expect(grants.partnerNodeTokenFor(view, 'w1')).resolves.toBeNull() + vi.setSystemTime(GRANT.expiresAt + 1) + await expect(grants.partnerNodeTokenFor(view, 'w1')).resolves.toBeNull() + + expect(refresh).not.toHaveBeenCalled() + expect(signIn).not.toHaveBeenCalled() + expect(openAuthorizePage).not.toHaveBeenCalled() + }) + it('a server kill refuses a view mint with no browser', async () => { await activeOnW2() mintReply = () => diff --git a/src/main/lib/viewWorkspaceGrants.ts b/src/main/lib/viewWorkspaceGrants.ts index 161d70d3a..ef0f1097e 100644 --- a/src/main/lib/viewWorkspaceGrants.ts +++ b/src/main/lib/viewWorkspaceGrants.ts @@ -219,9 +219,7 @@ export class ViewWorkspaceGrants { const result = await this.once(['workspace', key], fence, () => this.mint(accessToken, workspaceId).then((minted) => { reportMint(minted) - const outcome = classifyMint(minted) - if (outcome.kind === 'reauthorize' && outcome.reason === 'grant_ended') - this.session.endGrantFamily(accessToken) + this.endAnEndedGrant(accessToken, minted) if (minted.kind === 'failed' && minted.status === 401) this.onUnauthorized(accessToken) return minted }) @@ -255,7 +253,7 @@ export class ViewWorkspaceGrants { const result = await this.once(['partner-node', key], fence, () => cached ? this.renewOrMint(key, cached.token, accessToken, workspaceId, fence) - : this.partnerNode.mint(accessToken, workspaceId) + : this.mintPartnerNode(accessToken, workspaceId) ) const usable = result.kind === 'minted' && @@ -300,7 +298,22 @@ export class ViewWorkspaceGrants { if (renewed.kind === 'failed' && !isRetryableFailure(renewed)) this.forgetPartnerNodeToken(key, partnerNodeToken) if (isRetryableFailure(renewed) || !this.isCurrent(fence)) return renewed - return this.partnerNode.mint(accessToken, workspaceId) + return this.mintPartnerNode(accessToken, workspaceId) + } + + private async mintPartnerNode( + accessToken: string, + workspaceId: string + ): Promise { + const minted = await this.partnerNode.mint(accessToken, workspaceId) + this.endAnEndedGrant(accessToken, minted) + return minted + } + + private endAnEndedGrant(accessToken: string, result: WorkspaceTokenMint): void { + const outcome = classifyMint(result) + if (outcome.kind === 'reauthorize' && outcome.reason === 'grant_ended') + this.session.endGrantFamily(accessToken) } private forgetPartnerNodeToken(key: string, token: string): void { From 7ea45ce800c6ffb387d72f368c39846710bd90ff Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 10 Nov 2026 14:08:56 -0500 Subject: [PATCH 66/75] fix(auth): ask Cloud for a partner-node token instead of checking jobs:write locally Desktop refused to mint for a grant without comfy-cloud:jobs:write before asking Cloud. Cloud is the one that decides: with the scope exemption for comfy-desktop (Comfy-Org/cloud#18763) it mints for a grant that holds only comfy-cloud:user:read, or user:read plus the workspace mint scope, and Desktop's own check turned those into null. The view then queued its 15-minute workspace token. Desktop now asks for every signed-in grant. A refusal still hands the view null and waits before asking again, as any other refused mint does. Run against the real ingest handlers with the exemption on: a prompt queued with a grant that has the mint scope and no jobs:write carried a derived workspace token before this change and was rejected as expired 17 minutes later. After it the prompt carries a partner-node token that core v0.45.0 renews. --- src/main/cloud/claims.test.ts | 18 +----------------- src/main/cloud/claims.ts | 12 ++---------- src/main/lib/viewWorkspaceGrants.test.ts | 12 +++++++----- src/main/lib/viewWorkspaceGrants.ts | 11 ++--------- 4 files changed, 12 insertions(+), 41 deletions(-) diff --git a/src/main/cloud/claims.test.ts b/src/main/cloud/claims.test.ts index b1145a89f..bbc405b3d 100644 --- a/src/main/cloud/claims.test.ts +++ b/src/main/cloud/claims.test.ts @@ -1,12 +1,5 @@ import { describe, expect, it } from 'vitest' -import { - canMintPartnerNodeTokens, - identityOf, - statusFromAccessToken, - subjectOf, - workspaceIdOf -} from './claims' -import { CLOUD_CONFIG, WORKSPACE_MINT_SCOPE } from './config' +import { identityOf, statusFromAccessToken, subjectOf, workspaceIdOf } from './claims' function jwt(payload: Record): string { const b64 = (o: unknown): string => Buffer.from(JSON.stringify(o)).toString('base64url') @@ -57,13 +50,4 @@ describe('claims', () => { expect(identityOf(jwt({ email: 'a@b.co' }))).toBeNull() expect(identityOf('not-a-jwt')).toBeNull() }) - - it.each([ - ['a grant from a sign-in Desktop requests today', CLOUD_CONFIG.scope, true], - ['a grant from before jobs:write', `comfy-cloud:user:read ${WORKSPACE_MINT_SCOPE}`, false], - ['a grant without the mint scope', 'comfy-cloud:user:read comfy-cloud:jobs:write', false], - ['a token with no scope', undefined, false] - ])('canMintPartnerNodeTokens for %s', (_name, scope, expected) => { - expect(canMintPartnerNodeTokens(jwt({ sub: 'u', ...(scope ? { scope } : {}) }))).toBe(expected) - }) }) diff --git a/src/main/cloud/claims.ts b/src/main/cloud/claims.ts index 2a9ed6314..933bb0838 100644 --- a/src/main/cloud/claims.ts +++ b/src/main/cloud/claims.ts @@ -1,6 +1,6 @@ import { Buffer } from 'node:buffer' -import { PARTNER_NODE_MINT_SCOPE, WORKSPACE_MINT_SCOPE } from './config' +import { WORKSPACE_MINT_SCOPE } from './config' import type { AuthStatus } from './types' interface AccessTokenClaims { @@ -43,16 +43,8 @@ export function workspaceIdOf(accessToken: string): string | null { } export function canMintWorkspaceTokens(accessToken: string): boolean { - return hasScope(accessToken, WORKSPACE_MINT_SCOPE) -} - -export function canMintPartnerNodeTokens(accessToken: string): boolean { - return canMintWorkspaceTokens(accessToken) && hasScope(accessToken, PARTNER_NODE_MINT_SCOPE) -} - -function hasScope(accessToken: string, wanted: string): boolean { const scope = decodeJwtPayload(accessToken)?.scope - return typeof scope === 'string' && scope.split(' ').includes(wanted) + return typeof scope === 'string' && scope.split(' ').includes(WORKSPACE_MINT_SCOPE) } export function lifetimeSecondsOf(accessToken: string): number | null { diff --git a/src/main/lib/viewWorkspaceGrants.test.ts b/src/main/lib/viewWorkspaceGrants.test.ts index 57033d9ce..093ade5be 100644 --- a/src/main/lib/viewWorkspaceGrants.test.ts +++ b/src/main/lib/viewWorkspaceGrants.test.ts @@ -591,12 +591,14 @@ describe('ViewWorkspaceGrants partner-node tokens', () => { } ) - it('hands out nothing, and does not ask Cloud, for a grant from before jobs:write', async () => { - grants = build(`comfy-cloud:user:read ${WORKSPACE_MINT_SCOPE}`) + it.each([ + ['from before jobs:write', `comfy-cloud:user:read ${WORKSPACE_MINT_SCOPE}`], + ['from before the mint scope', 'comfy-cloud:user:read'] + ])('asks Cloud with a grant %s and hands out the token it mints', async (_name, scope) => { + grants = build(scope) - await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() - await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe(mintedToken('ws-1')) - expect(partnerMint).not.toHaveBeenCalled() + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe(partnerToken('ws-1')) + expect(partnerMint).toHaveBeenCalledExactlyOnceWith(accessToken('ws-1', scope), 'ws-1') }) it('hands out nothing for another workspace while the mint switch is off', async () => { diff --git a/src/main/lib/viewWorkspaceGrants.ts b/src/main/lib/viewWorkspaceGrants.ts index ef0f1097e..3ce983f10 100644 --- a/src/main/lib/viewWorkspaceGrants.ts +++ b/src/main/lib/viewWorkspaceGrants.ts @@ -1,12 +1,6 @@ import type { WebContents } from 'electron' -import { - canMintPartnerNodeTokens, - canMintWorkspaceTokens, - grantFamilyOf, - subjectOf, - workspaceIdOf -} from '../cloud/claims' +import { canMintWorkspaceTokens, grantFamilyOf, subjectOf, workspaceIdOf } from '../cloud/claims' import { classifyMint, mintPartnerNodeToken, @@ -238,8 +232,7 @@ export class ViewWorkspaceGrants { private async partnerNodeToken(workspaceId: string, fence: MintFence): Promise { const accessToken = await this.session.getGrantAccessToken() - if (!this.isCurrent(fence) || !accessToken || !canMintPartnerNodeTokens(accessToken)) - return null + if (!this.isCurrent(fence) || !accessToken) return null const subject = subjectOf(accessToken) if (!subject) return null const key = JSON.stringify([subject, grantFamilyOf(accessToken), workspaceId]) From ab4c97e0698518af156f7c5e5ee329f81e5a7fa6 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 10 Nov 2026 20:44:11 -0500 Subject: [PATCH 67/75] fix(auth): a 401 for an expired grant token no longer signs out on its 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. --- src/main/cloud/session.test.ts | 76 +++++++++++++++++++ src/main/cloud/session.ts | 16 +++- .../lib/viewWorkspaceGrants.session.test.ts | 21 +++++ 3 files changed, 112 insertions(+), 1 deletion(-) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index 16db7c393..2bbb145ce 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -2107,6 +2107,82 @@ describe('CloudSession token provider', () => { expect(onSignedOut).toHaveBeenCalledOnce() }) + it.each([ + ['a network error', () => refreshFailure('network')], + ['a 503', () => refreshFailure('http', 503)] + ])( + 'stays signed in when a rejected grant token had expired and the refresh fails with %s', + async (_name, failure) => { + const grant = grantOn('w1', { expiresAt: PAST }) + saveGrant(grant) + mocked(refresh).mockRejectedValue(failure()) + const session = new CloudSession() + const onSignedOut = vi.fn() + + session.asTokenProvider(onSignedOut).onUnauthorized?.(grant.accessToken) + await vi.waitFor(() => expect(refresh).toHaveBeenCalledOnce()) + await new Promise((resolve) => setImmediate(resolve)) + + expect(session.isSignedIn()).toBe(true) + expect(onSignedOut).not.toHaveBeenCalled() + } + ) + + it('signs out once Cloud refuses to refresh a rejected grant token that had expired', async () => { + const grant = grantOn('w1', { expiresAt: PAST }) + saveGrant(grant) + mocked(refresh).mockRejectedValue(refreshRefused()) + const session = new CloudSession() + const onSignedOut = vi.fn() + + session.asTokenProvider(onSignedOut).onUnauthorized?.(grant.accessToken) + + await vi.waitFor(() => expect(onSignedOut).toHaveBeenCalledOnce()) + expect(refresh).toHaveBeenCalledOnce() + expect(session.isSignedIn()).toBe(false) + }) + + it('leaves a newer sign-in alone when the refusal for a rejected expired grant lands late', async () => { + const grant = grantOn('w1', { expiresAt: PAST }) + saveGrant(grant) + let refuse: (reason: unknown) => void = () => {} + mocked(refresh).mockReturnValue( + new Promise((_resolve, reject) => { + refuse = reject + }) + ) + const signingIn = deferred>>() + mocked(signIn).mockReturnValue(signingIn.promise) + const fresh = grantOn('w1', { revision: '-fresh' }) + const session = new CloudSession() + const onSignedOut = vi.fn() + + session.asTokenProvider(onSignedOut).onUnauthorized?.(grant.accessToken) + const login = session.login() + refuse(refreshRefused()) + await new Promise((resolve) => setImmediate(resolve)) + signingIn.resolve(signedInResult(fresh)) + await login + + expect(onSignedOut).not.toHaveBeenCalled() + expect(vaultOnDisk().grant).toEqual(fresh) + }) + + it('keeps the refreshed grant when a rejected grant token had only expired', async () => { + const grant = grantOn('w1', { expiresAt: PAST }) + const rotated = grantOn('w1', { revision: 'rotated' }) + saveGrant(grant) + mocked(refresh).mockResolvedValue(rotated) + const session = new CloudSession() + const onSignedOut = vi.fn() + + session.asTokenProvider(onSignedOut).onUnauthorized?.(grant.accessToken) + + await vi.waitFor(() => expect(vaultOnDisk().grant).toEqual(rotated)) + expect(session.isSignedIn()).toBe(true) + expect(onSignedOut).not.toHaveBeenCalled() + }) + it('drops only a rejected minted token, stays signed in, and re-mints with no browser', async () => { saveGrant(grantOn('w1')) const session = new CloudSession() diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index 1401ef014..d8bb27e1e 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -508,10 +508,24 @@ export class CloudSession { getAccessToken: () => this.getAccessToken(), onUnauthorized: (rejectedAccessToken) => { if (dropWorkspaceToken(rejectedAccessToken)) return - if (loadGrant()?.accessToken !== rejectedAccessToken) return + const grant = loadGrant() + if (grant?.accessToken !== rejectedAccessToken) return + if (isExpired(grant) && grant.refreshToken) { + void this.signOutIfGrantEnded(grant, onSignedOut) + return + } this.logout() onSignedOut?.() } } } + + private async signOutIfGrantEnded(grant: AuthTokens, onSignedOut?: () => void): Promise { + const generation = this.authGeneration + const refreshed = await this.refreshGrant(grant) + if (refreshed !== 'ended' || generation !== this.authGeneration) return + if (loadGrant()?.accessToken !== grant.accessToken) return + this.logout() + onSignedOut?.() + } } diff --git a/src/main/lib/viewWorkspaceGrants.session.test.ts b/src/main/lib/viewWorkspaceGrants.session.test.ts index 6cc629eba..be4bdba35 100644 --- a/src/main/lib/viewWorkspaceGrants.session.test.ts +++ b/src/main/lib/viewWorkspaceGrants.session.test.ts @@ -134,6 +134,27 @@ describe('view token path through a real session', () => { expect(signIn).not.toHaveBeenCalled() }) + it.each([ + ['a network error', new Error('fetch failed')], + ['a 503', Object.assign(new Error('refresh failed: 503'), { status: 503 })] + ])( + 'stays signed in when the refresh fails with %s and the mint rejects the expired grant', + async (_name, failure) => { + vi.useFakeTimers({ toFake: ['Date'] }) + grants = new ViewWorkspaceGrants(session, undefined, (token) => + session.asTokenProvider().onUnauthorized?.(token) + ) + vi.setSystemTime(GRANT.expiresAt + 1) + vi.mocked(refresh).mockRejectedValue(failure) + mintReply = () => new Response(JSON.stringify({ code: 'UNAUTHORIZED' }), { status: 401 }) + + await expect(grants.tokenFor(view, 'w1')).resolves.toBeNull() + await new Promise((resolve) => setImmediate(resolve)) + + expect(session.status().signedIn).toBe(true) + } + ) + it('refuses to deliver or cache a token that is already expired', async () => { const expired = (workspaceId: string): Response => new Response( From 66a34453409ae9e54fb4b56efa7643b8b072d88e Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 10 Nov 2026 20:56:54 -0500 Subject: [PATCH 68/75] docs(bridge): qualify the no-browser switch for expired tokens and ended grants --- packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts | 3 ++- src/types/comfyDesktopBridge.ts | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts b/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts index b3c4e4485..8ddcb4908 100644 --- a/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts +++ b/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts @@ -137,7 +137,8 @@ export interface ComfyDesktop2AuthBridge { signOut(): Promise /** Re-scopes Desktop's session to `workspaceId` and resolves with the resulting * state; every view follows. No browser for the grant's own workspace or one - * Desktop already holds; any other workspace opens browser consent. */ + * Desktop holds an unexpired token for, unless the grant has ended; any other + * workspace opens browser consent. */ switchWorkspace(workspaceId: string): Promise /** Fires when Desktop signs in, signs out or switches workspace. */ onChanged(callback: (state: ComfyDesktop2AuthState) => void): () => void diff --git a/src/types/comfyDesktopBridge.ts b/src/types/comfyDesktopBridge.ts index 9c11358c3..10aa2dc37 100644 --- a/src/types/comfyDesktopBridge.ts +++ b/src/types/comfyDesktopBridge.ts @@ -136,7 +136,8 @@ export interface ComfyDesktop2AuthBridge { signOut(): Promise /** Re-scopes Desktop's session to `workspaceId` and resolves with the resulting * state; every view follows. No browser for the grant's own workspace or one - * Desktop already holds; any other workspace opens browser consent. */ + * Desktop holds an unexpired token for, unless the grant has ended; any other + * workspace opens browser consent. */ switchWorkspace(workspaceId: string): Promise /** Fires when Desktop signs in, signs out or switches workspace. */ onChanged(callback: (state: ComfyDesktop2AuthState) => void): () => void From 4b4a2312df8556debfd592e4295036065bdb8a35 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 10 Nov 2026 21:11:42 -0500 Subject: [PATCH 69/75] docs(bridge): note that a switch joins one already in flight --- .../comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts | 6 +++--- src/types/comfyDesktopBridge.ts | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts b/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts index 8ddcb4908..382631c85 100644 --- a/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts +++ b/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts @@ -136,9 +136,9 @@ export interface ComfyDesktop2AuthBridge { * the resulting state; Desktop may keep the session if an install needs it. */ signOut(): Promise /** Re-scopes Desktop's session to `workspaceId` and resolves with the resulting - * state; every view follows. No browser for the grant's own workspace or one - * Desktop holds an unexpired token for, unless the grant has ended; any other - * workspace opens browser consent. */ + * state; every view follows. No browser for the grant's own workspace, one + * Desktop holds an unexpired token for, or one Desktop is already switching + * to, unless the grant has ended; any other workspace opens browser consent. */ switchWorkspace(workspaceId: string): Promise /** Fires when Desktop signs in, signs out or switches workspace. */ onChanged(callback: (state: ComfyDesktop2AuthState) => void): () => void diff --git a/src/types/comfyDesktopBridge.ts b/src/types/comfyDesktopBridge.ts index 10aa2dc37..a7031682f 100644 --- a/src/types/comfyDesktopBridge.ts +++ b/src/types/comfyDesktopBridge.ts @@ -135,9 +135,9 @@ export interface ComfyDesktop2AuthBridge { * the resulting state; Desktop may keep the session if an install needs it. */ signOut(): Promise /** Re-scopes Desktop's session to `workspaceId` and resolves with the resulting - * state; every view follows. No browser for the grant's own workspace or one - * Desktop holds an unexpired token for, unless the grant has ended; any other - * workspace opens browser consent. */ + * state; every view follows. No browser for the grant's own workspace, one + * Desktop holds an unexpired token for, or one Desktop is already switching + * to, unless the grant has ended; any other workspace opens browser consent. */ switchWorkspace(workspaceId: string): Promise /** Fires when Desktop signs in, signs out or switches workspace. */ onChanged(callback: (state: ComfyDesktop2AuthState) => void): () => void From 2d05a983113c27b0c32e0812eedfc5c9d5e4b9e1 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 10 Nov 2026 21:21:43 -0500 Subject: [PATCH 70/75] docs(bridge): state when a view switch can open the browser --- .../comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts | 8 +++++--- src/types/comfyDesktopBridge.ts | 8 +++++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts b/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts index 382631c85..b853e6dd4 100644 --- a/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts +++ b/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts @@ -136,9 +136,11 @@ export interface ComfyDesktop2AuthBridge { * the resulting state; Desktop may keep the session if an install needs it. */ signOut(): Promise /** Re-scopes Desktop's session to `workspaceId` and resolves with the resulting - * state; every view follows. No browser for the grant's own workspace, one - * Desktop holds an unexpired token for, or one Desktop is already switching - * to, unless the grant has ended; any other workspace opens browser consent. */ + * state; every view follows. A view that is not signed in gets its current + * state back. Otherwise the switch may open browser consent: it does not for + * the grant's own workspace or one Desktop holds an unexpired token for, + * unless the grant has ended, and a request for a workspace Desktop is already + * switching to shares that switch's result. */ switchWorkspace(workspaceId: string): Promise /** Fires when Desktop signs in, signs out or switches workspace. */ onChanged(callback: (state: ComfyDesktop2AuthState) => void): () => void diff --git a/src/types/comfyDesktopBridge.ts b/src/types/comfyDesktopBridge.ts index a7031682f..e33e162b4 100644 --- a/src/types/comfyDesktopBridge.ts +++ b/src/types/comfyDesktopBridge.ts @@ -135,9 +135,11 @@ export interface ComfyDesktop2AuthBridge { * the resulting state; Desktop may keep the session if an install needs it. */ signOut(): Promise /** Re-scopes Desktop's session to `workspaceId` and resolves with the resulting - * state; every view follows. No browser for the grant's own workspace, one - * Desktop holds an unexpired token for, or one Desktop is already switching - * to, unless the grant has ended; any other workspace opens browser consent. */ + * state; every view follows. A view that is not signed in gets its current + * state back. Otherwise the switch may open browser consent: it does not for + * the grant's own workspace or one Desktop holds an unexpired token for, + * unless the grant has ended, and a request for a workspace Desktop is already + * switching to shares that switch's result. */ switchWorkspace(workspaceId: string): Promise /** Fires when Desktop signs in, signs out or switches workspace. */ onChanged(callback: (state: ComfyDesktop2AuthState) => void): () => void From 638a4fd55e803dd9e92b273ec3e1aa7c56980a28 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 10 Nov 2026 23:54:09 -0500 Subject: [PATCH 71/75] fix(auth): cap the partner-node retry wait at five minutes --- src/main/lib/viewWorkspaceGrants.test.ts | 14 ++++++++++++++ src/main/lib/viewWorkspaceGrants.ts | 5 ++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/main/lib/viewWorkspaceGrants.test.ts b/src/main/lib/viewWorkspaceGrants.test.ts index 093ade5be..860b06861 100644 --- a/src/main/lib/viewWorkspaceGrants.test.ts +++ b/src/main/lib/viewWorkspaceGrants.test.ts @@ -682,6 +682,20 @@ describe('ViewWorkspaceGrants partner-node tokens', () => { expect(partnerRenew).toHaveBeenCalledTimes(2) }) + it('asks Cloud again after five minutes however long Retry-After is', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + partnerRenew.mockResolvedValueOnce({ kind: 'failed', status: 429, retryAfterSeconds: 4 * 3600 }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 5 * 60_000 + 1_000) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe( + partnerToken('ws-1', 'sid-1', 1) + ) + expect(partnerRenew).toHaveBeenCalledTimes(2) + }) + it('does not ask Cloud again for a minute after a refused mint', async () => { vi.useFakeTimers({ toFake: ['Date'] }) partnerMint.mockResolvedValueOnce({ diff --git a/src/main/lib/viewWorkspaceGrants.ts b/src/main/lib/viewWorkspaceGrants.ts index 3ce983f10..05f859ac4 100644 --- a/src/main/lib/viewWorkspaceGrants.ts +++ b/src/main/lib/viewWorkspaceGrants.ts @@ -14,6 +14,7 @@ import * as mainTelemetry from './telemetry' const MINT_REFRESH_SKEW_MS = 60_000 const PARTNER_NODE_RENEW_BEFORE_MS = 60 * 60_000 const PARTNER_NODE_RETRY_MS = 60_000 +const PARTNER_NODE_MAX_RETRY_MS = 5 * 60_000 export const VIEW_TOKEN_MINTED_EVENT = 'comfy.desktop.auth.view_token_minted' export const VIEW_TOKEN_MINT_FAILED_EVENT = 'comfy.desktop.auth.view_token_mint_failed' @@ -258,7 +259,9 @@ export class ViewWorkspaceGrants { result.kind === 'failed' && result.retryAfterSeconds !== undefined ? result.retryAfterSeconds * 1000 : 0 - const retryAt = Date.now() + Math.max(PARTNER_NODE_RETRY_MS, retryAfterMs) + const retryAt = + Date.now() + + Math.min(Math.max(PARTNER_NODE_RETRY_MS, retryAfterMs), PARTNER_NODE_MAX_RETRY_MS) this.partnerNodeRetryAt.set(key, Math.max(retryAt, this.partnerNodeRetryAt.get(key) ?? 0)) if (cached && !isRetryableFailure(result)) this.forgetPartnerNodeToken(key, cached.token) } From 3b3a3e2b19001232278e5748607ce81772903346 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 11 Nov 2026 13:33:44 -0500 Subject: [PATCH 72/75] fix(auth): date a queued revocation no later than its file --- src/main/cloud/tokenStore.test.ts | 14 ++++++++++++++ src/main/cloud/tokenStore.ts | 6 ++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/main/cloud/tokenStore.test.ts b/src/main/cloud/tokenStore.test.ts index 8d05ead58..07ad35635 100644 --- a/src/main/cloud/tokenStore.test.ts +++ b/src/main/cloud/tokenStore.test.ts @@ -361,6 +361,20 @@ describe('grant vault', () => { } }) + it('dates a revocation queued with a clock running ahead no later than its file', () => { + const revocation = { + issuer: 'https://cloud.test', + clientId: 'cid', + refreshToken: 'refresh-1', + queuedAt: Date.now() + 365 * 24 * 3_600_000 + } + addPendingRevocation(revocation) + + expect(loadPendingRevocations().pending).toEqual([ + { ...revocation, queuedAt: expect.toSatisfy((at: number) => at < Date.now() + 1_000) } + ]) + }) + it('drops an unreadable queue file once it has outlived the refresh token, and only then', () => { const revocation = { issuer: 'https://cloud.test', diff --git a/src/main/cloud/tokenStore.ts b/src/main/cloud/tokenStore.ts index fbb221f32..bedcf5a4b 100644 --- a/src/main/cloud/tokenStore.ts +++ b/src/main/cloud/tokenStore.ts @@ -363,8 +363,10 @@ function readSavedRevocations(): PendingRevocations { const file = path.join(revocationsDir(), name) try { const parsed: unknown = JSON.parse(safeStorage.decryptString(fs.readFileSync(file))) - if (isSavedRevocation(parsed)) - return [{ ...parsed, queuedAt: parsed.queuedAt ?? fs.statSync(file).mtimeMs }] + if (isSavedRevocation(parsed)) { + const writtenAt = fs.statSync(file).mtimeMs + return [{ ...parsed, queuedAt: Math.min(parsed.queuedAt ?? writtenAt, writtenAt) }] + } } catch {} if (!dropIfOutlived(file)) unreadable += 1 return [] From 296ab547b1690bf4b088dc4a4a7ca409750ccdeb Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 11 Nov 2026 13:35:03 -0500 Subject: [PATCH 73/75] fix(auth): a view cannot open repeated consent tabs or cancel a switch in flight --- src/main/cloud/session.test.ts | 51 ++++++++++++++++++++++++++++++++++ src/main/cloud/session.ts | 13 +++++++++ 2 files changed, 64 insertions(+) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index 2bbb145ce..f58c26a98 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -1660,8 +1660,11 @@ describe('CloudSession.heldWorkspaceToken', () => { }) describe('CloudSession switches a local ComfyUI view requests', () => { + const member = (id: string) => ({ id, name: id, type: 'team', role: 'member' }) + it('asks the browser for a new workspace instead of minting silently', async () => { saveGrant(grantOn('w1')) + mocked(listWorkspaces).mockResolvedValueOnce([member('w1'), member('w2')]) browserSignInReturns(signedInResult(grantOn('w2'))) await expect(new CloudSession().switchWorkspace('w2', 'requested')).resolves.toMatchObject({ @@ -1673,6 +1676,54 @@ describe('CloudSession switches a local ComfyUI view requests', () => { expect(browserEvents()).toEqual([{ reauthorize_reason: 'view_requested' }]) }) + it('opens no browser for a workspace the user does not belong to', async () => { + saveGrant(grantOn('w1')) + mocked(listWorkspaces).mockResolvedValueOnce([member('w1'), member('w2')]) + + await expect(new CloudSession().switchWorkspace('w9', 'requested')).resolves.toMatchObject({ + workspaceSwitchFailure: 'unavailable', + reached: false + }) + + expect(signIn).not.toHaveBeenCalled() + expect(mintRequests).toEqual([]) + }) + + it('opens one browser at a time for view requests and leaves it pending', async () => { + saveGrant(grantOn('w1')) + mocked(listWorkspaces).mockResolvedValueOnce([member('w1'), member('w2'), member('w3')]) + const consent = deferred>>() + mocked(signIn).mockReturnValue(consent.promise) + const session = new CloudSession() + + const first = session.switchWorkspace('w2', 'requested') + await vi.waitFor(() => expect(signIn).toHaveBeenCalledOnce()) + await expect(session.switchWorkspace('w3', 'requested')).resolves.toMatchObject({ + reached: false + }) + consent.resolve(signedInResult(grantOn('w2'))) + + await expect(first).resolves.toMatchObject({ workspaceId: 'w2', reached: true }) + expect(signIn).toHaveBeenCalledOnce() + }) + + it('does not cancel a switch Desktop has in flight', async () => { + saveGrant(grantOn('w1')) + const slow = deferred() + mintReply = () => slow.promise + const session = new CloudSession() + + const chosen = session.switchWorkspace('w2') + await vi.waitFor(() => expect(mintRequests).toHaveLength(1)) + await expect(session.switchWorkspace('w3', 'requested')).resolves.toMatchObject({ + reached: false + }) + slow.resolve(minted('w2')) + + await expect(chosen).resolves.toMatchObject({ workspaceId: 'w2', reached: true }) + expect(signIn).not.toHaveBeenCalled() + }) + it('lets a view request joining a restored switch still ask the browser', async () => { saveGrant(grantOn('w1')) const slow = deferred() diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index d8bb27e1e..814a7aab4 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -10,6 +10,7 @@ import { dropWorkspaceToken, endGrant, getAuthStatus, + getCachedWorkspaceName, loadActiveWorkspaceId, loadGrant, loadWorkspaceToken, @@ -381,6 +382,9 @@ export class CloudSession { if (intent === 'chosen' || this.switchIntent === 'restored') this.switchIntent = intent return this.switching.result } + if (intent === 'requested' && (this.switching || this.loginInFlight)) { + return Promise.resolve(this.unreached()) + } this.clearPendingLogin() this.switchIntent = intent const generation = ++this.authGeneration @@ -400,6 +404,15 @@ export class CloudSession { const held = loadWorkspaceToken(workspaceId) if (held && held.expiresAt > Date.now()) return this.activated(workspaceId, 'cached') if (this.switchIntent === 'requested') { + if (getCachedWorkspaceName(workspaceId) === null) { + const workspaces = await this.listWorkspaces().catch(() => null) + if (generation !== this.authGeneration) return this.unreached() + if (!workspaces) return this.stayed('retryable') + if (!workspaces.some((workspace) => workspace.id === workspaceId)) { + reportSwitch('unavailable') + return this.stayed('unavailable') + } + } return this.reauthorize(workspaceId, generation, 'view_requested') } From cf3ba73d0fdb39bc5a22cb7e37737592a10dc85e Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 11 Nov 2026 13:38:44 -0500 Subject: [PATCH 74/75] fix(auth): check view-requested workspaces by own key and keep one view consent open --- src/main/cloud/session.test.ts | 63 ++++++++++++++++++++++++++++++++++ src/main/cloud/session.ts | 7 +++- src/main/cloud/tokenStore.ts | 3 +- 3 files changed, 71 insertions(+), 2 deletions(-) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index f58c26a98..a7e95dda0 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -1707,6 +1707,69 @@ describe('CloudSession switches a local ComfyUI view requests', () => { expect(signIn).toHaveBeenCalledOnce() }) + it('checks membership for an id that names an object property', async () => { + saveGrant(grantOn('w1')) + const session = new CloudSession() + mocked(listWorkspaces).mockResolvedValueOnce([member('w1'), member('w2')]) + await session.listWorkspaces() + + await expect(session.switchWorkspace('toString', 'requested')).resolves.toMatchObject({ + workspaceSwitchFailure: 'unavailable' + }) + expect(signIn).not.toHaveBeenCalled() + }) + + it('keeps one view consent open even after Desktop moves meanwhile', async () => { + saveGrant(grantOn('w1')) + mocked(listWorkspaces).mockResolvedValueOnce([member('w1'), member('w2'), member('w3')]) + const consent = deferred>>() + mocked(signIn).mockReturnValue(consent.promise) + const session = new CloudSession() + + void session.switchWorkspace('w2', 'requested') + await vi.waitFor(() => expect(signIn).toHaveBeenCalledOnce()) + await expect(session.switchWorkspace('w1')).resolves.toMatchObject({ reached: true }) + await expect(session.switchWorkspace('w3', 'requested')).resolves.toMatchObject({ + reached: false + }) + + expect(signIn).toHaveBeenCalledOnce() + consent.resolve(signedInResult(grantOn('w2'))) + }) + + it('does not cancel a sign-in Desktop has in flight', async () => { + saveGrant(grantOn('w1')) + const signingIn = deferred>>() + mocked(signIn).mockReturnValue(signingIn.promise) + const session = new CloudSession() + + const login = session.login() + await vi.waitFor(() => expect(signIn).toHaveBeenCalledOnce()) + await expect(session.switchWorkspace('w2', 'requested')).resolves.toMatchObject({ + reached: false + }) + signingIn.resolve(signedInResult(grantOn('w1', { revision: '-fresh' }))) + + await login + expect(vaultOnDisk().grant).toEqual(grantOn('w1', { revision: '-fresh' })) + expect(signIn).toHaveBeenCalledOnce() + }) + + it('opens no browser when the membership check returns after sign-out', async () => { + saveGrant(grantOn('w1')) + const list = deferred>>() + mocked(listWorkspaces).mockReturnValueOnce(list.promise) + const session = new CloudSession() + + const requested = session.switchWorkspace('w2', 'requested') + await vi.waitFor(() => expect(listWorkspaces).toHaveBeenCalledOnce()) + session.logout() + list.resolve([member('w1'), member('w2')]) + + await expect(requested).resolves.toMatchObject({ reached: false }) + expect(signIn).not.toHaveBeenCalled() + }) + it('does not cancel a switch Desktop has in flight', async () => { saveGrant(grantOn('w1')) const slow = deferred() diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index 814a7aab4..2b3e5af6f 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -106,6 +106,7 @@ export class CloudSession { private mintBlockedUntil = 0 private loginInFlight: Promise | null = null private loginAuthorizeUrl: string | null = null + private viewConsentOpen = false private returnedToAnchorHandler: (() => void) | null = null private authGeneration = 0 @@ -382,7 +383,7 @@ export class CloudSession { if (intent === 'chosen' || this.switchIntent === 'restored') this.switchIntent = intent return this.switching.result } - if (intent === 'requested' && (this.switching || this.loginInFlight)) { + if (intent === 'requested' && (this.switching || this.loginInFlight || this.viewConsentOpen)) { return Promise.resolve(this.unreached()) } this.clearPendingLogin() @@ -477,6 +478,8 @@ export class CloudSession { } let browserOpened = false let tokens: AuthTokens + const viewConsent = reason === 'view_requested' + if (viewConsent) this.viewConsentOpen = true try { ;({ tokens } = await signIn({ workspaceId, @@ -488,6 +491,8 @@ export class CloudSession { } catch { if (!browserOpened) reportSwitch('retryable', reason) return generation === this.authGeneration ? this.stayed('retryable') : this.unreached() + } finally { + if (viewConsent) this.viewConsentOpen = false } if (generation !== this.authGeneration) return this.unreached() this.storeSignedInGrant(tokens) diff --git a/src/main/cloud/tokenStore.ts b/src/main/cloud/tokenStore.ts index e89f7d875..3eafdbba2 100644 --- a/src/main/cloud/tokenStore.ts +++ b/src/main/cloud/tokenStore.ts @@ -219,7 +219,8 @@ export function saveWorkspaceNames(accessToken: string, workspaces: Workspace[]) } export function getCachedWorkspaceName(workspaceId: string): string | null { - return loadVault()?.workspaceNames?.[workspaceId] ?? null + const names = loadVault()?.workspaceNames + return names && Object.hasOwn(names, workspaceId) ? (names[workspaceId] ?? null) : null } export function activateWorkspace(workspaceId: string): boolean { From ff17458476d8843932cadb7c1c38557a59aafbdb Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 11 Nov 2026 13:42:13 -0500 Subject: [PATCH 75/75] fix(auth): count any consent opened for a view request as the one view consent --- src/main/cloud/session.test.ts | 25 +++++++++++++++++++++++++ src/main/cloud/session.ts | 2 +- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index a7e95dda0..5201f4458 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -1737,6 +1737,31 @@ describe('CloudSession switches a local ComfyUI view requests', () => { consent.resolve(signedInResult(grantOn('w2'))) }) + it('keeps one view consent open when a view joined a restored switch', async () => { + saveGrant(grantOn('w1')) + const listed = mocked(listWorkspaces).getMockImplementation() + mocked(listWorkspaces).mockResolvedValue([member('w1'), member('w2'), member('w3')]) + onTestFinished(() => void mocked(listWorkspaces).mockImplementation(listed!)) + const slow = deferred() + mintReply = () => slow.promise + const consent = deferred>>() + mocked(signIn).mockReturnValue(consent.promise) + const session = new CloudSession() + + void session.switchWorkspace('w2', 'restored') + await vi.waitFor(() => expect(mintRequests).toHaveLength(1)) + void session.switchWorkspace('w2', 'requested') + slow.resolve(json(403, { code: 'sso_required' })) + await vi.waitFor(() => expect(signIn).toHaveBeenCalledOnce()) + await expect(session.switchWorkspace('w1')).resolves.toMatchObject({ reached: true }) + await expect(session.switchWorkspace('w3', 'requested')).resolves.toMatchObject({ + reached: false + }) + + expect(signIn).toHaveBeenCalledOnce() + consent.resolve(signedInResult(grantOn('w2'))) + }) + it('does not cancel a sign-in Desktop has in flight', async () => { saveGrant(grantOn('w1')) const signingIn = deferred>>() diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index 2b3e5af6f..dca256fc9 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -478,7 +478,7 @@ export class CloudSession { } let browserOpened = false let tokens: AuthTokens - const viewConsent = reason === 'view_requested' + const viewConsent = this.switchIntent === 'requested' if (viewConsent) this.viewConsentOpen = true try { ;({ tokens } = await signIn({