Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
109 commits
Select commit Hold shift + click to select a range
0b0c408
feat(auth): keep the Cloud grant in main and give local views minted …
dante01yoon Nov 7, 2026
97d95ef
feat(auth): give local views only minted tokens and ask pre-mint-scop…
dante01yoon Nov 7, 2026
a53ca1d
fix: bind view workspace tokens to the account and drop pre-sign-out …
dante01yoon Nov 8, 2026
b3437a1
fix: drop view tokens minted for a replaced account and keep supersed…
dante01yoon Nov 8, 2026
515b9f8
fix: check the account when delivering a cached view token
dante01yoon Nov 8, 2026
f61e035
feat: report view workspace token mints and mirror failures to Datadog
dante01yoon Nov 8, 2026
3c60527
feat(auth): classify workspace mint replies into outcomes
dante01yoon Nov 9, 2026
efe4c57
feat(auth): add the desktop_workspace_mint_switch ops flag
dante01yoon Nov 9, 2026
923fbe6
feat(auth): keep one grant and switch workspaces by minting, with no …
dante01yoon Nov 9, 2026
def5a41
feat(auth): mirror workspace switch browser trips and anchor returns …
dante01yoon Nov 9, 2026
a2a9212
feat(auth): show a failed workspace switch in the instance-selection …
dante01yoon Nov 9, 2026
b869fdb
fix(auth): treat only invalid_grant and invalid_client as an ended grant
dante01yoon Nov 9, 2026
2994475
fix(auth): report a switch to an expired anchor as retryable during a…
dante01yoon Nov 9, 2026
cdc55fa
fix(auth): fence the mint backoff on generation and account
dante01yoon Nov 9, 2026
eb5127d
fix(auth): hold off the browser after a sign-in returned no mint scope
dante01yoon Nov 9, 2026
70b19b4
fix(auth): apply the mint kill switch to view minting through one ses…
dante01yoon Nov 9, 2026
a6f4a24
fix(auth): let views hold the workspace a promotion moved to
dante01yoon Nov 9, 2026
77acce7
test(auth): make the token vault tests detect bypassed encryption
dante01yoon Nov 9, 2026
1a3bad9
fix(auth): validate the workspace and subject of a token minted for a…
dante01yoon Nov 9, 2026
30ffc8c
test(auth): pin the backoff generation fence and lifting the scope hold
dante01yoon Nov 9, 2026
27a936b
fix(auth): keep the withheld mint scope in the vault across restarts
dante01yoon Nov 9, 2026
b14a446
fix(auth): fence the view permission writes of a workspace switch on …
dante01yoon Nov 9, 2026
62fa90c
fix(auth): refuse a mint reply that is already expired
dante01yoon Nov 9, 2026
642e9a9
fix(auth): re-establish the wizard's workspace before refreshing its …
dante01yoon Nov 9, 2026
2151ecd
fix(auth): treat a superseded switch as not completing a promotion
dante01yoon Nov 9, 2026
f13b8a6
fix(auth): derive a minted token's deadline from its own lifetime, no…
dante01yoon Nov 9, 2026
ddc1544
fix(auth): refuse a minted token whose deadline passed before the rep…
dante01yoon Nov 9, 2026
6ec9e41
fix(auth): let views hold a workspace reached through browser consent
dante01yoon Nov 9, 2026
0c693ff
fix(auth): count one workspace_switch_browser per real browser trip
dante01yoon Nov 9, 2026
57123ae
fix(auth): never hand back a token after the account or workspace cha…
dante01yoon Nov 9, 2026
9b43ff5
fix(auth): report a browser trip when the browser opens, not before s…
dante01yoon Nov 9, 2026
5378739
feat(auth): mirror a sign-in that returned no mint scope to Datadog
dante01yoon Nov 9, 2026
fedf100
test(auth): pin the account re-check when the new account lands on th…
dante01yoon Nov 9, 2026
b586ad2
test(auth): capture the authorize page in E2E runs and isolate userDa…
dante01yoon Nov 9, 2026
9e18e3c
test(auth): drive workspace switching end to end through the real sel…
dante01yoon Nov 9, 2026
7bfc295
fix(auth): keep the authorize capture out of packaged builds
dante01yoon Nov 9, 2026
44ef7df
fix(auth): open the browser only when a person asks for the workspace
dante01yoon Nov 9, 2026
d9424e8
fix(auth): hold a person's workspace pick in the dashboard scope store
dante01yoon Nov 9, 2026
4098de9
fix(auth): retire a workspace pick once the wizard attempts the switch
dante01yoon Nov 9, 2026
c64c3fd
chore(bridge): bump the bridge types for the switchWorkspace doc change
dante01yoon Nov 9, 2026
5d639ea
feat(auth): local views get a partner-node token minted by Desktop
dante01yoon Nov 10, 2026
bcc8cb6
feat(auth): sign-out revokes this device's Cloud grant, retrying unti…
dante01yoon Nov 10, 2026
30c0a7c
fix(auth): views may hold the workspace a local-instance promotion sw…
dante01yoon Nov 10, 2026
4cf376f
Merge remote-tracking branch 'origin/desktop-auth/main-only-grant' in…
dante01yoon Nov 10, 2026
2738055
fix(auth): a dashboard switch lets views hold a workspace only once i…
dante01yoon Nov 10, 2026
c32e255
Merge remote-tracking branch 'origin/desktop-auth/main-only-grant' in…
dante01yoon Nov 10, 2026
45b36d7
fix(auth): an ended grant goes straight to sign-in without a refresh
dante01yoon Nov 10, 2026
8036529
Merge remote-tracking branch 'origin/desktop-auth/switch-without-brow…
dante01yoon Nov 10, 2026
1b187e4
fix(auth): revoke the grant a fresh sign-in replaces
dante01yoon Nov 10, 2026
1882926
fix(auth): an ended grant also ends a rotation of it stored meanwhile
dante01yoon Nov 10, 2026
48452b5
Merge remote-tracking branch 'origin/desktop-auth/switch-without-brow…
dante01yoon Nov 10, 2026
7180ad5
test(auth): stub revoke where a switch now revokes the replaced grant
dante01yoon Nov 10, 2026
4718e70
fix(auth): revoke a replaced grant only once the new one is saved
dante01yoon Nov 10, 2026
9f520cc
fix(auth): a view mint told the grant ended also stops its refresh
dante01yoon Nov 10, 2026
de31b8f
Merge remote-tracking branch 'origin/desktop-auth/switch-without-brow…
dante01yoon Nov 10, 2026
eaf58c9
Merge remote-tracking branch 'origin/main' into desktop-auth/main-onl…
dante01yoon Nov 10, 2026
5a46f08
Merge remote-tracking branch 'origin/desktop-auth/main-only-grant' in…
dante01yoon Nov 10, 2026
94204fe
Merge remote-tracking branch 'origin/desktop-auth/switch-without-brow…
dante01yoon Nov 10, 2026
d42a61f
fix(auth): settle a revocation on any 2xx from /oauth/revoke
dante01yoon Nov 10, 2026
84cf227
fix(auth): send a newly queued revocation without waiting out another…
dante01yoon Nov 10, 2026
9494b02
fix(auth): let a view hold a workspace only after its own switch reac…
dante01yoon Nov 10, 2026
3c5a188
Merge remote-tracking branch 'origin/desktop-auth/main-only-grant' in…
dante01yoon Nov 10, 2026
0c71d16
fix(auth): cap the mint block, gate dashboard grants on supersession,…
dante01yoon Nov 10, 2026
83b8a91
fix(auth): return an explicit reached outcome from a workspace switch
dante01yoon Nov 10, 2026
8b608d9
Merge remote-tracking branch 'origin/desktop-auth/switch-without-brow…
dante01yoon Nov 10, 2026
76c352e
Merge remote-tracking branch 'origin/desktop-auth/main-only-grant' in…
dante01yoon Nov 10, 2026
483cc0f
Merge remote-tracking branch 'origin/desktop-auth/switch-without-brow…
dante01yoon Nov 10, 2026
19b0872
fix(auth): bound revocation retries and revoke dropped sign-ins
dante01yoon Nov 10, 2026
97c765e
fix(auth): sign views out on a rejected mint, keep them signed in wit…
dante01yoon Nov 10, 2026
b27f32f
fix(auth): keep view-requested switches visible and fall back to the …
dante01yoon Nov 10, 2026
1832e53
Merge remote-tracking branch 'origin/desktop-auth/main-only-grant' in…
dante01yoon Nov 10, 2026
272947e
Merge remote-tracking branch 'origin/desktop-auth/switch-without-brow…
dante01yoon Nov 10, 2026
13fe2d1
fix(auth): keep views on the held token without the scope, let a view…
dante01yoon Nov 10, 2026
c8e3e0e
Merge remote-tracking branch 'origin/desktop-auth/switch-without-brow…
dante01yoon Nov 10, 2026
fb46c20
fix(auth): read a view's held token without side effects
dante01yoon Nov 10, 2026
88a15a4
Merge remote-tracking branch 'origin/desktop-auth/switch-without-brow…
dante01yoon Nov 10, 2026
1006a9e
fix(auth): never hand a view a minted token that can mint
dante01yoon Nov 10, 2026
bd0eb97
Merge remote-tracking branch 'origin/desktop-auth/switch-without-brow…
dante01yoon Nov 10, 2026
79ba148
docs(auth): describe when a view's switchWorkspace opens consent
dante01yoon Nov 10, 2026
0c627d4
Merge remote-tracking branch 'origin/desktop-auth/switch-without-brow…
dante01yoon Nov 10, 2026
4daa5bc
fix(auth): drop an unreadable revocation file once its token has expired
dante01yoon Nov 10, 2026
dc25010
chore(types): regenerate bridge declarations
dante01yoon Nov 10, 2026
1563bd2
Merge remote-tracking branch 'origin/desktop-auth/switch-without-brow…
dante01yoon Nov 10, 2026
0a04c74
Merge remote-tracking branch 'origin/desktop-auth/switch-without-brow…
dante01yoon Nov 10, 2026
320e160
fix(auth): a partner-node mint told the grant ended also stops its re…
dante01yoon Nov 10, 2026
7ea45ce
fix(auth): ask Cloud for a partner-node token instead of checking job…
dante01yoon Nov 10, 2026
ab4c97e
fix(auth): a 401 for an expired grant token no longer signs out on it…
dante01yoon Nov 11, 2026
184836b
Merge branch 'desktop-auth/switch-without-browser' into desktop-auth/…
dante01yoon Nov 11, 2026
177f2ed
Merge branch 'desktop-auth/switch-without-browser' into desktop-auth/…
dante01yoon Nov 11, 2026
66a3445
docs(bridge): qualify the no-browser switch for expired tokens and en…
dante01yoon Nov 11, 2026
7cda12d
Merge remote-tracking branch 'origin/desktop-auth/switch-without-brow…
dante01yoon Nov 11, 2026
4b4a231
docs(bridge): note that a switch joins one already in flight
dante01yoon Nov 11, 2026
17ad3c8
Merge remote-tracking branch 'origin/desktop-auth/switch-without-brow…
dante01yoon Nov 11, 2026
2d05a98
docs(bridge): state when a view switch can open the browser
dante01yoon Nov 11, 2026
d45bb57
Merge remote-tracking branch 'origin/desktop-auth/switch-without-brow…
dante01yoon Nov 11, 2026
ca9cfc5
Merge remote-tracking branch 'origin/desktop-auth/durable-sign-out' i…
dante01yoon Nov 11, 2026
638a4fd
fix(auth): cap the partner-node retry wait at five minutes
dante01yoon Nov 11, 2026
3b3a3e2
fix(auth): date a queued revocation no later than its file
dante01yoon Nov 11, 2026
296ab54
fix(auth): a view cannot open repeated consent tabs or cancel a switc…
dante01yoon Nov 11, 2026
351b430
Merge remote-tracking branch 'origin/main' into desktop-auth/switch-w…
dante01yoon Nov 11, 2026
cf3ba73
fix(auth): check view-requested workspaces by own key and keep one vi…
dante01yoon Nov 11, 2026
3334d80
Merge remote-tracking branch 'origin/desktop-auth/switch-without-brow…
dante01yoon Nov 11, 2026
1870bd6
Merge remote-tracking branch 'origin/desktop-auth/durable-sign-out' i…
dante01yoon Nov 11, 2026
ff17458
fix(auth): count any consent opened for a view request as the one vie…
dante01yoon Nov 11, 2026
750dbbd
Merge remote-tracking branch 'origin/desktop-auth/switch-without-brow…
dante01yoon Nov 11, 2026
68f4af6
Merge remote-tracking branch 'origin/desktop-auth/durable-sign-out' i…
dante01yoon Nov 11, 2026
31c19cb
Merge remote-tracking branch 'origin/main' into desktop-auth/durable-…
dante01yoon Nov 11, 2026
47eacc4
Merge remote-tracking branch 'origin/desktop-auth/durable-sign-out' i…
dante01yoon Nov 11, 2026
7dedcb7
Merge remote-tracking branch 'origin/main' into desktop-auth/partner-…
dante01yoon Nov 11, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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<string | null>
/** 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<string | null>
/** Runs Desktop's browser sign-in and resolves with the resulting state. */
requestSignIn(): Promise<ComfyDesktop2AuthState>
/** Signs Desktop out of its account (every view follows) and resolves with
Expand Down
2 changes: 1 addition & 1 deletion packages/comfyui-desktop-bridge-types/package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
6 changes: 6 additions & 0 deletions src/main/cloud/claims.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ interface AccessTokenClaims {
workspace_type?: string
role?: string
scope?: string
fam?: unknown
iat?: unknown
exp?: unknown
}
Expand Down Expand Up @@ -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
}
Expand Down
4 changes: 3 additions & 1 deletion src/main/cloud/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
24 changes: 24 additions & 0 deletions src/main/cloud/oauth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>(() => {}))
Expand Down
7 changes: 6 additions & 1 deletion src/main/cloud/session.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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()
}
Expand Down
52 changes: 51 additions & 1 deletion src/main/cloud/workspaceToken.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, string> = {}): void {
Expand Down Expand Up @@ -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
Expand Down
45 changes: 37 additions & 8 deletions src/main/cloud/workspaceToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<WorkspaceTokenMint> {
return postForToken('/auth/token', accessToken, { workspace_id: workspaceId }, options)
}

export function mintPartnerNodeToken(
accessToken: string,
workspaceId: string,
options: MintWorkspaceTokenOptions = {}
): Promise<WorkspaceTokenMint> {
return postForToken(
'/auth/token',
accessToken,
{ workspace_id: workspaceId, resource: 'partner-node' },
options
)
}

export function renewPartnerNodeToken(
partnerNodeToken: string,
options: MintWorkspaceTokenOptions = {}
): Promise<WorkspaceTokenMint> {
return postForToken('/auth/partner-node/renew', partnerNodeToken, undefined, options)
}

async function postForToken(
route: string,
bearer: string,
body: Record<string, string> | undefined,
options: MintWorkspaceTokenOptions
): Promise<WorkspaceTokenMint> {
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',
Expand Down
74 changes: 71 additions & 3 deletions src/main/lib/embeddedSession.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,36 @@ import type * as WorkspaceTokenModule from '../cloud/workspaceToken'

const mocks = vi.hoisted(() => ({
enabled: true,
generation: 0,
flagRead: null as Promise<boolean> | null,
getGrantAccessToken: vi.fn<() => Promise<string | null>>(),
mint: vi.fn(),
partnerMint: vi.fn(),
current: 'ws-1',
entries: [] as unknown[]
}))

vi.mock('./embeddedSessionFlag', () => ({
isEmbeddedSessionEnabled: async () => mocks.enabled
isEmbeddedSessionEnabled: async () => (mocks.flagRead ? mocks.flagRead : mocks.enabled)
}))
vi.mock('../devplatform/session', () => ({
getCloudSession: () => ({
getGrantAccessToken: mocks.getGrantAccessToken,
heldWorkspaceToken: () => null,
currentWorkspaceId: () => mocks.current,
currentSubject: () => (mocks.current ? 'user-1' : null),
currentAuthGeneration: () => 0,
currentGrantFamily: () => null,
currentAuthGeneration: () => mocks.generation,
isWorkspaceMintAllowed: async () => true,
endGrantFamily: () => {}
}),
rejectAccessToken: vi.fn()
}))
vi.mock('../cloud/workspaceToken', async (importOriginal) => ({
...(await importOriginal<typeof WorkspaceTokenModule>()),
mintWorkspaceToken: mocks.mint
mintWorkspaceToken: mocks.mint,
mintPartnerNodeToken: mocks.partnerMint,
renewPartnerNodeToken: vi.fn()
}))
vi.mock('../host/registry', () => ({
get comfyWindows() {
Expand All @@ -41,6 +47,7 @@ vi.mock('../host/registry', () => ({

import {
EMBEDDED_SESSION_CHANNELS,
partnerNodeTokenForSender,
workspaceTokenForSender,
broadcastEmbeddedSessionChanged,
stateForSender,
Expand All @@ -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
Expand Down Expand Up @@ -89,13 +100,20 @@ 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) => ({
kind: 'minted',
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()
})
Expand All @@ -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([
Expand All @@ -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],
Expand Down Expand Up @@ -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()
})

Expand Down
Loading
Loading