Skip to content
Merged
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
38 changes: 38 additions & 0 deletions apps/billing-web/e2e/sign-in.spec.ts
Original file line number Diff line number Diff line change
@@ -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 ({
Expand Down Expand Up @@ -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
})
})
16 changes: 12 additions & 4 deletions apps/billing-web/src/auth/useSignInController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -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<SessionFailure, 'code' | 'organizationId'>

export type SessionEstablishment =
| { readonly status: 'ok' }
| { readonly status: 'error'; readonly code: SessionErrorCode }
Expand All @@ -35,7 +41,7 @@ export type SessionEstablishment =
export interface SignInPort {
/** Non-null once someone is signed in, restored or interactive. */
readonly user: Readonly<Ref<unknown>>
readonly failureCode: Readonly<Ref<SessionErrorCode | undefined>>
readonly failure: Readonly<Ref<SessionRefusal | undefined>>
readonly loadIdentity: () => Promise<FirebaseIdentity | undefined>
/** Establishes the workspace session; resolves whether it holds, and the code when it does not. */
readonly establish: (user?: User) => Promise<SessionEstablishment>
Expand All @@ -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
Expand Down Expand Up @@ -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,
Expand Down
90 changes: 90 additions & 0 deletions apps/billing-web/src/auth/useSsoRequiredRefusal.ts
Original file line number Diff line number Diff line change
@@ -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<Ref<SessionErrorCode | undefined>>
readonly organizationId: Readonly<Ref<string | undefined>>
/** This page, so the customer resumes here once SSO completes. */
readonly returnTo: Readonly<Ref<string>>
}

async function signOutOfFirebase(): Promise<boolean> {
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<string>()

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<void> {
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
}
}
57 changes: 57 additions & 0 deletions apps/billing-web/src/components/auth/SessionRefusalNotice.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<script setup lang="ts">
import { cn } from '@comfyorg/tailwind-utils'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'

import { buttonVariants } from '@comfyorg/design-system/button.variants'

/** Why the session was refused: the SSO step that fixes it, or the plain reason. */
const { ssoOffered, email, signOutFailed, message } = defineProps<{
ssoOffered: boolean
email: string | undefined
signOutFailed: boolean
message: string
}>()

const emit = defineEmits<{ continueWithSso: [] }>()

const { t } = useI18n()

const ssoBody = computed(() =>
email
? t('auth.sso.required.bodyWithEmail', { email })
: t('auth.sso.required.body')
)

const alertClass = 'rounded-lg bg-base-background p-3 text-sm'
</script>

<template>
<template v-if="ssoOffered">
<div role="alert" :class="cn(alertClass, 'text-base-foreground')">
<p class="m-0 font-semibold">{{ t('auth.sso.required.title') }}</p>
<p class="mt-1 mb-0 text-muted-foreground">{{ ssoBody }}</p>
</div>
<button
type="button"
:class="cn(buttonVariants({ variant: 'primary', size: 'lg' }), 'w-full')"
@click="emit('continueWithSso')"
>
{{ t('auth.sso.continueWithSso') }}
</button>
<div
v-if="signOutFailed"
role="alert"
:class="cn(alertClass, 'text-destructive-background')"
>
{{ t('auth.errors.generic') }}
</div>
</template>
<div
v-else
role="alert"
:class="cn(alertClass, 'text-destructive-background')"
>
{{ message }}
</div>
</template>
18 changes: 18 additions & 0 deletions apps/billing-web/src/config/ssoEnabled.ts
Original file line number Diff line number Diff line change
@@ -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<boolean> {
return resolveSsoEnabled({
cloudBaseUrl: CLOUD_BASE_URL,
timeoutMs: CONFIG_FETCH_TIMEOUT_MS
})
}
8 changes: 8 additions & 0 deletions apps/billing-web/src/locales/en/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
4 changes: 2 additions & 2 deletions apps/billing-web/src/session/billingWebAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
6 changes: 4 additions & 2 deletions apps/billing-web/src/session/unifiedBillingSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading