Line data Source code
1 : /**
2 : * Where the client is, for the sign-up region gate in `./regionGate`. Browser
3 : * APIs only — `fetch`, `navigator`, `performance` — so the package stays free
4 : * of an HTTP client the host would otherwise have to install.
5 : */
6 :
7 : /**
8 : * A CDN implementation detail, not a contract we own. The durable form is a
9 : * first-party endpoint echoing `CF-IPCountry`.
10 : */
11 13 : const CLIENT_COUNTRY_URL = 'https://cloud.comfy.org/cdn-cgi/trace'
12 :
13 : /** Bounds every probe leg; two previously had none. */
14 13 : const PROBE_TIMEOUT_MS = 2000
15 :
16 : /** Baidu answering this fast implies a China route. */
17 13 : const CHINA_LATENCY_MS = 150
18 :
19 : /** `XX` is an unknown country and `T1` is Tor: neither names where the client is. */
20 13 : const UNRESOLVED_COUNTRIES = new Set(['XX', 'T1'])
21 :
22 13 : const parseTraceCountry = (body: string): string | undefined => {
23 12 : const country =
24 : body
25 : .split('\n')
26 : .find((line) => line.startsWith('loc='))
27 : ?.slice('loc='.length)
28 : .trim()
29 : .toUpperCase() || undefined
30 :
31 12 : return country && UNRESOLVED_COUNTRIES.has(country) ? undefined : country
32 : }
33 :
34 : /**
35 : * The abort signal alone is not enough: a request the browser never resolves
36 : * nor rejects would hang forever, so the deadline rejects independently.
37 : *
38 : * `read` runs inside the deadline so a response that sends headers and then
39 : * stalls its body is bounded too.
40 : */
41 13 : async function fetchWithin<T>(
42 : url: string,
43 : init: RequestInit,
44 : read: (response: Response) => Promise<T>
45 : ): Promise<T> {
46 13 : const controller = new AbortController()
47 13 : let expire: ReturnType<typeof setTimeout> | undefined
48 :
49 13 : const deadline = new Promise<never>((_, reject) => {
50 13 : expire = setTimeout(() => {
51 0 : controller.abort()
52 0 : reject(new Error(`Timed out after ${PROBE_TIMEOUT_MS}ms: ${url}`))
53 : }, PROBE_TIMEOUT_MS)
54 : })
55 :
56 13 : try {
57 13 : return await Promise.race([
58 : fetch(url, { ...init, signal: controller.signal }).then(read),
59 : deadline
60 : ])
61 : } finally {
62 12 : clearTimeout(expire)
63 : }
64 : }
65 :
66 : /** ISO country from the CDN edge, or `undefined` when it cannot answer. */
67 13 : export async function getClientCountry(): Promise<string | undefined> {
68 13 : try {
69 13 : const body = await fetchWithin(
70 : CLIENT_COUNTRY_URL,
71 : { cache: 'no-store' },
72 : async (response) => (response.ok ? response.text() : undefined)
73 : )
74 13 : return body === undefined ? undefined : parseTraceCountry(body)
75 : } catch {
76 0 : return undefined
77 : }
78 : }
79 :
80 13 : const probe = (url: string) =>
81 : fetchWithin(url, { mode: 'no-cors', cache: 'no-cache' }, async () => {})
82 :
83 : /**
84 : * Fallback for when the edge cannot answer. Unsound both ways: a VPN user in
85 : * China reaches Google, and a `zh-CN` user anywhere is blocked whenever Google
86 : * is briefly unreachable.
87 : */
88 0 : async function isInChinaByProbe(): Promise<boolean> {
89 0 : const isChineseLocale = navigator.language.toLowerCase().startsWith('zh-cn')
90 :
91 0 : try {
92 0 : await probe('https://www.google.com')
93 0 : return false
94 : } catch {
95 0 : if (isChineseLocale) return true
96 :
97 0 : try {
98 0 : const start = performance.now()
99 0 : await probe('https://www.baidu.com')
100 0 : return performance.now() - start < CHINA_LATENCY_MS
101 : } catch {
102 0 : return isChineseLocale
103 : }
104 : }
105 : }
106 :
107 : /**
108 : * Prefers the edge's geo-IP, falling back to the heuristic. Always settles, so
109 : * callers must not add a timeout that could pre-empt a slow but real answer.
110 : */
111 13 : export async function isInChina(): Promise<boolean> {
112 13 : const country = await getClientCountry()
113 12 : if (country !== undefined) return country === 'CN'
114 :
115 0 : return isInChinaByProbe()
116 : }
|