diff --git a/apps/billing-web/e2e/sign-in.spec.ts b/apps/billing-web/e2e/sign-in.spec.ts index ab0c1ff17aa..2c65778c688 100644 --- a/apps/billing-web/e2e/sign-in.spec.ts +++ b/apps/billing-web/e2e/sign-in.spec.ts @@ -1,3 +1,4 @@ +import { E2E_FIREBASE_CONFIG, E2E_USER } from './fixtures/env' import { entryPath, expect, test } from './fixtures/test' test('an entry link without a session goes through sign-in and comes back to the intent', async ({ @@ -39,3 +40,40 @@ test('a returning visitor is restored without seeing the form', async ({ ).toBeVisible() await expect(page).toHaveURL(subscription) }) + +test('an account its SSO organization holds is offered Continue with SSO, which leaves for that organization and back to the product', async ({ + page, + cloud +}) => { + cloud.reply('GET', '/features', () => ({ + body: { firebase_config: E2E_FIREBASE_CONFIG, sso_enabled: true } + })) + cloud.reply('POST', '/auth/token', () => ({ + status: 403, + body: { + code: 'sso_required', + message: 'sign in with your organization', + organization_id: 'org_e2e' + } + })) + await page.goto(entryPath('subscription', { return_to: 'comfyui_credits' })) + await page.getByRole('button', { name: 'Use email instead' }).click() + await page.getByLabel('Email').fill(E2E_USER.email) + await page.getByLabel('Password', { exact: true }).fill(E2E_USER.password) + await page.getByRole('button', { name: 'Sign in', exact: true }).click() + + await expect(page.getByRole('alert')).toContainText( + 'Your organization requires single sign-on' + ) + const signInPage = page.url() + await page.getByRole('button', { name: 'Continue with SSO' }).click() + + await page.waitForURL((url) => url.pathname === '/api/auth/sso/start') + const start = new URL(page.url()) + expect(start.origin).toBe('https://testcloud.comfy.org') + expect(Object.fromEntries(start.searchParams)).toStrictEqual({ + email: E2E_USER.email, + organization: 'org_e2e', + return_to: signInPage + }) +}) diff --git a/apps/billing-web/src/auth/useSignInController.ts b/apps/billing-web/src/auth/useSignInController.ts index 66ffb81eac9..6623ec5011a 100644 --- a/apps/billing-web/src/auth/useSignInController.ts +++ b/apps/billing-web/src/auth/useSignInController.ts @@ -6,7 +6,10 @@ import type { FirebaseIdentity } from '@comfyorg/account-core/firebase' import { authErrorMessage } from '@comfyorg/account-core/firebaseAuthError' import type { AuthErrorCopy } from '@comfyorg/account-core/firebaseAuthError' -import type { SessionErrorCode } from '@comfyorg/account-core/session' +import type { + SessionErrorCode, + SessionFailure +} from '@comfyorg/account-core/session' import type { User, UserCredential } from 'firebase/auth' import { computed, ref, watch } from 'vue' import type { Ref } from 'vue' @@ -27,6 +30,9 @@ import { const AUTH_ERROR_COPY: AuthErrorCopy = en.auth.errors +/** Why the workspace session was refused, as far as the sign-in page acts on it. */ +export type SessionRefusal = Pick + export type SessionEstablishment = | { readonly status: 'ok' } | { readonly status: 'error'; readonly code: SessionErrorCode } @@ -35,7 +41,7 @@ export type SessionEstablishment = export interface SignInPort { /** Non-null once someone is signed in, restored or interactive. */ readonly user: Readonly> - readonly failureCode: Readonly> + readonly failure: Readonly> readonly loadIdentity: () => Promise /** Establishes the workspace session; resolves whether it holds, and the code when it does not. */ readonly establish: (user?: User) => Promise @@ -45,7 +51,7 @@ export function sessionClientPort(): SignInPort { const { user, failure } = useBillingWebSession() return { user, - failureCode: computed(() => failure.value?.code), + failure, loadIdentity: resolveBillingWebIdentity, /** * The client no longer auto-mints (see `billingWebSession.ts`), so every @@ -189,7 +195,9 @@ export function useSignInController( leaving, errorMessage, /** The mint's own refusal, e.g. naming a workspace this account is not in. */ - sessionFailureCode: port.failureCode, + sessionFailureCode: computed(() => port.failure.value?.code), + /** The organization an `SSO_REQUIRED` refusal names, when it names one. */ + ssoOrganizationId: computed(() => port.failure.value?.organizationId), available: computed(() => identity.value !== undefined), signInWith, submitEmail, diff --git a/apps/billing-web/src/auth/useSsoRequiredRefusal.ts b/apps/billing-web/src/auth/useSsoRequiredRefusal.ts new file mode 100644 index 00000000000..05c27d83584 --- /dev/null +++ b/apps/billing-web/src/auth/useSsoRequiredRefusal.ts @@ -0,0 +1,90 @@ +/** + * An `SSO_REQUIRED` refusal, while `sso_enabled` is on, offers the SSO + * sign-in that fixes it instead of the workspace refusal. Firebase is signed + * out before leaving, or this page would restore the refused account and be + * refused again when the customer comes back. + */ +import type { SessionErrorCode } from '@comfyorg/account-core/session' +import { ssoStartUrl } from '@comfyorg/account-core/sso' +import { computed, ref, watch } from 'vue' +import type { Ref } from 'vue' + +import { CLOUD_BASE_URL } from '@/config/env' +import { resolveBillingWebIdentity } from '@/config/firebase' +import { readBillingWebSsoEnabled } from '@/config/ssoEnabled' + +interface SsoRequiredRefusal { + readonly code: Readonly> + readonly organizationId: Readonly> + /** This page, so the customer resumes here once SSO completes. */ + readonly returnTo: Readonly> +} + +async function signOutOfFirebase(): Promise { + const identity = await resolveBillingWebIdentity() + if (!identity?.currentUser()) return true + try { + await identity.signOut() + return true + } catch { + return false + } +} + +export function useSsoRequiredRefusal(refusal: SsoRequiredRefusal) { + const enabled = ref(false) + const email = ref() + + watch( + refusal.code, + async (code) => { + if (code !== 'SSO_REQUIRED') return + const [flag, identity] = await Promise.all([ + readBillingWebSsoEnabled(), + resolveBillingWebIdentity() + ]) + enabled.value = flag + email.value = identity?.currentUser()?.email ?? undefined + }, + { immediate: true } + ) + + const destination = computed(() => { + if (!enabled.value || refusal.code.value !== 'SSO_REQUIRED') return + const back = { + returnTo: refusal.returnTo.value, + origin: CLOUD_BASE_URL, + appOrigin: window.location.origin + } + const organizationId = refusal.organizationId.value + if (organizationId) + return ssoStartUrl({ organizationId, email: email.value, ...back }) + return email.value + ? ssoStartUrl({ email: email.value, ...back }) + : undefined + }) + + const leaving = ref(false) + const signOutFailed = ref(false) + + async function continueWithSso(): Promise { + const target = destination.value + if (target === undefined || leaving.value) return + leaving.value = true + signOutFailed.value = false + if (!(await signOutOfFirebase())) { + leaving.value = false + signOutFailed.value = true + return + } + window.location.assign(target) + } + + return { + offered: computed(() => destination.value !== undefined), + email, + leaving, + signOutFailed, + continueWithSso + } +} diff --git a/apps/billing-web/src/components/auth/SessionRefusalNotice.vue b/apps/billing-web/src/components/auth/SessionRefusalNotice.vue new file mode 100644 index 00000000000..1a1a82e4c73 --- /dev/null +++ b/apps/billing-web/src/components/auth/SessionRefusalNotice.vue @@ -0,0 +1,57 @@ + + + diff --git a/apps/billing-web/src/config/ssoEnabled.ts b/apps/billing-web/src/config/ssoEnabled.ts new file mode 100644 index 00000000000..636c6f61086 --- /dev/null +++ b/apps/billing-web/src/config/ssoEnabled.ts @@ -0,0 +1,18 @@ +/** + * The Cloud app's `sso_enabled` rollout flag, read from the anonymous + * `/api/features` document this origin already fetches for its Firebase + * config, so with that read done it adds no request. + */ +import { resolveSsoEnabled } from '@comfyorg/account-core/firebase' + +import { CLOUD_BASE_URL } from '@/config/env' + +/** Same value as `@/config/firebase`, so the flag shares its fetch. */ +const CONFIG_FETCH_TIMEOUT_MS = 4000 + +export function readBillingWebSsoEnabled(): Promise { + return resolveSsoEnabled({ + cloudBaseUrl: CLOUD_BASE_URL, + timeoutMs: CONFIG_FETCH_TIMEOUT_MS + }) +} diff --git a/apps/billing-web/src/locales/en/main.json b/apps/billing-web/src/locales/en/main.json index b50e05ea9ae..97ca8f0e1af 100644 --- a/apps/billing-web/src/locales/en/main.json +++ b/apps/billing-web/src/locales/en/main.json @@ -17,6 +17,14 @@ "sessionError": "You are signed in, but your workspace session could not be started. Retry, or sign in again with another account.", "retry": "Retry session" }, + "sso": { + "continueWithSso": "Continue with SSO", + "required": { + "title": "Your organization requires single sign-on", + "body": "This account signs in with your organization's single sign-on. Continue with SSO to sign in.", + "bodyWithEmail": "{email} signs in with your organization's single sign-on. Continue with SSO to sign in." + } + }, "email": { "label": "Email", "placeholder": "Enter your email" diff --git a/apps/billing-web/src/session/billingWebAuth.ts b/apps/billing-web/src/session/billingWebAuth.ts index c388a4fd57d..1f2821d4239 100644 --- a/apps/billing-web/src/session/billingWebAuth.ts +++ b/apps/billing-web/src/session/billingWebAuth.ts @@ -149,8 +149,8 @@ export function billingWebSignInPort(): SignInPort { user: computed(() => mode.value ? decidedPort(mode.value).user.value : null ), - failureCode: computed(() => - mode.value ? decidedPort(mode.value).failureCode.value : undefined + failure: computed(() => + mode.value ? decidedPort(mode.value).failure.value : undefined ), loadIdentity: async () => decidedPort(await decideMode()).loadIdentity(), establish: async (user) => { diff --git a/apps/billing-web/src/session/unifiedBillingSession.test.ts b/apps/billing-web/src/session/unifiedBillingSession.test.ts index 9d88ad21644..ed2c32cf30f 100644 --- a/apps/billing-web/src/session/unifiedBillingSession.test.ts +++ b/apps/billing-web/src/session/unifiedBillingSession.test.ts @@ -278,7 +278,7 @@ describe('billing-web on the shared web session', () => { await expect(session.settledPhase()).resolves.toBe('error') - expect(session.signInPort.failureCode.value).toBe(failure) + expect(session.signInPort.failure.value?.code).toBe(failure) expect(session.billedScope.value).toBeUndefined() await expect(session.signInPort.loadIdentity()).resolves.toBeUndefined() expect(firebase.loadFirebase).not.toHaveBeenCalled() diff --git a/apps/billing-web/src/session/unifiedBillingSession.ts b/apps/billing-web/src/session/unifiedBillingSession.ts index 5804947dc06..561093aa701 100644 --- a/apps/billing-web/src/session/unifiedBillingSession.ts +++ b/apps/billing-web/src/session/unifiedBillingSession.ts @@ -265,8 +265,10 @@ export function createUnifiedBillingSession(deps: UnifiedBillingSessionDeps) { user: computed(() => state.value.phase === 'signed_in' ? state.value.session.user : null ), - failureCode: computed(() => - workspace.value?.status === 'error' ? workspace.value.code : undefined + failure: computed(() => + workspace.value?.status === 'error' + ? { code: workspace.value.code } + : undefined ), loadIdentity: async () => (await settledPhase()) === 'signed-out' ? deps.loadFirebase() : undefined, diff --git a/apps/billing-web/src/views/SignInView.test.ts b/apps/billing-web/src/views/SignInView.test.ts index 8ed7ebac354..2c11966c0bc 100644 --- a/apps/billing-web/src/views/SignInView.test.ts +++ b/apps/billing-web/src/views/SignInView.test.ts @@ -15,6 +15,10 @@ const h = vi.hoisted(() => ({ available: true, initialState: undefined as SignInState | undefined, sessionFailureCode: undefined as SessionErrorCode | undefined, + ssoOrganizationId: undefined as string | undefined, + ssoEnabled: vi.fn<() => Promise>(), + accountEmail: 'someone@acme.com' as string | null, + signOut: vi.fn<() => Promise>(), signInWith: vi.fn(), submitEmail: vi.fn(), retryMint: vi.fn(), @@ -34,6 +38,7 @@ vi.mock(import('@/auth/useSignInController'), async () => { leaving: computed(() => false), errorMessage: computed(() => ''), sessionFailureCode: computed(() => h.sessionFailureCode), + ssoOrganizationId: computed(() => h.ssoOrganizationId), available: computed(() => h.available), signInWith: h.signInWith, submitEmail: h.submitEmail, @@ -44,6 +49,17 @@ vi.mock(import('@/auth/useSignInController'), async () => { } }) +vi.mock(import('@/config/ssoEnabled'), () => ({ + readBillingWebSsoEnabled: h.ssoEnabled +})) + +vi.mock(import('@/config/firebase'), () => ({ + resolveBillingWebIdentity: async () => ({ + currentUser: () => ({ email: h.accountEmail }), + signOut: h.signOut + }) +})) + async function renderSignIn(path = '/sign-in') { const router = createBillingRouter( createMemoryHistory(), @@ -67,6 +83,10 @@ beforeEach(() => { h.retryMint.mockClear() h.initialState = undefined h.sessionFailureCode = undefined + h.ssoOrganizationId = undefined + h.ssoEnabled.mockResolvedValue(false) + h.accountEmail = 'someone@acme.com' + h.signOut.mockResolvedValue(undefined) h.phase = 'signed-out' recordBillingEntry(undefined) }) @@ -359,4 +379,112 @@ describe('SignInView', () => { ).not.toBeInTheDocument() } ) + + describe('an SSO_REQUIRED refusal with sso_enabled on', () => { + const SSO_START = 'https://testcloud.comfy.org/api/auth/sso/start' + + beforeEach(() => { + h.ssoEnabled.mockResolvedValue(true) + h.sessionFailureCode = 'SSO_REQUIRED' + h.initialState = { + step: 'signedIn', + origin: 'interactive', + mintFailed: true + } + }) + + it.for([ + { + refusal: 'naming its organization', + organizationId: 'org_acme', + path: REFUSED_ENTRY, + query: 'email=someone%40acme.com&organization=org_acme' + }, + { + refusal: 'naming no organization', + organizationId: undefined, + path: REFUSED_ENTRY, + query: 'email=someone%40acme.com' + } + ])( + 'signs out and continues with SSO for a refusal $refusal', + async ({ organizationId, path, query }) => { + h.ssoOrganizationId = organizationId + const assign = vi + .spyOn(window.location, 'assign') + .mockImplementation(() => {}) + const router = await renderSignIn(path) + + const action = await screen.findByRole('button', { + name: 'Continue with SSO' + }) + expect(screen.getByRole('alert')).toHaveTextContent( + "Your organization requires single sign-onsomeone@acme.com signs in with your organization's single sign-on." + ) + await userEvent.click(action) + + expect(h.signOut).toHaveBeenCalledOnce() + const backToThisPage = encodeURIComponent( + `${window.location.origin}${router.currentRoute.value.fullPath}` + ) + expect(assign).toHaveBeenCalledExactlyOnceWith( + `${SSO_START}?${query}&return_to=${backToThisPage}` + ) + } + ) + + it('offers nothing it cannot start when neither an organization nor an email is known', async () => { + h.accountEmail = null + await renderSignIn(REFUSED_ENTRY) + + await vi.waitFor(() => expect(h.ssoEnabled).toHaveBeenCalled()) + expect(screen.getByRole('alert')).toHaveTextContent( + "This account can't manage billing for that workspace." + ) + expect( + screen.queryByRole('button', { name: 'Continue with SSO' }) + ).toBeNull() + }) + + it('stays on the page when signing out fails', async () => { + h.signOut.mockRejectedValue(new Error('auth/network-request-failed')) + const assign = vi + .spyOn(window.location, 'assign') + .mockImplementation(() => {}) + await renderSignIn(REFUSED_ENTRY) + + await userEvent.click( + await screen.findByRole('button', { name: 'Continue with SSO' }) + ) + + expect(assign).not.toHaveBeenCalled() + expect( + await screen.findByText( + 'Something went wrong while signing you in. Please try again.' + ) + ).toBeInTheDocument() + expect( + screen.getByRole('button', { name: 'Continue with SSO' }) + ).toBeInTheDocument() + }) + }) + + it('keeps the workspace refusal for SSO_REQUIRED while sso_enabled is off', async () => { + h.sessionFailureCode = 'SSO_REQUIRED' + h.ssoOrganizationId = 'org_acme' + h.initialState = { + step: 'signedIn', + origin: 'interactive', + mintFailed: true + } + await renderSignIn(REFUSED_ENTRY) + + await vi.waitFor(() => expect(h.ssoEnabled).toHaveBeenCalled()) + expect(screen.getByRole('alert')).toHaveTextContent( + "This account can't manage billing for that workspace." + ) + expect( + screen.queryByRole('button', { name: 'Continue with SSO' }) + ).toBeNull() + }) }) diff --git a/apps/billing-web/src/views/SignInView.vue b/apps/billing-web/src/views/SignInView.vue index e1b1e9e8acf..7a57efd5d89 100644 --- a/apps/billing-web/src/views/SignInView.vue +++ b/apps/billing-web/src/views/SignInView.vue @@ -10,7 +10,9 @@ import SocialAuthButtons from '@comfyorg/account-ui/auth/SocialAuthButtons' import { safeReturnTo } from '@/auth/returnTo' import { useSignInController } from '@/auth/useSignInController' +import { useSsoRequiredRefusal } from '@/auth/useSsoRequiredRefusal' import SessionFailureAction from '@/components/auth/SessionFailureAction.vue' +import SessionRefusalNotice from '@/components/auth/SessionRefusalNotice.vue' import SignInEmailForm from '@/components/auth/SignInEmailForm.vue' import { useHostedCopy } from '@/composables/useHostedCopy' import { BILLING_WEB_ENV } from '@/config/env' @@ -29,6 +31,7 @@ const { leaving, errorMessage, sessionFailureCode, + ssoOrganizationId, available, signInWith, submitEmail, @@ -124,6 +127,20 @@ const appReturnLink = computed(() => { } }) +const { + offered: ssoOffered, + email: ssoEmail, + leaving: leavingForSso, + signOutFailed, + continueWithSso +} = useSsoRequiredRefusal({ + code: sessionFailureCode, + organizationId: ssoOrganizationId, + returnTo: computed(() => new URL(route.fullPath, window.location.origin).href) +}) + +const leavingPage = computed(() => leaving.value || leavingForSso.value) + const linkButtonClass = 'cursor-pointer self-center border-none bg-transparent p-0 text-sm text-muted-foreground underline transition-colors hover:text-base-foreground disabled:cursor-not-allowed disabled:opacity-50' const alertClass = 'rounded-lg bg-base-background p-3 text-sm' @@ -134,7 +151,7 @@ const alertClass = 'rounded-lg bg-base-background p-3 text-sm' class="dark-theme fixed inset-0 overflow-auto bg-charcoal-950 px-4 py-6 font-inter sm:px-6 sm:py-10" >
@@ -217,12 +234,13 @@ const alertClass = 'rounded-lg bg-base-background p-3 text-sm'