Skip to content

Conversation

@jacekradko
Copy link
Member

@jacekradko jacekradko commented Dec 1, 2025

Description

Looks like Safari ITP sometimes blocks the Strict cookies on cross-origin redirects ( __clerk_uat ) in development so if you are redirecting directly to a protected route, the middleware will keep trying to handshake in order to acquire that particular cookie leading to an infinite redirect loop.

In the scenario where we detect a handshake redirect loop (attempt 2 +), we just validate the token and returned signed in instead of forcing a handshake.

Checklist

  • pnpm test runs as expected.
  • pnpm build runs as expected.
  • (If applicable) JSDoc comments have been added or updated for any package exports
  • (If applicable) Documentation has been updated

Type of change

  • 🐛 Bug fix
  • 🌟 New feature
  • 🔨 Breaking change
  • 📖 Refactoring / dependency upgrade / documentation
  • other:

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced session authentication handling to better support Safari's Intelligent Tracking Prevention (ITP) and prevent infinite redirect loops by properly verifying existing sessions.

✏️ Tip: You can customize this high-level summary in your review settings.

@changeset-bot
Copy link

changeset-bot bot commented Dec 1, 2025

⚠️ No Changeset found

Latest commit: 5d7b78d

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@vercel
Copy link

vercel bot commented Dec 1, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Ready Preview Comment Dec 1, 2025 7:47pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 1, 2025

Walkthrough

Added redirect-loop handling to the token authentication flow to address Safari ITP (Intelligent Tracking Prevention) scenarios. When a request lacks an active client but contains a valid session token and a redirect-loop counter, the system attempts to verify the session token. Successful verification returns a signed-in state, while failures fall back to the existing handshake flow.

Changes

Cohort / File(s) Summary
Redirect-loop handling and tests
packages/backend/src/tokens/request.ts, packages/backend/src/tokens/__tests__/request.test.ts
Introduced new conditional path in authenticateRequest to detect and handle redirect loops with valid session tokens. Added two test cases: one verifying signed-in state when session token is valid despite redirect loop, and one verifying handshake fallback when session token is invalid.

Sequence Diagram

sequenceDiagram
    participant Client
    participant AuthRequest as authenticateRequest()
    participant SessionVerifier
    participant CookieStore

    Client->>AuthRequest: Request with __clerk_redirect_count cookie
    AuthRequest->>CookieStore: Check for session token & redirect count
    
    alt No Active Client + Session Token + Redirect Count > 0
        AuthRequest->>SessionVerifier: Verify session token
        
        alt Verification Succeeds
            SessionVerifier-->>AuthRequest: Valid session
            AuthRequest-->>Client: Return signed-in state
            Note over AuthRequest: Safari ITP workaround successful
        else Verification Fails
            SessionVerifier-->>AuthRequest: Invalid session
            AuthRequest-->>Client: Fall back to handshake flow
            Note over AuthRequest: Handshake with SessionTokenWithoutClientUAT
        end
    else Normal Flow
        AuthRequest-->>Client: Continue standard authentication
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • New conditional logic path in authenticateRequest requires careful verification of session token handling and cookie interactions
  • Test coverage for both success and failure scenarios should be validated for completeness
  • Interaction with existing handshake flow fallback path warrants attention to ensure no regressions

Poem

🐰 A loop once trapped our session shy,
But redirect counts caught our eye—
With token check and Safari's quirk,
We've crafted workarounds that work!
No more infinite hops today,
Just smooth authentication's way!

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Title check ⚠️ Warning The title indicates this is a work-in-progress (WIP) pull request and should not be reviewed, which is not suitable for a pull request intended for merge. Remove the 'DO NOT REVIEW - WIP' prefix and provide a clear, descriptive title that summarizes the actual fix, such as 'Fix Safari ITP handshake loop by verifying session tokens on redirect'.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/safari-itp-handshake-loop

Comment @coderabbitai help to get the list of available commands and usage tips.

@pkg-pr-new
Copy link

pkg-pr-new bot commented Dec 1, 2025

Open in StackBlitz

@clerk/agent-toolkit

npm i https://pkg.pr.new/@clerk/agent-toolkit@7335

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@7335

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@7335

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@7335

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@7335

@clerk/dev-cli

npm i https://pkg.pr.new/@clerk/dev-cli@7335

@clerk/elements

npm i https://pkg.pr.new/@clerk/elements@7335

@clerk/clerk-expo

npm i https://pkg.pr.new/@clerk/clerk-expo@7335

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@7335

@clerk/express

npm i https://pkg.pr.new/@clerk/express@7335

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@7335

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@7335

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@7335

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@7335

@clerk/clerk-react

npm i https://pkg.pr.new/@clerk/clerk-react@7335

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@7335

@clerk/remix

npm i https://pkg.pr.new/@clerk/remix@7335

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@7335

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@7335

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@7335

@clerk/themes

npm i https://pkg.pr.new/@clerk/themes@7335

@clerk/types

npm i https://pkg.pr.new/@clerk/types@7335

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@7335

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@7335

commit: 5d7b78d

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
packages/backend/src/tokens/request.ts (1)

547-560: Consider catching specific error types for better error handling.

The catch block currently catches all errors indiscriminately. Consider catching only TokenVerificationError to avoid masking unexpected errors.

Apply this diff to catch specific error types:

       try {
         const { data } = await verifyToken(authenticateContext.sessionTokenInCookie!, authenticateContext);
         if (data) {
           return signedIn({
             tokenType: TokenType.SessionToken,
             authenticateContext,
             sessionClaims: data,
             headers: new Headers(),
             token: authenticateContext.sessionTokenInCookie!,
           });
         }
-      } catch {
+      } catch (err) {
         // Token verification failed, proceed with normal handshake flow
+        if (err instanceof TokenVerificationError) {
+          console.log('Clerk: Session token verification failed in redirect loop, falling back to handshake');
+        } else {
+          // Unexpected error - rethrow or log prominently
+          console.error('Clerk: Unexpected error during redirect loop token verification:', err);
+          throw err;
+        }
       }
packages/backend/src/tokens/__tests__/request.test.ts (1)

880-925: Consider adding test coverage for expired tokens in redirect loop.

While the current tests cover valid and malformed tokens, consider adding a test for expired tokens in the redirect loop scenario to ensure comprehensive coverage of all token verification error paths.

Example test to add:

test('cookieToken: returns handshake when no clientUat and redirect loop but expired session token', async () => {
  server.use(
    http.get('https://api.clerk.test/v1/jwks', () => {
      return HttpResponse.json(mockJwks);
    }),
  );

  // Advance time to expire the token
  vi.advanceTimersByTime(3600 * 1000);

  const requestState = await authenticateRequest(
    mockRequestWithCookies(
      {},
      {
        __clerk_db_jwt: 'deadbeef',
        __session: mockJwt, // Will be expired due to time advance
        __clerk_redirect_count: '1',
      },
    ),
    mockOptions({
      secretKey: 'test_deadbeef',
    }),
  );

  // Should return handshake since token verification failed
  expect(requestState).toMatchHandshake({ reason: AuthErrorReason.SessionTokenWithoutClientUAT });
  expect(requestState.toAuth()).toBeNull();
});
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 02798f5 and 5d7b78d.

📒 Files selected for processing (2)
  • packages/backend/src/tokens/__tests__/request.test.ts (1 hunks)
  • packages/backend/src/tokens/request.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

All code must pass ESLint checks with the project's configuration

Files:

  • packages/backend/src/tokens/request.ts
  • packages/backend/src/tokens/__tests__/request.test.ts
**/*.{js,jsx,ts,tsx,json,md,yml,yaml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/backend/src/tokens/request.ts
  • packages/backend/src/tokens/__tests__/request.test.ts
packages/**/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/backend/src/tokens/request.ts
  • packages/backend/src/tokens/__tests__/request.test.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Follow established naming conventions (PascalCase for components, camelCase for variables)

Prefer importing types from @clerk/shared/types instead of the deprecated @clerk/types alias

Files:

  • packages/backend/src/tokens/request.ts
  • packages/backend/src/tokens/__tests__/request.test.ts
packages/**/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

packages/**/src/**/*.{ts,tsx,js,jsx}: Maintain comprehensive JSDoc comments for public APIs
Use tree-shaking friendly exports
Validate all inputs and sanitize outputs
All public APIs must be documented with JSDoc
Use dynamic imports for optional features
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Implement proper logging with different levels

Files:

  • packages/backend/src/tokens/request.ts
  • packages/backend/src/tokens/__tests__/request.test.ts
**/*.ts?(x)

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

Files:

  • packages/backend/src/tokens/request.ts
  • packages/backend/src/tokens/__tests__/request.test.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Implement type guards for unknown types using the pattern function isType(value: unknown): value is Type
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details in classes
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Use mixins for shared behavior across unrelated classes in TypeScript
Use generic constraints with bounded type parameters like <T extends { id: string }>
Use utility types like Omit, Partial, and Pick for data transformation instead of manual type construction
Use discriminated unions instead of boolean flags for state management and API responses
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation at the type level
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Document functions with JSDoc comments including @param, @returns, @throws, and @example tags
Create custom error classes that extend Error for specific error types
Use the Result pattern for error handling instead of throwing exceptions
Use optional chaining (?.) and nullish coalescing (??) operators for safe property access
Let TypeScript infer obvious types to reduce verbosity
Use const assertions with as const for literal types
Use satisfies operator for type checking without widening types
Declare readonly arrays and objects for immutable data structures
Use spread operator and array spread for immutable updates instead of mutations
Use lazy loading for large types...

Files:

  • packages/backend/src/tokens/request.ts
  • packages/backend/src/tokens/__tests__/request.test.ts
**/*.{test,spec}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{test,spec}.{ts,tsx,js,jsx}: Unit tests are required for all new functionality
Verify proper error handling and edge cases
Include tests for all new features

Files:

  • packages/backend/src/tokens/__tests__/request.test.ts
**/*.{test,spec,e2e}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use real Clerk instances for integration tests

Files:

  • packages/backend/src/tokens/__tests__/request.test.ts
🧬 Code graph analysis (1)
packages/backend/src/tokens/__tests__/request.test.ts (4)
packages/backend/src/mock-server.ts (1)
  • server (6-6)
packages/backend/src/fixtures/index.ts (2)
  • mockJwks (47-49)
  • mockMalformedJwt (14-15)
packages/remix/src/ssr/authenticateRequest.ts (1)
  • authenticateRequest (9-54)
packages/backend/src/tokens/authStatus.ts (2)
  • AuthErrorReason (105-122)
  • AuthErrorReason (124-124)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (2)
packages/backend/src/tokens/__tests__/request.test.ts (2)

880-904: Good test coverage for Safari ITP workaround scenario.

The test correctly validates that when in a redirect loop with a valid session token, the authentication succeeds despite missing clientUat. This aligns with the Safari ITP mitigation logic.


906-925: Good test coverage for redirect loop with invalid token.

The test correctly validates that when the session token is invalid during a redirect loop, the system falls back to the handshake flow. This ensures the workaround doesn't bypass security for invalid tokens.

Comment on lines +558 to +560
} catch {
// Token verification failed, proceed with normal handshake flow
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Add error logging in the catch block.

The empty catch block silently swallows all token verification errors, making debugging difficult in production. At minimum, log the error before proceeding to the handshake flow.

Apply this diff to add error logging:

       } catch {
         // Token verification failed, proceed with normal handshake flow
+        console.log('Clerk: Session token verification failed in redirect loop, falling back to handshake');
       }

Or better yet, log the actual error:

-      } catch {
+      } catch (err) {
         // Token verification failed, proceed with normal handshake flow
+        console.log('Clerk: Session token verification failed in redirect loop, falling back to handshake:', err);
       }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} catch {
// Token verification failed, proceed with normal handshake flow
}
} catch (err) {
// Token verification failed, proceed with normal handshake flow
console.log('Clerk: Session token verification failed in redirect loop, falling back to handshake:', err);
}
🤖 Prompt for AI Agents
In packages/backend/src/tokens/request.ts around lines 558-560, the empty catch
block for token verification swallows errors; change it to catch the error
(e.g., catch (err)) and log the error before continuing the handshake flow — use
the module's existing logger (e.g., logger.error or processLogger.error) and
include a concise message plus the error object, and if no logger is available
fall back to console.error so token verification failures are visible in logs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants