Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
@@ -0,0 +1,99 @@
import type {
AccountCredential,
SessionSnapshot
} from '@comfyorg/account-core/session'
import { fromPartial } from '@total-typescript/shoehorn'
import type { User } from 'firebase/auth'
import { beforeEach, describe, expect, it, vi } from 'vitest'

import { useBillingContext } from '@/composables/billing/useBillingContext'
import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore'
import { stubAccountIdentityPort } from '@/utils/__tests__/stubAccountIdentityPort'

import { useBillingSdkStore } from './billingSdkStore'
import { cloudJwtFor } from './billingSdkTestUtils'

vi.mock(import('@/composables/billing/useBillingContext'))

vi.mock(import('@/platform/workspace/composables/useBillingCapabilities'))

vi.mock(import('@/platform/settings/composables/useSettingsDialog'))

vi.mock(import('@/platform/telemetry'))

vi.mock(import('@/composables/useFeatureFlags'))

vi.mock(import('@/platform/distribution/types'), () => ({ isCloud: true }))

vi.mock(import('firebase/auth'))

const FIREBASE_UID = 'firebase-uid'
const COMFY_USER_ID = 'comfy-user-id'

const CREDENTIAL: AccountCredential = {
token: cloudJwtFor(COMFY_USER_ID),
expiresAt: Date.now() + 60 * 60 * 1000,
uid: FIREBASE_UID,
workspace: { id: 'ws-1', name: 'Personal', type: 'personal' },
role: 'owner',
permissions: []
}

const SNAPSHOT: SessionSnapshot<User> = {
phase: 'authenticated',
user: fromPartial<User>({ uid: FIREBASE_UID }),
session: CREDENTIAL
}

const CAPABILITIES = {
capabilities: {
can_cancel: false,
can_change_seats: false,
can_downgrade_to_personal: false,
can_invite_members: false,
can_manage_members: false,
can_reactivate: false,
can_revert_scheduled_change: false,
can_subscribe_self_serve: true,
can_top_up: true
},
expires_at: new Date(Date.now() + 10 * 60 * 1000).toISOString(),
resolved_for: { user_id: COMFY_USER_ID, workspace_id: 'ws-1' },
revision: 1,
rollout_defaults_applied: {
can_downgrade_to_personal: false,
can_subscribe_self_serve: false,
can_top_up: false
}
}

describe('useBillingSdkStore on the token session', () => {
beforeEach(() => {
stubAccountIdentityPort()
vi.mocked(useBillingContext).mockReturnValue(useBillingContext())
vi.mocked(fetch).mockImplementation(
async () =>
new Response(JSON.stringify(CAPABILITIES), {
status: 200
})
)
const session = useWorkspaceAuthStore().getUnifiedSessionClient()
vi.spyOn(session, 'getSnapshot').mockReturnValue(SNAPSHOT)
vi.spyOn(session, 'ensureFresh').mockResolvedValue({
status: 'ok',
session: CREDENTIAL
})
})

it('accepts capabilities resolved for the Comfy user its token names when that is not the Firebase uid', async () => {
const result = await useBillingSdkStore().readCapabilities({})

expect(result).toMatchObject({
status: 'ok',
value: {
capabilities: { can_subscribe_self_serve: true },
resolved_for: { user_id: COMFY_USER_ID, workspace_id: 'ws-1' }
}
})
})
})
24 changes: 23 additions & 1 deletion src/platform/workspace/billing/sdk/billingSdkStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
BillingEventsReadOptions,
BillingOperationTelemetryEvent,
BillingResult,
BillingScopeSource,
BillingSession,
CapabilitiesReadOptions,
EmbeddedChallengePort,
PendingBillingOperation,
Expand All @@ -32,6 +34,7 @@
import { useBillingContext } from '@/composables/billing/useBillingContext'
import { useFeatureFlags } from '@/composables/useFeatureFlags'
import { t } from '@/i18n'
import { readAccessTokenIdentity } from '@/platform/auth/localWeb/accessTokenIdentity'

Check warning on line 37 in src/platform/workspace/billing/sdk/billingSdkStore.ts

View workflow job for this annotation

GitHub Actions / fallow / fallow

Boundary violation

Import from zone 'billing/application' to zone 'authentication/domain' is not allowed. src/platform/workspace/billing/sdk/billingSdkStore.ts -> src/platform/auth/localWeb/accessTokenIdentity.ts Route the import through an allowed zone or restructure the dependency.
import { webSessionRequests } from '@/platform/auth/session/webSessionFetch'
import { isCloud } from '@/platform/distribution/types'
import { useSettingsDialog } from '@/platform/settings/composables/useSettingsDialog'
Expand Down Expand Up @@ -120,6 +123,23 @@
}
}

function tokenSessionScopeSource(session: BillingSession): BillingScopeSource {
return {
getScope: () => {
const credential = session.getSnapshot().session
const identity = credential && readAccessTokenIdentity(credential.token)
return (
identity && {
userId: identity.userId,
workspaceId: credential.workspace.id,
role: credential.role
}
)
},
subscribe: (listener) => session.subscribe(listener)
}
}

export const useBillingSdkStore = defineStore('billingSdk', () => {
const workspaceAuthStore = useWorkspaceAuthStore()
const workspaceStore = useTeamWorkspaceStore()
Expand Down Expand Up @@ -148,8 +168,10 @@
workspaceId: requests.workspaceId
}
}
const session = workspaceAuthStore.getUnifiedSessionClient()
return {
session: workspaceAuthStore.getUnifiedSessionClient(),
session,
scopeSource: tokenSessionScopeSource(session),
workspaceId: () => workspaceAuthStore.getUnifiedMintWorkspaceId()
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ import {
stubFirebaseAuthHarness
} from '@/utils/__tests__/stubAccountIdentityPort'

import { cloudJwtFor } from './billingSdkTestUtils'

vi.mock(import('@/platform/telemetry'))
vi.mock(import('@/composables/useFeatureFlags'))
vi.mock(import('@/composables/billing/useBillingContext'))
Expand All @@ -63,7 +65,7 @@ vi.mock<unknown>(
})
)
const CREDENTIAL: AccountCredential = {
token: 'workspace-jwt',
token: cloudJwtFor('uid-1'),
expiresAt: Date.now() + 60 * 60 * 1000,
uid: 'uid-1',
workspace: { id: 'ws-1', name: 'Personal', type: 'personal' },
Expand Down
7 changes: 7 additions & 0 deletions src/platform/workspace/billing/sdk/billingSdkTestUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@ import { vi } from 'vitest'

import type { BillingSdk } from './createBillingSdk'

/** An unsigned token shaped like a Cloud JWT issued for `subject`. */
export function cloudJwtFor(subject: string): string {
const encode = (value: object) =>
btoa(JSON.stringify(value)).replace(/=+$/, '')
return `${encode({ alg: 'RS256' })}.${encode({ sub: subject })}.signature`
}

/** A server code minted the one sanctioned way, so a test cannot invent one. */
export function serverCode(code: string): BillingServerCode | undefined {
return readBillingErrorCode({ code, message: 'server text' })
Expand Down
Loading