diff --git a/e2e/support/electronHarness.ts b/e2e/support/electronHarness.ts index 96fd5aa90..b01a8bdf9 100644 --- a/e2e/support/electronHarness.ts +++ b/e2e/support/electronHarness.ts @@ -20,6 +20,7 @@ export interface SeedOptions { onSetup?: (paths: { homeDir: string; appDataDir: string }) => Promise opsFlags?: Record profileDir?: string + userDataDir?: string } export interface SeedInstallation { @@ -188,6 +189,10 @@ export async function launchLauncherApp(options?: SeedOptions): Promise 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 + 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') + 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) + 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 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: {} }) + + 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) +}) diff --git a/locales/en.json b/locales/en.json index b58f9ccf1..94c4cc13e 100644 --- a/locales/en.json +++ b/locales/en.json @@ -1355,6 +1355,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 afaa86854..ac3c93b27 100644 --- a/locales/zh.json +++ b/locales/zh.json @@ -1355,6 +1355,8 @@ "personalLabel": "个人", "switchLabel": "工作区", "currentFallback": "当前工作区", + "switchUnavailable": "此工作区不可用。", + "switchRetryable": "无法切换工作区。请检查网络连接后重试。", "instanceCountLabel": "实例", "loadError": "无法加载工作区,请重试", "refresh": "刷新工作区", diff --git a/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts b/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts index ac6c9fd02..b853e6dd4 100644 --- a/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts +++ b/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts @@ -135,8 +135,12 @@ 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` and resolves with the resulting + * 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/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", diff --git a/src/main/cloud/claims.ts b/src/main/cloud/claims.ts index f09e08b0a..92b7bcd61 100644 --- a/src/main/cloud/claims.ts +++ b/src/main/cloud/claims.ts @@ -10,6 +10,8 @@ interface AccessTokenClaims { workspace_type?: string role?: string scope?: string + iat?: unknown + exp?: unknown } function decodeJwtPayload(token: string): AccessTokenClaims | null { @@ -44,6 +46,13 @@ export function canMintWorkspaceTokens(accessToken: string): boolean { return typeof scope === 'string' && scope.split(' ').includes(WORKSPACE_MINT_SCOPE) } +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 +} + export function subjectOf(accessToken: string): string | null { return decodeJwtPayload(accessToken)?.sub ?? null } diff --git a/src/main/cloud/index.ts b/src/main/cloud/index.ts index 314edaac2..cf138eaaa 100644 --- a/src/main/cloud/index.ts +++ b/src/main/cloud/index.ts @@ -9,5 +9,8 @@ export type { AuthTokens, Workspace, WorkspaceMember, - WorkspaceSwitchOutcome + WorkspaceSwitchFailure, + WorkspaceSwitchIntent, + WorkspaceSwitchOutcome, + WorkspaceSwitchStatus } from './types' diff --git a/src/main/cloud/oauth.test.ts b/src/main/cloud/oauth.test.ts index 4275f44c5..bc4775ad4 100644 --- a/src/main/cloud/oauth.test.ts +++ b/src/main/cloud/oauth.test.ts @@ -1,10 +1,20 @@ 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 { refresh, signIn } from './oauth' +import { app, shell } from 'electron' +import { startLoopbackListener } from './loopback' +import type * as LoopbackModule from './loopback' +import { getShellOpenExternalCalls, resetShellOpenExternalCalls } from '../lib/e2eOverrides' +import { openAuthorizePage, refresh, signIn } from './oauth' function stub(status: number, body: unknown): void { vi.stubGlobal( @@ -58,6 +68,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( @@ -110,6 +136,53 @@ describe('oauth.signIn', () => { 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 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() + + 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() + 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/oauth.ts b/src/main/cloud/oauth.ts index e6ed51d60..15dd39ffd 100644 --- a/src/main/cloud/oauth.ts +++ b/src/main/cloud/oauth.ts @@ -1,5 +1,6 @@ -import { shell } from 'electron' +import { app, shell } from 'electron' +import { recordShellOpenExternal } from '../lib/e2eOverrides' import { statusFromAccessToken } from './claims' import { CLOUD_CONFIG } from './config' import { startLoopbackListener } from './loopback' @@ -53,6 +54,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() const timer = setTimeout(() => controller.abort(), TOKEN_REQUEST_TIMEOUT_MS) @@ -74,7 +86,7 @@ async function requestToken(tokenUrl: string, body: URLSearchParams): Promise { @@ -100,6 +112,10 @@ async function requestToken(tokenUrl: string, body: URLSearchParams): Promise { + if (process.env['E2E'] === '1' && !app.isPackaged) { + recordShellOpenExternal(authorizeUrl) + return Promise.resolve() + } return shell.openExternal(authorizeUrl) } diff --git a/src/main/cloud/session.test.ts b/src/main/cloud/session.test.ts index 819bfc61b..5201f4458 100644 --- a/src/main/cloud/session.test.ts +++ b/src/main/cloud/session.test.ts @@ -1,216 +1,491 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import * as fs from 'node:fs' +import * as os from 'node:os' +import * as path from 'node:path' +import { afterEach, beforeEach, describe, expect, it, onTestFinished, 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(`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()) } +})) 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 { safeStorage } from 'electron' + +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, + MINT_SCOPE_NOT_GRANTED_EVENT, + WORKSPACE_RETURNED_TO_ANCHOR_EVENT, + WORKSPACE_SWITCH_BROWSER_EVENT, + WORKSPACE_SWITCH_EVENT +} from './session' +import { SignInFailure } from './signInFailure' +import { _resetForTest, clearTokens, saveGrant, saveWorkspaceToken } 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` } -function makeTokens(workspaceId: string, expiresAt = future, suffix = ''): AuthTokens { +interface GrantOptions { + expiresAt?: number + scope?: string + revision?: string + subject?: string +} + +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' + }) } -beforeEach(() => { - active = null - bundles = new Map() - mocked(loadTokens).mockImplementation(() => active) - mocked(loadWorkspaceTokens).mockImplementation((workspaceId) => - workspaceId ? (bundles.get(workspaceId) ?? null) : null +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 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) => { + resolve = r + }) + return { promise, resolve } +} + +function switchEvents(): unknown[] { + return mocked(mainTelemetry.emit) + .mock.calls.filter(([event]) => event === WORKSPACE_SWITCH_EVENT) + .map(([, context]) => context) +} + +function mintScopeNotGrantedEvents(): unknown[] { + return mocked(mainTelemetry.emit).mock.calls.filter( + ([event]) => event === MINT_SCOPE_NOT_GRANTED_EVENT ) - 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 +} + +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 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 }) + } + return new SignInFailure('refresh failed', kind) +} + +function vaultOnDisk(): Record { + return JSON.parse( + safeStorage.decryptString( + fs.readFileSync(path.join(electronState.userData, 'comfy-cloud-auth.bin')) + ) + ) as Record +} + +beforeEach(() => { + 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(() => { + vi.useRealTimers() + 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({ status: { workspaceId: 'w2' }, reached: true }) - 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(refreshRefused()) + + 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')) const session = new CloudSession() + await session.switchWorkspace('w2') + saveWorkspaceToken('w2', { accessToken: mintedJwt('w2'), expiresAt }) + 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(refreshRefused()) + + await expect(session.getAccessToken()).resolves.toBeNull() + + expect(refresh).not.toHaveBeenCalled() + 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('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, {})], + ['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')) + browserSignInReturns(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 () => { @@ -247,191 +522,1830 @@ 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 () => { + browserSignInReturns(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('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({ - status: { workspaceId: 'w2' }, - reached: true + workspaceId: 'w1', + workspaceSwitchFailure: 'retryable' }) - await expect(session.switchWorkspace('w1')).resolves.toMatchObject({ - status: { workspaceId: 'w1' }, - reached: true + + expect(session.currentWorkspaceId()).toBe('w1') + expect(vaultOnDisk().workspaceTokens).toEqual({}) + 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() - expect(activateWorkspace).toHaveBeenNthCalledWith(1, 'w2') - expect(activateWorkspace).toHaveBeenNthCalledWith(2, 'w1') + 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('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('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(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ - status: { workspaceId: 'w2' }, - reached: true + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w1', + workspaceSwitchFailure: 'retryable' }) - expect(refresh).toHaveBeenCalledExactlyOnceWith(staleTwo.refreshToken) - expect(activateWorkspace).toHaveBeenCalledExactlyOnceWith('w2') + expect(session.currentWorkspaceId()).toBe('w1') + expect(vaultOnDisk().workspaceTokens).toEqual({}) 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('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') + saveWorkspaceToken('w2', { accessToken: mintedJwt('w2'), expiresAt: PAST }) - await expect(new CloudSession().switchWorkspace('w1')).resolves.toMatchObject({ - status: { workspaceId: 'w1' }, - reached: true - }) + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) - expect(refresh).toHaveBeenCalledExactlyOnceWith(stale.refreshToken) - expect(signIn).toHaveBeenCalledExactlyOnceWith({ workspaceId: 'w1' }) - expect(saveTokens).toHaveBeenCalledExactlyOnceWith(authorized) + expect(mintRequests).toHaveLength(2) + expect(signIn).not.toHaveBeenCalled() }) - 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('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({ - status: { workspaceId: 'w1' }, - reached: false + workspaceId: 'w2' }) - expect(signIn).toHaveBeenCalledExactlyOnceWith({ workspaceId: 'w2' }) - expect(saveTokens).not.toHaveBeenCalled() + expect(mintRequests).toEqual([{ workspaceId: 'w2', bearer: fresh.accessToken }]) + expect(signIn).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 - }) - ) + it('shares one flight between concurrent switches to the same workspace', async () => { + saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) + browserSignInReturns(signedInResult(grantOn('w2'))) const session = new CloudSession() - const superseded = session.switchWorkspace('w2') - const newer = session.switchWorkspace('w1') - finishRefresh(freshTwo) + await Promise.all([session.switchWorkspace('w2'), session.switchWorkspace('w2')]) - await expect(superseded).resolves.toMatchObject({ reached: false }) - await expect(newer).resolves.toMatchObject({ status: { workspaceId: 'w1' }, reached: true }) + expect(signIn).toHaveBeenCalledOnce() }) - 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) - }) + 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(new CloudSession().switchWorkspace('w1')).resolves.toMatchObject({ - status: { workspaceId: 'w1' }, - reached: false + 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(saveTokens).not.toHaveBeenCalled() + + expect(signIn).not.toHaveBeenCalled() }) - 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('respects Retry-After instead of asking Cloud again', async () => { + saveGrant(grantOn('w1')) + mintReply = () => json(429, {}, { 'Retry-After': '60' }) const session = new CloudSession() - 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 + await session.switchWorkspace('w2') + await expect(session.switchWorkspace('w3')).resolves.toMatchObject({ + workspaceSwitchFailure: 'retryable' }) - expect(signIn).toHaveBeenCalledOnce() - expect(saveTokens).toHaveBeenCalledExactlyOnceWith(workspaceTwo) + expect(mintRequests).toHaveLength(1) }) - it('listWorkspaces and the provider use only the active token', async () => { - const tokens = makeTokens('w1') - cache(tokens, true) + it('caps a huge Retry-After at five minutes', async () => { + saveGrant(grantOn('w1')) + mintReply = () => json(429, {}, { 'Retry-After': '1000000000' }) const session = new CloudSession() - await session.listWorkspaces() - expect(listWorkspaces).toHaveBeenCalledWith(tokens.accessToken) - expect(saveWorkspaceNames).toHaveBeenCalledExactlyOnceWith(tokens.accessToken, [{ id: 'w-1' }]) + const start = Date.now() + const now = vi.spyOn(Date, 'now').mockReturnValue(start) + onTestFinished(() => now.mockRestore()) - const onSignedOut = vi.fn() - const provider = session.asTokenProvider(onSignedOut) - await expect(provider.getAccessToken()).resolves.toBe(tokens.accessToken) - provider.onUnauthorized?.(tokens.accessToken) - expect(clearTokens).toHaveBeenCalledOnce() - expect(onSignedOut).toHaveBeenCalledOnce() + 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('lists members using only the active workspace token', async () => { - const tokens = makeTokens('w1') - cache(tokens, true) + 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') - await expect(new CloudSession().listWorkspaceMembers()).resolves.toEqual([ - { id: 'user-1', name: 'One' } - ]) - expect(listWorkspaceMembers).toHaveBeenCalledExactlyOnceWith(tokens.accessToken) + 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() + await held.switchWorkspace('w2') + saveWorkspaceToken('w2', { accessToken: mintedJwt('w2'), expiresAt: PAST }) + 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) + }) + + 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('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() + 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 = () => + 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 reached', () => { + it('reports a switch that minted, reused or returned to the anchor as reached', async () => { + saveGrant(grantOn('w1')) + const session = new CloudSession() + + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w2', + reached: true + }) + await expect(session.switchWorkspace('w1')).resolves.toMatchObject({ + workspaceId: 'w1', + reached: true + }) + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w2', + reached: true + }) + }) + + it('reports a switch that stayed on the current workspace as unreached', async () => { + saveGrant(grantOn('w1')) + mintReply = () => json(500, {}) + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w1', + workspaceSwitchFailure: 'retryable', + reached: false + }) + }) + + it('reports a switch superseded during its mint as unreached', async () => { + saveGrant(grantOn('w1')) + const pendingMint = deferred() + mintReply = () => pendingMint.promise + const session = new CloudSession() + + const superseded = session.switchWorkspace('w2') + const newer = session.switchWorkspace('w1') + pendingMint.resolve(minted('w2')) + + await expect(superseded).resolves.toMatchObject({ reached: false }) + await expect(newer).resolves.toMatchObject({ workspaceId: 'w1', reached: true }) + }) + + it('reports an unreached switch when browser auth for the expired anchor picks another workspace', async () => { + saveGrant(grantOn('w1', { expiresAt: Date.now() - 1_000 })) + mocked(refresh).mockRejectedValue(refreshRefused()) + browserSignInReturns(signedInResult(grantOn('w2', { scope: READ_ONLY_SCOPE }))) + + await expect(new CloudSession().switchWorkspace('w1')).resolves.toMatchObject({ + workspaceId: 'w2', + reached: false + }) + }) +}) + +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' }) + const sso = grantOn('w2', { revision: '-sso' }) + browserSignInReturns(signedInResult(sso)) + const session = new CloudSession() + + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ 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' }]) + }) + + 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') + browserSignInReturns(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(refreshRefused('invalid_client')) + 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(expect.objectContaining({ 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 oauth_grant_ended 401 after a good refresh is reauthorize', async () => { + saveGrant(grantOn('w1')) + 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'))) + + 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)], + ['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, {}) + 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<[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(refreshRefused(oauthError)) + browserSignInReturns(signedInResult(grantOn('w2'))) + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w2' + }) + + expect(signIn).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ workspaceId: 'w2' })) + } + ) + + 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('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(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 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') + 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) + + 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() + }) + + it('switching to the anchor with a refused refresh opens one browser', async () => { + saveGrant(grantOn('w1', { expiresAt: PAST })) + mocked(refresh).mockRejectedValue(refreshRefused()) + browserSignInReturns(signedInResult(grantOn('w1', { revision: '-new' }))) + + await expect(new CloudSession().switchWorkspace('w1')).resolves.toMatchObject({ + 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 () => { + 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(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() + }) + + it('a second refusal after the browser trip does not open another', async () => { + saveGrant(grantOn('w1')) + mintReply = () => json(403, { code: 'sso_required' }) + browserSignInReturns(signedInResult(grantOn('w3'))) + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + 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, {})) + 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' }) + 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' }) + browserSignInReturns(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') + browserSignInReturns(signedInResult(consented)) + const session = new CloudSession() + + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ 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' }]) + expect(browserEvents()).toEqual([{ reauthorize_reason: 'mint_disabled' }]) + }) + + 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 + browserSignInReturns(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() + browserSignInReturns(signedInResult(grantOn('w2'))) + const session = new CloudSession() + + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) + + expect(mintRequests).toEqual([]) + 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() + browserSignInReturns(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(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'), + 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() + browserSignInReturns(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, reached: false }) + expect(signIn).not.toHaveBeenCalled() + }) + + 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.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', () => { + 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({ + workspaceId: 'w2' + }) + + expect(signIn).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ workspaceId: 'w2' })) + expect(mintRequests).toEqual([]) + 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('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('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>>() + 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() + 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() + 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() + 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 })) + browserSignInReturns(signedInResult(grantOn('w3'))) + const session = new CloudSession() + + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ workspaceId: 'w2' }) + + expect(signIn).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ 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 })) + browserSignInReturns( + 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' }]) + }) + + 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() + + for (const workspaceId of ['w2', 'w2', 'w3']) { + await expect(session.switchWorkspace(workspaceId)).resolves.toMatchObject({ + workspaceId: 'w1', + workspaceSwitchFailure: 'retryable' + }) + } + + expect(signIn).toHaveBeenCalledTimes(3) + expect(mintRequests).toEqual([]) + }) + + 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 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() + await session.switchWorkspace('w2') + + await expect(session.switchWorkspace('w3')).resolves.toMatchObject({ + workspaceId: 'w2', + workspaceSwitchFailure: 'retryable' + }) + + expect(signIn).toHaveBeenCalledTimes(2) + }) + + 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' })) + ) + const session = new CloudSession() + await session.switchWorkspace('w2') + browserSignInReturnsOnce(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('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' })) + ) + const session = new CloudSession() + await session.switchWorkspace('w2') + browserSignInReturnsOnce( + 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') + browserSignInReturnsOnce(signedInResult(grantOn('w3'))) + + await expect(session.switchWorkspace('w3')).resolves.toMatchObject({ workspaceId: 'w3' }) + + expect(signIn).toHaveBeenCalledTimes(3) + }) + + 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' })) + ) + const session = new CloudSession() + + await session.login() + await expect(session.switchWorkspace('w2')).resolves.toMatchObject({ + workspaceSwitchFailure: 'retryable' + }) + + expect(signIn).toHaveBeenCalledTimes(2) + }) + + 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' })) + ) + const session = new CloudSession() + await session.switchWorkspace('w2') + browserSignInReturnsOnce(signedInResult(grantOn('w1', { revision: '-scoped' }))) + await session.login() + _resetForTest() + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + workspaceId: 'w2' + }) + + expect(signIn).toHaveBeenCalledTimes(2) + }) + + 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() + + await session.switchWorkspace('w2') + await session.switchWorkspace('w3') + + expect(mintScopeNotGrantedEvents()).toHaveLength(2) + }) + + 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' }) + browserSignInReturns(signedInResult(grantOn('w1', { scope: READ_ONLY_SCOPE }))) + + await expect(new CloudSession().switchWorkspace('w2')).resolves.toMatchObject({ + workspaceSwitchFailure: 'retryable' + }) + + expect(signIn).toHaveBeenCalledOnce() + 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 () => { + saveGrant(grantOn('w1', { scope: READ_ONLY_SCOPE })) + browserSignInReturns(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(switchEvents()).toContainEqual({ + outcome: 'anchor', + reauthorize_reason: 'scope_not_granted' + }) + expect(browserEvents()).toEqual([{ reauthorize_reason: 'mint_scope_missing' }]) + }) +}) + +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, reached: 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, reached: 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')) + const session = new CloudSession() + + await session.switchWorkspace('w2') + saveWorkspaceToken('w2', { accessToken: mintedJwt('w2'), expiresAt: PAST }) + + 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() + 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() + + session.asTokenProvider(onSignedOut).onUnauthorized?.(grant.accessToken) + + expect(session.isSignedIn()).toBe(false) + 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() + await session.switchWorkspace('w2') + const onSignedOut = vi.fn() + const provider = session.asTokenProvider(onSignedOut) + + 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 424c2db65..dca256fc9 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -1,52 +1,158 @@ 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, + endGrant, getAuthStatus, - loadTokens, - loadWorkspaceTokens, - replaceWorkspaceTokens, - saveTokens, - saveWorkspaceNames + getCachedWorkspaceName, + loadActiveWorkspaceId, + loadGrant, + loadWorkspaceToken, + replaceGrant, + saveGrant, + saveWorkspaceNames, + saveWorkspaceToken } from './tokenStore' import type { AuthStatus, AuthTokens, Workspace, WorkspaceMember, - WorkspaceSwitchOutcome + WorkspaceSwitchFailure, + WorkspaceSwitchIntent, + WorkspaceSwitchStatus } from './types' +import { classifyMint, mintWorkspaceToken } from './workspaceToken' +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' +export const MINT_SCOPE_NOT_GRANTED_EVENT = 'comfy.desktop.auth.mint_scope_not_granted' +export const WORKSPACE_RETURNED_TO_ANCHOR_EVENT = 'comfy.desktop.auth.workspace_returned_to_anchor' + +export interface SessionSwitchReply extends WorkspaceSwitchStatus { + reached: boolean + reachedThroughConsent?: true +} + +type SwitchTelemetryOutcome = + | 'cached' + | 'anchor' + | 'minted' + | 'browser' + | 'unavailable' + | 'retryable' + | 'refused' + +type SwitchReason = ReauthorizeReason | 'scope_not_granted' + +type GrantRefresh = 'refreshed' | 'ended' | 'unavailable' + +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 isExpired(tokens: AuthTokens): boolean { + return tokens.expiresAt <= Date.now() +} + +function isDefinitiveRefreshRefusal(error: unknown): boolean { + return ( + error instanceof SignInFailure && + (error.httpStatus === 400 || error.httpStatus === 401) && + error.oauthError !== undefined && + ENDED_GRANT_OAUTH_ERRORS.has(error.oauthError) + ) +} + +function refreshFailureOutcome(refreshed: GrantRefresh): SettledMintOutcome { + return refreshed === 'ended' ? { kind: 'reauthorize', reason: 'grant_ended' } : RETRYABLE +} + +function reportSwitch(outcome: SwitchTelemetryOutcome, reason?: SwitchReason): void { + mainTelemetry.emit( + WORKSPACE_SWITCH_EVENT, + reason ? { outcome, reauthorize_reason: reason } : { outcome } + ) +} + +function reportBrowser(reason: ReauthorizeReason): void { + reportSwitch('browser', reason) + mainTelemetry.emit(WORKSPACE_SWITCH_BROWSER_EVENT, { reauthorize_reason: reason }) +} export class CloudSession { - private readonly refreshing = new Map>() + 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' + private mintBlockedUntil = 0 private loginInFlight: Promise | null = null private loginAuthorizeUrl: string | null = null + private viewConsentOpen = false + private returnedToAnchorHandler: (() => void) | null = null private authGeneration = 0 + async isWorkspaceMintAllowed(workspaceId: string): Promise { + const grant = loadGrant() + if (grant && workspaceIdOf(grant.accessToken) === workspaceId) return true + return isWorkspaceMintSwitchEnabled() + } + + setReturnedToAnchorHandler(handler: () => void): void { + this.returnedToAnchorHandler = handler + } + login(): Promise { if (this.loginInFlight) { if (this.loginAuthorizeUrl) void openAuthorizePage(this.loginAuthorizeUrl).catch(() => {}) return this.loginInFlight } + this.switching = null const generation = ++this.authGeneration - const login = this.authenticateAtGeneration(generation, { + 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 } }) - .then(({ status }) => status) - .finally(() => { - if (this.loginInFlight === login) this.clearPendingLogin() - }) - this.loginInFlight = login - return login + 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) + if (!canMintWorkspaceTokens(tokens.accessToken)) + mainTelemetry.emit(MINT_SCOPE_NOT_GRANTED_EVENT) } private clearPendingLogin(): void { @@ -56,6 +162,8 @@ export class CloudSession { logout(): void { this.authGeneration += 1 + this.switching = null + this.mintBlockedUntil = 0 this.clearPendingLogin() clearTokens() } @@ -73,61 +181,188 @@ export class CloudSession { } currentSubject(): string | null { - const t = loadTokens() - return t ? subjectOf(t.accessToken) : null + const grant = loadGrant() + return grant ? subjectOf(grant.accessToken) : null } currentWorkspaceId(): string | null { - const t = loadTokens() - return t ? workspaceIdOf(t.accessToken) : null + 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 + 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 } 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 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 (!unchanged()) return null + if (refreshed === 'unavailable' && isExpired(grant)) 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 (!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) + 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) + if (replaceGrant(grant.accessToken, refreshToken, rotated)) + this.rotatedTo.set(grant.accessToken, rotated.accessToken) + 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: SettledMintOutcome + ): SettledMintOutcome { + 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 { + const subject = this.currentSubject() + if (!(await this.isWorkspaceMintAllowed(workspaceId))) { + 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 === 'ended' || (refreshed === 'unavailable' && isExpired(grant))) + return refreshFailureOutcome(refreshed) + } + const first = await this.postMint(workspaceId, generation, subject) + if (first.kind !== 'unauthorized') return first + const current = loadGrant() + if (!current) return RETRYABLE + const refreshed = await this.refreshGrant(current) + if (refreshed !== 'refreshed') return refreshFailureOutcome(refreshed) + const second = await this.postMint(workspaceId, generation, subject) + return second.kind === 'unauthorized' ? RETRYABLE : second + } + + private async postMint( + workspaceId: string, + generation: number, + subject: string | null + ): Promise { + const grant = loadGrant() + if ( + !grant || + generation !== this.authGeneration || + subject !== subjectOf(grant.accessToken) || + Date.now() < this.mintBlockedUntil + ) + return RETRYABLE + const outcome = classifyMint(await mintWorkspaceToken(grant.accessToken, workspaceId)) + if (outcome.kind === 'reauthorize' && outcome.reason === 'grant_ended') { + this.endGrantFamily(grant.accessToken) + } + if ( + outcome.kind === 'retryable' && + outcome.retryAfterSeconds !== undefined && + generation === this.authGeneration && + subjectOf(grant.accessToken) === this.currentSubject() + ) { + this.mintBlockedUntil = + Date.now() + Math.min(outcome.retryAfterSeconds * 1000, MAX_MINT_BLOCK_MS) + } + return outcome + } + + endGrantFamily(accessToken: string): void { + for (let token: string | undefined = accessToken; token; token = this.rotatedTo.get(token)) { + endGrant(token) } } async listWorkspaces(): Promise { - const token = await this.getAccessToken() + const token = await this.getGrantAccessToken() if (!token) return [] const workspaces = await listWorkspaces(token) saveWorkspaceNames(token, workspaces) @@ -140,46 +375,175 @@ export class CloudSession { return listWorkspaceMembers(token) } - async switchWorkspace(workspaceId: string): Promise { + switchWorkspace( + workspaceId: string, + intent: WorkspaceSwitchIntent = 'chosen' + ): Promise { + if (this.switching?.workspaceId === workspaceId) { + if (intent === 'chosen' || this.switchIntent === 'restored') this.switchIntent = intent + return this.switching.result + } + if (intent === 'requested' && (this.switching || this.loginInFlight || this.viewConsentOpen)) { + return Promise.resolve(this.unreached()) + } this.clearPendingLogin() + this.switchIntent = intent 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.unreached() + 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') + 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') } - if (generation !== this.authGeneration) return { status: this.status(), reached: false } - if (cached && cached.expiresAt > Date.now()) { - if (cached !== current) activateWorkspace(workspaceId) - return { status: this.status(), reached: true } + + const outcome = await this.mintForWorkspace(workspaceId, generation) + if (generation !== this.authGeneration) return this.unreached() + 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) } - return this.authenticateAtGeneration(generation, { workspaceId }) } - private async authenticateAtGeneration( + private async switchToAnchor( + workspaceId: string, generation: number, - options: OAuthOptions - ): Promise { - const { workspaceId } = options - const { tokens, status } = await signIn(options) - 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, reached: true } + grant: AuthTokens + ): Promise { + if (!isFresh(grant)) { + const refreshed = await this.refreshGrant(grant) + if (generation !== this.authGeneration) return this.unreached() + 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') + } + + private activated(workspaceId: string, outcome: SwitchTelemetryOutcome): SessionSwitchReply { + activateWorkspace(workspaceId) + reportSwitch(outcome) + return { ...this.status(), reached: true } + } + + private stayed(failure: WorkspaceSwitchFailure): SessionSwitchReply { + return { ...this.status(), workspaceSwitchFailure: failure, reached: false } + } + + private unreached(): SessionSwitchReply { + return { ...this.status(), reached: false } + } + + private async reauthorize( + workspaceId: string, + generation: number, + reason: ReauthorizeReason + ): Promise { + if (this.switchIntent === 'restored') { + reportSwitch('retryable', reason) + return this.stayed('retryable') + } + let browserOpened = false + let tokens: AuthTokens + const viewConsent = this.switchIntent === 'requested' + if (viewConsent) this.viewConsentOpen = true + try { + ;({ tokens } = await signIn({ + workspaceId, + onAuthorizeUrl: () => { + browserOpened = true + reportBrowser(reason) + } + })) + } 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) + + const canMint = canMintWorkspaceTokens(tokens.accessToken) + const isAnchor = workspaceId === workspaceIdOf(tokens.accessToken) + if (!canMint) reportSwitch(isAnchor ? 'anchor' : 'retryable', 'scope_not_granted') + if (isAnchor) { + activateWorkspace(workspaceId) + return this.afterConsent({ ...this.status(), reached: true }, tokens) + } + if (!canMint) return this.afterConsent(this.stayed('retryable'), tokens) + + const outcome = await this.mintForWorkspace(workspaceId, generation) + if (generation !== this.authGeneration) return this.unreached() + if (outcome.kind === 'minted') { + activateWorkspace(workspaceId) + return { ...this.status(), reached: true } + } + const unavailable = outcome.kind === 'unavailable' || outcome.kind === 'refused' + return this.afterConsent(this.stayed(unavailable ? 'unavailable' : 'retryable'), tokens) + } + + private afterConsent(reply: SessionSwitchReply, tokens: AuthTokens): SessionSwitchReply { + const reached = loadActiveWorkspaceId() === workspaceIdOf(tokens.accessToken) + return reached ? { ...reply, reachedThroughConsent: true } : reply } asTokenProvider(onSignedOut?: () => void): TokenProvider { return { getAccessToken: () => this.getAccessToken(), onUnauthorized: (rejectedAccessToken) => { - if (loadTokens()?.accessToken !== rejectedAccessToken) return + if (dropWorkspaceToken(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/cloud/signInFailure.ts b/src/main/cloud/signInFailure.ts index 048ca1bad..0fe2208d5 100644 --- a/src/main/cloud/signInFailure.ts +++ b/src/main/cloud/signInFailure.ts @@ -10,15 +10,17 @@ export class SignInFailure extends Error { override readonly name = 'SignInFailure' readonly reason: SignInFailureReason readonly httpStatus: number | undefined + 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/tokenStore.test.ts b/src/main/cloud/tokenStore.test.ts index e40ad4353..f0f94145d 100644 --- a/src/main/cloud/tokenStore.test.ts +++ b/src/main/cloud/tokenStore.test.ts @@ -9,22 +9,33 @@ 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, clearTokens, + dropWorkspaceToken, getAuthStatus, getCachedWorkspaceName, - loadTokens, - loadWorkspaceTokens, - replaceWorkspaceTokens, - saveTokens, - saveWorkspaceNames + loadActiveWorkspaceId, + loadGrant, + loadWorkspaceToken, + replaceGrant, + saveGrant, + saveWorkspaceNames, + saveWorkspaceToken } from './tokenStore' import type { AuthTokens } from './types' @@ -48,7 +59,26 @@ 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(), safeStorage.encryptString(JSON.stringify(payload))) +} + +function readVault(): Record { + return JSON.parse(safeStorage.decryptString(fs.readFileSync(vaultPath()))) as Record< + string, + unknown + > +} + +describe('grant vault', () => { beforeEach(() => { electronState.userData = fs.mkdtempSync(path.join(os.tmpdir(), 'comfy-cloud-tokens-')) electronState.encryptionAvailable = true @@ -61,40 +91,163 @@ 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 } + }) - expect(activateWorkspace('w1')).toEqual(workspaceOne) - expect(loadTokens()).toEqual(workspaceOne) - expect(loadWorkspaceTokens('w2')).toEqual(workspaceTwo) + _resetForTest() + + 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('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')) + + 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' } ]) @@ -111,8 +264,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' } @@ -121,56 +274,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( - replaceWorkspaceTokens('w1', workspaceOne.accessToken, workspaceOne.refreshToken!, rotated) - ).toBe(true) - expect(loadWorkspaceTokens('w1')).toEqual(rotated) - expect(loadWorkspaceTokens('w2')).toEqual(workspaceTwo) + 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('rejects a refresh response scoped to another workspace', () => { - const workspaceOne = tokens('user-1', 'w1') - saveTokens(workspaceOne) + 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!, - tokens('user-1', 'w2') - ) - ).toBe(false) - expect(loadWorkspaceTokens('w1')).toEqual(workspaceOne) + saveGrant(grant) + + expect(loadGrant()).toEqual(grant) + expect(fs.existsSync(vaultPath())).toBe(false) + }) + + 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(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') - ) + writeVault(legacy) + + expect(loadGrant()).toEqual(legacy) + expect(loadActiveWorkspaceId()).toBe('w1') + expect(readVault()).toMatchObject({ version: 2 }) + }) - expect(loadTokens()).toEqual(legacy) - expect(loadWorkspaceTokens('w1')).toEqual(legacy) + 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) - const persisted = JSON.parse( - fs.readFileSync(path.join(electronState.userData, 'comfy-cloud-auth.bin'), 'utf-8') - ) as { version?: number } - expect(persisted.version).toBe(1) + expect(loadGrant()).toBeNull() + expect(getAuthStatus()).toEqual({ signedIn: false }) }) }) diff --git a/src/main/cloud/tokenStore.ts b/src/main/cloud/tokenStore.ts index 9ab0dc8da..3eafdbba2 100644 --- a/src/main/cloud/tokenStore.ts +++ b/src/main/cloud/tokenStore.ts @@ -6,11 +6,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 @@ -50,44 +58,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 workspaceKey(workspaceId: string | null): string { - return workspaceId === null ? DEFAULT_WORKSPACE_KEY : `workspace:${workspaceId}` +function isWorkspaceNames(v: unknown): boolean { + return ( + v === undefined || (isRecord(v) && Object.values(v).every((name) => typeof name === 'string')) + ) +} + +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 } : {}) } } @@ -113,36 +133,79 @@ function loadVault(): TokenVault | null { cachedVault = parsed return cachedVault } - if (isTokens(parsed)) { - 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 } } -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) + ) +} + +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) } -export function loadTokens(): AuthTokens | null { +export function loadGrant(): AuthTokens | null { + return loadVault()?.grant ?? null +} + +export function loadActiveWorkspaceId(): string | null { + return loadVault()?.activeWorkspaceId ?? null +} + +export function loadWorkspaceToken(workspaceId: string): AuthTokens | null { + return loadVault()?.workspaceTokens[workspaceId] ?? null +} + +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) } -export function loadWorkspaceTokens(workspaceId: string | null): AuthTokens | null { - return loadVault()?.bundles[workspaceKey(workspaceId)] ?? null +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 } export function saveWorkspaceNames(accessToken: string, workspaces: Workspace[]): void { @@ -156,44 +219,46 @@ 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): AuthTokens | null { +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 } -export function replaceWorkspaceTokens( - workspaceId: string | null, +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 } +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 { @@ -201,13 +266,24 @@ export function clearTokens(): void { } catch {} } +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 f6afe4f5f..ea8e97ec4 100644 --- a/src/main/cloud/types.ts +++ b/src/main/cloud/types.ts @@ -13,8 +13,16 @@ export interface AuthStatus { role?: string } +export type WorkspaceSwitchFailure = 'unavailable' | 'retryable' + +export type WorkspaceSwitchIntent = 'chosen' | 'restored' | 'requested' + +export interface WorkspaceSwitchStatus extends AuthStatus { + workspaceSwitchFailure?: WorkspaceSwitchFailure +} + export interface WorkspaceSwitchOutcome { - status: AuthStatus + status: WorkspaceSwitchStatus reached: boolean } diff --git a/src/main/cloud/workspaceToken.test.ts b/src/main/cloud/workspaceToken.test.ts index eb8c772f9..0260fc2fe 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 { afterEach, beforeEach, 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 })) ) } @@ -16,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', @@ -36,19 +38,49 @@ 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], + [ + '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) 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 +98,240 @@ 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('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 }], + ['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', + 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: 'reauthorize', reason: 'mint_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: 'unauthorized' }], + [ + '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 6db95687a..ebfc6890a 100644 --- a/src/main/cloud/workspaceToken.ts +++ b/src/main/cloud/workspaceToken.ts @@ -1,22 +1,87 @@ +import { lifetimeSecondsOf } from './claims' + import { CLOUD_CONFIG } from './config' 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 } + +export type ReauthorizeReason = + | 'sso_required' + | '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 } + | { kind: 'unavailable' } + | { kind: 'unauthorized' } + | { kind: 'reauthorize'; reason: ReauthorizeReason } + | { kind: 'refused' } + | { kind: 'retryable'; retryAfterSeconds?: number } + +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 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' } + if (status === 403 && code === MINT_REFUSED_CODE) + return { kind: 'reauthorize', reason: 'mint_refused' } + return { kind: 'refused' } +} export interface MintWorkspaceTokenOptions { apiBase?: string timeoutMs?: number } -function mintedFrom(body: unknown): WorkspaceTokenMint | null { +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, 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) { + const deadline = requestedAt + lifetimeSeconds * 1000 + return lifetimeSeconds > 0 && deadline > Date.now() + ? { kind: 'minted', token, expiresAt: deadline } + : null + } + if (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( @@ -25,6 +90,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`, { @@ -41,6 +107,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, requestedAt) ?? { 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 }) + } } diff --git a/src/main/index.ts b/src/main/index.ts index 9ab732b8d..104fea7b4 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' @@ -1017,6 +1018,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/embeddedSession.test.ts b/src/main/lib/embeddedSession.test.ts index a74591dfb..569d226d9 100644 --- a/src/main/lib/embeddedSession.test.ts +++ b/src/main/lib/embeddedSession.test.ts @@ -1,8 +1,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' +import type * as WorkspaceTokenModule from '../cloud/workspaceToken' + const mocks = vi.hoisted(() => ({ enabled: true, - getAccessToken: vi.fn<() => Promise>(), + getGrantAccessToken: vi.fn<() => Promise>(), mint: vi.fn(), current: 'ws-1', entries: [] as unknown[] @@ -13,13 +15,18 @@ vi.mock('./embeddedSessionFlag', () => ({ })) vi.mock('../devplatform/session', () => ({ getCloudSession: () => ({ - getAccessToken: mocks.getAccessToken, + getGrantAccessToken: mocks.getGrantAccessToken, + heldWorkspaceToken: () => null, currentWorkspaceId: () => mocks.current, - currentSubject: () => (mocks.current ? 'user-1' : null) + currentSubject: () => (mocks.current ? 'user-1' : null), + currentAuthGeneration: () => 0, + isWorkspaceMintAllowed: async () => true, + endGrantFamily: () => {} }), rejectAccessToken: vi.fn() })) -vi.mock('../cloud/workspaceToken', () => ({ +vi.mock('../cloud/workspaceToken', async (importOriginal) => ({ + ...(await importOriginal()), mintWorkspaceToken: mocks.mint })) vi.mock('../host/registry', () => ({ @@ -49,7 +56,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', scope: undefined }) +} + +const MINTED = mintedFor('ws-1') interface ViewOptions { frameUrl?: string @@ -79,10 +90,12 @@ function view(comfyUrl: string, options: ViewOptions = {}) { 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.getGrantAccessToken.mockReset().mockResolvedValue(ACCESS) + mocks.mint.mockReset().mockImplementation(async (_grant: string, workspaceId: string) => ({ + kind: 'minted', + token: mintedFor(workspaceId), + expiresAt: Date.now() + 900_000 + })) mocks.current = 'ws-1' resetViewGrants() }) @@ -115,7 +128,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 +149,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 (workspaceId: string) => { - mocks.getAccessToken.mockResolvedValue( - jwt({ sub: 'user-1', email: 'a@example.com', workspace_id: workspaceId }) - ) + mocks.current = workspaceId return { status: { signedIn: true, workspaceId }, reached: true } }) @@ -156,13 +167,12 @@ describe('embeddedSession', () => { const bystander = view('http://127.0.0.1:8001') const switchWorkspace = vi.fn(async (workspaceId: string) => { mocks.current = workspaceId - mocks.getAccessToken.mockResolvedValue(jwt({ sub: 'user-1', workspace_id: workspaceId })) return { status: { signedIn: true, workspaceId }, reached: true } }) 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() }) @@ -178,7 +188,6 @@ describe('embeddedSession', () => { 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() }) @@ -189,7 +198,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 () => ({ status: { signedIn: true }, reached: true })) @@ -227,12 +236,12 @@ 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('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) + mocks.getGrantAccessToken.mockResolvedValue(grant) const { event } = view('http://127.0.0.1:8000') await expect(stateForSender(event)).resolves.toMatchObject({ status: 'signed_in' }) @@ -240,8 +249,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' }) @@ -274,13 +295,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 27a910b12..02ce151fa 100644 --- a/src/main/lib/embeddedSession.ts +++ b/src/main/lib/embeddedSession.ts @@ -63,9 +63,18 @@ 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 - return identity ? { status: 'signed_in', ...identity } : { status: 'signed_out' } + const session = getCloudSession() + const grant = await session.getGrantAccessToken() + const identity = 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 6f1d8465d..3bbac5350 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts @@ -14,6 +14,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), getBuilderClient: vi.fn(() => ({ @@ -69,6 +71,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, @@ -121,7 +125,16 @@ vi.mock('./shared', () => ({ i18n: { t: mocks.translate } })) -import { registerDevPlatformHandlers, signInToCloud } from './registerDevPlatformHandlers' +import type { WebContents } from 'electron' + +import { CLOUD_CONFIG } from '../../cloud/config' +import type * as ViewGrantsModule from '../viewWorkspaceGrants' +import { + registerDevPlatformHandlers, + signInToCloud, + signOutOfCloud, + switchCloudWorkspace +} from './registerDevPlatformHandlers' import { comfyWindows, type ComfyWindowEntry } from '../../host/registry' type IpcHandler = (event: unknown, ...args: unknown[]) => unknown @@ -479,17 +492,441 @@ describe('registerDevPlatformHandlers', () => { const win = { webContents: { isDestroyed: () => false, send: vi.fn() } } mocks.getAllWindows.mockReturnValue([win]) mocks.switchWorkspace.mockResolvedValue({ - status: { signedIn: true, workspaceId: 'w2', workspaceType: 'team' }, + signedIn: true, + workspaceId: 'w2', + workspaceType: 'team', reached: true }) 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) }) + 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' }) + 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) + }) + + 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, + heldWorkspaceToken: () => null, + endGrantFamily: () => {} + }, + 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, reached: true } + }) + 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') + }) + }) + + 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, + heldWorkspaceToken: () => null, + endGrantFamily: () => {} + }, + 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(), reached: true } + }) + 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 => + 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, + heldWorkspaceToken: () => null, + endGrantFamily: () => {} + }, + 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]) + 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.for([ ['signed out', { signedIn: false }], ['still on another workspace', { signedIn: true, workspaceId: 'w1', workspaceType: 'team' }], @@ -497,7 +934,7 @@ describe('registerDevPlatformHandlers', () => { ] as const)( 'a dashboard switch that ends %s lets no view hold the target', async ([, status]) => { - mocks.switchWorkspace.mockResolvedValue({ status, reached: false }) + mocks.switchWorkspace.mockResolvedValue({ ...status, reached: false }) await handler('comfybuilder:switchWorkspace')({}, 'w2') @@ -601,7 +1038,7 @@ describe('registerDevPlatformHandlers', () => { mocks.switchWorkspace.mockImplementationOnce(async () => { const status = { signedIn: true, workspaceId: 'w2', workspaceType: 'team' } mocks.status.mockReturnValue(status) - return { status, reached: true } + return { ...status, reached: true } }) mocks.createBuildDraft.mockResolvedValue({ buildId: 'build-2', @@ -613,7 +1050,7 @@ describe('registerDevPlatformHandlers', () => { ok: true }) - expect(mocks.switchWorkspace).toHaveBeenCalledExactlyOnceWith('w2') + expect(mocks.switchWorkspace).toHaveBeenCalledExactlyOnceWith('w2', 'chosen') expect(mocks.allowDesktopWorkspace).toHaveBeenCalledExactlyOnceWith('w2') expect(mocks.createBuildDraft).toHaveBeenCalledOnce() expect(mocks.openExternal).toHaveBeenCalledExactlyOnceWith( @@ -631,7 +1068,9 @@ describe('registerDevPlatformHandlers', () => { installPath: '/installs/local-1' }) mocks.switchWorkspace.mockResolvedValueOnce({ - status: { signedIn: true, workspaceId: 'w1', workspaceType: 'team' }, + signedIn: true, + workspaceId: 'w1', + workspaceType: 'team', reached: false }) diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.ts b/src/main/lib/ipc/registerDevPlatformHandlers.ts index 91ff61b4d..f949a3e14 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.ts @@ -20,7 +20,13 @@ import { } from '../../devplatform/builds' import type { BuildRow } from '../../devplatform/builds' import { clearVersionCache, getVersionCacheGeneration } from '../../devplatform/versionCache' -import type { AuthStatus, Workspace, WorkspaceSwitchOutcome } from '../../cloud' +import type { + AuthStatus, + Workspace, + WorkspaceSwitchIntent, + WorkspaceSwitchOutcome, + WorkspaceSwitchStatus +} from '../../cloud' import { installations, defaultInstallDir, @@ -102,12 +108,35 @@ export async function signInToCloud(): Promise { return status } -export async function switchCloudWorkspace(workspaceId: string): Promise { +async function switchAndAnnounce( + workspaceId: string, + intent: WorkspaceSwitchIntent +): Promise<{ reply: WorkspaceSwitchStatus; reached: boolean }> { + const session = getCloudSession() + const subjectBefore = session.currentSubject() clearVersionCache() - const outcome = await getCloudSession().switchWorkspace(workspaceId) + const switching = session.switchWorkspace(workspaceId, intent) + const generation = session.currentAuthGeneration() + const { reachedThroughConsent, reached, ...reply } = await switching clearVersionCache() - broadcastAuthChanged(outcome.status) - return outcome + 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, reached: reached && !superseded } +} + +export async function switchCloudWorkspace( + workspaceId: string, + intent: WorkspaceSwitchIntent = 'chosen' +): Promise { + const { reply, reached } = await switchAndAnnounce(workspaceId, intent) + return { status: reply, reached } } export async function signOutOfCloud(host: ComfyWindowEntry | undefined): Promise { @@ -157,6 +186,12 @@ export function registerDevPlatformHandlers(): void { clearVersionCache() broadcastAuthChanged(SIGNED_OUT) }) + session.setReturnedToAnchorHandler(() => { + const status = session.status() + getViewWorkspaceGrants().allowDesktop(status.workspaceId) + clearVersionCache() + broadcastAuthChanged(status) + }) const installing = new Set() const promoting = new Set() @@ -194,11 +229,17 @@ export function registerDevPlatformHandlers(): void { } ) - ipcMain.handle(DEVPLATFORM_CHANNELS.switchWorkspace, async (_event, workspaceId: string) => { - const { status, reached } = await switchCloudWorkspace(workspaceId) - if (reached) getViewWorkspaceGrants().allowDesktop(workspaceId) - return status - }) + ipcMain.handle( + DEVPLATFORM_CHANNELS.switchWorkspace, + async (_event, workspaceId: string, intent?: WorkspaceSwitchIntent) => { + const { reply: status, reached } = await switchAndAnnounce( + workspaceId, + intent === 'restored' ? 'restored' : 'chosen' + ) + if (reached) getViewWorkspaceGrants().allowDesktop(workspaceId) + return status + } + ) ipcMain.handle( DEVPLATFORM_CHANNELS.promoteLocalInstance, @@ -215,6 +256,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 = @@ -226,14 +268,14 @@ export function registerDevPlatformHandlers(): void { } if (!workspaceId) return { ok: false, message: 'No active workspace.' } if (status.workspaceId !== workspaceId) { - clearVersionCache() - const { status: switched, reached } = await session.switchWorkspace(workspaceId) - clearVersionCache() - if (reached) getViewWorkspaceGrants().allowDesktop(workspaceId) - broadcastAuthChanged(switched) + if (session.currentSubject() !== subject) { + return { ok: false, message: 'Could not activate the instance workspace.' } + } + const { reached } = await switchAndAnnounce(workspaceId, 'chosen') if (!reached) { return { ok: false, message: 'Could not activate the instance workspace.' } } + getViewWorkspaceGrants().allowDesktop(workspaceId) } const filename = await saveSnapshot(inst.installPath, inst, 'manual') @@ -249,7 +291,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.' } } @@ -266,7 +308,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.' } } const url = new URL( diff --git a/src/main/lib/ipc/registerEmbeddedSessionHandlers.test.ts b/src/main/lib/ipc/registerEmbeddedSessionHandlers.test.ts index f3524bd27..f74c855fc 100644 --- a/src/main/lib/ipc/registerEmbeddedSessionHandlers.test.ts +++ b/src/main/lib/ipc/registerEmbeddedSessionHandlers.test.ts @@ -7,7 +7,9 @@ const mocks = vi.hoisted(() => ({ emit: vi.fn(), handle: vi.fn(), signInToCloud: vi.fn(), - stateForSender: vi.fn() + stateForSender: vi.fn(), + switchWorkspaceForSender: vi.fn(), + switchCloudWorkspace: vi.fn() })) vi.mock('electron', () => ({ ipcMain: { handle: mocks.handle } })) @@ -25,14 +27,14 @@ vi.mock('../embeddedSession', () => ({ switchWorkspace: 'desktop2-auth:switch-workspace' }, stateForSender: mocks.stateForSender, - switchWorkspaceForSender: vi.fn(), + switchWorkspaceForSender: mocks.switchWorkspaceForSender, workspaceTokenForSender: vi.fn() })) vi.mock('./registerDevPlatformHandlers', () => ({ signInToCloud: mocks.signInToCloud, signOutOfCloud: vi.fn(), - switchCloudWorkspace: vi.fn() + switchCloudWorkspace: mocks.switchCloudWorkspace })) import { registerEmbeddedSessionHandlers } from './registerEmbeddedSessionHandlers' @@ -164,3 +166,19 @@ describe('desktop2-auth:request-sign-in telemetry', () => { ]) }) }) + +describe('desktop2-auth:switch-workspace', () => { + it('switches as a view request, which never mints a new workspace silently', async () => { + const call = mocks.handle.mock.calls.find( + ([channel]) => channel === 'desktop2-auth:switch-workspace' + ) + const event = {} + await (call![1] as (event: unknown, id: unknown) => Promise)(event, 'ws-2') + const [sender, workspaceId, switchWorkspace] = mocks.switchWorkspaceForSender.mock.calls[0]! + + await switchWorkspace('ws-2') + + expect([sender, workspaceId]).toEqual([event, 'ws-2']) + expect(mocks.switchCloudWorkspace).toHaveBeenCalledExactlyOnceWith('ws-2', 'requested') + }) +}) 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')) ) } 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..6268071fd --- /dev/null +++ b/src/main/lib/ipc/switchCloudWorkspace.session.test.ts @@ -0,0 +1,233 @@ +// @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(), + rejectAccessToken: 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 { status: reply, reached } = await switchCloudWorkspace('B') + + expect(reply).toMatchObject({ workspaceId: 'C', workspaceSwitchFailure: 'unavailable' }) + expect(reached).toBe(false) + 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({ + status: { workspaceId: 'X' }, + reached: true + }) + + 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({ + status: { workspaceId: 'X' }, + reached: true + }) + + 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({ + status: { workspaceId: 'A', workspaceSwitchFailure: 'retryable' }, + reached: false + }) + + 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 { status: reply } = await switchCloudWorkspace('X') + + expect(reply).not.toHaveProperty('reachedThroughConsent') + expect(reply).not.toHaveProperty('reached') + expect(send.mock.calls[0]?.[1]).not.toHaveProperty('reachedThroughConsent') + expect(send.mock.calls[0]?.[1]).not.toHaveProperty('reached') + }) +}) diff --git a/src/main/lib/viewWorkspaceGrants.session.test.ts b/src/main/lib/viewWorkspaceGrants.session.test.ts new file mode 100644 index 000000000..be4bdba35 --- /dev/null +++ b/src/main/lib/viewWorkspaceGrants.session.test.ts @@ -0,0 +1,277 @@ +// @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, refresh, 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(() => { + vi.useRealTimers() + 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.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( + 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('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'] }) + 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') + mintRequests = [] + kill() + + await expect(grants.tokenFor(view, 'w2')).resolves.toBe(mintedJwt('w2')) + + 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 = () => + 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 newer switch while the policy is read drops the view request', 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 880d0944b..ae816d1ac 100644 --- a/src/main/lib/viewWorkspaceGrants.test.ts +++ b/src/main/lib/viewWorkspaceGrants.test.ts @@ -28,10 +28,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 } } @@ -49,6 +57,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> > @@ -57,20 +66,33 @@ let rejected: string[] function signInAt(workspaceId: string | null): void { current = workspaceId + generation += 1 +} + +function grantSession( + getGrantAccessToken: () => Promise, + heldWorkspaceToken: (workspaceId: string) => string | null = () => null +): ConstructorParameters[0] { + return { + currentWorkspaceId: () => current, + currentSubject: () => (current ? user : null), + currentAuthGeneration: () => generation, + getGrantAccessToken, + heldWorkspaceToken, + isWorkspaceMintAllowed: async () => true, + endGrantFamily: () => {} + } } beforeEach(() => { vi.mocked(mainTelemetry.emit).mockClear() user = 'user-1' + generation = 0 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) - }, + grantSession(async () => (current ? accessToken('ws-1') : null)), mint, (token) => rejected.push(token) ) @@ -98,10 +120,32 @@ 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') }) + 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(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 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 }) + + 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('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') @@ -126,7 +170,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() }) @@ -139,7 +183,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() }) @@ -147,8 +191,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 () => { @@ -172,6 +216,60 @@ 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: staleToken('ws-1'), + expiresAt: Date.now() + 15 * 60_000 + }) + + await expect(pending).resolves.toBeNull() + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe(mintedToken('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(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(mintedToken('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) @@ -211,11 +309,7 @@ describe('ViewWorkspaceGrants', () => { it('hands out the grant itself, without asking Cloud, when it cannot mint', 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 ) @@ -225,11 +319,37 @@ 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'), + () => 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'), + () => 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' - 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') }) @@ -238,12 +358,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') @@ -254,7 +369,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') }) @@ -277,11 +392,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 69f09afca..c13998263 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, rejectAccessToken } from '../devplatform/session' import * as mainTelemetry from './telemetry' @@ -25,7 +25,11 @@ function reportMint(result: WorkspaceTokenMint): void { export interface GrantSession { currentWorkspaceId(): string | null currentSubject(): string | null - getAccessToken(): Promise + currentAuthGeneration(): number + getGrantAccessToken(): Promise + heldWorkspaceToken(workspaceId: string): string | null + isWorkspaceMintAllowed(workspaceId: string): Promise + endGrantFamily(accessToken: string): void } export type MintWorkspaceToken = ( @@ -37,6 +41,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 @@ -84,12 +93,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() + } + seed(): void { if (this.seeded) return this.seeded = true @@ -105,21 +122,37 @@ 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 + 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 } + } + + 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 { token: accessToken, subject } + 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()) return { token: cached.token, subject } - const result = await this.mintOnce(accessToken, key, workspaceId) - if (epoch !== this.epoch || this.session.currentSubject() !== subject) return null + 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 + 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 } } @@ -127,21 +160,26 @@ 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) .then((result) => { reportMint(result) + const outcome = classifyMint(result) + if (outcome.kind === 'reauthorize' && outcome.reason === 'grant_ended') + this.session.endGrantFamily(accessToken) if (result.kind === 'failed' && result.status === 401) this.onUnauthorized(accessToken) 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/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..67cd5130c --- /dev/null +++ b/src/main/lib/workspaceMintSwitchFlag.ts @@ -0,0 +1,16 @@ +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 +}) + +export const initWorkspaceMintSwitchFlag = flag.init + +export const isWorkspaceMintSwitchEnabled = flag.get + +export const _resetForTest = flag._resetForTest diff --git a/src/preload/api.ts b/src/preload/api.ts index 5413fc849..11121193b 100644 --- a/src/preload/api.ts +++ b/src/preload/api.ts @@ -241,8 +241,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.test.ts b/src/renderer/src/stores/authStore.test.ts index 40e547bfe..007e4c188 100644 --- a/src/renderer/src/stores/authStore.test.ts +++ b/src/renderer/src/stores/authStore.test.ts @@ -191,6 +191,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 15b837bdc..d417dd245 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 } 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' @@ -18,6 +24,8 @@ export const useAuthStore = defineStore('auth', () => { const buildsLoaded = ref(false) const workspacesError = ref(false) const buildsError = ref(false) + const workspaceSwitchFailure = ref() + let latestSwitch = 0 const comfybuilderApi = (window as Window & { api: ElectronApi }).api.comfybuilder let revision = 0 @@ -42,6 +50,7 @@ export const useAuthStore = defineStore('auth', () => { loadingBuilds.value = false workspacesError.value = false buildsError.value = false + workspaceSwitchFailure.value = undefined } function sameIdentity(a: AuthStatus, b: AuthStatus): boolean { @@ -124,9 +133,18 @@ export const useAuthStore = defineStore('auth', () => { } } - async function switchWorkspace(workspaceId: string): Promise { - const next = await comfybuilderApi.switchWorkspace(workspaceId) + async function switchWorkspace( + workspaceId: string, + intent: WorkspaceSwitchIntent = 'chosen' + ): Promise { + const thisSwitch = ++latestSwitch + workspaceSwitchFailure.value = undefined + const { workspaceSwitchFailure: failure, ...next } = await comfybuilderApi.switchWorkspace( + workspaceId, + intent + ) applyAuthoritativeStatus(next) + if (thisSwitch === latestSwitch) workspaceSwitchFailure.value = failure return next } @@ -179,6 +197,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 3f416addd..a0cf19c6b 100644 --- a/src/renderer/src/stores/dashboardScopeStore.test.ts +++ b/src/renderer/src/stores/dashboardScopeStore.test.ts @@ -190,6 +190,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() @@ -209,4 +222,86 @@ 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('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') + + 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 ca96d6b7a..8cf4242f8 100644 --- a/src/renderer/src/stores/dashboardScopeStore.ts +++ b/src/renderer/src/stores/dashboardScopeStore.ts @@ -19,6 +19,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 @@ -38,6 +39,7 @@ export const useDashboardScopeStore = defineStore('dashboardScope', () => { } function applySelection(workspaceId: string): void { + if (workspaceId !== chosenWorkspaceId) chosenWorkspaceId = undefined selectedWorkspaceId.value = workspaceId if ( !initialized.value || @@ -65,7 +67,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 { @@ -132,6 +136,7 @@ export const useDashboardScopeStore = defineStore('dashboardScope', () => { (next, previous) => { if (!initialized.value || !next.loaded) return if (!next.signedIn) { + chosenWorkspaceId = undefined applySelection(PERSONAL_WORKSPACE_ID) return } @@ -157,5 +162,11 @@ export const useDashboardScopeStore = defineStore('dashboardScope', () => { } }) - return { selectedWorkspaceId, initialized, initialize, selectWorkspace } + 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 696a13e45..0252e90cf 100644 --- a/src/renderer/src/views/ChooserView.test.ts +++ b/src/renderer/src/views/ChooserView.test.ts @@ -7,7 +7,9 @@ import BaseSelect from '../components/ui/BaseSelect.vue' import SegmentedControl from '../components/ui/SegmentedControl.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' @@ -909,10 +911,202 @@ describe('ChooserView', () => { await selectWorkspace('w2') - expect(api.comfybuilder.switchWorkspace).toHaveBeenCalledExactlyOnceWith('w2') + expect(api.comfybuilder.switchWorkspace).toHaveBeenCalledExactlyOnceWith('w2', 'chosen') expect(api.comfybuilder.listBuilds).toHaveBeenCalledOnce() }) + it.each([ + ['unavailable', 'This workspace is unavailable.'], + ['retryable', "Couldn't switch workspace. Check your connection and 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 selectWorkspace('w2') + + 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 selectWorkspace('w2') + expect(useDashboardScopeStore().selectedWorkspaceId).toBe('w2') + api.comfybuilder.switchWorkspace.mockClear() + api.comfybuilder.listBuilds.mockClear() + + authChanged({ signedIn: true, workspaceType: 'team', workspaceId: 'w1' }) + await flushPromises() + + 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 selectWorkspace('w2') + 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', '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 selectWorkspace(PERSONAL_WORKSPACE_ID) + 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('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) + 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([ + { 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 2d44d1836..59bc070c3 100644 --- a/src/renderer/src/views/ChooserView.vue +++ b/src/renderer/src/views/ChooserView.vue @@ -90,13 +90,15 @@ watch( async ([signedIn, workspaceId]) => { const generation = ++buildPrefetchGeneration if (!signedIn || !workspaceId) return + const intent = dashboardScope.takeChosenSelection() ? 'chosen' : 'restored' try { if (authStore.status.workspaceId !== workspaceId) { - await authStore.switchWorkspace(workspaceId) + await authStore.switchWorkspace(workspaceId, intent) } if ( generation !== buildPrefetchGeneration || - selectedManagedWorkspaceId.value !== workspaceId + selectedManagedWorkspaceId.value !== workspaceId || + authStore.status.workspaceId !== workspaceId ) return await authStore.fetchBuilds() @@ -157,6 +159,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()]) } @@ -372,6 +378,18 @@ const gridHandlers = { +

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

{ 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), @@ -654,6 +656,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({ @@ -672,7 +696,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] @@ -684,6 +708,120 @@ 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', 'chosen') + 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.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({ + 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 b8e40494f..2260d8db5 100644 --- a/src/renderer/src/views/InstallWizardModal.vue +++ b/src/renderer/src/views/InstallWizardModal.vue @@ -8,6 +8,7 @@ import { HardDrive, CircleAlert, RefreshCw } from 'lucide-vue-next' import Button from '@comfyorg/design-system/button/Button' import { useModal } from '../composables/useModal' import { useAuthStore } from '../stores/authStore' +import { useDashboardScopeStore } from '../stores/dashboardScopeStore' import type { InstallBuildResult, @@ -591,6 +592,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 { @@ -611,6 +613,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) @@ -1281,8 +1288,8 @@ defineExpose({ open }) class="workspace-build-refresh" :title="$t('newInstall.refreshWorkspaceBuilds')" :aria-label="$t('newInstall.refreshWorkspaceBuilds')" - :disabled="authStore.loadingBuilds" - @click="authStore.fetchBuilds()" + :disabled="authStore.loadingBuilds || authorizingWorkspace" + @click="refreshManagedBuilds" > {{ $t('devPlatform.build.loadError') }} diff --git a/src/shared/datadogMirroredEvents.test.ts b/src/shared/datadogMirroredEvents.test.ts index 4094abb8f..1d2971bbb 100644 --- a/src/shared/datadogMirroredEvents.test.ts +++ b/src/shared/datadogMirroredEvents.test.ts @@ -19,6 +19,13 @@ 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.mint_scope_not_granted')).toBe(true) + expect(isDatadogMirroredEvent('comfy.desktop.auth.workspace_switch')).toBe(false) + }) + it('mirrors install.not_started but not install.dispatched', () => { expect(isDatadogMirroredEvent('comfy.desktop.install.not_started')).toBe(true) expect(isDatadogMirroredEvent('comfy.desktop.install.dispatched')).toBe(false) diff --git a/src/shared/datadogMirroredEvents.ts b/src/shared/datadogMirroredEvents.ts index 7a5b63eba..7dd45fe03 100644 --- a/src/shared/datadogMirroredEvents.ts +++ b/src/shared/datadogMirroredEvents.ts @@ -1,5 +1,8 @@ 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', 'comfy.desktop.execution.error', 'comfy.desktop.comfyui.exited', diff --git a/src/types/comfyDesktopBridge.ts b/src/types/comfyDesktopBridge.ts index 814dc904e..e33e162b4 100644 --- a/src/types/comfyDesktopBridge.ts +++ b/src/types/comfyDesktopBridge.ts @@ -134,8 +134,12 @@ 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` and resolves with the resulting + * 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/ipc.ts b/src/types/ipc.ts index 94bad0340..cd7bdbcea 100644 --- a/src/types/ipc.ts +++ b/src/types/ipc.ts @@ -2,8 +2,20 @@ import type { FirstUseMode } from '../shared/firstUseMode' import type { GpuTier } from '../shared/gpuTier' export type { FirstUseMode } -import type { AuthStatus, Workspace } from '../main/cloud/types' -export type { AuthStatus, Workspace } +import type { + AuthStatus, + Workspace, + WorkspaceSwitchFailure, + WorkspaceSwitchIntent, + WorkspaceSwitchStatus +} from '../main/cloud/types' +export type { + AuthStatus, + Workspace, + WorkspaceSwitchFailure, + WorkspaceSwitchIntent, + WorkspaceSwitchStatus +} import type { BetaActivationNotice } from '../main/lib/betaActivationNotice' export type { BetaActivationNotice } @@ -1232,7 +1244,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