Skip to content

Conversation

@appflowy
Copy link
Contributor

@appflowy appflowy commented Nov 16, 2025

Fixes three critical race conditions that caused redirect loops after OAuth login:

  1. Clear old token before processing OAuth callback to prevent axios
    interceptor from attempting auto-refresh of expired old token while
    processing new OAuth tokens

  2. Add multi-stage authentication checks in AppAuthLayer with proper
    timeouts to wait for React state sync before triggering logout

  3. Add proactive state sync in AppConfig to ensure isAuthenticated
    state matches localStorage token on mount

  4. Create AppWorkspaceRedirect component to handle /app -> /app/:workspaceId
    navigation after OAuth callback, preventing undefined workspace errors

Summary by Sourcery

Fix race conditions in the OAuth login flow by clearing old tokens before callback processing, adding staged auth checks and proactive state sync to prevent redirect loops, and redirecting /app to the proper workspace route.

New Features:

  • Add AppWorkspaceRedirect component to handle navigation from /app to the user's workspace

Bug Fixes:

  • Clear old expired token before processing new OAuth tokens to prevent interceptor auto-refresh race
  • Add multi-stage authentication checks in AppAuthLayer with delays to wait for React state sync before triggering logout
  • Sync authentication state proactively in AppConfig on mount and state changes to avoid redirect loops after OAuth callback or page reload

Enhancements:

  • Enhance HTTP API service with debug and warning logs for token absence and refresh failures

Tests:

  • Add end-to-end Cypress test for old token race condition during OAuth login

…after OAuth login:

   1. Clear old token before processing OAuth callback to prevent axios
      interceptor from attempting auto-refresh of expired old token while
      processing new OAuth tokens

   2. Add multi-stage authentication checks in AppAuthLayer with proper
      timeouts to wait for React state sync before triggering logout

   3. Add proactive state sync in AppConfig to ensure isAuthenticated
      state matches localStorage token on mount

   4. Create AppWorkspaceRedirect component to handle /app -> /app/:workspaceId
      navigation after OAuth callback, preventing undefined workspace errors
@sourcery-ai
Copy link

sourcery-ai bot commented Nov 16, 2025

Reviewer's Guide

This PR resolves multiple race conditions around OAuth authentication and redirect loops by enhancing HTTP service logging and token handling, implementing multi-stage auth state checks, proactively syncing auth status in AppConfig, and introducing a dedicated component to handle post-login workspace redirects, backed by a new Cypress test for the old-token scenario.

Sequence diagram for OAuth login flow with race condition fixes

sequenceDiagram
    actor User
    participant "LoginAuth"
    participant "signInWithUrl()"
    participant "verifyToken()"
    participant "refreshToken()"
    participant "AppConfig"
    participant "AppAuthLayer"
    participant "AppWorkspaceRedirect"
    User->>"LoginAuth": Complete OAuth, redirected to /auth/callback
    "LoginAuth"->>"signInWithUrl()": Process callback URL
    "signInWithUrl()"->>"signInWithUrl()": Clear old token from localStorage
    "signInWithUrl()"->>"verifyToken()": Verify new access token
    "signInWithUrl()"->>"refreshToken()": Refresh new token
    "refreshToken()"->>"AppConfig": Save new token to localStorage
    "AppConfig"->>"AppConfig": Proactively sync isAuthenticated state
    "AppAuthLayer"->>"AppAuthLayer": Multi-stage authentication checks (timeouts)
    "AppAuthLayer"->>"AppWorkspaceRedirect": Load workspace info
    "AppWorkspaceRedirect"->>User: Redirect to /app/:workspaceId
Loading

Class diagram for new AppWorkspaceRedirect component and related hooks

classDiagram
    class AppWorkspaceRedirect {
        +useEffect()
        +useNavigate()
        +useUserWorkspaceInfo()
        +LoadingDots
    }
    class useUserWorkspaceInfo {
        <<hook>>
    }
    class LoadingDots {
    }
    AppWorkspaceRedirect --> useUserWorkspaceInfo
    AppWorkspaceRedirect --> LoadingDots
Loading

Class diagram for updated AppAuthLayer authentication logic

classDiagram
    class AppAuthLayer {
        +useEffect() multi-stage auth check
        +logout()
        +context
        +isAuthenticated
    }
    class AuthInternalContext {
    }
    AppAuthLayer --> AuthInternalContext
Loading

Class diagram for updated AppConfig authentication state sync

classDiagram
    class AppConfig {
        +useEffect() sync isAuthenticated on mount
        +useEffect() sync isAuthenticated on change
        +setIsAuthenticated()
        +isAuthenticated
    }
    AppConfig --> setIsAuthenticated
Loading

File-Level Changes

Change Details Files
Enhance HTTP API and OAuth token processing with logging and stale token clearance
  • Added debug logs for missing tokens in initAPIService request flow
  • Emit warnings and invalidToken events on refresh failures in request/response interceptors
  • Clear old localStorage token before verifyToken/refreshToken in signInWithUrl with debug logging
  • Log warnings on callback URL parsing or missing tokens
src/application/services/js-services/http/http_api.ts
Add Cypress test for old token race condition
  • Pre-populate localStorage with an expired token and clear it before OAuth callback
  • Mock refresh and verify endpoints for old vs. new tokens
  • Assert new token is verified, refreshed, and persisted without invoking old-token flows
  • Ensure no redirect loops and proper navigation to /app
cypress/e2e/auth/oauth-login.cy.ts
Implement multi-stage authentication checks in AppAuthLayer
  • Introduce 50ms initial and 100ms secondary timeouts around auth validation
  • Skip logout if a valid token exists or auth context isn’t ready
  • Only redirect to login after double-check confirms no token and isAuthenticated false
  • Add detailed debug logging for each check stage
src/components/app/layers/AppAuthLayer.tsx
Add proactive authentication state sync in AppConfig
  • Add mount-only effect with delay to force isAuthenticated based on localStorage token
  • Extend sync effect to invalidate session when token is removed
  • Include debug logs for sync decisions on mount and on isAuthenticated changes
src/components/main/AppConfig.tsx
Introduce AppWorkspaceRedirect component for /app routing
  • Create AppWorkspaceRedirect to wait for workspace info and navigate to selected workspace
  • Update AppRouter to route /app index to AppWorkspaceRedirect instead of empty page
src/components/app/AppWorkspaceRedirect.tsx
src/components/app/AppRouter.tsx

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location> `src/components/app/layers/AppAuthLayer.tsx:105-107` </location>
<code_context>
+    // 1. Wait for React context to initialize (50ms)
+    // 2. Check token and auth state multiple times to handle async state updates
+    // 3. Only logout if consistently unauthenticated across multiple checks
+    let secondCheckTimeoutId: NodeJS.Timeout | null = null;
+
     const timeoutId = setTimeout(() => {
</code_context>

<issue_to_address>
**suggestion:** Consider using window.setTimeout for browser compatibility.

NodeJS.Timeout is not compatible with browsers, which expect setTimeout to return a number. Use window.setTimeout and window.clearTimeout for cross-environment compatibility.

```suggestion
    let secondCheckTimeoutId: number | null = null;

    const timeoutId = window.setTimeout(() => {
```
</issue_to_address>

### Comment 2
<location> `src/components/app/AppWorkspaceRedirect.tsx:24-19` </location>
<code_context>
+
+    const workspaceId = userWorkspaceInfo.selectedWorkspace?.id;
+
+    if (!workspaceId) {
+      console.warn('[AppWorkspaceRedirect] No selected workspace found in user info', userWorkspaceInfo);
+      return;
+    }
+
</code_context>

<issue_to_address>
**suggestion:** No fallback for missing workspaceId may leave user stuck.

Consider adding a fallback UI or redirecting to an error page when workspaceId is missing to prevent users from being stuck on a loading screen.

Suggested implementation:

```typescript
    if (!workspaceId) {
      console.warn('[AppWorkspaceRedirect] No selected workspace found in user info', userWorkspaceInfo);
      // Optionally, you can redirect to an error page:
      // navigate('/app/error');
      // Or set a local state to show a fallback UI
      setShowWorkspaceError(true);
      return;
    }

```

```typescript
import { useState } from 'react';

export function AppWorkspaceRedirect() {
  const userWorkspaceInfo = useUserWorkspaceInfo();
  const [showWorkspaceError, setShowWorkspaceError] = useState(false);

```

```typescript
  const userWorkspaceInfo = useUserWorkspaceInfo();

  if (showWorkspaceError) {
    return (
      <div style={{ textAlign: 'center', marginTop: '2rem' }}>
        <h2>Workspace Not Found</h2>
        <p>
          We couldn't find a workspace for your account. Please check your account or contact support.
        </p>
        <button onClick={() => navigate('/app')}>Go to Home</button>
      </div>
    );
  }

```
</issue_to_address>

### Comment 3
<location> `src/components/main/AppConfig.tsx:90` </location>
<code_context>
+  const userWorkspaceInfo = useUserWorkspaceInfo();
+  const navigate = useNavigate();
+
+  useEffect(() => {
+    if (!userWorkspaceInfo) {
+      console.debug('[AppWorkspaceRedirect] Waiting for workspace info to load...');
</code_context>

<issue_to_address>
**issue (complexity):** Consider consolidating multiple authentication sync effects into a single effect or custom hook to reduce duplication.

You can collapse all of the “sync on mount”, “sync on isAuthenticated change”, “storage” and “SESSION_INVALID” effects into one (or a small custom hook) to eliminate duplication.  

For example, in‐place you might do:

```ts
useEffect(() => {
  const syncAuth = () => {
    const hasToken = isTokenValid();
    console.debug('[AppConfig] sync', {hasToken, isAuthenticated});
    if (hasToken && !isAuthenticated) {
      setIsAuthenticated(true);
    } else if (!hasToken && isAuthenticated) {
      setIsAuthenticated(false);
    }
  };

  // immediate + delayed mount sync
  syncAuth();
  const timeoutId = setTimeout(syncAuth, 100);

  // storage listener
  const onStorage = (e: StorageEvent) => e.key === 'token' && syncAuth();
  window.addEventListener('storage', onStorage);

  // session‐invalid listener
  const offInvalid = on(EventType.SESSION_INVALID, () => setIsAuthenticated(false));

  return () => {
    clearTimeout(timeoutId);
    window.removeEventListener('storage', onStorage);
    offInvalid();
  };
}, [isAuthenticated]);
```

Or extract it into a `useAuthSync` hook:

```ts
function useAuthSync(
  isAuthenticated: boolean,
  setIsAuthenticated: (v: boolean) => void
) {
  useEffect(() => {
    // …same body as above…
  }, [isAuthenticated]);
}

// in AppConfig.tsx
const [isAuthenticated, setIsAuthenticated] = useState(isTokenValid());
useAuthSync(isAuthenticated, setIsAuthenticated);
```

This eliminates three separate effects plus duplicated logic but keeps exactly the same behavior.
</issue_to_address>

### Comment 4
<location> `cypress/e2e/auth/oauth-login.cy.ts:516` </location>
<code_context>
                const body = req.body;

</code_context>

<issue_to_address>
**suggestion (code-quality):** Prefer object destructuring when accessing and using properties. ([`use-object-destructuring`](https://docs.sourcery.ai/Reference/Rules-and-In-Line-Suggestions/TypeScript/Default-Rules/use-object-destructuring))

```suggestion
                const {body} = req;
```

<br/><details><summary>Explanation</summary>Object destructuring can often remove an unnecessary temporary reference, as well as making your code more succinct.

From the [Airbnb Javascript Style Guide](https://airbnb.io/javascript/#destructuring--object)
</details>
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@appflowy appflowy merged commit d3eb7cf into main Nov 16, 2025
11 checks passed
@appflowy appflowy deleted the fix_flaky_login branch November 16, 2025 13:01
josue693 pushed a commit to josue693/AppFlowy-Web that referenced this pull request Dec 21, 2025
fix: Fixes three critical race conditions that caused redirect loops …
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants