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): hand off browser login and retire expired PKCE

chenhong8ae63d742204
diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsx
index e7527151ea..5509f589c8 100644
--- a/apps/mobile/src/auth/AuthContext.tsx
+++ b/apps/mobile/src/auth/AuthContext.tsx
@@ -1755,6 +1755,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const concurrent = currentCompletion();
if (concurrent) return concurrent;
loginInitializationRef.current = null;
+ const browserAction = loginActionInFlightRef.current;
suspendSessionRecoveryForLogin();
const run = (async () => {
setIsBusy(true);
@@ -1786,6 +1787,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {
expectedLoginFlowEpoch,
);
assertLoginFlowCurrent(expectedLoginFlowEpoch);
+ // Release only the browser action that produced this continuation.
+ // Until exchange completes, native cancellation still cancels it.
+ if (loginActionInFlightRef.current === browserAction) {
+ loginActionInFlightRef.current = null;
+ loginActionInFlightEpochRef.current = null;
+ }
setAuthError(null);
} catch (error) {
if (loginFlowEpochRef.current !== expectedLoginFlowEpoch) throw error;
@@ -1883,9 +1890,14 @@ export function AuthProvider({ children }: { children: ReactNode }) {
try {
const did = await (deviceIdRef.current ?? prepareBetaChannelForCurrentDevice());
if (!isCurrent()) return false;
- const pending = await readPendingOAuth().catch((error: unknown) => {
- if (authErrorCode(error) === 'INVALID_AUTH_CODE') return null;
- throw error;
+ const pending = await readPendingOAuth().catch(async (error: unknown) => {
+ if (authErrorCode(error) !== 'INVALID_AUTH_CODE') throw error;
+ // Only the still-current initializer may enqueue retirement.
+ // Serialized writes keep this cleanup ahead of any new attempt.
+ if (isCurrent() && error instanceof Error && 'expiredPendingOAuth' in error) {
+ await persistPendingOAuth(null);
+ }
+ return null;
});
if (!isCurrent()) return false;
if (pending && !oauthCancelledRef.current) {
@@ -1998,6 +2010,9 @@ export function AuthProvider({ children }: { children: ReactNode }) {
MOBILE_REDIRECT_URL,
);
assertLoginFlowCurrent(expectedLoginFlowEpoch);
+ // Linking may already have handed ownership to a continuation.
+ // A late native result must not cancel or mutate that newer work.
+ if (loginActionInFlightRef.current !== run) return true;
if (result.type === 'success') {
await completeOAuthCallback(result.url, expectedLoginFlowEpoch);
return true;
@@ -3565,7 +3580,7 @@ async function readPendingOAuth(expectedState?: string): Promise<PendingOAuth> {
throw authCodeError('STATE_MISMATCH');
}
if (Date.now() - parsed.createdAt > PENDING_OAUTH_MAX_AGE_MS) {
- throw authCodeError('INVALID_AUTH_CODE');
+ throw Object.assign(authCodeError('INVALID_AUTH_CODE'), { expiredPendingOAuth: true });
}
return parsed as PendingOAuth;
}
diff --git a/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx b/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx
index 4db37271e5..d388107eb4 100644
--- a/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx
+++ b/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx
@@ -345,6 +345,56 @@ describe('browser auth session lifecycle (real AuthProvider, mocked native/netwo
expect(native.exchange).not.toHaveBeenCalled();
});
+ it.each([
+ { outcome: verifiedOutcome, action: {type: 'request-sso-verification-code'}, request: native.requestVerification, step: 'sso-verification', args: ['fixture-ticket'] },
+ { outcome: {status: 'select_account', loginTicket: 'fixture-ticket', accounts: []}, action: {type: 'select-account', accountId: 'fixture-account'}, request: native.selectAccount, step: 'account-selection', args: ['fixture-ticket', 'fixture-account'] },
+ { outcome: {status: 'binding_required', bindType: 'email', bindTicket: 'fixture-ticket'}, action: {type: 'request-binding-code', contact: '[email protected]'}, request: native.requestBinding, step: 'binding', args: ['fixture-ticket', 'email', '[email protected]'] },
+ ] as const)('allows $step actions before the browser settles without late cancel clearing new work', async fixture => {
+ native.exchange.mockResolvedValueOnce(fixture.outcome);
+ let finishBrowser!: (value: {type: 'cancel'}) => void;
+ native.open.mockImplementationOnce(() => new Promise(resolve => { finishBrowser = resolve; }));
+ let opening!: Promise<unknown>;
+ await act(async () => { opening = auth.dispatchLoginAction({type: 'start-social-browser', provider: 'wechat', label: 'WeChat'}).catch(e => e); });
+ await emitLink(callbackUrl());
+ expect(auth.loginState?.step).toBe(fixture.step);
+ let finishRequest!: () => void;
+ fixture.request.mockImplementationOnce(() => new Promise(resolve => { finishRequest = () => resolve(verifiedOutcome); }));
+ let requesting!: Promise<boolean>;
+ await act(async () => { requesting = auth.dispatchLoginAction(fixture.action); });
+ expect(fixture.request).toHaveBeenCalledExactlyOnceWith(...fixture.args);
+ expect(auth.isBusy).toBe(true);
+ await act(async () => { finishBrowser({type: 'cancel'}); await opening; });
+ expect(auth.loginState?.step).toBe(fixture.step);
+ expect(auth.isBusy).toBe(true);
+ await act(async () => { finishRequest(); expect(await requesting).toBe(true); });
+ expect(auth.isBusy).toBe(false);
+ });
+
+ it('retires expired credentials during cold initialization', async () => {
+ native.storage.set(pendingKey, JSON.stringify({state: 'expired', codeVerifier: 'fixture-verifier', deviceId: 'fixture-device', realm: 'cn', label: 'SSO', createdAt: Date.now() - 11 * 60 * 1000}));
+ await restartProvider();
+ await mountLoginScreen('expired-cold');
+ expect(auth.loginState?.step).toBe('identifier');
+ expect(native.storage.has(pendingKey)).toBe(false);
+ });
+
+ it('queues expired cleanup before a newer browser credential write', async () => {
+ native.storage.set(pendingKey, JSON.stringify({state: 'expired', codeVerifier: 'fixture-verifier', deviceId: 'fixture-device', realm: 'cn', label: 'SSO', createdAt: Date.now() - 11 * 60 * 1000}));
+ await restartProvider();
+ let finishDelete!: () => void;
+ native.deleteSecure.mockImplementationOnce(() => new Promise<void>(resolve => {
+ finishDelete = () => { native.storage.delete(pendingKey); resolve(); };
+ }));
+ await mountLoginScreen('expired-cleanup');
+ let opening!: Promise<boolean>;
+ await act(async () => { opening = auth.dispatchLoginAction({type: 'reset'}).then(() => auth.dispatchLoginAction({type: 'start-social-browser', provider: 'wechat', label: 'WeChat'})); });
+ await act(async () => { finishDelete(); await opening; });
+ expect(auth.loginState?.step).toBe('browser-redirect');
+ expect(JSON.parse(native.storage.get(pendingKey)!).state).not.toBe('expired');
+ await emitLink(callbackUrl());
+ expect(auth.loginState?.step).toBe('sso-verification');
+ });
+
it('explicit reset cancels the pending login; its late callback cannot authenticate', async () => {
await start();
const oldCallback = callbackUrl();