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..0fa7d65e586 --- /dev/null +++ b/packages/shared-frontend-utils/src/networkUtil.test.ts @@ -0,0 +1,169 @@ +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` + +/** Blackholes: never settles and ignores the abort signal. */ +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'))], + [ + 'an unknown-country sentinel', + () => Promise.resolve(traceResponse(TRACE_BODY('XX'))) + ], + ['a Tor sentinel', () => Promise.resolve(traceResponse(TRACE_BODY('T1')))], + ['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() + }) + + it('gives up when the edge sends headers and then stalls the body', async () => { + vi.useFakeTimers() + fetchMock.mockResolvedValue({ + ok: true, + text: () => new Promise(() => {}) + } as Response) + + 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('reports inside China when only Baidu answers, and fast', async () => { + fetchMock.mockImplementation((url: string) => + url.includes('cdn-cgi') || url.includes('google') + ? Promise.reject(new Error('blocked')) + : Promise.resolve({ ok: true } as Response) + ) + + await expect( + isInChina(), + 'a China-routed client on a non-zh locale is only detectable by Baidu latency' + ).resolves.toBe(true) + }) + + it.for(['XX', 'T1'] as const)( + 'falls back to the heuristic when the edge answers %s', + async (sentinel) => { + vi.stubGlobal('navigator', { language: 'zh-CN' }) + fetchMock.mockImplementation((url: string) => + url.includes('cdn-cgi') + ? Promise.resolve(traceResponse(TRACE_BODY(sentinel))) + : Promise.reject(new Error('blocked')) + ) + + await expect( + isInChina(), + 'a sentinel names no country, so treating it as "not China" would wave through Tor and unknown-IP clients' + ).resolves.toBe(true) + } + ) + + it('reports outside China when the edge is down but Google answers', async () => { + fetchMock.mockImplementation((url: string) => + url.includes('cdn-cgi') + ? Promise.reject(new Error('edge down')) + : Promise.resolve({ ok: true } as Response) + ) + + await expect(isInChina()).resolves.toBe(false) + }) + + it('falls back to the locale when neither probe answers', async () => { + fetchMock.mockRejectedValue(new Error('blocked')) + + 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() + 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..2f3c2ef32db 100644 --- a/packages/shared-frontend-utils/src/networkUtil.ts +++ b/packages/shared-frontend-utils/src/networkUtil.ts @@ -4,7 +4,6 @@ const VALID_STATUS_CODES = [200, 201, 301, 302, 307, 308] export const checkUrlReachable = async (url: string): Promise => { try { const response = await axios.head(url) - // Additional check for successful response return VALID_STATUS_CODES.includes(response.status) } catch { return false @@ -12,51 +11,112 @@ 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 + * A CDN implementation detail, not a contract we own. The durable form is a + * first-party endpoint echoing `CF-IPCountry`. */ -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' + +/** Bounds every probe leg; two previously had none. */ +const PROBE_TIMEOUT_MS = 2000 + +/** Baidu answering this fast implies a China route. */ +const CHINA_LATENCY_MS = 150 + +/** `XX` is an unknown country and `T1` is Tor: neither names where the client is. */ +const UNRESOLVED_COUNTRIES = new Set(['XX', 'T1']) + +const parseTraceCountry = (body: string): string | undefined => { + const country = + body + .split('\n') + .find((line) => line.startsWith('loc=')) + ?.slice('loc='.length) + .trim() + .toUpperCase() || undefined + + return country && UNRESOLVED_COUNTRIES.has(country) ? undefined : country +} + +/** + * The abort signal alone is not enough: a request the browser never resolves + * nor rejects would hang forever, so the deadline rejects independently. + * + * `read` runs inside the deadline so a response that sends headers and then + * stalls its body is bounded too. + */ +async function fetchWithin( + url: string, + init: RequestInit, + read: (response: Response) => Promise +): 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 }).then(read), + deadline ]) + } finally { + clearTimeout(expire) + } +} - // If Google is accessible, user is likely not in China - if (googleTest) { - return false - } +/** ISO country from the CDN edge, or `undefined` when it cannot answer. */ +export async function getClientCountry(): Promise { + try { + const body = await fetchWithin( + CLIENT_COUNTRY_URL, + { cache: 'no-store' }, + async (response) => (response.ok ? response.text() : undefined) + ) + return body === undefined ? undefined : parseTraceCountry(body) } 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' }, async () => {}) + +/** + * Fallback for when the edge cannot answer. Unsound both ways: 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 } } +} + +/** + * Prefers the edge's geo-IP, falling back to the heuristic. Always settles, so + * callers must not add a timeout that could 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..3c2c54f6b30 --- /dev/null +++ b/src/components/dialog/content/SignInContent.test.ts @@ -0,0 +1,220 @@ +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: '
' } + } + } + }) +} + +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() + expect( + screen.getByRole('button', { name: /Sign up with Google/ }), + 'only email sign-up is gated on region; third-party auth never waits on the probe' + ).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() + + 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() + + await vi.advanceTimersByTimeAsync(60_000) + + expect( + screen.queryByTestId('signup-form'), + "no caller-side fallback may release the form on detection's behalf" + ).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 @@