Skip to content

Conversation

brkalow
Copy link
Member

@brkalow brkalow commented Sep 11, 2025

Description

Context: https://clerkinc.slack.com/archives/C08KSPJA6JZ/p1757533420619729

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 redirect loops during cross-origin handshakes in development, improving stability for satellite-to-primary requests.
  • Chores

    • Added a changeset entry for a patch release of @clerk/backend.

Copy link

changeset-bot bot commented Sep 11, 2025

🦋 Changeset detected

Latest commit: f6a2894

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

Copy link

vercel bot commented Sep 11, 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 Sep 11, 2025 4:11pm

Copy link
Contributor

coderabbitai bot commented Sep 11, 2025

Walkthrough

Adds a patch-level changeset and refines cross-origin handshake control in request token handling by adding a guard to prevent redirect loops during development.

Changes

Cohort / File(s) Summary of Changes
Release metadata
\.changeset/clear-forks-ring.md
Adds a patch changeset for @clerk/backend documenting a bug fix: prevent cross-origin handshake loops in development. No code changes.
Handshake guard logic
packages/backend/src/tokens/request.ts
Adds an extra condition requiring handshakeRedirectLoopCounter === 0 alongside non-Clerk referrer to trigger cross-origin handshake; suppresses handshake when a loop is detected. No public API changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant S as Server (Backend)
  participant R as Request Token Handler
  participant H as Handshake Logic

  C->>S: HTTP Request (possible cross-origin)
  S->>R: Process request tokens
  R->>H: Evaluate cross-origin handshake conditions
  note over H: New guard: trigger only if<br/>not KnownClerkReferrer AND<br/>handshakeRedirectLoopCounter == 0
  alt Conditions met
    H-->>R: Initiate handshake redirect
    R-->>S: Respond with redirect
    S-->>C: 3xx Redirect to handshake
  else Loop detected or not needed
    H-->>R: Suppress handshake
    R-->>S: Continue normal processing
    S-->>C: Proceed without handshake
  end

  %% Styling (subtle)
  rect rgba(220,235,255,0.3)
  note right of H: Changed decision point
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I twitch my ears at loops that spin,
A handshake paused, we don’t begin.
One hop back, I check the trail—
No endless bounds, no rabbit tail.
Patch applied, the burrow’s clear,
Cross-winds calm—onward, engineer! 🐇✨

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.

Pre-merge checks (2 passed, 1 warning)

❌ 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title is concise, a single sentence, and highlights the core bugfix — avoiding a handshake loop in the backend during primary-domain synchronization. It matches the changeset and the code change that adds a guard to suppress cross-origin/satellite-to-primary handshake redirect loops, so it accurately reflects the main change for reviewers.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch brk.fix/handshake-primary-sync-loop

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

@brkalow brkalow changed the title fix(backend): avoid handshake loop on primary domain sync fix(backend): Avoid handshake loop on primary domain sync Sep 11, 2025
Copy link

pkg-pr-new bot commented Sep 11, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: f6a2894

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: 0

🧹 Nitpick comments (2)
.changeset/clear-forks-ring.md (1)

5-6: Polish the release note phrasing (hyphenate “cross‑origin”).

Clearer and more concise wording.

-Fix a case where handshakes would get triggered in a loop on cross origin requests in development.
+Fix a case where handshakes would loop on cross-origin requests in development.
packages/backend/src/tokens/request.ts (1)

575-589: Scope the cross‑origin handshake guard to development to avoid unintended prod behavior.

PR/changeset describe a dev-only loop; keep prod semantics unchanged.

-      const shouldForceHandshakeForCrossDomain =
-        !authenticateContext.isSatellite && // We're on primary
+      const shouldForceHandshakeForCrossDomain =
+        authenticateContext.instanceType === 'development' && // Scope guard to dev
+        !authenticateContext.isSatellite && // We're on primary
         authenticateContext.secFetchDest === 'document' && // Document navigation
         authenticateContext.isCrossOriginReferrer() && // Came from different domain
         !authenticateContext.isKnownClerkReferrer() && // Not from Clerk accounts portal or FAPI
         authenticateContext.handshakeRedirectLoopCounter === 0; // Not in a redirect loop

Please confirm we don’t rely on this path for any production cross-domain sync on primary; if we do, consider a separate prod-safe heuristic.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • 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 b1d9aac and f6a2894.

📒 Files selected for processing (2)
  • .changeset/clear-forks-ring.md (1 hunks)
  • packages/backend/src/tokens/request.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/clear-forks-ring.md
**/*.{js,jsx,ts,tsx}

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

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
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
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

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

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

Use Prettier for consistent code formatting

Files:

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

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

TypeScript is required for all packages

Files:

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

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

Packages should export TypeScript types alongside runtime code

Files:

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

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

Use proper TypeScript error types

**/*.{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
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
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

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

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

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/backend/src/tokens/request.ts
⏰ 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). (4)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep/ci
🔇 Additional comments (1)
packages/backend/src/tokens/request.ts (1)

580-582: LGTM: extra loop-guard condition is correct.

Adding both “not a known Clerk referrer” and “loop counter is 0” prevents redundant handshakes after a detected loop.

@brkalow brkalow merged commit 8d1514a into main Sep 17, 2025
42 of 43 checks passed
@brkalow brkalow deleted the brk.fix/handshake-primary-sync-loop branch September 17, 2025 21:58
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