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 return 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

    • Prevents infinite handshake redirect loops in browsers that block cross-origin cookies (e.g., Safari ITP) by verifying existing session tokens so valid sessions remain signed in.
  • Tests

    • Added tests covering redirect-loop scenarios to ensure correct handling of valid and invalid session tokens.
  • Chores

    • Added a patch changeset documenting the redirect-loop fix for the backend package.

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

@changeset-bot
Copy link

changeset-bot bot commented Dec 1, 2025

🦋 Changeset detected

Latest commit: fe817e4

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 11 packages
Name Type
@clerk/backend Patch
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/testing Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another 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 4, 2025 2:33pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 1, 2025

Walkthrough

Adds redirect-loop detection to authenticateRequest: when no clientUat exists but a session token and a redirect-count cookie are present, it tries to verify the session token and returns a signed-in state on success; on failure it falls back to the existing handshake flow.

Changes

Cohort / File(s) Summary
Redirect-loop handling & tests
packages/backend/src/tokens/request.ts, packages/backend/src/tokens/__tests__/request.test.ts
Adds a conditional branch in authenticateRequest to detect redirect loops via __clerk_redirect_count; if no clientUat but a session token exists it attempts cookie-based session verification and returns a signed-in auth state on success, otherwise falls back to handshake (SessionTokenWithoutClientUAT). Adds two tests covering successful verification and handshake fallback.
Changeset / Manifest
.changeset/true-carpets-happen.md, package.json
Adds a patch changeset describing the redirect-loop fix for development browsers that block cross-origin Strict cookies and updates package metadata as part of the release changeset.

Sequence Diagram

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

    Client->>AuthRequest: HTTP request (cookies include __clerk_redirect_count)
    AuthRequest->>CookieStore: Read session token & redirect count

    alt No clientUat && session token present && redirect_count > 0
        AuthRequest->>SessionVerifier: Verify session token from cookie
        alt Verification succeeds
            SessionVerifier-->>AuthRequest: Valid session token & claims
            AuthRequest-->>Client: Return signed-in auth state (session token)
        else Verification fails
            SessionVerifier-->>AuthRequest: Invalid or expired token
            AuthRequest-->>Client: Continue to handshake (SessionTokenWithoutClientUAT / null auth)
        end
    else Normal flow
        AuthRequest-->>Client: Proceed with existing auth/handshake logic
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Inspect packages/backend/src/tokens/request.ts for correctness of the new conditional, cookie parsing, and error/edge-case handling.
  • Verify test accuracy and JWKS mocking in packages/backend/src/tokens/__tests__/request.test.ts.
  • Check .changeset/true-carpets-happen.md and package.json for correct changeset metadata and versioning intent.

Poem

🐰
A loop that chased us round and round,
I sniffed the cookie, then found the sound.
If token sings, I'll open the gate—
If silent, handshake decides our fate.
Hops saved, code tidy, rabbit elate!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
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 (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: resolving an infinite handshake redirect loop caused by Safari ITP blocking cross-origin redirect cookies.
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: fe817e4

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.

@jacekradko jacekradko changed the title DO NOT REVIEW - WIP safari ITP handshake loop fix(backend) - Resolve Safari ITP handshake loop Dec 4, 2025
@jacekradko jacekradko changed the title fix(backend) - Resolve Safari ITP handshake loop fix(backend): Resolve Safari ITP handshake loop Dec 4, 2025
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.

5 participants