From c756d2487e6e7bed3a7ba5cdcb44346a0839dfc7 Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Sat, 8 Aug 2026 21:49:43 +0530 Subject: [PATCH 1/9] fix: never render the cloud sign-up email form before region detection settles isInChina() races a fetch against a 2000ms timeout, but userIsInChina defaulted to false, so the email sign-up form rendered immediately and was replaced by the region notice up to ~2s later. The form was briefly interactive, letting a fast typist begin entering the PII the region policy exists to avoid collecting. Model detection as boolean | undefined and render a skeleton placeholder while it is pending, so the form only ever appears once detection resolves to false. Detection still starts on mount, so the common path usually settles before the user switches to the email tab. Social sign-up is unchanged and never waits on the probe. Sign-in remains unguarded by design, since an existing account already completed sign-up; both are pinned by tests. --- .../cloud/onboarding/CloudLoginView.test.ts | 18 ++++ .../cloud/onboarding/CloudSignupView.test.ts | 83 ++++++++++++++++++- .../cloud/onboarding/CloudSignupView.vue | 15 +++- 3 files changed, 111 insertions(+), 5 deletions(-) diff --git a/src/platform/cloud/onboarding/CloudLoginView.test.ts b/src/platform/cloud/onboarding/CloudLoginView.test.ts index 4e1bddbd797..c22038a5366 100644 --- a/src/platform/cloud/onboarding/CloudLoginView.test.ts +++ b/src/platform/cloud/onboarding/CloudLoginView.test.ts @@ -1,4 +1,5 @@ import { render, screen } from '@testing-library/vue' +import { readFile } from 'node:fs/promises' import { afterEach, describe, expect, it, vi } from 'vitest' import { createI18n } from 'vue-i18n' import { createMemoryHistory, createRouter } from 'vue-router' @@ -107,6 +108,23 @@ describe('CloudLoginView', () => { ).not.toBeInTheDocument() }) + it('does not region-gate sign-in, because an existing account already completed sign-up', async () => { + const user = (await import('@testing-library/user-event')).default.setup() + await renderLoginView() + + await user.click( + screen.getByRole('button', { name: 'auth.login.useEmailInstead' }) + ) + + expect(screen.getByTestId('signin-form')).toBeInTheDocument() + + const source = await readFile( + 'src/platform/cloud/onboarding/CloudLoginView.vue', + 'utf8' + ) + expect(source).not.toContain('isInChina') + }) + it('shows the in-app browser notice only inside an embedded webview', async () => { const { unmount } = await renderLoginView() expect( diff --git a/src/platform/cloud/onboarding/CloudSignupView.test.ts b/src/platform/cloud/onboarding/CloudSignupView.test.ts index 37108442148..e738299278a 100644 --- a/src/platform/cloud/onboarding/CloudSignupView.test.ts +++ b/src/platform/cloud/onboarding/CloudSignupView.test.ts @@ -20,9 +20,20 @@ vi.mock('@/platform/cloud/onboarding/composables/usePostAuthRedirect', () => ({ vi.mock('@/base/webviewDetection', () => ({ isEmbeddedWebView: () => false })) vi.mock('@/platform/telemetry', () => ({ useTelemetry: () => undefined })) -const inChina = vi.hoisted(() => ({ value: false })) +const inChina = vi.hoisted(() => ({ + value: false, + pending: null as Promise | null, + /** Holds detection in its pending state; returns the settle function. */ + defer(): (inChina: boolean) => void { + let settle!: (inChina: boolean) => void + this.pending = new Promise((resolve) => { + settle = resolve + }) + return settle + } +})) vi.mock('@/utils/networkUtil', () => ({ - isInChina: () => Promise.resolve(inChina.value) + isInChina: () => inChina.pending ?? Promise.resolve(inChina.value) })) const freeTier = vi.hoisted(() => ({ value: false })) @@ -40,6 +51,8 @@ const MESSAGES = { login: { useEmailInstead: 'Use email instead' }, signup: { signIn: 'Sign in', + signUpWithGoogle: 'Sign up with Google', + signUpWithGithub: 'Sign up with GitHub', regionRestrictionChina: 'Email sign-up is unavailable in your region.' } } @@ -76,6 +89,7 @@ async function renderSignupView(url = '/cloud/signup') { beforeEach(() => { inChina.value = false + inChina.pending = null freeTier.value = false }) @@ -113,9 +127,72 @@ describe('CloudSignupView', () => { await user.click(screen.getByRole('button', { name: 'Use email instead' })) - expect(screen.getByTestId('signup-form')).toBeInTheDocument() + await waitFor(() => { + expect(screen.getByTestId('signup-form')).toBeInTheDocument() + }) expect( screen.queryByText('Email sign-up is unavailable in your region.') ).not.toBeInTheDocument() }) + + it('withholds the sign-up form while region detection is still pending', async () => { + const user = (await import('@testing-library/user-event')).default.setup() + const settle = inChina.defer() + await renderSignupView() + + await user.click(screen.getByRole('button', { name: 'Use email instead' })) + + await waitFor(() => { + expect(screen.getByTestId('region-check-pending')).toBeInTheDocument() + }) + expect(screen.queryByTestId('signup-form')).not.toBeInTheDocument() + + settle(false) + + await waitFor(() => { + expect(screen.getByTestId('signup-form')).toBeInTheDocument() + }) + }) + + it('never renders the sign-up form inside China, pending or settled', async () => { + const user = (await import('@testing-library/user-event')).default.setup() + const settle = inChina.defer() + await renderSignupView() + + await user.click(screen.getByRole('button', { name: 'Use email instead' })) + + await waitFor(() => { + expect(screen.getByTestId('region-check-pending')).toBeInTheDocument() + }) + expect(screen.queryByTestId('signup-form')).not.toBeInTheDocument() + + settle(true) + + await waitFor(() => { + expect( + screen.getByText('Email sign-up is unavailable in your region.') + ).toBeInTheDocument() + }) + expect(screen.queryByTestId('signup-form')).not.toBeInTheDocument() + }) + + it.for([ + ['pending', null], + ['inside China', true], + ['outside China', false] + ] as const)('offers social sign-up %s', async ([, resolved]) => { + if (resolved === null) { + inChina.defer() + } else { + inChina.value = resolved + } + await renderSignupView() + + expect( + screen.getByRole('button', { name: 'Sign up with Google' }) + ).toBeInTheDocument() + expect( + screen.getByRole('button', { name: 'Sign up with GitHub' }) + ).toBeInTheDocument() + }) }) diff --git a/src/platform/cloud/onboarding/CloudSignupView.vue b/src/platform/cloud/onboarding/CloudSignupView.vue index b850844c586..35081fc6e4a 100644 --- a/src/platform/cloud/onboarding/CloudSignupView.vue +++ b/src/platform/cloud/onboarding/CloudSignupView.vue @@ -46,7 +46,16 @@ {{ t('auth.signup.emailNotEligibleForFreeTier') }} - +
+ + + +
+ {{ t('auth.signup.regionRestrictionChina') }} (undefined) const { isFreeTierEnabled } = useFreeTierOnboarding() const { From 6ef7590583e721ff1fcef0861aa3e66520d54e26 Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Mon, 10 Aug 2026 18:44:42 +0530 Subject: [PATCH 2/9] fix: bound the cloud sign-up region check so it always releases the form isInChina bounds only its Google leg; the Baidu fallback awaits a bare fetch with no AbortSignal, so on networks that blackhole rather than reset it hangs until the browser's own network timeout. Withholding the form on undefined turned that into an indefinitely blank email tab for exactly those users, who previously got a usable form. Race the probe against a 1500ms fail-open fallback and catch rejections, so the pending state always has a guaranteed exit. Also drops the source-text assertion on CloudLoginView: it asserted on file contents rather than behaviour, and its relative path resolved against vitest's cwd. The rendered-form assertion above it already covers the claim. --- .../cloud/onboarding/CloudLoginView.test.ts | 7 ------ .../cloud/onboarding/CloudSignupView.test.ts | 22 +++++++++++++++++++ .../cloud/onboarding/CloudSignupView.vue | 12 +++++++++- 3 files changed, 33 insertions(+), 8 deletions(-) diff --git a/src/platform/cloud/onboarding/CloudLoginView.test.ts b/src/platform/cloud/onboarding/CloudLoginView.test.ts index c22038a5366..a566175c787 100644 --- a/src/platform/cloud/onboarding/CloudLoginView.test.ts +++ b/src/platform/cloud/onboarding/CloudLoginView.test.ts @@ -1,5 +1,4 @@ import { render, screen } from '@testing-library/vue' -import { readFile } from 'node:fs/promises' import { afterEach, describe, expect, it, vi } from 'vitest' import { createI18n } from 'vue-i18n' import { createMemoryHistory, createRouter } from 'vue-router' @@ -117,12 +116,6 @@ describe('CloudLoginView', () => { ) expect(screen.getByTestId('signin-form')).toBeInTheDocument() - - const source = await readFile( - 'src/platform/cloud/onboarding/CloudLoginView.vue', - 'utf8' - ) - expect(source).not.toContain('isInChina') }) it('shows the in-app browser notice only inside an embedded webview', async () => { diff --git a/src/platform/cloud/onboarding/CloudSignupView.test.ts b/src/platform/cloud/onboarding/CloudSignupView.test.ts index e738299278a..3be3ff6f3c3 100644 --- a/src/platform/cloud/onboarding/CloudSignupView.test.ts +++ b/src/platform/cloud/onboarding/CloudSignupView.test.ts @@ -154,6 +154,28 @@ describe('CloudSignupView', () => { }) }) + it('releases the sign-up form when region detection never settles', async () => { + vi.useFakeTimers() + try { + const user = (await import('@testing-library/user-event')).default.setup({ + advanceTimers: vi.advanceTimersByTime + }) + inChina.defer() + await renderSignupView() + + await user.click( + screen.getByRole('button', { name: 'Use email instead' }) + ) + expect(screen.getByTestId('region-check-pending')).toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(1500) + + expect(screen.getByTestId('signup-form')).toBeInTheDocument() + } finally { + vi.useRealTimers() + } + }) + it('never renders the sign-up form inside China, pending or settled', async () => { const user = (await import('@testing-library/user-event')).default.setup() const settle = inChina.defer() diff --git a/src/platform/cloud/onboarding/CloudSignupView.vue b/src/platform/cloud/onboarding/CloudSignupView.vue index 35081fc6e4a..086f13092ed 100644 --- a/src/platform/cloud/onboarding/CloudSignupView.vue +++ b/src/platform/cloud/onboarding/CloudSignupView.vue @@ -105,6 +105,8 @@ const { t } = useI18n() const route = useRoute() const authActions = useAuthActions() const telemetry = useTelemetry() +const REGION_CHECK_TIMEOUT_MS = 1500 + /** `undefined` while detection is pending, so the email form cannot render early. */ const userIsInChina = ref(undefined) const { isFreeTierEnabled } = useFreeTierOnboarding() @@ -147,6 +149,14 @@ const signUpWithEmail = async (values: SignUpData, turnstileToken?: string) => { onMounted(async () => { telemetry?.trackSignupOpened() - userIsInChina.value = await isInChina() + // Fail open. `isInChina` bounds only its Google leg; its Baidu fallback can + // hang on networks that blackhole rather than reset, and a probe that never + // settles must not be indistinguishable from a permanent block. + userIsInChina.value = await Promise.race([ + isInChina().catch(() => false), + new Promise((resolve) => + setTimeout(() => resolve(false), REGION_CHECK_TIMEOUT_MS) + ) + ]) }) From ebc981305113390facefe285a9158e04f79ba8fa Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Mon, 10 Aug 2026 21:21:11 +0530 Subject: [PATCH 3/9] fix: source the sign-up region gate from the CDN edge and bound every probe The email sign-up gate withheld the form behind an async China check that had no guaranteed exit, and the detector behind it was unsound. A caller-side 1500ms fallback made it worse: it fired before the probe's own 2000ms Google leg could answer, so a real "in China" verdict was silently overridden with "allowed" -- the exact leak the gate exists to close. Prefer the client country from the CDN edge, which returns a geo-IP answer cross-origin in one request and drops the google.com/baidu.com pings from the common path. Those pings leaked the user's IP to third parties from the very page whose purpose is minimizing data exposure. The reachability heuristic survives only as a fallback for when the edge cannot answer, so the desktop installer's mirror choice keeps working. Every leg is now bounded by a deadline the code owns rather than an abort signal alone, since a request the browser never settles would otherwise hang forever. The two durations are the pre-existing 2000ms and 150ms values, named rather than retuned; no new timeout was invented. Extract useRegionGate so the pending/blocked/allowed tri-state lives in one place with fail-open behaviour baked in, and consume it from both sign-up surfaces. SignInContent carried an identical submit race behind ref(false), so the leak was only ever closed on the cloud view. Policy shape is unchanged: email sign-up blocked in CN, OAuth allowed, login ungated, and the region copy is byte-identical pending legal review. --- .../src/networkUtil.test.ts | 107 +++++++++ .../shared-frontend-utils/src/networkUtil.ts | 121 +++++++--- .../dialog/content/SignInContent.test.ts | 217 ++++++++++++++++++ .../dialog/content/SignInContent.vue | 25 +- src/composables/auth/useRegionGate.test.ts | 71 ++++++ src/composables/auth/useRegionGate.ts | 26 +++ .../cloud/onboarding/CloudSignupView.test.ts | 33 ++- .../cloud/onboarding/CloudSignupView.vue | 26 +-- 8 files changed, 565 insertions(+), 61 deletions(-) create mode 100644 packages/shared-frontend-utils/src/networkUtil.test.ts create mode 100644 src/components/dialog/content/SignInContent.test.ts create mode 100644 src/composables/auth/useRegionGate.test.ts create mode 100644 src/composables/auth/useRegionGate.ts diff --git a/packages/shared-frontend-utils/src/networkUtil.test.ts b/packages/shared-frontend-utils/src/networkUtil.test.ts new file mode 100644 index 00000000000..085453a193d --- /dev/null +++ b/packages/shared-frontend-utils/src/networkUtil.test.ts @@ -0,0 +1,107 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { getClientCountry, isInChina } from './networkUtil' + +const traceResponse = (body: string, ok = true) => + ({ ok, text: () => Promise.resolve(body) }) as Response + +const TRACE_BODY = (loc: string) => + `fl=1187f27\nh=cloud.comfy.org\nloc=${loc}\ntls=TLSv1.3\n` + +/** + * A network that blackholes: never resolves, never rejects, and ignores the + * abort signal entirely. Only a deadline of our own can escape it. + */ +const neverSettles = () => new Promise(() => {}) + +/** Resolves to the settled value, or to `PENDING` if the promise has not. */ +const settlementOf = (promise: Promise) => + Promise.race([promise, Promise.resolve().then(() => 'PENDING' as const)]) + +const fetchMock = vi.fn() + +beforeEach(() => { + vi.stubGlobal('fetch', fetchMock) + vi.stubGlobal('navigator', { language: 'en-US' }) + fetchMock.mockReset() +}) + +afterEach(() => { + vi.unstubAllGlobals() + vi.useRealTimers() +}) + +describe('getClientCountry', () => { + it('returns the uppercased loc value from the edge trace', async () => { + fetchMock.mockResolvedValue(traceResponse(TRACE_BODY('cn'))) + + await expect(getClientCountry()).resolves.toBe('CN') + }) + + it.for([ + [ + 'a non-200 response', + () => Promise.resolve(traceResponse('loc=CN', false)) + ], + [ + 'a body with no loc line', + () => Promise.resolve(traceResponse('h=x\nts=1')) + ], + ['an empty loc value', () => Promise.resolve(traceResponse('loc=\n'))], + ['a network error', () => Promise.reject(new Error('offline'))] + ] as const)('returns undefined for %s', async ([, respond]) => { + fetchMock.mockImplementation(respond) + + await expect(getClientCountry()).resolves.toBeUndefined() + }) + + it('gives up rather than hanging when the edge never answers', async () => { + vi.useFakeTimers() + fetchMock.mockImplementation(neverSettles) + + const country = getClientCountry() + expect(await settlementOf(country)).toBe('PENDING') + + await vi.advanceTimersByTimeAsync(2000) + + expect(await settlementOf(country)).toBeUndefined() + }) +}) + +describe('isInChina', () => { + it('trusts the edge answer over the reachability heuristic', async () => { + fetchMock.mockResolvedValue(traceResponse(TRACE_BODY('CN'))) + + await expect(isInChina()).resolves.toBe(true) + expect(fetchMock).toHaveBeenCalledTimes(1) + }) + + it('reports outside China when the edge names another country', async () => { + fetchMock.mockResolvedValue(traceResponse(TRACE_BODY('IN'))) + + await expect(isInChina()).resolves.toBe(false) + }) + + it('falls back to the reachability heuristic when the edge cannot answer', async () => { + vi.stubGlobal('navigator', { language: 'zh-CN' }) + fetchMock.mockImplementation((url: string) => + url.includes('cdn-cgi') + ? Promise.reject(new Error('edge down')) + : Promise.reject(new Error('blocked')) + ) + + await expect(isInChina()).resolves.toBe(true) + }) + + it('settles even when every probe hangs forever', async () => { + vi.useFakeTimers() + fetchMock.mockImplementation(neverSettles) + + const verdict = isInChina() + // Each leg only schedules its deadline once the previous one has expired. + for (const _ of [0, 1, 2]) await vi.advanceTimersByTimeAsync(2000) + + expect(await settlementOf(verdict)).toBe(false) + expect(fetchMock).toHaveBeenCalledTimes(3) + }) +}) diff --git a/packages/shared-frontend-utils/src/networkUtil.ts b/packages/shared-frontend-utils/src/networkUtil.ts index 7ae59723265..c13eb2730f0 100644 --- a/packages/shared-frontend-utils/src/networkUtil.ts +++ b/packages/shared-frontend-utils/src/networkUtil.ts @@ -12,51 +12,106 @@ export const checkUrlReachable = async (url: string): Promise => { } /** - * Checks if the user is likely in mainland China by: - * 1. Checking navigator.language - * 2. Testing connectivity to commonly blocked services - * 3. Testing latency to China-specific domains + * Cloudflare's edge echoes the request's geo-IP country here. It is an + * implementation detail of our CDN rather than a contract we own; the durable + * form is a first-party endpoint echoing the `CF-IPCountry` header. */ -export async function isInChina(): Promise { - // Quick check based on language/locale - const isChineseLocale = navigator.language.toLowerCase().startsWith('zh-cn') +const CLIENT_COUNTRY_URL = 'https://cloud.comfy.org/cdn-cgi/trace' + +/** Pre-existing bound on the Google reachability probe, reused for every leg. */ +const PROBE_TIMEOUT_MS = 2000 + +/** Pre-existing threshold: Baidu answering this fast implies a China route. */ +const CHINA_LATENCY_MS = 150 + +const parseTraceCountry = (body: string): string | undefined => + body + .split('\n') + .find((line) => line.startsWith('loc=')) + ?.slice('loc='.length) + .trim() + .toUpperCase() || undefined + +/** + * Fetches with a deadline the caller controls. The abort signal alone is not + * enough: a request the browser never resolves nor rejects would leave the + * promise pending forever, so the deadline also rejects on its own. + */ +async function fetchWithin(url: string, init: RequestInit): Promise { + const controller = new AbortController() + let expire: ReturnType | undefined + + const deadline = new Promise((_, reject) => { + expire = setTimeout(() => { + controller.abort() + reject(new Error(`Timed out after ${PROBE_TIMEOUT_MS}ms: ${url}`)) + }, PROBE_TIMEOUT_MS) + }) try { - // Test connectivity to Google - commonly blocked in China - const googleTest = await Promise.race([ - fetch('https://www.google.com', { - mode: 'no-cors', - cache: 'no-cache' - }), - new Promise((_, reject) => setTimeout(() => reject(), 2000)) + return await Promise.race([ + fetch(url, { ...init, signal: controller.signal }), + deadline ]) + } finally { + clearTimeout(expire) + } +} - // If Google is accessible, user is likely not in China - if (googleTest) { - return false - } +/** + * Resolves the client's ISO country code from the CDN edge, or `undefined` when + * the edge cannot answer. One bounded request, no third-party pings. + */ +export async function getClientCountry(): Promise { + try { + const response = await fetchWithin(CLIENT_COUNTRY_URL, { + cache: 'no-store' + }) + if (!response.ok) return undefined + + return parseTraceCountry(await response.text()) } catch { - // Google is not accessible - potential indicator of being in China - if (isChineseLocale) { - return true - } + return undefined + } +} + +const probe = (url: string) => + fetchWithin(url, { mode: 'no-cors', cache: 'no-cache' }) + +/** + * Reachability heuristic used only when the edge cannot name the country. + * Unsound in both directions — a VPN user in China reaches Google, and a + * `zh-CN` user anywhere is blocked whenever Google is briefly unreachable. + */ +async function isInChinaByProbe(): Promise { + const isChineseLocale = navigator.language.toLowerCase().startsWith('zh-cn') + + try { + await probe('https://www.google.com') + return false + } catch { + if (isChineseLocale) return true - // Additional check - test latency to a reliable Chinese domain try { const start = performance.now() - await fetch('https://www.baidu.com', { - mode: 'no-cors', - cache: 'no-cache' - }) - const latency = performance.now() - start - - // If Baidu responds quickly (<150ms), user is likely in China - return latency < 150 + await probe('https://www.baidu.com') + return performance.now() - start < CHINA_LATENCY_MS } catch { - // If both tests fail, default to locale check return isChineseLocale } } +} + +/** + * Whether the client is in mainland China. Prefers the edge's geo-IP answer and + * falls back to the reachability heuristic when the edge is unreachable. + * + * Every leg is bounded, so this always settles — callers must not add a timeout + * of their own, which would pre-empt a slow but real answer. + */ +export async function isInChina(): Promise { + const country = await getClientCountry() + if (country !== undefined) return country === 'CN' - return false + return isInChinaByProbe() } diff --git a/src/components/dialog/content/SignInContent.test.ts b/src/components/dialog/content/SignInContent.test.ts new file mode 100644 index 00000000000..1baf9c7756d --- /dev/null +++ b/src/components/dialog/content/SignInContent.test.ts @@ -0,0 +1,217 @@ +import { render, screen, waitFor } from '@testing-library/vue' +import { ref } from 'vue' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { createI18n } from 'vue-i18n' + +import SignInContent from '@/components/dialog/content/SignInContent.vue' + +vi.mock('@/composables/auth/useAuthActions', () => ({ + useAuthActions: () => ({ + signInWithGoogle: vi.fn(), + signInWithGithub: vi.fn(), + signInWithEmail: vi.fn(), + signUpWithEmail: vi.fn(), + accessError: ref(false) + }) +})) + +vi.mock('@/base/webviewDetection', () => ({ isEmbeddedWebView: () => false })) +vi.mock('@/utils/hostWhitelist', () => ({ + isHostWhitelisted: () => true, + normalizeHost: (host: string) => host +})) +vi.mock('@/platform/remoteConfig/remoteConfig', () => ({ + remoteConfig: ref({}), + configValueOrDefault: (_config: unknown, _key: string, fallback: string) => + fallback +})) + +const inChina = vi.hoisted(() => ({ + value: false, + pending: null as Promise | null, + /** Detection that never settles, as on a network that blackholes. */ + hang() { + this.pending = new Promise(() => {}) + }, + /** Holds detection pending; returns the settle function. */ + defer(): (inChina: boolean) => void { + let settle!: (inChina: boolean) => void + this.pending = new Promise((resolve) => { + settle = resolve + }) + return settle + }, + reject(error: Error) { + this.pending = Promise.reject(error) + } +})) +vi.mock('@/utils/networkUtil', () => ({ + isInChina: () => inChina.pending ?? Promise.resolve(inChina.value) +})) + +const MESSAGES = { + auth: { + login: { + title: 'Sign in', + newUser: 'New user?', + signUp: 'Sign up', + orContinueWith: 'or continue with', + loginWithGoogle: 'Sign in with Google', + loginWithGithub: 'Sign in with GitHub', + useApiKey: 'Use API key', + termsText: 'Terms', + termsLink: 'Terms of Service', + andText: 'and', + privacyLink: 'Privacy Policy', + questionsContactPrefix: 'Questions?', + insecureContextWarning: 'Insecure context' + }, + signup: { + title: 'Sign up', + alreadyHaveAccount: 'Already have an account?', + signIn: 'Sign in', + signUpWithGoogle: 'Sign up with Google', + signUpWithGithub: 'Sign up with GitHub', + regionRestrictionChina: 'Email sign-up is unavailable in your region.' + }, + apiKey: { helpText: 'Help', generateKey: 'Generate key' }, + reauthRequired: { title: 'Reauth', message: 'Reauth' } + }, + g: { comfy: 'Comfy' }, + toastMessages: { useApiKeyTip: 'Tip' } +} + +function renderSignInContent() { + return render(SignInContent, { + props: { onSuccess: vi.fn() }, + global: { + plugins: [ + createI18n({ legacy: false, locale: 'en', messages: { en: MESSAGES } }) + ], + stubs: { + SignUpForm: { template: '
' }, + SignInForm: { template: '' }, + ApiKeyForm: true, + Divider: true, + Message: { template: '
' } + } + } + }) +} + +/** The dialog opens on sign-in; sign-up is the gated surface. */ +async function switchToSignUp(advanceTimers?: (ms: number) => void) { + const user = (await import('@testing-library/user-event')).default.setup( + advanceTimers ? { advanceTimers } : {} + ) + await user.click(screen.getByText('Sign up')) +} + +beforeEach(() => { + inChina.value = false + inChina.pending = null +}) + +describe('SignInContent', () => { + it('withholds the sign-up form while region detection is pending', async () => { + const settle = inChina.defer() + renderSignInContent() + await switchToSignUp() + + expect(screen.getByTestId('region-check-pending')).toBeInTheDocument() + expect(screen.queryByTestId('signup-form')).not.toBeInTheDocument() + + settle(false) + + await waitFor(() => { + expect(screen.getByTestId('signup-form')).toBeInTheDocument() + }) + }) + + it('never renders the sign-up form inside China, pending or settled', async () => { + const settle = inChina.defer() + renderSignInContent() + await switchToSignUp() + + expect(screen.queryByTestId('signup-form')).not.toBeInTheDocument() + + // A slow but real "in China" answer must win; no fallback may pre-empt it. + settle(true) + + await waitFor(() => { + expect( + screen.getByText('Email sign-up is unavailable in your region.') + ).toBeInTheDocument() + }) + expect(screen.queryByTestId('signup-form')).not.toBeInTheDocument() + }) + + it('renders the sign-up form outside China', async () => { + renderSignInContent() + await switchToSignUp() + + await waitFor(() => { + expect(screen.getByTestId('signup-form')).toBeInTheDocument() + }) + expect( + screen.queryByText('Email sign-up is unavailable in your region.') + ).not.toBeInTheDocument() + }) + + it('releases the sign-up form when region detection fails', async () => { + inChina.reject(new Error('probe failed')) + renderSignInContent() + await switchToSignUp() + + await waitFor(() => { + expect(screen.getByTestId('signup-form')).toBeInTheDocument() + }) + }) + + it('keeps the form withheld however long detection takes', async () => { + // Fake timers must predate mount, or a fallback scheduled during mount runs + // on the real clock and escapes the drain below. + vi.useFakeTimers() + try { + inChina.hang() + renderSignInContent() + await switchToSignUp(vi.advanceTimersByTime) + + expect(screen.getByTestId('region-check-pending')).toBeInTheDocument() + + // Draining every scheduled timer proves no caller-side fallback releases + // the form on detection's behalf. + await vi.advanceTimersByTimeAsync(60_000) + + expect(screen.queryByTestId('signup-form')).not.toBeInTheDocument() + expect(screen.getByTestId('region-check-pending')).toBeInTheDocument() + } finally { + vi.useRealTimers() + } + }) + + it('leaves sign-in ungated by region', async () => { + inChina.value = true + renderSignInContent() + + await waitFor(() => { + expect(screen.getByTestId('signin-form')).toBeInTheDocument() + }) + expect(screen.queryByTestId('region-check-pending')).not.toBeInTheDocument() + }) + + it('offers social sign-up inside China', async () => { + inChina.value = true + renderSignInContent() + await switchToSignUp() + + await waitFor(() => { + expect( + screen.getByRole('button', { name: /Sign up with Google/ }) + ).toBeInTheDocument() + }) + expect( + screen.getByRole('button', { name: /Sign up with GitHub/ }) + ).toBeInTheDocument() + }) +}) diff --git a/src/components/dialog/content/SignInContent.vue b/src/components/dialog/content/SignInContent.vue index 34746e44998..f86a5947f70 100644 --- a/src/components/dialog/content/SignInContent.vue +++ b/src/components/dialog/content/SignInContent.vue @@ -34,7 +34,20 @@