fix(sync): drop a device check that answers after Go Back or Sign Out

Answers CodeRabbit's second review of #7945.

- Go Back now abandons a Free plan sign-in whose device check is still
  running, as it already did for one that is held: it signs the session
  out, and the check's answer neither signs in nor shows the device list.
  A check answering after the page unmounts is dropped too.
- AuthProvider doesn't publish a session whose device check answers while
  Sign Out is running.

Verified:
- New tests failed before the fix and pass with it:
  auth-page-device-limit.test.tsx ("abandons a sign-in whose device check
  is still running on Go Back": expected signOut with { scope: 'local' },
  not called) and auth-context-device-limit.test.tsx ("does not sign in
  when the device check answers during Sign Out": expected 'new-token' to
  be null).
- Related suites: 187 files, 2280 tests passed. pnpm lint clean.
- dev-web against a local self-hosted Supabase: 15/15 end-to-end checks
  and both reload-during-hold checks pass again.

Not run: the Tauri desktop and mobile apps.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
This commit is contained in:
Huang Xin 2026-11-26 05:55:40 +08:00
parent 647a38d3eb
commit 2f02f8275c
No known key found for this signature in database
GPG key ID: FEB86D637D085E7D
4 changed files with 64 additions and 12 deletions

View file

@ -188,6 +188,21 @@ describe('AuthPage over the Free plan device limit', () => {
expect(mocks.router.replace).not.toHaveBeenCalled();
});
it('abandons a sign-in whose device check is still running on Go Back', async () => {
let finish = (_value: unknown) => {};
mocks.checkSignInDeviceLimit.mockReturnValue(new Promise((resolve) => (finish = resolve)));
signIn();
fireEvent.click(screen.getAllByRole('button', { name: 'Go Back' })[0]!);
await waitFor(() => expect(mocks.router.back).toHaveBeenCalledTimes(1));
await act(async () => finish(null));
expect(mocks.signOut).toHaveBeenCalledWith({ scope: 'local' });
expect(mocks.login).not.toHaveBeenCalled();
expect(mocks.router.replace).not.toHaveBeenCalled();
expect(mocks.router.back).toHaveBeenCalledTimes(1);
});
it('signs this device out again when leaving with Go Back', async () => {
signIn();
await screen.findByText('Chrome on macOS');

View file

@ -11,6 +11,7 @@ const h = vi.hoisted(() => ({
listener: undefined as Listener | undefined,
hasDeviceLimit: vi.fn((_token: string) => true),
checkSignInDeviceLimit: vi.fn(async (_token: string): Promise<unknown> => null),
refreshSession: vi.fn(async (): Promise<unknown> => ({ data: { session: null }, error: null })),
}));
vi.mock('@/utils/supabase', () => ({
@ -20,7 +21,7 @@ vi.mock('@/utils/supabase', () => ({
h.listener = listener;
return { data: { subscription: { unsubscribe: vi.fn() } } };
},
refreshSession: vi.fn().mockResolvedValue({ data: { session: null }, error: null }),
refreshSession: h.refreshSession,
signOut: vi.fn().mockResolvedValue(undefined),
},
},
@ -109,3 +110,28 @@ it('does not sign in when the session ended while the check ran', async () => {
expect(auth.current.token).toBeNull();
expect(localStorage.getItem('token')).toBeNull();
});
// Sign Out clears the app at once and then waits on the network; a device
// check answering meanwhile must not sign the user back in.
it('does not sign in when the device check answers during Sign Out', async () => {
let finishCheck = (_value: unknown) => {};
h.checkSignInDeviceLimit.mockReturnValue(new Promise((resolve) => (finishCheck = resolve)));
const auth = renderAuth();
await act(async () => {});
act(() => h.listener?.('SIGNED_IN', session('new-token')));
let finishRefresh = (_value: unknown) => {};
h.refreshSession.mockReturnValue(new Promise((resolve) => (finishRefresh = resolve)));
let loggingOut: Promise<void> = Promise.resolve();
act(() => {
loggingOut = Promise.resolve(auth.current.logout());
});
await act(async () => finishCheck(null));
expect(auth.current.token).toBeNull();
expect(localStorage.getItem('token')).toBeNull();
await act(async () => {
finishRefresh({ data: { session: null }, error: null });
await loggingOut;
});
});

View file

@ -67,9 +67,12 @@ export default function AuthPage() {
const [heldSignIn, setHeldSignIn] = useState<(SyncDevicesResponse & { session: Session }) | null>(
null,
);
// Counts cancelled holds, so a device sign-out that answers after Cancel or
// Go Back can't sign in the session they ended.
const cancelledHolds = useRef(0);
// A Free plan sign-in whose device check is running, or that is held.
const pendingSignIn = useRef(false);
// Counts abandoned sign-ins (Cancel, Go Back, leaving the page), so a device
// check or sign-out that answers afterwards can't sign in or hold the
// session they ended.
const abandonedSignIns = useRef(0);
const headerRef = useRef<HTMLDivElement>(null);
@ -253,8 +256,9 @@ export default function AuthPage() {
}
};
const cancelHeldSignIn = () => {
cancelledHolds.current += 1;
const abandonSignIn = () => {
abandonedSignIns.current += 1;
pendingSignIn.current = false;
setHeldSignIn(null);
void supabase.auth.signOut({ scope: 'local' });
};
@ -262,7 +266,7 @@ export default function AuthPage() {
const handleGoBack = async () => {
if (isLeaving.current) return;
isLeaving.current = true;
if (heldSignIn) cancelHeldSignIn();
if (pendingSignIn.current) abandonSignIn();
// Keep login false to avoid infinite loop to redirect to the login page.
// Leave only once it is saved: the library reads settings from disk when it
// mounts, and an unfinished write opened this page once more (#7726).
@ -313,6 +317,7 @@ export default function AuthPage() {
}, []);
const finishSignIn = (session: Session) => {
pendingSignIn.current = false;
setHeldSignIn(null);
login(session.access_token, session.user);
const redirectTo = new URLSearchParams(window.location.search).get('redirect');
@ -334,9 +339,9 @@ export default function AuthPage() {
const handleSignOutDevice = async (device: SyncDevice) => {
if (!heldSignIn) return;
const { session } = heldSignIn;
const hold = cancelledHolds.current;
const attempt = abandonedSignIns.current;
const next = await signOutSyncDevice(session.access_token, device.id);
if (hold !== cancelledHolds.current) return;
if (attempt !== abandonedSignIns.current) return;
if (next.blocked) {
setHeldSignIn({ ...next, session });
} else {
@ -352,7 +357,10 @@ export default function AuthPage() {
finishSignIn(session);
return;
}
pendingSignIn.current = true;
const attempt = abandonedSignIns.current;
void checkSignInDeviceLimit(session.access_token).then((blocked) => {
if (attempt !== abandonedSignIns.current) return;
if (!blocked) {
finishSignIn(session);
return;
@ -363,6 +371,7 @@ export default function AuthPage() {
return () => {
subscription?.subscription.unsubscribe();
abandonedSignIns.current += 1;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [router]);
@ -442,7 +451,7 @@ export default function AuthPage() {
devices={heldSignIn.devices}
limit={heldSignIn.limit ?? 0}
onSignOut={handleSignOutDevice}
onCancel={cancelHeldSignIn}
onCancel={abandonSignIn}
/>
) : (
<AuthPanel
@ -472,7 +481,7 @@ export default function AuthPage() {
devices={heldSignIn.devices}
limit={heldSignIn.limit ?? 0}
onSignOut={handleSignOutDevice}
onCancel={cancelHeldSignIn}
onCancel={abandonSignIn}
/>
) : (
<AuthPanel

View file

@ -79,7 +79,9 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
return;
}
void checkSignInDeviceLimit(session.access_token).then((blocked) => {
if (!blocked && latestSession === session) publishSession(session);
if (!blocked && !signingOut.current && latestSession === session) {
publishSession(session);
}
});
};
const refreshSession = async () => {