diff --git a/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts b/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts index b853e6dd4..b7de71f2b 100644 --- a/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts +++ b/packages/comfyui-desktop-bridge-types/comfyDesktopBridge.d.ts @@ -130,6 +130,10 @@ export interface ComfyDesktop2AuthBridge { * is scoped to; null when signed out, disabled, or the scope is missing, * malformed or different. The refresh token never leaves Desktop. */ getWorkspaceToken(workspaceId: string): Promise + /** The partner-node token for prompts in `workspaceId`, under the same rules + * as `getWorkspaceToken`. Desktop mints and renews it; null means use the + * workspace token. Absent on Desktop builds before it. */ + getPartnerNodeToken?(workspaceId: string): Promise /** Runs Desktop's browser sign-in and resolves with the resulting state. */ requestSignIn(): Promise /** Signs Desktop out of its account (every view follows) and resolves with diff --git a/packages/comfyui-desktop-bridge-types/package.json b/packages/comfyui-desktop-bridge-types/package.json index 79cc36c65..ad59ecade 100644 --- a/packages/comfyui-desktop-bridge-types/package.json +++ b/packages/comfyui-desktop-bridge-types/package.json @@ -1,6 +1,6 @@ { "name": "@comfyorg/comfyui-desktop-bridge-types", - "version": "0.6.1", + "version": "0.7.0", "description": "TypeScript definitions for the Comfy Desktop hosted frontend bridge", "type": "module", "main": "./index.js", diff --git a/src/main/cloud/claims.ts b/src/main/cloud/claims.ts index 92b7bcd61..933bb0838 100644 --- a/src/main/cloud/claims.ts +++ b/src/main/cloud/claims.ts @@ -10,6 +10,7 @@ interface AccessTokenClaims { workspace_type?: string role?: string scope?: string + fam?: unknown iat?: unknown exp?: unknown } @@ -53,6 +54,11 @@ export function lifetimeSecondsOf(accessToken: string): number | null { return Number.isFinite(lifetime) ? lifetime : null } +export function grantFamilyOf(accessToken: string): string | null { + const fam = decodeJwtPayload(accessToken)?.fam + return typeof fam === 'string' ? fam : null +} + export function subjectOf(accessToken: string): string | null { return decodeJwtPayload(accessToken)?.sub ?? null } diff --git a/src/main/cloud/config.ts b/src/main/cloud/config.ts index 9a587a1a0..fa141374e 100644 --- a/src/main/cloud/config.ts +++ b/src/main/cloud/config.ts @@ -5,6 +5,8 @@ export const CLOUD_REFRESH_TOKEN_LIFETIME_MS = 720 * 60 * 60_000 export const WORKSPACE_MINT_SCOPE = 'comfy-cloud:workspace-token:mint' +export const PARTNER_NODE_MINT_SCOPE = 'comfy-cloud:jobs:write' + export const CLOUD_ISSUER = process.env.COMFY_CLOUD_ISSUER || DEFAULT_ISSUER export function revokeUrlOf(issuer: string): string { @@ -19,7 +21,7 @@ export const CLOUD_CONFIG = { jwksUrl: `${CLOUD_ISSUER}/.well-known/jwks.json`, apiBase: `${CLOUD_ISSUER}/api`, clientId: process.env.COMFY_CLOUD_CLIENT_ID || DEFAULT_CLIENT_ID, - scope: `comfy-cloud:user:read ${WORKSPACE_MINT_SCOPE}`, + scope: `comfy-cloud:user:read ${PARTNER_NODE_MINT_SCOPE} ${WORKSPACE_MINT_SCOPE}`, resource: `${CLOUD_ISSUER}/api`, audience: 'comfy-cloud' } as const diff --git a/src/main/cloud/oauth.test.ts b/src/main/cloud/oauth.test.ts index bc4775ad4..af537bfd2 100644 --- a/src/main/cloud/oauth.test.ts +++ b/src/main/cloud/oauth.test.ts @@ -197,6 +197,30 @@ describe('oauth.signIn', () => { expect(status.signedIn).toBe(true) }) + it('asks for the partner-node and workspace mint scopes by default', async () => { + stub(200, { access_token: 'tok', refresh_token: 'r1', expires_in: 3600 }) + let requested: string[] = [] + vi.mocked(shell.openExternal).mockImplementation(async (authorizeUrl: string) => { + const u = new URL(authorizeUrl) + requested = (u.searchParams.get('scope') ?? '').split(' ') + get( + `${u.searchParams.get('redirect_uri')}?code=abc&state=${u.searchParams.get('state')}`, + (res) => res.resume() + ) + }) + const { scope: _scope, ...defaults } = opts + + await signIn({ ...defaults, timeoutMs: 5000 }) + + expect(requested).toEqual( + expect.arrayContaining([ + 'comfy-cloud:user:read', + 'comfy-cloud:jobs:write', + 'comfy-cloud:workspace-token:mint' + ]) + ) + }) + it('rejects on the callback timeout even when openExternal never settles', async () => { stub(200, {}) vi.mocked(shell.openExternal).mockImplementation(() => new Promise(() => {})) diff --git a/src/main/cloud/session.ts b/src/main/cloud/session.ts index a7e4563f5..40b355e0e 100644 --- a/src/main/cloud/session.ts +++ b/src/main/cloud/session.ts @@ -1,7 +1,7 @@ import type { TokenProvider } from '../comfybuilder' import * as mainTelemetry from '../lib/telemetry' import { isWorkspaceMintSwitchEnabled } from '../lib/workspaceMintSwitchFlag' -import { canMintWorkspaceTokens, subjectOf, workspaceIdOf } from './claims' +import { canMintWorkspaceTokens, grantFamilyOf, subjectOf, workspaceIdOf } from './claims' import { CLOUD_CONFIG } from './config' import { openAuthorizePage, refresh, signIn } from './oauth' import { Revocations } from './revocation' @@ -219,6 +219,11 @@ export class CloudSession { return grant ? subjectOf(grant.accessToken) : null } + currentGrantFamily(): string | null { + const grant = loadGrant() + return grant ? grantFamilyOf(grant.accessToken) : null + } + currentWorkspaceId(): string | null { return loadActiveWorkspaceId() } diff --git a/src/main/cloud/workspaceToken.test.ts b/src/main/cloud/workspaceToken.test.ts index 0260fc2fe..2428d9e8d 100644 --- a/src/main/cloud/workspaceToken.test.ts +++ b/src/main/cloud/workspaceToken.test.ts @@ -1,7 +1,12 @@ // @vitest-environment node import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { classifyMint, mintWorkspaceToken } from './workspaceToken' +import { + classifyMint, + mintPartnerNodeToken, + mintWorkspaceToken, + renewPartnerNodeToken +} from './workspaceToken' import type { WorkspaceTokenMint } from './workspaceToken' function respond(status: number, body: unknown, headers: Record = {}): void { @@ -99,6 +104,51 @@ describe('mintWorkspaceToken', () => { }) }) +describe('partner-node tokens', () => { + it('mints with the access token, naming the workspace and the partner-node resource', async () => { + const expiresAt = new Date(Date.now() + 90 * 60_000).toISOString() + respond(200, { token: 'partner-jwt', expires_at: expiresAt }) + + await expect( + mintPartnerNodeToken('oauth-access', 'ws-2', { apiBase: 'https://cloud.test/api' }) + ).resolves.toEqual({ kind: 'minted', token: 'partner-jwt', expiresAt: Date.parse(expiresAt) }) + expect(fetch).toHaveBeenCalledWith( + 'https://cloud.test/api/auth/token', + expect.objectContaining({ + method: 'POST', + headers: expect.objectContaining({ Authorization: 'Bearer oauth-access' }), + body: JSON.stringify({ workspace_id: 'ws-2', resource: 'partner-node' }) + }) + ) + }) + + it('renews with the partner-node token as Bearer and no body', async () => { + const expiresAt = new Date(Date.now() + 90 * 60_000).toISOString() + respond(200, { token: 'renewed-jwt', expires_at: expiresAt }) + + await expect( + renewPartnerNodeToken('partner-jwt', { apiBase: 'https://cloud.test/api' }) + ).resolves.toEqual({ kind: 'minted', token: 'renewed-jwt', expiresAt: Date.parse(expiresAt) }) + const [url, init] = vi.mocked(fetch).mock.calls[0] ?? [] + expect(url).toBe('https://cloud.test/api/auth/partner-node/renew') + expect(init).toMatchObject({ + method: 'POST', + headers: { Authorization: 'Bearer partner-jwt' } + }) + expect(init?.body).toBeUndefined() + }) + + it('carries a refused renewal code', async () => { + respond(403, { code: 'partner_node_session_ended', message: 'ended' }) + + await expect(renewPartnerNodeToken('partner-jwt')).resolves.toEqual({ + kind: 'failed', + status: 403, + code: 'partner_node_session_ended' + }) + }) +}) + describe('mintWorkspaceToken and the local clock', () => { const SERVER_NOW_MS = Date.parse('2026-11-08T12:00:00Z') const SERVER_NOW = SERVER_NOW_MS / 1000 diff --git a/src/main/cloud/workspaceToken.ts b/src/main/cloud/workspaceToken.ts index ebfc6890a..f8ef33271 100644 --- a/src/main/cloud/workspaceToken.ts +++ b/src/main/cloud/workspaceToken.ts @@ -84,31 +84,60 @@ function mintedFrom(body: unknown, requestedAt: number): WorkspaceTokenMint | nu return expiresAtMs > Date.now() ? { kind: 'minted', token, expiresAt: expiresAtMs } : null } -export async function mintWorkspaceToken( +export function mintWorkspaceToken( accessToken: string, workspaceId: string, options: MintWorkspaceTokenOptions = {} +): Promise { + return postForToken('/auth/token', accessToken, { workspace_id: workspaceId }, options) +} + +export function mintPartnerNodeToken( + accessToken: string, + workspaceId: string, + options: MintWorkspaceTokenOptions = {} +): Promise { + return postForToken( + '/auth/token', + accessToken, + { workspace_id: workspaceId, resource: 'partner-node' }, + options + ) +} + +export function renewPartnerNodeToken( + partnerNodeToken: string, + options: MintWorkspaceTokenOptions = {} +): Promise { + return postForToken('/auth/partner-node/renew', partnerNodeToken, undefined, options) +} + +async function postForToken( + route: string, + bearer: string, + body: Record | undefined, + options: MintWorkspaceTokenOptions ): Promise { const base = (options.apiBase ?? CLOUD_CONFIG.apiBase).replace(/\/+$/, '') const requestedAt = Date.now() let res: Response try { - res = await fetch(`${base}/auth/token`, { + res = await fetch(`${base}${route}`, { method: 'POST', headers: { Accept: 'application/json', - 'Content-Type': 'application/json', - Authorization: `Bearer ${accessToken}` + ...(body ? { 'Content-Type': 'application/json' } : {}), + Authorization: `Bearer ${bearer}` }, - body: JSON.stringify({ workspace_id: workspaceId }), + ...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS) }) } catch { return { kind: 'failed', status: null } } - const body: unknown = await res.json().catch(() => null) - if (res.ok) return mintedFrom(body, requestedAt) ?? { kind: 'failed', status: res.status } - const code = errorCodeOf(body) + const reply: unknown = await res.json().catch(() => null) + if (res.ok) return mintedFrom(reply, requestedAt) ?? { kind: 'failed', status: res.status } + const code = errorCodeOf(reply) const retryAfterSeconds = retryAfterSecondsOf(res) return { kind: 'failed', diff --git a/src/main/lib/embeddedSession.test.ts b/src/main/lib/embeddedSession.test.ts index 569d226d9..0b3b19e12 100644 --- a/src/main/lib/embeddedSession.test.ts +++ b/src/main/lib/embeddedSession.test.ts @@ -4,14 +4,17 @@ import type * as WorkspaceTokenModule from '../cloud/workspaceToken' const mocks = vi.hoisted(() => ({ enabled: true, + generation: 0, + flagRead: null as Promise | null, getGrantAccessToken: vi.fn<() => Promise>(), mint: vi.fn(), + partnerMint: vi.fn(), current: 'ws-1', entries: [] as unknown[] })) vi.mock('./embeddedSessionFlag', () => ({ - isEmbeddedSessionEnabled: async () => mocks.enabled + isEmbeddedSessionEnabled: async () => (mocks.flagRead ? mocks.flagRead : mocks.enabled) })) vi.mock('../devplatform/session', () => ({ getCloudSession: () => ({ @@ -19,7 +22,8 @@ vi.mock('../devplatform/session', () => ({ heldWorkspaceToken: () => null, currentWorkspaceId: () => mocks.current, currentSubject: () => (mocks.current ? 'user-1' : null), - currentAuthGeneration: () => 0, + currentGrantFamily: () => null, + currentAuthGeneration: () => mocks.generation, isWorkspaceMintAllowed: async () => true, endGrantFamily: () => {} }), @@ -27,7 +31,9 @@ vi.mock('../devplatform/session', () => ({ })) vi.mock('../cloud/workspaceToken', async (importOriginal) => ({ ...(await importOriginal()), - mintWorkspaceToken: mocks.mint + mintWorkspaceToken: mocks.mint, + mintPartnerNodeToken: mocks.partnerMint, + renewPartnerNodeToken: vi.fn() })) vi.mock('../host/registry', () => ({ get comfyWindows() { @@ -41,6 +47,7 @@ vi.mock('../host/registry', () => ({ import { EMBEDDED_SESSION_CHANNELS, + partnerNodeTokenForSender, workspaceTokenForSender, broadcastEmbeddedSessionChanged, stateForSender, @@ -62,6 +69,10 @@ function mintedFor(workspaceId: string): string { const MINTED = mintedFor('ws-1') +function partnerNodeFor(workspaceId: string): string { + return jwt({ sub: 'user-1', workspace_id: workspaceId, aud: 'comfy-partner-node', sid: 's-1' }) +} + interface ViewOptions { frameUrl?: string installationId?: string | null @@ -89,6 +100,8 @@ function view(comfyUrl: string, options: ViewOptions = {}) { beforeEach(() => { mocks.enabled = true + mocks.generation = 0 + mocks.flagRead = null mocks.entries = [] mocks.getGrantAccessToken.mockReset().mockResolvedValue(ACCESS) mocks.mint.mockReset().mockImplementation(async (_grant: string, workspaceId: string) => ({ @@ -96,6 +109,11 @@ beforeEach(() => { token: mintedFor(workspaceId), expiresAt: Date.now() + 900_000 })) + mocks.partnerMint.mockReset().mockImplementation(async (_grant: string, workspaceId: string) => ({ + kind: 'minted', + token: partnerNodeFor(workspaceId), + expiresAt: Date.now() + 90 * 60_000 + })) mocks.current = 'ws-1' resetViewGrants() }) @@ -115,6 +133,7 @@ describe('embeddedSession', () => { workspaceId: 'ws-1' }) await expect(workspaceTokenForSender(event, 'ws-1')).resolves.toBe(MINTED) + await expect(partnerNodeTokenForSender(event, 'ws-1')).resolves.toBe(partnerNodeFor('ws-1')) }) it.each([ @@ -128,9 +147,57 @@ describe('embeddedSession', () => { await expect(stateForSender(event)).resolves.toEqual({ status: 'disabled' }) await expect(workspaceTokenForSender(event, 'ws-1')).resolves.toBeNull() + await expect(partnerNodeTokenForSender(event, 'ws-1')).resolves.toBeNull() + expect(mocks.getGrantAccessToken).not.toHaveBeenCalled() + }) + + it.each([ + ['its own workspace', 'ws-1', partnerNodeFor('ws-1')], + ['no workspace', undefined, null], + ['an empty workspace', '', null], + ['another workspace', 'ws-2', null], + ['a non-string workspace', 42, null] + ])( + 'releases the partner-node token for %s only on an exact match', + async (_name, workspaceId, expected) => { + const { event } = view('http://127.0.0.1:8000') + + await expect(partnerNodeTokenForSender(event, workspaceId)).resolves.toBe(expected) + } + ) + + it.each([ + ['workspace', workspaceTokenForSender], + ['partner-node', partnerNodeTokenForSender] + ])('drops a %s token request whose flag read spans a sign-in', async (_name, tokenForSender) => { + let release: (enabled: boolean) => void = () => {} + mocks.flagRead = new Promise((resolve) => { + release = resolve + }) + const { event } = view('http://127.0.0.1:8000') + const pending = tokenForSender(event, 'ws-1') + mocks.generation += 1 + release(true) + + await expect(pending).resolves.toBeNull() expect(mocks.getGrantAccessToken).not.toHaveBeenCalled() }) + it('T-V6: hands a view switched to B a partner-node token for B, and a bystander none', async () => { + const switcher = view('http://127.0.0.1:8000') + const bystander = view('http://127.0.0.1:8001') + await switchWorkspaceForSender(switcher.event, 'ws-2', async () => { + mocks.current = 'ws-2' + return { status: { signedIn: true, workspaceId: 'ws-2' }, reached: true } + }) + + await expect(partnerNodeTokenForSender(switcher.event, 'ws-2')).resolves.toBe( + partnerNodeFor('ws-2') + ) + await expect(partnerNodeTokenForSender(bystander.event, 'ws-2')).resolves.toBeNull() + expect(mocks.partnerMint).toHaveBeenCalledExactlyOnceWith(ACCESS, 'ws-2') + }) + it.each([ ['its own workspace', 'ws-1', MINTED], ['no workspace', undefined, null], @@ -236,6 +303,7 @@ describe('embeddedSession', () => { await expect(stateForSender(event)).resolves.toEqual({ status: 'disabled' }) await expect(workspaceTokenForSender(event, 'ws-1')).resolves.toBeNull() + await expect(partnerNodeTokenForSender(event, 'ws-1')).resolves.toBeNull() expect(mocks.getGrantAccessToken).not.toHaveBeenCalled() }) diff --git a/src/main/lib/embeddedSession.ts b/src/main/lib/embeddedSession.ts index 02ce151fa..358ccd562 100644 --- a/src/main/lib/embeddedSession.ts +++ b/src/main/lib/embeddedSession.ts @@ -12,6 +12,7 @@ import { getViewWorkspaceGrants } from './viewWorkspaceGrants' export const EMBEDDED_SESSION_CHANNELS = { getState: 'desktop2-auth:get-state', getWorkspaceToken: 'desktop2-auth:get-workspace-token', + getPartnerNodeToken: 'desktop2-auth:get-partner-node-token', requestSignIn: 'desktop2-auth:request-sign-in', signOut: 'desktop2-auth:sign-out', switchWorkspace: 'desktop2-auth:switch-workspace', @@ -88,8 +89,21 @@ export async function workspaceTokenForSender( workspaceId: unknown ): Promise { if (typeof workspaceId !== 'string' || workspaceId === '') return null - if (!isTrustedSender(event) || !(await isEmbeddedSessionEnabled())) return null - return getViewWorkspaceGrants().tokenFor(event.sender, workspaceId) + if (!isTrustedSender(event)) return null + return getViewWorkspaceGrants().tokenFor(event.sender, workspaceId, isEmbeddedSessionEnabled) +} + +export async function partnerNodeTokenForSender( + event: EmbeddedSessionSender, + workspaceId: unknown +): Promise { + if (typeof workspaceId !== 'string' || workspaceId === '') return null + if (!isTrustedSender(event)) return null + return getViewWorkspaceGrants().partnerNodeTokenFor( + event.sender, + workspaceId, + isEmbeddedSessionEnabled + ) } export async function switchWorkspaceForSender( diff --git a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts index 3bbac5350..77cad6b79 100644 --- a/src/main/lib/ipc/registerDevPlatformHandlers.test.ts +++ b/src/main/lib/ipc/registerDevPlatformHandlers.test.ts @@ -574,6 +574,7 @@ describe('registerDevPlatformHandlers', () => { { currentWorkspaceId: active, currentSubject: () => 'user-1', + currentGrantFamily: () => null, currentAuthGeneration: () => 1, getGrantAccessToken: async () => jwt({ sub: 'user-1', workspace_id: 'w1', scope: CLOUD_CONFIG.scope }), @@ -670,6 +671,7 @@ describe('registerDevPlatformHandlers', () => { { currentWorkspaceId: () => auth.active, currentSubject: () => auth.subject, + currentGrantFamily: () => null, currentAuthGeneration: () => auth.generation, getGrantAccessToken: async () => auth.subject @@ -852,6 +854,7 @@ describe('registerDevPlatformHandlers', () => { { currentWorkspaceId: () => active, currentSubject: () => subject, + currentGrantFamily: () => null, currentAuthGeneration: () => generation, getGrantAccessToken: async () => jwt({ sub: subject, workspace_id: 'home', scope: CLOUD_CONFIG.scope }), diff --git a/src/main/lib/ipc/registerEmbeddedSessionHandlers.test.ts b/src/main/lib/ipc/registerEmbeddedSessionHandlers.test.ts index f74c855fc..c0eecee58 100644 --- a/src/main/lib/ipc/registerEmbeddedSessionHandlers.test.ts +++ b/src/main/lib/ipc/registerEmbeddedSessionHandlers.test.ts @@ -22,10 +22,12 @@ vi.mock('../embeddedSession', () => ({ EMBEDDED_SESSION_CHANNELS: { getState: 'desktop2-auth:get-state', getWorkspaceToken: 'desktop2-auth:get-workspace-token', + getPartnerNodeToken: 'desktop2-auth:get-partner-node-token', requestSignIn: 'desktop2-auth:request-sign-in', signOut: 'desktop2-auth:sign-out', switchWorkspace: 'desktop2-auth:switch-workspace' }, + partnerNodeTokenForSender: vi.fn(), stateForSender: mocks.stateForSender, switchWorkspaceForSender: mocks.switchWorkspaceForSender, workspaceTokenForSender: vi.fn() diff --git a/src/main/lib/ipc/registerEmbeddedSessionHandlers.ts b/src/main/lib/ipc/registerEmbeddedSessionHandlers.ts index e6d09f60f..8aee57fc0 100644 --- a/src/main/lib/ipc/registerEmbeddedSessionHandlers.ts +++ b/src/main/lib/ipc/registerEmbeddedSessionHandlers.ts @@ -4,6 +4,7 @@ import { findEntryByComfySender } from '../../host/registry' import type { ComfyDesktop2AuthState } from '../../../types/comfyDesktopBridge' import { EMBEDDED_SESSION_CHANNELS, + partnerNodeTokenForSender, stateForSender, switchWorkspaceForSender, workspaceTokenForSender @@ -18,6 +19,10 @@ export function registerEmbeddedSessionHandlers(): void { workspaceTokenForSender(event, workspaceId) ) + ipcMain.handle(EMBEDDED_SESSION_CHANNELS.getPartnerNodeToken, (event, workspaceId: unknown) => + partnerNodeTokenForSender(event, workspaceId) + ) + ipcMain.handle( EMBEDDED_SESSION_CHANNELS.requestSignIn, async (event): Promise => { diff --git a/src/main/lib/viewWorkspaceGrants.session.test.ts b/src/main/lib/viewWorkspaceGrants.session.test.ts index be4bdba35..991f878c3 100644 --- a/src/main/lib/viewWorkspaceGrants.session.test.ts +++ b/src/main/lib/viewWorkspaceGrants.session.test.ts @@ -247,6 +247,19 @@ describe('view token path through a real session', () => { expect(openAuthorizePage).not.toHaveBeenCalled() }) + it('a partner-node mint told the grant ended never lets the grant be refreshed', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + mintReply = () => new Response(JSON.stringify({ code: 'oauth_grant_ended' }), { status: 401 }) + + await expect(grants.partnerNodeTokenFor(view, 'w1')).resolves.toBeNull() + vi.setSystemTime(GRANT.expiresAt + 1) + await expect(grants.partnerNodeTokenFor(view, 'w1')).resolves.toBeNull() + + expect(refresh).not.toHaveBeenCalled() + expect(signIn).not.toHaveBeenCalled() + expect(openAuthorizePage).not.toHaveBeenCalled() + }) + it('a server kill refuses a view mint with no browser', async () => { await activeOnW2() mintReply = () => @@ -274,4 +287,35 @@ describe('view token path through a real session', () => { await expect(pending).resolves.toBeNull() expect(mintRequests).toEqual([]) }) + + it('keeps the partner-node session across a refresh and starts a new one after a new sign-in', async () => { + const grantIn = (family: string): AuthTokens => ({ + ...GRANT, + accessToken: jwt({ + sub: 'user-1', + workspace_id: 'w1', + scope: CLOUD_CONFIG.scope, + fam: family + }) + }) + mintReply = (workspaceId) => + new Response( + JSON.stringify({ + token: mintedJwt(workspaceId), + expires_at: new Date(Date.now() + 90 * 60_000).toISOString() + }), + { status: 200 } + ) + saveGrant(grantIn('fam-1')) + await grants.partnerNodeTokenFor(view, 'w1') + saveGrant({ ...grantIn('fam-1'), refreshToken: 'refreshed' }) + await grants.partnerNodeTokenFor(view, 'w1') + expect(mintRequests).toEqual(['w1']) + + saveGrant(grantIn('fam-2')) + + await expect(grants.partnerNodeTokenFor(view, 'w1')).resolves.toBe(mintedJwt('w1')) + expect(mintRequests).toEqual(['w1', 'w1']) + expect(session.currentGrantFamily()).toBe('fam-2') + }) }) diff --git a/src/main/lib/viewWorkspaceGrants.test.ts b/src/main/lib/viewWorkspaceGrants.test.ts index ae816d1ac..860b06861 100644 --- a/src/main/lib/viewWorkspaceGrants.test.ts +++ b/src/main/lib/viewWorkspaceGrants.test.ts @@ -2,7 +2,7 @@ import { Buffer } from 'node:buffer' import type { WebContents } from 'electron' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' vi.mock('../devplatform/session', () => ({ getCloudSession: () => ({}), @@ -10,7 +10,7 @@ vi.mock('../devplatform/session', () => ({ })) vi.mock('./telemetry', () => ({ emit: vi.fn() })) -import { CLOUD_CONFIG } from '../cloud/config' +import { CLOUD_CONFIG, WORKSPACE_MINT_SCOPE } from '../cloud/config' import type { WorkspaceTokenMint } from '../cloud/workspaceToken' import * as mainTelemetry from './telemetry' import { @@ -76,6 +76,7 @@ function grantSession( return { currentWorkspaceId: () => current, currentSubject: () => (current ? user : null), + currentGrantFamily: () => null, currentAuthGeneration: () => generation, getGrantAccessToken, heldWorkspaceToken, @@ -363,6 +364,7 @@ describe('ViewWorkspaceGrants', () => { ) const stale = grants.tokenFor(viewA, 'ws-1') const firstUserToken = accessToken('ws-1') + await vi.waitFor(() => expect(reads).toBe(1)) grants.endAll() grants.allowDesktop('ws-1') user = 'user-2' @@ -404,3 +406,552 @@ describe('ViewWorkspaceGrants', () => { expect(mint).toHaveBeenCalledOnce() }) }) + +describe('ViewWorkspaceGrants partner-node tokens', () => { + let partnerMint: ReturnType< + typeof vi.fn<(token: string, workspaceId: string) => Promise> + > + let partnerRenew: ReturnType Promise>> + let mintScopeAllowed: boolean + + function partnerToken(workspaceId: string, session = 'sid-1', round = 0): string { + return jwt({ + sub: user, + workspace_id: workspaceId, + aud: 'comfy-partner-node', + sid: session, + round + }) + } + + function partnerMinted(token: string, lifetimeMs = 90 * 60_000): WorkspaceTokenMint { + return { kind: 'minted', token, expiresAt: Date.now() + lifetimeMs } + } + + function build(scope: string = CLOUD_CONFIG.scope): ViewWorkspaceGrants { + return new ViewWorkspaceGrants( + { + ...grantSession(async () => (current ? accessToken('ws-1', scope) : null)), + isWorkspaceMintAllowed: async () => mintScopeAllowed + }, + mint, + undefined, + { mint: partnerMint, renew: partnerRenew } + ) + } + + beforeEach(() => { + mintScopeAllowed = true + partnerMint = vi.fn(async (_token: string, workspaceId: string) => + partnerMinted(partnerToken(workspaceId)) + ) + partnerRenew = vi.fn(async () => partnerMinted(partnerToken('ws-1', 'sid-1', 1))) + grants = build() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('T-V7: hands the view a partner-node token minted from the grant, never the grant or the workspace token', async () => { + const token = await grants.partnerNodeTokenFor(viewA, 'ws-1') + + expect(token).toBe(partnerToken('ws-1')) + expect(token).not.toBe(accessToken('ws-1')) + expect(token).not.toBe(mintedToken('ws-1')) + expect(partnerMint).toHaveBeenCalledExactlyOnceWith(accessToken('ws-1'), 'ws-1') + expect(mint).not.toHaveBeenCalled() + }) + + it('T-V6: a view switched to B gets a partner-node token for B, and a view that did not switch gets none', async () => { + await grants.partnerNodeTokenFor(viewA, 'ws-1') + grants.allowView(viewA, 'ws-2') + signInAt('ws-2') + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-2')).resolves.toBe(partnerToken('ws-2')) + await expect(grants.partnerNodeTokenFor(viewB, 'ws-2')).resolves.toBeNull() + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() + expect(partnerMint).toHaveBeenLastCalledWith(accessToken('ws-1'), 'ws-2') + }) + + it('mints once for concurrent requests and reuses the token while it has over an hour left', async () => { + await Promise.all([ + grants.partnerNodeTokenFor(viewA, 'ws-1'), + grants.partnerNodeTokenFor(viewB, 'ws-1') + ]) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + + expect(partnerMint).toHaveBeenCalledOnce() + expect(partnerRenew).not.toHaveBeenCalled() + }) + + it('renews in the same session before expiry and hands the view only the renewed token', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe( + partnerToken('ws-1', 'sid-1', 1) + ) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + + expect(partnerRenew).toHaveBeenCalledExactlyOnceWith(partnerToken('ws-1')) + expect(partnerMint).toHaveBeenCalledOnce() + }) + + it.each<[string, () => WorkspaceTokenMint]>([ + [ + 'a session that ended', + () => ({ kind: 'failed', status: 403, code: 'partner_node_session_ended' }) + ], + [ + 'a revoked session', + () => ({ kind: 'failed', status: 403, code: 'partner_node_session_revoked' }) + ], + ['an unknown session', () => ({ kind: 'failed', status: 401 })], + [ + 'a session in its last hour', + () => partnerMinted(partnerToken('ws-1', 'sid-1', 1), 20 * 60_000) + ] + ])('starts a new session after %s', async (_name, renewal) => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + partnerRenew.mockResolvedValueOnce(renewal()) + partnerMint.mockResolvedValueOnce(partnerMinted(partnerToken('ws-1', 'sid-2'))) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe( + partnerToken('ws-1', 'sid-2') + ) + expect(partnerMint).toHaveBeenCalledTimes(2) + }) + + it('drops the held token when its session was refused and no new session could start', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + partnerRenew.mockResolvedValueOnce({ + kind: 'failed', + status: 403, + code: 'partner_node_session_ended' + }) + partnerMint.mockResolvedValueOnce({ kind: 'failed', status: 401, code: 'oauth_grant_ended' }) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() + }) + + it.each<[string, number | null]>([ + ['a network error', null], + ['a rate limit', 429], + ['a server error', 503] + ])( + 'hands out nothing when the session was refused and the new mint met %s', + async (_name, status) => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + partnerRenew.mockResolvedValueOnce({ + kind: 'failed', + status: 403, + code: 'partner_node_session_revoked' + }) + partnerMint.mockResolvedValueOnce({ kind: 'failed', status }) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() + } + ) + + it.each<[string, number | null]>([ + ['a rate limit', 429], + ['a server error', 500], + ['a network error', null] + ])('keeps handing out the current token after %s on renewal', async (_name, status) => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + partnerRenew.mockResolvedValueOnce({ kind: 'failed', status }) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe(partnerToken('ws-1')) + expect(partnerMint).toHaveBeenCalledOnce() + }) + + it.each<[string, WorkspaceTokenMint]>([ + ['the mint switched off', { kind: 'failed', status: 503, code: 'partner_node_token_disabled' }], + ['a client not allowed', { kind: 'failed', status: 403, code: 'oauth_token_mint_refused' }], + ['a grant without jobs:write', { kind: 'failed', status: 403, code: 'insufficient_scope' }], + ['a network error', { kind: 'failed', status: null }] + ])( + 'hands out nothing after %s, so the view keeps the workspace token', + async (_name, refusal) => { + partnerMint.mockResolvedValueOnce(refusal) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe(mintedToken('ws-1')) + } + ) + + it.each([ + ['from before jobs:write', `comfy-cloud:user:read ${WORKSPACE_MINT_SCOPE}`], + ['from before the mint scope', 'comfy-cloud:user:read'] + ])('asks Cloud with a grant %s and hands out the token it mints', async (_name, scope) => { + grants = build(scope) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe(partnerToken('ws-1')) + expect(partnerMint).toHaveBeenCalledExactlyOnceWith(accessToken('ws-1', scope), 'ws-1') + }) + + it('hands out nothing for another workspace while the mint switch is off', async () => { + mintScopeAllowed = false + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() + expect(partnerMint).not.toHaveBeenCalled() + }) + + it.each<[string, () => string]>([ + ['another workspace', () => partnerToken('ws-9')], + ['another account', () => jwt({ sub: 'user-9', workspace_id: 'ws-1', sid: 'sid-1' })] + ])('refuses a partner-node token minted for %s', async (_name, token) => { + partnerMint.mockResolvedValueOnce(partnerMinted(token())) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() + }) + + it('T-V27: drops a mint reply that lands after a switch to B', async () => { + const reply = deferred() + partnerMint.mockReturnValueOnce(reply.promise) + const pending = grants.partnerNodeTokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(partnerMint).toHaveBeenCalledOnce()) + grants.allowView(viewA, 'ws-2') + signInAt('ws-2') + reply.resolve(partnerMinted(partnerToken('ws-1'))) + + await expect(pending).resolves.toBeNull() + }) + + it('T-V27: drops a mint reply that lands after sign-out, and does not keep its token', async () => { + const reply = deferred() + partnerMint.mockReturnValueOnce(reply.promise) + const pending = grants.partnerNodeTokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(partnerMint).toHaveBeenCalledOnce()) + signInAt(null) + grants.endAll() + reply.resolve(partnerMinted(partnerToken('ws-1', 'stale'))) + + await expect(pending).resolves.toBeNull() + signInAt('ws-1') + grants.allowDesktop('ws-1') + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe(partnerToken('ws-1')) + expect(partnerMint).toHaveBeenCalledTimes(2) + }) + + it('T-V28: drops a renewal that lands after sign-out, and does not renew a token from before it', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + const renewal = deferred() + partnerRenew.mockReturnValueOnce(renewal.promise) + const pending = grants.partnerNodeTokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(partnerRenew).toHaveBeenCalledOnce()) + signInAt(null) + grants.endAll() + renewal.resolve(partnerMinted(partnerToken('ws-1', 'sid-1', 1))) + + await expect(pending).resolves.toBeNull() + signInAt('ws-1') + grants.allowDesktop('ws-1') + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe(partnerToken('ws-1')) + expect(partnerRenew).toHaveBeenCalledOnce() + }) + + it('does not ask Cloud again until Retry-After passes after a rate-limited renewal', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + partnerRenew.mockResolvedValueOnce({ kind: 'failed', status: 429, retryAfterSeconds: 120 }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 90_000) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe(partnerToken('ws-1')) + expect(partnerRenew).toHaveBeenCalledOnce() + + vi.setSystemTime(Date.now() + 31_000) + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe( + partnerToken('ws-1', 'sid-1', 1) + ) + expect(partnerRenew).toHaveBeenCalledTimes(2) + }) + + it('asks Cloud again after five minutes however long Retry-After is', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + partnerRenew.mockResolvedValueOnce({ kind: 'failed', status: 429, retryAfterSeconds: 4 * 3600 }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 5 * 60_000 + 1_000) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe( + partnerToken('ws-1', 'sid-1', 1) + ) + expect(partnerRenew).toHaveBeenCalledTimes(2) + }) + + it('does not ask Cloud again for a minute after a refused mint', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + partnerMint.mockResolvedValueOnce({ + kind: 'failed', + status: 503, + code: 'partner_node_token_disabled' + }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() + expect(partnerMint).toHaveBeenCalledOnce() + + vi.setSystemTime(Date.now() + 61_000) + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe(partnerToken('ws-1')) + expect(partnerMint).toHaveBeenCalledTimes(2) + }) + + it.each<[string, WorkspaceTokenMint, string | null]>([ + ['refused', { kind: 'failed', status: 403, code: 'oauth_token_mint_refused' }, null], + ['switched off', { kind: 'failed', status: 503, code: 'partner_node_token_disabled' }, null], + ['unreachable', { kind: 'failed', status: null }, 'held'] + ])( + 'does not hand out a last-hour renewal when the new session is %s', + async (_name, refusal, expected) => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + partnerRenew.mockResolvedValueOnce( + partnerMinted(partnerToken('ws-1', 'sid-1', 1), 20 * 60_000) + ) + partnerMint.mockResolvedValueOnce(refusal) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe( + expected === 'held' ? partnerToken('ws-1') : null + ) + } + ) + + it('does not start a new session for a renewal refused after sign-out', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + const renewal = deferred() + partnerRenew.mockReturnValueOnce(renewal.promise) + const pending = grants.partnerNodeTokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(partnerRenew).toHaveBeenCalledOnce()) + signInAt(null) + grants.endAll() + renewal.resolve({ kind: 'failed', status: 403, code: 'partner_node_session_revoked' }) + + await expect(pending).resolves.toBeNull() + expect(partnerMint).toHaveBeenCalledOnce() + }) + + it('starts a new session when a renewal comes back already expired', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + const renewal = deferred() + partnerRenew.mockReturnValueOnce(renewal.promise) + partnerMint.mockImplementationOnce(async () => partnerMinted(partnerToken('ws-1', 'sid-2'))) + const pending = grants.partnerNodeTokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(partnerRenew).toHaveBeenCalledOnce()) + const renewed = partnerMinted(partnerToken('ws-1', 'sid-1', 1), 70 * 60_000) + vi.setSystemTime(Date.now() + 2 * 60 * 60_000) + renewal.resolve(renewed) + + await expect(pending).resolves.toBe(partnerToken('ws-1', 'sid-2')) + }) + + it('renews a token for A again after A to B to A, and gives B its own session', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + grants.allowView(viewA, 'ws-2') + await grants.partnerNodeTokenFor(viewA, 'ws-1') + signInAt('ws-2') + await expect(grants.partnerNodeTokenFor(viewA, 'ws-2')).resolves.toBe(partnerToken('ws-2')) + signInAt('ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe( + partnerToken('ws-1', 'sid-1', 1) + ) + expect(partnerRenew).toHaveBeenCalledExactlyOnceWith(partnerToken('ws-1')) + expect(partnerMint.mock.calls.map(([, workspaceId]) => workspaceId)).toEqual(['ws-1', 'ws-2']) + }) + + it('starts over after the same account signs in again', async () => { + await grants.partnerNodeTokenFor(viewA, 'ws-1') + grants.endAll() + signInAt('ws-1') + grants.allowDesktop('ws-1') + partnerMint.mockResolvedValueOnce(partnerMinted(partnerToken('ws-1', 'sid-2'))) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe( + partnerToken('ws-1', 'sid-2') + ) + expect(partnerRenew).not.toHaveBeenCalled() + }) + + describe('when a new sign-in replaces the grant for the same account', () => { + let family: string + + beforeEach(() => { + family = 'fam-1' + grants = new ViewWorkspaceGrants( + { + ...grantSession(async () => + jwt({ sub: user, workspace_id: 'ws-1', scope: CLOUD_CONFIG.scope, fam: family }) + ), + currentGrantFamily: () => family + }, + mint, + undefined, + { mint: partnerMint, renew: partnerRenew } + ) + }) + + it('starts a new session instead of reusing the old grant one', async () => { + await grants.partnerNodeTokenFor(viewA, 'ws-1') + family = 'fam-2' + partnerMint.mockResolvedValueOnce(partnerMinted(partnerToken('ws-1', 'sid-2'))) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe( + partnerToken('ws-1', 'sid-2') + ) + expect(partnerMint).toHaveBeenCalledTimes(2) + }) + + it('drops a mint reply from the old grant that lands after the new sign-in', async () => { + const reply = deferred() + partnerMint.mockReturnValueOnce(reply.promise) + const pending = grants.partnerNodeTokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(partnerMint).toHaveBeenCalledOnce()) + family = 'fam-2' + reply.resolve(partnerMinted(partnerToken('ws-1', 'old-grant'))) + + await expect(pending).resolves.toBeNull() + }) + + it('drops a workspace token reply from the old grant that lands after the new sign-in', async () => { + const reply = deferred() + mint.mockReturnValueOnce(reply.promise) + const pending = grants.tokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(mint).toHaveBeenCalledOnce()) + family = 'fam-2' + reply.resolve({ kind: 'minted', token: staleToken('ws-1'), expiresAt: Date.now() + 900_000 }) + + await expect(pending).resolves.toBeNull() + await expect(grants.tokenFor(viewA, 'ws-1')).resolves.toBe(mintedToken('ws-1')) + }) + }) + + it('forgets a token whose renewal was refused after a switch, so A to B to A does not hand it out', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + grants.allowView(viewA, 'ws-2') + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + const renewal = deferred() + partnerRenew.mockReturnValueOnce(renewal.promise) + const pending = grants.partnerNodeTokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(partnerRenew).toHaveBeenCalledOnce()) + signInAt('ws-2') + renewal.resolve({ kind: 'failed', status: 403, code: 'partner_node_session_revoked' }) + await expect(pending).resolves.toBeNull() + signInAt('ws-1') + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() + expect(partnerRenew).toHaveBeenCalledOnce() + expect(partnerMint).toHaveBeenCalledOnce() + }) + + it('keeps the Retry-After of a renewal that lands after a switch, once back on A', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + grants.allowView(viewA, 'ws-2') + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + const renewal = deferred() + partnerRenew.mockReturnValueOnce(renewal.promise) + const pending = grants.partnerNodeTokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(partnerRenew).toHaveBeenCalledOnce()) + signInAt('ws-2') + renewal.resolve({ kind: 'failed', status: 429, retryAfterSeconds: 120 }) + await expect(pending).resolves.toBeNull() + signInAt('ws-1') + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe(partnerToken('ws-1')) + expect(partnerRenew).toHaveBeenCalledOnce() + }) + + it('forgets the held token when a new session is refused after a switch, once back on A', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + grants.allowView(viewA, 'ws-2') + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + partnerRenew.mockResolvedValueOnce(partnerMinted(partnerToken('ws-1', 'sid-1', 1), 20 * 60_000)) + const reply = deferred() + partnerMint.mockReturnValueOnce(reply.promise) + const pending = grants.partnerNodeTokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(partnerMint).toHaveBeenCalledTimes(2)) + signInAt('ws-2') + reply.resolve({ kind: 'failed', status: 503, code: 'partner_node_token_disabled' }) + await expect(pending).resolves.toBeNull() + signInAt('ws-1') + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() + }) + + it('keeps the longer of two retry deadlines when a shorter failure lands later', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + const older = deferred() + partnerMint.mockReturnValueOnce(older.promise) + grants.allowView(viewA, 'ws-2') + const stale = grants.partnerNodeTokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(partnerMint).toHaveBeenCalledOnce()) + signInAt('ws-2') + signInAt('ws-1') + partnerMint.mockResolvedValueOnce({ kind: 'failed', status: 429, retryAfterSeconds: 3600 }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + older.resolve({ kind: 'failed', status: 503 }) + await stale + vi.setSystemTime(Date.now() + 61_000) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBeNull() + expect(partnerMint).toHaveBeenCalledTimes(2) + }) + + it('keeps the held token when a renewal reply could not be read', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + partnerRenew.mockResolvedValueOnce({ kind: 'failed', status: 200 }) + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe(partnerToken('ws-1')) + expect(partnerMint).toHaveBeenCalledOnce() + }) + + it('keeps a newer token when a refusal for the older one lands late', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + grants.allowView(viewA, 'ws-2') + await grants.partnerNodeTokenFor(viewA, 'ws-1') + vi.setSystemTime(Date.now() + 31 * 60_000) + const late = deferred() + partnerRenew.mockReturnValueOnce(late.promise) + const stale = grants.partnerNodeTokenFor(viewA, 'ws-1') + await vi.waitFor(() => expect(partnerRenew).toHaveBeenCalledOnce()) + signInAt('ws-2') + signInAt('ws-1') + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe( + partnerToken('ws-1', 'sid-1', 1) + ) + late.resolve({ kind: 'failed', status: 403, code: 'partner_node_session_revoked' }) + await expect(stale).resolves.toBeNull() + + await expect(grants.partnerNodeTokenFor(viewA, 'ws-1')).resolves.toBe( + partnerToken('ws-1', 'sid-1', 1) + ) + expect(partnerRenew).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/main/lib/viewWorkspaceGrants.ts b/src/main/lib/viewWorkspaceGrants.ts index c13998263..05f859ac4 100644 --- a/src/main/lib/viewWorkspaceGrants.ts +++ b/src/main/lib/viewWorkspaceGrants.ts @@ -1,12 +1,20 @@ import type { WebContents } from 'electron' -import { canMintWorkspaceTokens, subjectOf, workspaceIdOf } from '../cloud/claims' -import { classifyMint, mintWorkspaceToken } from '../cloud/workspaceToken' +import { canMintWorkspaceTokens, grantFamilyOf, subjectOf, workspaceIdOf } from '../cloud/claims' +import { + classifyMint, + mintPartnerNodeToken, + mintWorkspaceToken, + renewPartnerNodeToken +} from '../cloud/workspaceToken' import type { WorkspaceTokenMint } from '../cloud/workspaceToken' import { getCloudSession, rejectAccessToken } from '../devplatform/session' import * as mainTelemetry from './telemetry' const MINT_REFRESH_SKEW_MS = 60_000 +const PARTNER_NODE_RENEW_BEFORE_MS = 60 * 60_000 +const PARTNER_NODE_RETRY_MS = 60_000 +const PARTNER_NODE_MAX_RETRY_MS = 5 * 60_000 export const VIEW_TOKEN_MINTED_EVENT = 'comfy.desktop.auth.view_token_minted' export const VIEW_TOKEN_MINT_FAILED_EVENT = 'comfy.desktop.auth.view_token_mint_failed' @@ -25,6 +33,7 @@ function reportMint(result: WorkspaceTokenMint): void { export interface GrantSession { currentWorkspaceId(): string | null currentSubject(): string | null + currentGrantFamily(): string | null currentAuthGeneration(): number getGrantAccessToken(): Promise heldWorkspaceToken(workspaceId: string): string | null @@ -37,13 +46,38 @@ export type MintWorkspaceToken = ( workspaceId: string ) => Promise +export interface PartnerNodeTokenCalls { + mint: MintWorkspaceToken + renew(partnerNodeToken: string): Promise +} + +const PARTNER_NODE_TOKEN_CALLS: PartnerNodeTokenCalls = { + mint: (accessToken, workspaceId) => mintPartnerNodeToken(accessToken, workspaceId), + renew: (partnerNodeToken) => renewPartnerNodeToken(partnerNodeToken) +} + +const PARTNER_NODE_MINT_DISABLED_CODE = 'partner_node_token_disabled' + +function isRetryableFailure(result: WorkspaceTokenMint): boolean { + return ( + result.kind === 'failed' && + result.code !== PARTNER_NODE_MINT_DISABLED_CODE && + (result.status === null || result.status === 429 || result.status >= 500 || result.status < 300) + ) +} + function mintKey(subject: string, workspaceId: string): string { return JSON.stringify([subject, workspaceId]) } +type Gate = () => Promise + +const OPEN: Gate = async () => true + interface MintFence { epoch: number generation: number + family: string | null } interface HeldToken { @@ -62,12 +96,15 @@ export class ViewWorkspaceGrants { private desktopAllowed = new Set() private viewAllowed = new WeakMap>() private minted = new Map() + private partnerNodeMinted = new Map() + private partnerNodeRetryAt = new Map() private minting = new Map>() constructor( private readonly session: GrantSession, private readonly mint: MintWorkspaceToken = mintWorkspaceToken, - private readonly onUnauthorized: (accessToken: string) => void = () => {} + private readonly onUnauthorized: (accessToken: string) => void = () => {}, + private readonly partnerNode: PartnerNodeTokenCalls = PARTNER_NODE_TOKEN_CALLS ) {} allowDesktop(workspaceId: string | undefined): void { @@ -88,23 +125,53 @@ export class ViewWorkspaceGrants { this.desktopAllowed = new Set() this.viewAllowed = new WeakMap() this.minted = new Map() + this.partnerNodeMinted = new Map() + this.partnerNodeRetryAt = new Map() this.minting = new Map() } - async tokenFor(view: WebContents, workspaceId: string): Promise { + tokenFor(view: WebContents, workspaceId: string, gate: Gate = OPEN): Promise { + return this.handOut(view, workspaceId, gate, (fence) => this.workspaceToken(workspaceId, fence)) + } + + partnerNodeTokenFor( + view: WebContents, + workspaceId: string, + gate: Gate = OPEN + ): Promise { + return this.handOut(view, workspaceId, gate, (fence) => + this.partnerNodeToken(workspaceId, fence) + ) + } + + private async handOut( + view: WebContents, + workspaceId: string, + gate: Gate, + read: (fence: MintFence) => Promise + ): Promise { if (!this.mayHold(view, workspaceId)) return null const fence = this.currentFence() - const held = await this.workspaceToken(workspaceId, fence) + if (!(await gate()) || !this.isCurrent(fence)) return null + const held = await read(fence) if (!held || !this.isCurrent(fence) || !this.mayHold(view, workspaceId)) return null return this.session.currentSubject() === held.subject ? held.token : null } private currentFence(): MintFence { - return { epoch: this.epoch, generation: this.session.currentAuthGeneration() } + return { + epoch: this.epoch, + generation: this.session.currentAuthGeneration(), + family: this.session.currentGrantFamily() + } } private isCurrent(fence: MintFence): boolean { - return fence.epoch === this.epoch && fence.generation === this.session.currentAuthGeneration() + return ( + fence.epoch === this.epoch && + fence.generation === this.session.currentAuthGeneration() && + fence.family === this.session.currentGrantFamily() + ) } seed(): void { @@ -144,7 +211,14 @@ export class ViewWorkspaceGrants { const allowed = await this.session.isWorkspaceMintAllowed(workspaceId) if (!allowed || !this.isCurrent(fence)) return null - const result = await this.mintOnce(accessToken, key, workspaceId, fence) + const result = await this.once(['workspace', key], fence, () => + this.mint(accessToken, workspaceId).then((minted) => { + reportMint(minted) + this.endAnEndedGrant(accessToken, minted) + if (minted.kind === 'failed' && minted.status === 401) this.onUnauthorized(accessToken) + return minted + }) + ) if (!this.isCurrent(fence) || this.session.currentSubject() !== subject) return null if (result.kind !== 'minted') return null if ( @@ -157,28 +231,103 @@ export class ViewWorkspaceGrants { return { token: result.token, subject } } - private mintOnce( - accessToken: string, + private async partnerNodeToken(workspaceId: string, fence: MintFence): Promise { + const accessToken = await this.session.getGrantAccessToken() + if (!this.isCurrent(fence) || !accessToken) return null + const subject = subjectOf(accessToken) + if (!subject) return null + const key = JSON.stringify([subject, grantFamilyOf(accessToken), workspaceId]) + const cached = this.partnerNodeMinted.get(key) + if (cached && cached.expiresAt - PARTNER_NODE_RENEW_BEFORE_MS > Date.now()) + return { token: cached.token, subject } + if (Date.now() < (this.partnerNodeRetryAt.get(key) ?? 0)) return this.stillHeld(key, subject) + + const allowed = await this.session.isWorkspaceMintAllowed(workspaceId) + if (!allowed || !this.isCurrent(fence)) return null + const result = await this.once(['partner-node', key], fence, () => + cached + ? this.renewOrMint(key, cached.token, accessToken, workspaceId, fence) + : this.mintPartnerNode(accessToken, workspaceId) + ) + const usable = + result.kind === 'minted' && + workspaceIdOf(result.token) === workspaceId && + subjectOf(result.token) === subject && + result.expiresAt - MINT_REFRESH_SKEW_MS > Date.now() + if (!usable && fence.epoch === this.epoch) { + const retryAfterMs = + result.kind === 'failed' && result.retryAfterSeconds !== undefined + ? result.retryAfterSeconds * 1000 + : 0 + const retryAt = + Date.now() + + Math.min(Math.max(PARTNER_NODE_RETRY_MS, retryAfterMs), PARTNER_NODE_MAX_RETRY_MS) + this.partnerNodeRetryAt.set(key, Math.max(retryAt, this.partnerNodeRetryAt.get(key) ?? 0)) + if (cached && !isRetryableFailure(result)) this.forgetPartnerNodeToken(key, cached.token) + } + if (!this.isCurrent(fence) || this.session.currentSubject() !== subject) return null + if (usable) { + this.partnerNodeRetryAt.delete(key) + this.partnerNodeMinted.set(key, { token: result.token, expiresAt: result.expiresAt }) + return { token: result.token, subject } + } + return this.stillHeld(key, subject) + } + + private stillHeld(key: string, subject: string): HeldToken | null { + const held = this.partnerNodeMinted.get(key) + return held && held.expiresAt - MINT_REFRESH_SKEW_MS > Date.now() + ? { token: held.token, subject } + : null + } + + private async renewOrMint( key: string, + partnerNodeToken: string, + accessToken: string, workspaceId: string, fence: MintFence ): Promise { - const flight = JSON.stringify([fence.generation, key]) + const renewed = await this.partnerNode.renew(partnerNodeToken) + if (renewed.kind === 'minted' && renewed.expiresAt - PARTNER_NODE_RENEW_BEFORE_MS > Date.now()) + return renewed + if (renewed.kind === 'failed' && !isRetryableFailure(renewed)) + this.forgetPartnerNodeToken(key, partnerNodeToken) + if (isRetryableFailure(renewed) || !this.isCurrent(fence)) return renewed + return this.mintPartnerNode(accessToken, workspaceId) + } + + private async mintPartnerNode( + accessToken: string, + workspaceId: string + ): Promise { + const minted = await this.partnerNode.mint(accessToken, workspaceId) + this.endAnEndedGrant(accessToken, minted) + return minted + } + + private endAnEndedGrant(accessToken: string, result: WorkspaceTokenMint): void { + const outcome = classifyMint(result) + if (outcome.kind === 'reauthorize' && outcome.reason === 'grant_ended') + this.session.endGrantFamily(accessToken) + } + + private forgetPartnerNodeToken(key: string, token: string): void { + if (this.partnerNodeMinted.get(key)?.token === token) this.partnerNodeMinted.delete(key) + } + + private once( + key: readonly string[], + fence: MintFence, + start: () => Promise + ): Promise { + const flight = JSON.stringify([fence.generation, fence.family, ...key]) const inFlight = this.minting.get(flight) if (inFlight) return inFlight const minting = this.minting - const pending = this.mint(accessToken, workspaceId) - .then((result) => { - reportMint(result) - 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(flight) === pending) minting.delete(flight) - }) + const pending = start().finally(() => { + if (minting.get(flight) === pending) minting.delete(flight) + }) minting.set(flight, pending) return pending } diff --git a/src/preload/comfyPreload.test.ts b/src/preload/comfyPreload.test.ts index 8e921c0f5..dd2895fef 100644 --- a/src/preload/comfyPreload.test.ts +++ b/src/preload/comfyPreload.test.ts @@ -386,6 +386,7 @@ describe('comfyPreload auth bridge', () => { await Auth.getState() await Auth.getWorkspaceToken('ws-1') + await Auth.getPartnerNodeToken?.('ws-1') await Auth.requestSignIn() await Auth.signOut() await Auth.switchWorkspace('ws-2') @@ -393,6 +394,7 @@ describe('comfyPreload auth bridge', () => { expect(mocks.invoke.mock.calls).toEqual([ ['desktop2-auth:get-state'], ['desktop2-auth:get-workspace-token', 'ws-1'], + ['desktop2-auth:get-partner-node-token', 'ws-1'], ['desktop2-auth:request-sign-in'], ['desktop2-auth:sign-out'], ['desktop2-auth:switch-workspace', 'ws-2'] diff --git a/src/preload/comfyPreload.ts b/src/preload/comfyPreload.ts index 7b0375aa3..542da6d03 100644 --- a/src/preload/comfyPreload.ts +++ b/src/preload/comfyPreload.ts @@ -273,6 +273,8 @@ const Auth: ComfyDesktop2AuthBridge = { getState: () => ipcRenderer.invoke('desktop2-auth:get-state'), getWorkspaceToken: (workspaceId) => ipcRenderer.invoke('desktop2-auth:get-workspace-token', workspaceId), + getPartnerNodeToken: (workspaceId) => + ipcRenderer.invoke('desktop2-auth:get-partner-node-token', workspaceId), requestSignIn: () => ipcRenderer.invoke('desktop2-auth:request-sign-in'), signOut: () => ipcRenderer.invoke('desktop2-auth:sign-out'), switchWorkspace: (workspaceId) => diff --git a/src/types/comfyDesktopBridge.ts b/src/types/comfyDesktopBridge.ts index e33e162b4..0e0682dc0 100644 --- a/src/types/comfyDesktopBridge.ts +++ b/src/types/comfyDesktopBridge.ts @@ -129,6 +129,10 @@ export interface ComfyDesktop2AuthBridge { * is scoped to; null when signed out, disabled, or the scope is missing, * malformed or different. The refresh token never leaves Desktop. */ getWorkspaceToken(workspaceId: string): Promise + /** The partner-node token for prompts in `workspaceId`, under the same rules + * as `getWorkspaceToken`. Desktop mints and renews it; null means use the + * workspace token. Absent on Desktop builds before it. */ + getPartnerNodeToken?(workspaceId: string): Promise /** Runs Desktop's browser sign-in and resolves with the resulting state. */ requestSignIn(): Promise /** Signs Desktop out of its account (every view follows) and resolves with