Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 校验国内微信登录配置并隔离 Global (#4480)
bobo2d87efd57084
diff --git a/apps/mobile/.env.example b/apps/mobile/.env.exampleindex 4d5c73a9b7..f8a8fba064 100644--- a/apps/mobile/.env.example+++ b/apps/mobile/.env.example@@ -18,9 +18,16 @@ EXPO_PUBLIC_XDT_DEVICE_LINK_API_BASE_URL=EXPO_PUBLIC_CINDY_GOOGLE_WEB_CLIENT_ID=EXPO_PUBLIC_CINDY_GOOGLE_IOS_CLIENT_ID=EXPO_PUBLIC_CINDY_GOOGLE_IOS_URL_SCHEME=-# CN WeChat 原生登录(部署时由 EAS environment 注入)+# CN WeChat 原生登录:本地填 apps/mobile/.env;EAS/自建打包机注入下面两个公开变量。+# 仅 EXPO_PUBLIC_CINDY_AUTH_REGION=cn 或 dev 消费;Global 不启用微信。+# 两项同时留空表示未启用;启用时必须同时填写,部分填写或非法链接会在 prebuild 报错。+# 移动应用 AppID,须与 auth-server/.env.cn 的 WECHAT_MOBILE_APPID 一致(不是网站应用 AppID)。EXPO_PUBLIC_CINDY_WECHAT_APP_ID=+# 已在微信开放平台登记的 iOS HTTPS Universal Link,例如 https://login.example.com/wechat/。+# 域名须部署匹配 Team ID / Bundle ID 的 apple-app-site-association;Android 仍使用同一移动应用配置。EXPO_PUBLIC_CINDY_WECHAT_UNIVERSAL_LINK=+# AppSecret 只保存在 auth-server 的环境配置中,禁止加入客户端变量或安装包。+# 首次启用需重新生成/构建原生安装包;仅更新 JS 不会补上 URL Scheme、Associated Domains 或 WXEntryActivity。# Dev / EAS TapDB 配置。自建线不读这里,改读 scripts/self-host-regions.json 的 tapdb 块。EXPO_PUBLIC_TAPTAP_CLIENT_ID=EXPO_PUBLIC_TAPTAP_CLIENT_TOKEN=diff --git a/apps/mobile/app.config.js b/apps/mobile/app.config.jsindex d4bab3d716..e5e0f20bdf 100644--- a/apps/mobile/app.config.js+++ b/apps/mobile/app.config.js@@ -185,7 +185,7 @@ function resolveAppStoreId(region) {return value;}-function withNativeAuthPlugins(plugins, env) {+function withNativeAuthPlugins(plugins, env, region) {const next = [...plugins];if (env.googleIosUrlScheme) {next.push([@@ -193,10 +193,38 @@ function withNativeAuthPlugins(plugins, env) {{ iosUrlScheme: env.googleIosUrlScheme },]);}- if (env.wechatAppId && env.wechatUniversalLink) {+ // 微信公开配置可能残留在同一打包机的 shell 中,不能进入 Global 原生配置。+ // 两项全空表示未启用;只填一项必须在 prebuild 阶段报错,避免发出无回跳能力的包。+ const wechatEnabled = region === 'cn' || region === 'dev';+ const appId = wechatEnabled ? env.wechatAppId?.trim() || '' : '';+ const universalLink = wechatEnabled ? env.wechatUniversalLink?.trim() || '' : '';+ if (!!appId !== !!universalLink) {+ throw new Error(+ 'EXPO_PUBLIC_CINDY_WECHAT_APP_ID and EXPO_PUBLIC_CINDY_WECHAT_UNIVERSAL_LINK must both be set or both be empty',+ );+ }+ if (appId && universalLink) {+ let parsed;+ try {+ parsed = new URL(universalLink);+ } catch {+ throw new Error('EXPO_PUBLIC_CINDY_WECHAT_UNIVERSAL_LINK must be an https URL');+ }+ if (+ parsed.protocol !== 'https:' ||+ !parsed.hostname ||+ parsed.username ||+ parsed.password ||+ parsed.search ||+ parsed.hash+ ) {+ throw new Error(+ 'EXPO_PUBLIC_CINDY_WECHAT_UNIVERSAL_LINK must be an https URL without credentials, query, or fragment',+ );+ }next.push(['xdt-wechat-login/plugin',- { appId: env.wechatAppId, universalLink: env.wechatUniversalLink },+ { appId, universalLink },]);}return next;@@ -295,7 +323,7 @@ module.exports = (context = {}) => {wechatAppId: process.env.EXPO_PUBLIC_CINDY_WECHAT_APP_ID?.trim(),wechatUniversalLink:process.env.EXPO_PUBLIC_CINDY_WECHAT_UNIVERSAL_LINK?.trim(),- }),+ }, region),extra: {...baseConfig.extra,...(easProjectId ? { eas: { projectId: easProjectId } } : {}),diff --git a/apps/mobile/src/__tests__/env.test.ts b/apps/mobile/src/__tests__/env.test.tsindex 937c6b3364..bc06b9b34a 100644--- a/apps/mobile/src/__tests__/env.test.ts+++ b/apps/mobile/src/__tests__/env.test.ts@@ -8,9 +8,24 @@ import {resolveEnvFlag,resolveDeviceLinkApiBaseUrl,resolveMobileGoogleConfig,+ resolveMobileWechatConfig,} from '@/config/env';describe('mobile env', () => {+ it('keeps WeChat public configuration in CN and explicitly configured dev builds', () => {+ const env = {+ EXPO_PUBLIC_CINDY_WECHAT_APP_ID: ' wx-test-mobile ',+ EXPO_PUBLIC_CINDY_WECHAT_UNIVERSAL_LINK: ' https://login.example.com/wechat/ ',+ };+ for (const region of ['cn', 'dev'] as const) {+ expect(resolveMobileWechatConfig(region, env)).toEqual({+ appId: 'wx-test-mobile',+ universalLink: 'https://login.example.com/wechat/',+ });+ }+ expect(resolveMobileWechatConfig('global', env)).toEqual({ appId: '', universalLink: '' });+ expect(resolveMobileWechatConfig('cn', {})).toEqual({ appId: '', universalLink: '' });+ });it('resolves the device-link relay base URL(显式值优先,否则回落 env/dev 默认)', () => {expect(resolveDeviceLinkApiBaseUrl(undefined)).toBe(DEFAULT_DEVICE_LINK_API_BASE_URL);expect(resolveDeviceLinkApiBaseUrl('')).toBe(DEFAULT_DEVICE_LINK_API_BASE_URL);diff --git a/apps/mobile/src/__tests__/nativeAppConfig.test.ts b/apps/mobile/src/__tests__/nativeAppConfig.test.tsindex 64742181d9..85881b131d 100644--- a/apps/mobile/src/__tests__/nativeAppConfig.test.ts+++ b/apps/mobile/src/__tests__/nativeAppConfig.test.ts@@ -22,6 +22,8 @@ const managedEnvKeys = ['EXPO_PUBLIC_CINDY_GOOGLE_WEB_CLIENT_ID','EXPO_PUBLIC_CINDY_GOOGLE_IOS_CLIENT_ID','EXPO_PUBLIC_CINDY_GOOGLE_IOS_URL_SCHEME',+ 'EXPO_PUBLIC_CINDY_WECHAT_APP_ID',+ 'EXPO_PUBLIC_CINDY_WECHAT_UNIVERSAL_LINK','CINDY_USE_LOCAL_REGION_CONFIG','CINDY_SELF_HOST_REGIONS_FILE','CINDY_MOBILE_OTA_NATIVE',@@ -49,6 +51,35 @@ afterEach(() => {});describe('mobile native app config', () => {+ it('enables the existing WeChat SDK plugin only for configured CN builds', () => {+ const buildConfig = require(resolve(process.cwd(), 'app.config.js'));+ process.env.EXPO_PUBLIC_CINDY_AUTH_REGION = 'cn';+ expect(buildConfig().plugins).not.toContainEqual(expect.arrayContaining(['xdt-wechat-login/plugin']));+ process.env.EXPO_PUBLIC_CINDY_WECHAT_APP_ID = ' wx-test-mobile ';+ process.env.EXPO_PUBLIC_CINDY_WECHAT_UNIVERSAL_LINK = ' https://login.example.com/wechat/ ';+ expect(buildConfig().plugins).toContainEqual([+ 'xdt-wechat-login/plugin',+ { appId: 'wx-test-mobile', universalLink: 'https://login.example.com/wechat/' },+ ]);+ process.env.EXPO_PUBLIC_CINDY_AUTH_REGION = 'global';+ expect(buildConfig().plugins).not.toContainEqual(expect.arrayContaining(['xdt-wechat-login/plugin']));+ });++ it.each([+ ['wx-test-mobile', ''],+ ['', 'https://login.example.com/wechat/'],+ ['wx-test-mobile', 'http://login.example.com/wechat/'],+ ['wx-test-mobile', 'not-a-url'],+ ['wx-test-mobile', 'https://user:[email protected]/wechat/'],+ ['wx-test-mobile', 'https://login.example.com/wechat/?source=build'],+ ['wx-test-mobile', 'https://login.example.com/wechat/#callback'],+ ])('rejects incomplete or invalid WeChat config before native generation (%s, %s)', (appId, link) => {+ const buildConfig = require(resolve(process.cwd(), 'app.config.js'));+ process.env.EXPO_PUBLIC_CINDY_AUTH_REGION = 'cn';+ process.env.EXPO_PUBLIC_CINDY_WECHAT_APP_ID = appId;+ process.env.EXPO_PUBLIC_CINDY_WECHAT_UNIVERSAL_LINK = link;+ expect(() => buildConfig()).toThrow(/EXPO_PUBLIC_CINDY_WECHAT/);+ });it('defaults to the CN app identity and requires an explicit Global build', () => {const appJson = JSON.parse(readFileSync(resolve(process.cwd(), 'app.json'), 'utf8'),diff --git a/apps/mobile/src/auth/__tests__/mobileSocialLoginMode.test.ts b/apps/mobile/src/auth/__tests__/mobileSocialLoginMode.test.tsindex 822bc15900..e7af9b4bf0 100644--- a/apps/mobile/src/auth/__tests__/mobileSocialLoginMode.test.ts+++ b/apps/mobile/src/auth/__tests__/mobileSocialLoginMode.test.ts@@ -3,6 +3,17 @@ import { describe, expect, it } from 'vitest';import { resolveMobileSocialLoginMode } from '@/auth/mobileSocialLoginMode';describe('resolveMobileSocialLoginMode', () => {+ it.each(['ios', 'android'])('uses native WeChat on configured CN %s', (platform) => {+ expect(resolveMobileSocialLoginMode({+ provider: 'wechat', region: 'cn', platform, nativeSupported: true,+ })).toBe('native');+ expect(resolveMobileSocialLoginMode({+ provider: 'wechat', region: 'cn', platform, nativeSupported: false,+ })).toBeNull();+ expect(resolveMobileSocialLoginMode({+ provider: 'wechat', region: 'global', platform, nativeSupported: true,+ })).toBeNull();+ });it('uses browser PKCE for Apple on Global Android', () => {expect(resolveMobileSocialLoginMode({diff --git a/apps/mobile/src/auth/__tests__/nativeWechatLogin.test.ts b/apps/mobile/src/auth/__tests__/nativeWechatLogin.test.tsnew file mode 100644index 0000000000..03a7f947ea--- /dev/null+++ b/apps/mobile/src/auth/__tests__/nativeWechatLogin.test.ts@@ -0,0 +1,122 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const native = vi.hoisted(() => ({+ platform: 'ios',+ appId: 'wx-test-mobile',+ universalLink: 'https://login.example.com/wechat/',+ appState: 'active',+ listeners: new Set<(state: string) => void>(),+ installed: vi.fn(),+ request: vi.fn(),+ cancel: vi.fn(),+}));++vi.mock('expo-crypto', () => ({}));+vi.mock('@/auth/pkce', () => ({ createState: () => 'test-random-wechat-state' }));+vi.mock('@/config/env', () => ({+ GOOGLE_IOS_CLIENT_ID: '',+ GOOGLE_IOS_URL_SCHEME: '',+ GOOGLE_WEB_CLIENT_ID: '',+ get WECHAT_APP_ID() { return native.appId; },+ get WECHAT_UNIVERSAL_LINK() { return native.universalLink; },+}));+vi.mock('react-native', () => ({+ Platform: { get OS() { return native.platform; } },+ AppState: {+ get currentState() { return native.appState; },+ addEventListener: (_name: string, listener: (state: string) => void) => {+ native.listeners.add(listener);+ return { remove: () => native.listeners.delete(listener) };+ },+ },+}));+vi.mock('xdt-wechat-login', () => ({+ isWechatInstalled: native.installed,+ requestWechatAuthCode: native.request,+ cancelWechatAuthRequest: native.cancel,+}));++import { acquireNativeSocialCredential, isNativeSocialProviderSupported } from '../nativeSocial';++function changeAppState(state: string) {+ native.appState = state;+ for (const listener of native.listeners) listener(state);+}++beforeEach(() => {+ vi.useFakeTimers();+ native.platform = 'ios';+ native.appState = 'active';+ native.appId = 'wx-test-mobile';+ native.universalLink = 'https://login.example.com/wechat/';+ native.installed.mockReset().mockResolvedValue(true);+ native.request.mockReset().mockResolvedValue({ code: 'test-wechat-code' });+ native.cancel.mockReset().mockResolvedValue(undefined);+});++afterEach(() => {+ expect(native.listeners.size).toBe(0);+ expect(vi.getTimerCount()).toBe(0);+ vi.useRealTimers();+});++describe('native WeChat credential acquisition', () => {+ it.each(['ios', 'android'])('acquires only an authorization code on %s', async (platform) => {+ native.platform = platform;+ expect(isNativeSocialProviderSupported('wechat')).toBe(true);+ await expect(acquireNativeSocialCredential('wechat')).resolves.toEqual({ code: 'test-wechat-code' });+ expect(native.request).toHaveBeenCalledWith({+ appId: 'wx-test-mobile',+ universalLink: 'https://login.example.com/wechat/',+ scope: 'snsapi_userinfo',+ state: 'test-random-wechat-state',+ });+ expect(native.cancel).not.toHaveBeenCalled();+ });++ it('does not launch WeChat when public configuration is missing', async () => {+ native.appId = '';+ expect(isNativeSocialProviderSupported('wechat')).toBe(false);+ await expect(acquireNativeSocialCredential('wechat')).rejects.toMatchObject({+ code: 'SOCIAL_PROVIDER_NOT_CONFIGURED',+ });+ expect(native.installed).not.toHaveBeenCalled();+ expect(native.request).not.toHaveBeenCalled();+ });++ it('reports WeChat as unavailable when it is not installed', async () => {+ native.installed.mockResolvedValue(false);+ await expect(acquireNativeSocialCredential('wechat')).rejects.toMatchObject({+ code: 'SOCIAL_PROVIDER_UNAVAILABLE',+ });+ expect(native.request).not.toHaveBeenCalled();+ });++ it('cleans up after cancellation and permits a new request', async () => {+ native.request.mockRejectedValueOnce(Object.assign(new Error('cancelled'), { code: 'ERR_WECHAT_CANCELLED' }));+ await expect(acquireNativeSocialCredential('wechat')).rejects.toMatchObject({ code: 'ERR_WECHAT_CANCELLED' });+ await expect(acquireNativeSocialCredential('wechat')).resolves.toEqual({ code: 'test-wechat-code' });+ });++ it('does not time out while the user authorizes in WeChat', async () => {+ let complete!: (result: { code: string }) => void;+ native.request.mockImplementationOnce(() => new Promise((resolve) => { complete = resolve; }));+ const result = acquireNativeSocialCredential('wechat');+ await vi.advanceTimersByTimeAsync(2_000);+ changeAppState('background');+ await vi.advanceTimersByTimeAsync(60_000);+ expect(native.cancel).not.toHaveBeenCalled();+ changeAppState('active');+ complete({ code: 'test-delayed-wechat-code' });+ await expect(result).resolves.toEqual({ code: 'test-delayed-wechat-code' });+ });++ it('releases a timed-out native request before retrying', async () => {+ native.request.mockImplementationOnce(() => new Promise(() => undefined));+ const result = expect(acquireNativeSocialCredential('wechat')).rejects.toMatchObject({ code: 'REQUEST_TIMEOUT' });+ await vi.advanceTimersByTimeAsync(8_000);+ await result;+ expect(native.cancel).toHaveBeenCalledOnce();+ await expect(acquireNativeSocialCredential('wechat')).resolves.toEqual({ code: 'test-wechat-code' });+ });+});diff --git a/apps/mobile/src/auth/mobileSocialLoginMode.ts b/apps/mobile/src/auth/mobileSocialLoginMode.tsindex eaad4453cd..1f1ca439c3 100644--- a/apps/mobile/src/auth/mobileSocialLoginMode.ts+++ b/apps/mobile/src/auth/mobileSocialLoginMode.ts@@ -13,6 +13,7 @@ export function resolveMobileSocialLoginMode(input: {platform: string;nativeSupported: boolean;}): MobileSocialLoginMode | null {+ if (input.provider === 'wechat' && input.region !== 'cn') return null;if (input.nativeSupported) return 'native';if (input.provider === 'apple' &&diff --git a/apps/mobile/src/config/env.ts b/apps/mobile/src/config/env.tsindex 2071bf25f2..ccd99746f9 100644--- a/apps/mobile/src/config/env.ts+++ b/apps/mobile/src/config/env.ts@@ -231,10 +231,29 @@ const GOOGLE_CONFIG = resolveMobileGoogleConfig(export const GOOGLE_WEB_CLIENT_ID = GOOGLE_CONFIG.webClientId;export const GOOGLE_IOS_CLIENT_ID = GOOGLE_CONFIG.iosClientId;export const GOOGLE_IOS_URL_SCHEME = GOOGLE_CONFIG.iosUrlScheme;-export const WECHAT_APP_ID =- process.env.EXPO_PUBLIC_CINDY_WECHAT_APP_ID?.trim() || '';-export const WECHAT_UNIVERSAL_LINK =- process.env.EXPO_PUBLIC_CINDY_WECHAT_UNIVERSAL_LINK?.trim() || '';+/** 微信配置只属于国内构建;与原生插件选择同源,不受登录后的组织区域影响。 */+export function resolveMobileWechatConfig(+ region: CindyAuthRegion,+ env: {+ EXPO_PUBLIC_CINDY_WECHAT_APP_ID?: string;+ EXPO_PUBLIC_CINDY_WECHAT_UNIVERSAL_LINK?: string;+ },+): { appId: string; universalLink: string } {+ if (region === 'global') return { appId: '', universalLink: '' };+ return {+ appId: env.EXPO_PUBLIC_CINDY_WECHAT_APP_ID?.trim() || '',+ universalLink: env.EXPO_PUBLIC_CINDY_WECHAT_UNIVERSAL_LINK?.trim() || '',+ };+}++const WECHAT_CONFIG = resolveMobileWechatConfig(AUTH_REGION, {+ // Metro 只内联静态 process.env.KEY,不能改为动态键或直接传 process.env。+ EXPO_PUBLIC_CINDY_WECHAT_APP_ID: process.env.EXPO_PUBLIC_CINDY_WECHAT_APP_ID,+ EXPO_PUBLIC_CINDY_WECHAT_UNIVERSAL_LINK:+ process.env.EXPO_PUBLIC_CINDY_WECHAT_UNIVERSAL_LINK,+});+export const WECHAT_APP_ID = WECHAT_CONFIG.appId;+export const WECHAT_UNIVERSAL_LINK = WECHAT_CONFIG.universalLink;export let DEVICE_LINK_API_BASE_URL = resolveDeviceLinkApiBaseUrl(configuredValue('EXPO_PUBLIC_XDT_DEVICE_LINK_API_BASE_URL'),diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.mdindex d3c124f735..f1afef27ab 100644--- a/docs/dev-rules/mobile-development.md+++ b/docs/dev-rules/mobile-development.md@@ -81,6 +81,22 @@ pnpm --filter mobile test:smoke## 专项入口+### 中国大陆版微信个人登录++- 复用 `xdt-wechat-login`:iOS/Android 拉起微信取临时 code,再由 auth-server 交换。+ PC 使用同一服务端的网站应用扫码入口。登录结果统一进入手机号补绑或身份选择流程。+- 在 Mobile `.env`(本地)或打包机环境中成对填写+ `EXPO_PUBLIC_CINDY_WECHAT_APP_ID` 与 `EXPO_PUBLIC_CINDY_WECHAT_UNIVERSAL_LINK`,+ 说明与空值占位见 `apps/mobile/.env.example`。AppID 必须匹配服务端+ `WECHAT_MOBILE_APPID`;服务端两组 Secret 不进入客户端。自建构建继续继承这两个+ 公开环境变量,不从服务端环境文件读取密钥。+- 仅 cn 和显式配置的 dev 构建消费微信配置;Global 忽略残留值。全空关闭入口,+ 半配置或非法 Universal Link 在原生配置生成前报错。首次启用需重新出原生包,+ 仅 OTA 无法添加回调配置;按下方冷更规则比对 fingerprint。+- 真机验证 iOS Universal Link/AASA、Android 包名/签名与 WXEntryActivity,覆盖+ 同意授权、取消、未安装微信、回到前台超时后重试。iOS Simulator 不支持微信授权。+ 未绑手机号须短信验证,已绑用户免短信;用同一微信在 PC 和两种手机上确认账号一致。+- 模拟器与真机排错:[`simulator-debugging.md`](../../apps/mobile/docs/simulator-debugging.md)。