Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(mobile): 修复微信回调并暂时隐藏手机登录入口 (#4943)

boboe4d05c9bee64
diff --git a/apps/mobile/app/+native-intent.ts b/apps/mobile/app/+native-intent.ts
index dc005e25cb..51ecb9cae4 100644
--- a/apps/mobile/app/+native-intent.ts
+++ b/apps/mobile/app/+native-intent.ts
@@ -8,14 +8,24 @@
// 实际的 PKCE code 交换**不依赖路由**:由 src/auth/AuthContext.tsx 的 Linking.addEventListener /
// getInitialURL 监听器独立捕获原始 URL 并完成(见其 handleDeepLink)。本文件只负责别让路由 404。
//
-// 背景(为何 Android 暴露、iOS 不会):iOS 的系统认证会话通常会在会话内捕获
-// 自定义 scheme 并 inline 完成,router 不会导航到 /auth;Android 上服务器 302 到自定义
-// scheme 常以新 intent 冷启 App,expo-router 就撞上无路由的 /auth。此拦截让两端一致落到 index。
+// 系统浏览器认证与微信原生授权的回跳都可能同时送到 Router;微信 SDK 的
+// oauth / refreshToken 及 Universal Link 校验回跳由原生 delegate 消费,也不对应页面。本文件仅控制导航,
+// 不交换或解析授权票据,不更改原生 SDK 的 state 校验。
//
// 纯 JS(不进 @expo/fingerprint / 不改 runtimeVersion),可随热更下发。
+import { WECHAT_APP_ID, WECHAT_UNIVERSAL_LINK } from '@/config/env';
+import { isWechatSdkCallback } from '@/auth/wechatCallback';
+
export function redirectSystemPath({ path }: { path: string; initial: boolean }): string {
try {
+ // OpenSDK 的授权及 Universal Link 校验回调也会被 Expo Linking 广播给 Router。
+ // 它们由原生 delegate 消费,不能当页面显示(更不能在 404 中展示 code)。
+ // 不把微信 code 交给 auth-server 的 /auth PKCE 交换:两者不是同一种票据。
+ if (isWechatSdkCallback(path, {
+ appId: WECHAT_APP_ID,
+ universalLink: WECHAT_UNIVERSAL_LINK,
+ })) return '/';
// path 可能是完整 URL('cindycn://auth?code=...')或路径('/auth?code=...'),统一取出 pathname。
const noScheme = path.replace(/^[a-zA-Z][\w+.-]*:\/\//, '/');
const pathname = noScheme.split('?')[0].split('#')[0].replace(/\/+$/, '') || '/';
diff --git a/apps/mobile/modules/xdt-wechat-login/plugin/index.js b/apps/mobile/modules/xdt-wechat-login/plugin/index.js
index 4798879b83..2d4268ed93 100644
--- a/apps/mobile/modules/xdt-wechat-login/plugin/index.js
+++ b/apps/mobile/modules/xdt-wechat-login/plugin/index.js
@@ -38,6 +38,7 @@ function withWechatInfoPlist(config, appId) {
...(info.LSApplicationQueriesSchemes || []),
'weixin',
'weixinULAPI',
+ 'weixinURLParamsAPI',
]);
const urlTypes = Array.isArray(info.CFBundleURLTypes)
? info.CFBundleURLTypes
diff --git a/apps/mobile/src/__tests__/nativeAppConfig.test.ts b/apps/mobile/src/__tests__/nativeAppConfig.test.ts
index 85881b131d..b60c1a61e6 100644
--- a/apps/mobile/src/__tests__/nativeAppConfig.test.ts
+++ b/apps/mobile/src/__tests__/nativeAppConfig.test.ts
@@ -51,6 +51,29 @@ afterEach(() => {
});
describe('mobile native app config', () => {
+ it('generates all three official WeChat query schemes without dropping existing callbacks', async () => {
+ const withWechatLogin = require(resolve(process.cwd(), 'modules/xdt-wechat-login/plugin/index.js'));
+ const config = withWechatLogin({ name: 'Test app', slug: 'test-app' }, {
+ appId: 'wx-test-mobile',
+ universalLink: 'https://login.example.com/app/',
+ });
+ const result = await config.mods.ios.infoPlist({
+ ...config,
+ modResults: {
+ LSApplicationQueriesSchemes: ['existing-app', 'weixin'],
+ CFBundleURLTypes: [{ CFBundleURLSchemes: ['cindycn'] }],
+ },
+ modRequest: { platform: 'ios', modName: 'infoPlist' },
+ });
+ expect(result.modResults.LSApplicationQueriesSchemes).toEqual([
+ 'existing-app', 'weixin', 'weixinULAPI', 'weixinURLParamsAPI',
+ ]);
+ expect(result.modResults.CFBundleURLTypes).toEqual([
+ { CFBundleURLSchemes: ['cindycn'] },
+ { CFBundleURLName: 'wx-test-mobile', CFBundleURLSchemes: ['wx-test-mobile'] },
+ ]);
+ });
+
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';
diff --git a/apps/mobile/src/__tests__/nativeIntent.test.ts b/apps/mobile/src/__tests__/nativeIntent.test.ts
index 51b36a6cbe..7d509ca5f6 100644
--- a/apps/mobile/src/__tests__/nativeIntent.test.ts
+++ b/apps/mobile/src/__tests__/nativeIntent.test.ts
@@ -1,8 +1,52 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/config/env', () => ({
+ WECHAT_APP_ID: 'wx-test-mobile',
+ WECHAT_UNIVERSAL_LINK: 'https://login.example.com/app/',
+}));
import { redirectSystemPath } from '../../app/+native-intent';
describe('mobile native deep-link redirects', () => {
+ it.each([true, false])('keeps WeChat SDK callbacks out of navigation (initial=%s)', (initial) => {
+ for (const path of [
+ 'cindycn://oauth?code=test-wechat-code&state=test-state',
+ 'wx-test-mobile://oauth?code=test-wechat-code&state=test-state',
+ '/oauth/?code=test-wechat-code#fragment',
+ 'wx-test-mobile://refreshToken?wechat_auth_context_id=test-context',
+ 'https://login.example.com/app/wx-test-mobile/oauth?code=test-wechat-code',
+ 'https://login.example.com/app/wx-test-mobile/refreshToken/',
+ 'https://login.example.com/app/oauth?code=test-wechat-code',
+ 'cindycn://app/wx-test-mobile/oauth?code=test-wechat-code',
+ '/app/wx-test-mobile/refreshToken/',
+ 'https://login.example.com/app/wx-test-mobile/?_wechat_sdk_biz_data=test-payload&_wechat_sdk_biz_data_len=12',
+ 'cindycn://app/wx-test-mobile/?_wechat_sdk_biz_data=test-payload&_wechat_sdk_biz_data_len=12',
+ '/app/wx-test-mobile/?_wechat_sdk_biz_data=test-payload',
+ ]) {
+ expect(redirectSystemPath({ path, initial })).toBe('/');
+ }
+ });
+
+ it('does not consume unrelated paths, hosts or app IDs', () => {
+ for (const path of [
+ 'cindycn://oauth/another-route',
+ 'https://other.example.com/app/oauth?code=test-code',
+ 'https://login.example.com/elsewhere/oauth',
+ 'https://login.example.com/app/wx-other/oauth',
+ 'https://login.example.com/app/article',
+ 'https://[email protected]/app/oauth',
+ 'https://other.example.com/app/wx-test-mobile/?_wechat_sdk_biz_data=test-payload',
+ 'cindycn://app/wx-other/?_wechat_sdk_biz_data=test-payload',
+ 'cindycn://elsewhere/wx-test-mobile/?_wechat_sdk_biz_data=test-payload',
+ 'cindycn://app/wx-test-mobile/article?_wechat_sdk_biz_data=test-payload',
+ 'cindycn://app/wx-test-mobile/',
+ 'cindycn://app/wx-test-mobile/?other=test-payload#_wechat_sdk_biz_data=test-payload',
+ 'cindycn://app/wx-test-mobile/?_wechat_sdk_biz_data_extra=test-payload',
+ ]) {
+ expect(redirectSystemPath({ path, initial: false })).toBe(path);
+ }
+ });
+
it('routes the Share Extension handoff into a new conversation', () => {
expect(redirectSystemPath({
path: 'cindycn://expo-sharing',
diff --git a/apps/mobile/src/auth/__tests__/mobileSocialLoginMode.test.ts b/apps/mobile/src/auth/__tests__/mobileSocialLoginMode.test.ts
index e7af9b4bf0..c8ad6a1ee6 100644
--- a/apps/mobile/src/auth/__tests__/mobileSocialLoginMode.test.ts
+++ b/apps/mobile/src/auth/__tests__/mobileSocialLoginMode.test.ts
@@ -3,17 +3,57 @@ 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.each(['ios', 'android'])(
+ 'temporarily hides WeChat on %s even when configured',
+ (platform) => {
+ for (const region of ['cn', 'global'] as const) {
+ for (const nativeSupported of [true, false]) {
+ expect(
+ resolveMobileSocialLoginMode({
+ provider: 'wechat',
+ region,
+ platform,
+ nativeSupported,
+ }),
+ ).toBeNull();
+ }
+ }
+ },
+ );
+
+ it.each(['ios', 'android'])(
+ 'restores the configured CN WeChat path on %s when re-enabled',
+ (platform) => {
+ expect(
+ resolveMobileSocialLoginMode({
+ provider: 'wechat',
+ region: 'cn',
+ platform,
+ nativeSupported: true,
+ wechatLoginEnabled: true,
+ }),
+ ).toBe('native');
+ expect(
+ resolveMobileSocialLoginMode({
+ provider: 'wechat',
+ region: 'cn',
+ platform,
+ nativeSupported: false,
+ wechatLoginEnabled: true,
+ }),
+ ).toBeNull();
+ expect(
+ resolveMobileSocialLoginMode({
+ provider: 'wechat',
+ region: 'global',
+ platform,
+ nativeSupported: true,
+ wechatLoginEnabled: true,
+ }),
+ ).toBeNull();
+ },
+ );
+
it('uses browser PKCE for Apple on Global Android', () => {
expect(
resolveMobileSocialLoginMode({
diff --git a/apps/mobile/src/auth/__tests__/useMobileSocialProviderModes.test.tsx b/apps/mobile/src/auth/__tests__/useMobileSocialProviderModes.test.tsx
index d0ab5aa2f7..8c0a2f7872 100644
--- a/apps/mobile/src/auth/__tests__/useMobileSocialProviderModes.test.tsx
+++ b/apps/mobile/src/auth/__tests__/useMobileSocialProviderModes.test.tsx
@@ -37,8 +37,12 @@ import { useMobileSocialProviderModes } from '../useMobileSocialProviderModes';
const providers: SocialProvider[] = ['wechat'];
-function Probe() {
- const modes = useMobileSocialProviderModes({ providers, region: 'cn' });
+function Probe({ wechatLoginEnabled }: { wechatLoginEnabled?: boolean }) {
+ const modes = useMobileSocialProviderModes({
+ providers,
+ region: 'cn',
+ wechatLoginEnabled,
+ });
return (
<div>
{[...modes.keys()].map((provider) => (
@@ -51,9 +55,9 @@ function Probe() {
let host: HTMLDivElement;
let root: Root;
-async function renderProbe() {
+async function renderProbe(wechatLoginEnabled?: boolean) {
await act(async () => {
- root.render(<Probe />);
+ root.render(<Probe wechatLoginEnabled={wechatLoginEnabled} />);
await Promise.resolve();
});
}
@@ -78,23 +82,36 @@ describe('mobile social provider visibility', () => {
expect(native.listeners.size).toBe(0);
});
- it('shows WeChat on iOS only after the installation probe succeeds', async () => {
+ it('hides WeChat on iOS without probing the SDK', async () => {
native.available.mockResolvedValue(true);
await renderProbe();
+ expect(wechatButton()).toBeNull();
+ expect(native.available).not.toHaveBeenCalled();
+ expect(native.listeners.size).toBe(0);
+ });
+
+ it('hides WeChat on Android without probing installation', async () => {
+ native.platform = 'android';
+ await renderProbe();
+ expect(wechatButton()).toBeNull();
+ expect(native.available).not.toHaveBeenCalled();
+ });
+
+ it('shows WeChat on iOS after the first successful installation probe when re-enabled', async () => {
+ native.available.mockResolvedValue(true);
+ await renderProbe(true);
expect(wechatButton()).not.toBeNull();
expect(native.available).toHaveBeenCalledWith('wechat');
});
- it('hides WeChat on iOS when the installation probe returns false', async () => {
- await renderProbe();
+ it('keeps WeChat hidden on iOS when the installation probe fails after re-enabling', async () => {
+ await renderProbe(true);
expect(wechatButton()).toBeNull();
});
- it('refreshes iOS visibility when the app returns to the foreground', async () => {
- native.available
- .mockResolvedValueOnce(false)
- .mockResolvedValueOnce(true);
- await renderProbe();
+ it('refreshes iOS WeChat visibility on foreground when re-enabled', async () => {
+ native.available.mockResolvedValueOnce(false).mockResolvedValueOnce(true);
+ await renderProbe(true);
expect(wechatButton()).toBeNull();
await act(async () => {
@@ -106,9 +123,9 @@ describe('mobile social provider visibility', () => {
expect(native.available).toHaveBeenCalledTimes(2);
});
- it('keeps configured WeChat visible on Android without probing installation', async () => {
+ it('shows configured WeChat on Android without probing installation when re-enabled', async () => {
native.platform = 'android';
- await renderProbe();
+ await renderProbe(true);
expect(wechatButton()).not.toBeNull();
expect(native.available).not.toHaveBeenCalled();
});
diff --git a/apps/mobile/src/auth/mobileSocialLoginMode.ts b/apps/mobile/src/auth/mobileSocialLoginMode.ts
index 1f1ca439c3..918a5ff8f7 100644
--- a/apps/mobile/src/auth/mobileSocialLoginMode.ts
+++ b/apps/mobile/src/auth/mobileSocialLoginMode.ts
@@ -2,6 +2,10 @@ import type { AuthRegion, SocialProvider } from '@cindy/auth-client';
export type MobileSocialLoginMode = 'native' | 'browser';
+// The mobile app's WeChat Open Platform configuration is being corrected.
+// Keep native integration intact so the entry can return after both platforms pass verification.
+export const MOBILE_WECHAT_LOGIN_ENABLED = false;
+
/**
* Chooses the credential path for a provider advertised by auth-server.
* Native support remains the default; Global Android falls back to the
@@ -12,8 +16,15 @@ export function resolveMobileSocialLoginMode(input: {
region: AuthRegion;
platform: string;
nativeSupported: boolean;
+ wechatLoginEnabled?: boolean;
}): MobileSocialLoginMode | null {
- if (input.provider === 'wechat' && input.region !== 'cn') return null;
+ if (
+ input.provider === 'wechat' &&
+ (!(input.wechatLoginEnabled ?? MOBILE_WECHAT_LOGIN_ENABLED) ||
+ input.region !== 'cn')
+ ) {
+ return null;
+ }
if (input.nativeSupported) return 'native';
if (
input.provider === 'apple' &&
diff --git a/apps/mobile/src/auth/useMobileSocialProviderModes.ts b/apps/mobile/src/auth/useMobileSocialProviderModes.ts
index 11a97ef471..1a597bd325 100644
--- a/apps/mobile/src/auth/useMobileSocialProviderModes.ts
+++ b/apps/mobile/src/auth/useMobileSocialProviderModes.ts
@@ -7,6 +7,7 @@ import {
isNativeSocialProviderSupported,
} from '@/auth/nativeSocial';
import {
+ MOBILE_WECHAT_LOGIN_ENABLED,
resolveMobileSocialLoginMode,
type MobileSocialLoginMode,
} from '@/auth/mobileSocialLoginMode';
@@ -15,14 +16,16 @@ import {
export function useMobileSocialProviderModes({
providers,
region,
+ wechatLoginEnabled = MOBILE_WECHAT_LOGIN_ENABLED,
}: {
providers: readonly SocialProvider[];
region: AuthRegion;
+ wechatLoginEnabled?: boolean;
}): ReadonlyMap<SocialProvider, MobileSocialLoginMode> {
const [iosWechatAvailable, setIosWechatAvailable] = useState(false);
useEffect(() => {
- if (Platform.OS !== 'ios') return;
+ if (!wechatLoginEnabled || Platform.OS !== 'ios') return;
let cancelled = false;
const refresh = async () => {
const available = await isNativeSocialProviderAvailable('wechat');
@@ -36,7 +39,7 @@ export function useMobileSocialProviderModes({
cancelled = true;
subscription.remove();
};
- }, []);
+ }, [wechatLoginEnabled]);
return useMemo(() => {
const modes = new Map<SocialProvider, MobileSocialLoginMode>();
@@ -45,6 +48,7 @@ export function useMobileSocialProviderModes({
provider,
region,
platform: Platform.OS,
+ wechatLoginEnabled,
nativeSupported:
provider === 'wechat' && Platform.OS === 'ios'
? iosWechatAvailable
@@ -53,5 +57,5 @@ export function useMobileSocialProviderModes({
if (mode) modes.set(provider, mode);
}
return modes;
- }, [iosWechatAvailable, providers, region]);
+ }, [iosWechatAvailable, providers, region, wechatLoginEnabled]);
}
diff --git a/apps/mobile/src/auth/wechatCallback.ts b/apps/mobile/src/auth/wechatCallback.ts
new file mode 100644
index 0000000000..847fccd46f
--- /dev/null
+++ b/apps/mobile/src/auth/wechatCallback.ts
@@ -0,0 +1,31 @@
+/** Router-only classification. Credentials and state are still consumed by OpenSDK. */
+export function isWechatSdkCallback(
+ path: string,
+ config: { appId: string; universalLink: string },
+): boolean {
+ const isCallbackPath = (value: string) =>
+ /^(?:oauth|refreshToken)\/?$/.test(value);
+ try {
+ // Expo Router may already have replaced the incoming wx<AppID> scheme with
+ // Cindy's scheme, or reduced the URL to a path. Neither is a navigable page.
+ const customPath = path.replace(/^[a-zA-Z][\w+.-]*:\/\//, '/');
+ const isWebLink = /^https?:\/\//i.test(path);
+ if (!isWebLink && isCallbackPath(customPath.split(/[?#]/)[0].replace(/^\/+/, ''))) return true;
+ if (!config.appId || !config.universalLink) return false;
+ const base = new URL(config.universalLink);
+ const actual = isWebLink ? new URL(path) : new URL(customPath, 'https://wechat-routing.invalid');
+ if (actual.username || actual.password || (isWebLink && actual.origin !== base.origin)) return false;
+ const prefix = `${base.pathname.replace(/\/+$/, '')}/`;
+ if (!actual.pathname.startsWith(prefix)) return false;
+ const suffix = actual.pathname.slice(prefix.length);
+ // OpenSDK also returns to <base>/<appId>/ with an opaque payload while
+ // checking Universal Links. Match its route and marker, never decode it.
+ if (suffix.replace(/\/$/, '') === config.appId && actual.searchParams.has('_wechat_sdk_biz_data')) return true;
+ return isCallbackPath(suffix) || (
+ suffix.startsWith(`${config.appId}/`) &&
+ isCallbackPath(suffix.slice(config.appId.length + 1))
+ );
+ } catch {
+ return false;
+ }
+}
diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.md
index d426aba791..08d4325708 100644
--- a/docs/dev-rules/mobile-development.md
+++ b/docs/dev-rules/mobile-development.md
@@ -106,6 +106,9 @@ pnpm --filter mobile test:smoke
### 中国大陆版微信个人登录
+- 微信开放平台的移动应用配置修正并完成双平台真机验收前,iOS / Android 登录页暂时隐藏
+ 微信入口;开关位于 `src/auth/mobileSocialLoginMode.ts`,不移除原生 SDK 或构建配置,
+ 以便配置修正后恢复。此处仅改 JS 行为,不额外触发原生冷更。
- 复用 `xdt-wechat-login`:iOS/Android 拉起微信取临时 code,再由 auth-server 交换。
PC 使用同一服务端的网站应用扫码入口。登录结果统一进入手机号补绑或身份选择流程。
- 在 Mobile `.env`(本地)或打包机环境中成对填写
@@ -116,12 +119,23 @@ pnpm --filter mobile test:smoke
- 仅 cn 和显式配置的 dev 构建消费微信配置;Global 忽略残留值。全空关闭入口,
半配置或非法 Universal Link 在原生配置生成前报错。首次启用需重新出原生包,
仅 OTA 无法添加回调配置;按下方冷更规则比对 fingerprint。
-- 真机验证 iOS Universal Link/AASA、Android 包名/签名与 WXEntryActivity,覆盖
+- iOS config plugin 按[微信官方接入说明](https://developers.weixin.qq.com/doc/oplatform/Mobile_App/Access_Guide/iOS.html)
+ 生成 `weixin`、`weixinULAPI`、`weixinURLParamsAPI` 三项查询白名单,并保留 AppID URL Scheme
+ 与 Universal Link 的 Associated Domains。遗漏白名单需重建原生包,不能通过 JS 热更补齐。
+- 恢复入口前真机验证 iOS Universal Link/AASA、Android 包名/签名与 WXEntryActivity,覆盖
同意授权、取消、未安装微信、回到前台超时后重试。iOS Simulator 不支持微信授权。
- iOS 登录页仅在 OpenSDK 确认已安装微信后显示微信入口;Android 保持入口可见,点击时
- 再由原生桥确认微信是否可用。凭据获取前仍须二次检查安装状态,不能只依赖页面显隐。
+ 入口恢复后,iOS 登录页仅在 OpenSDK 确认已安装微信后显示微信入口;Android 保持入口
+ 可见,点击时再由原生桥确认微信是否可用。凭据获取前仍须二次检查安装状态,不能只依赖页面显隐。
未绑手机号须短信验证,已绑用户免短信;用同一微信在 PC 和两种手机上确认账号一致。
+- 微信 OpenSDK 的 `oauth` / `refreshToken` 回调会同时到达原生 delegate 与 Expo Router;
+ Universal Link 校验还会回跳配置路径下的 `<AppID>/?_wechat_sdk_biz_data=…`,Router 可能
+ 将 HTTPS 链接转成 Cindy scheme 或路径形式,这些形式也必须识别;仅按路径与参数名分类,
+ 不解析 SDK 的不透明 payload。
+ `app/+native-intent.ts` 只负责将这些非页面链接送回首页,避免 404 展示授权参数。
+ 微信 code/state 仍只由原生 SDK 校验,不得复用 auth-server `/auth` 的 PKCE 交换。
+ 真机回归需分别覆盖微信已在后台与微信冷启动,确认回跳后继续完成登录而非进入错误页。
+
- 模拟器与真机排错:
[`simulator-debugging.md`](../../apps/mobile/docs/simulator-debugging.md)。