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): preserve OAuth routes and fence account cancellation

chenhong3ec00ebe8501
diff --git a/apps/mobile/app/+native-intent.ts b/apps/mobile/app/+native-intent.ts
index 9b33a01b55..085d967b84 100644
--- a/apps/mobile/app/+native-intent.ts
+++ b/apps/mobile/app/+native-intent.ts
@@ -2,7 +2,7 @@
//
// auth-server 回调 cindycn://auth / cindy://auth 与 Share Extension 的
// cindycn://expo-sharing / cindy://expo-sharing 都没有对应路由页,默认会落到
-// expo-router 的 +not-found(「Unmatched Route」白屏)。这里分别把它们重定向到首页与
+// expo-router 的 +not-found(「Unmatched Route」白屏)。这里在冷启动时把认证回跳重定向到首页,热回跳保留当前页面;分享跳到
// 新建任务页;分享 payload 由根级 IncomingShareBridge 独立领取。
//
// 实际的 PKCE code 交换**不依赖路由**:由 src/auth/AuthContext.tsx 的 Linking.addEventListener /
@@ -23,7 +23,7 @@ import {
import { WECHAT_APP_ID, WECHAT_UNIVERSAL_LINK } from '@/config/env';
import { isWechatSdkCallback } from '@/auth/wechatCallback';
-export function redirectSystemPath({ path, initial }: { path: string; initial: boolean }): string {
+export function redirectSystemPath({ path, initial }: { path: string; initial: boolean }): string | null {
try {
// OpenSDK 的授权及 Universal Link 校验回调也会被 Expo Linking 广播给 Router。
// 它们由原生 delegate 消费,不能当页面显示(更不能在 404 中展示 code)。
@@ -40,8 +40,9 @@ export function redirectSystemPath({ path, initial }: { path: string; initial: b
// path 可能是完整 URL('cindycn://auth?code=...')或路径('/auth?code=...'),统一取出 pathname。
const noScheme = path.replace(/^[a-zA-Z][\w+.-]*:\/\//, '/');
const pathname = noScheme.split('?')[0].split('#')[0].replace(/\/+$/, '') || '/';
- // 命中 OAuth 回调 → 回首页;Share Extension → 新建任务;其余深链原样放行。
- if (pathname === '/auth') return '/';
+ // OAuth 冷启动回首页;热回跳不导航,保留正在处理授权的页面。
+ // PKCE 仍由 AuthProvider 的独立 Linking 监听处理。其余深链沿用原规则。
+ if (pathname === '/auth') return initial ? '/' : null;
// A restored launch URL is not proof of an unconsumed share. On cold start,
// let IncomingShareBridge navigate only after reading an actual pending batch.
if (pathname === '/expo-sharing') return initial ? '/' : '/sessions/new';
diff --git a/apps/mobile/src/__tests__/nativeIntent.test.ts b/apps/mobile/src/__tests__/nativeIntent.test.ts
index c8e02b1bd9..c86474732e 100644
--- a/apps/mobile/src/__tests__/nativeIntent.test.ts
+++ b/apps/mobile/src/__tests__/nativeIntent.test.ts
@@ -147,6 +147,11 @@ describe('mobile native deep-link redirects', () => {
})).toBe('/sessions/new');
});
+ it.each(['cindy://auth?code=fixture&state=fixture', 'cindycn://auth?error=access_denied&state=fixture', '/auth?code=fixture'])('keeps the current route for warm OAuth callbacks: %s', path => {
+ expect(redirectSystemPath({path, initial: false})).toBeNull();
+ expect(redirectSystemPath({path, initial: true})).toBe('/');
+ });
+
it('preserves existing auth and ordinary deep-link behavior', () => {
expect(redirectSystemPath({
path: 'cindy://auth?code=abc',
diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsx
index 7dac7f8555..da37bb4048 100644
--- a/apps/mobile/src/auth/AuthContext.tsx
+++ b/apps/mobile/src/auth/AuthContext.tsx
@@ -401,6 +401,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const pendingAccountRefreshTokenRef = useRef<string | null>(null);
const pendingAccountMembershipsRef = useRef<AuthMembership[]>([]);
const additionalLoginRef = useRef(false);
+ const addAccountCancellationEpochRef = useRef<number | null>(null);
const [accountGeneration, setAccountGeneration] = useState(0);
const [savedAccounts, setSavedAccounts] = useState<MobileSavedAccount[]>([]);
const [accountsLoading, setAccountsLoading] = useState(false);
@@ -1890,6 +1891,9 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const dispatchLoginAction = useCallback(
(action: MobileLoginAction): Promise<boolean> => {
+ if (addAccountCancellationEpochRef.current === loginFlowEpochRef.current) {
+ return Promise.resolve(false);
+ }
if (action.type === 'initialize') {
const epoch = loginFlowEpochRef.current;
// Initialization has its own deduplication slot. A callback or explicit
@@ -2831,7 +2835,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {
oauthCancelledRef.current = true;
loginFlowEpochRef.current += 1;
const cancelledEpoch = loginFlowEpochRef.current;
- setIsBusy(false);
+ addAccountCancellationEpochRef.current = cancelledEpoch;
+ setIsBusy(true);
try {
await persistPendingOAuth(null);
} catch (error) {
@@ -2840,6 +2845,11 @@ export function AuthProvider({ children }: { children: ReactNode }) {
updateLoginState({ step: 'error', code, recoverTo: 'identifier' });
setAuthError(code);
throw error;
+ } finally {
+ if (addAccountCancellationEpochRef.current === cancelledEpoch) {
+ addAccountCancellationEpochRef.current = null;
+ }
+ if (loginFlowEpochRef.current === cancelledEpoch) setIsBusy(false);
}
if (loginFlowEpochRef.current !== cancelledEpoch) return;
pendingAccountTokenRef.current = null;
diff --git a/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx b/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx
index ecfbab84f0..e56d693a58 100644
--- a/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx
+++ b/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx
@@ -49,6 +49,7 @@ vi.mock('expo-web-browser', () => ({
vi.mock('expo-modules-core', () => ({ requireNativeModule: () => ({ addCustomField() {} }) }));
vi.mock('@/config/env', () => ({
BUILD_AUTH_REGION: 'cn', MOBILE_REDIRECT_URL: 'cindycn://auth',
+ WECHAT_APP_ID: '', WECHAT_UNIVERSAL_LINK: '',
IS_OTA_SELFHOST: false, MOBILE_VISUAL_MOCK_ENABLED: false,
OAUTH_BROKER_API_BASE_URL: 'https://auth.example.invalid',
getMobileEndpointForRealm: () => 'https://auth.example.invalid',
@@ -115,6 +116,7 @@ vi.mock('@/update/fetchLatestRelease', () => ({}));
import { AuthProvider, useAuth } from '../AuthContext';
import AddAccountScreen from '../../../app/add-account';
+import { redirectSystemPath } from '../../../app/+native-intent';
const pendingKey = 'cindy.mobile.auth.pendingOAuth';
const verifiedOutcome = {
@@ -467,6 +469,46 @@ describe('browser auth session lifecycle (real AuthProvider, mocked native/netwo
expect(native.storage.has(pendingKey)).toBe(false);
});
+ it('keeps the add-account route mounted for a delayed warm auth link', async () => {
+ await act(async () => { await auth.beginAddAccount(); });
+ await start();
+ await act(async () => { root.render(<AuthProvider><Probe /><AddAccountScreen /></AuthProvider>); });
+ const url = callbackUrl();
+ const target = redirectSystemPath({path: url, initial: false});
+ // Expo Router only navigates for a truthy redirectSystemPath result.
+ if (target) await act(async () => { root.render(<AuthProvider><Probe /></AuthProvider>); });
+ await emitLink(url);
+ expect(target).toBeNull();
+ expect(native.exchange).toHaveBeenCalledExactlyOnceWith('fixture-code', 'fixture-verifier');
+ expect(auth.loginState?.step).toBe('sso-verification');
+ expect(native.replaceRoute).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ {outcome: verifiedOutcome, action: {type: 'request-sso-verification-code'}, request: native.requestVerification},
+ {outcome: {status: 'select_account', loginTicket: 'fixture-ticket', accounts: []}, action: {type: 'select-account', accountId: 'fixture-account'}, request: native.selectAccount},
+ {outcome: {status: 'binding_required', bindType: 'email', bindTicket: 'fixture-ticket'}, action: {type: 'request-binding-code', contact: '[email protected]'}, request: native.requestBinding},
+ ] as const)('blocks $action.type while add-account cancellation is persisting', async fixture => {
+ native.exchange.mockResolvedValueOnce(fixture.outcome);
+ await act(async () => { await auth.beginAddAccount(); });
+ await start();
+ await emitLink(callbackUrl());
+ let finishDelete!: () => void;
+ native.deleteSecure.mockImplementationOnce(() => new Promise<void>(resolve => {
+ finishDelete = () => { native.storage.delete(pendingKey); resolve(); };
+ }));
+ let closing!: Promise<void>;
+ await act(async () => { closing = auth.cancelAddAccount(); });
+ expect(auth.isBusy).toBe(true);
+ await act(async () => {
+ expect(await auth.dispatchLoginAction(fixture.action)).toBe(false);
+ });
+ expect(fixture.request).not.toHaveBeenCalled();
+ await act(async () => { finishDelete(); await closing; });
+ expect(auth.loginState).toBeNull();
+ expect(auth.isBusy).toBe(false);
+ });
+
it('explicit reset cancels the pending login; its late callback cannot authenticate', async () => {
await start();
const oldCallback = callbackUrl();