-
Notifications
You must be signed in to change notification settings - Fork 408
fix(backend): Prevent excessive handshakes #6635
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
…, and tighten redirect counter detection to reduce false positives
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughAdds a patch changeset and adjusts backend handshake behavior: removes Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant U as User Agent
participant S as Backend
participant H as resolveHandshake
participant L as Loop Guard
U->>S: Request (possible org activation)
activate S
S->>H: resolveHandshake(instanceType)
activate H
alt instanceType == development
H->>H: Remove Handshake, HandshakeHelp, DevBrowser from redirect URL
else
H->>H: Remove Handshake, HandshakeHelp
end
H-->>S: Clean redirect URL
deactivate H
S->>U: Redirect response with RedirectCount cookie (Max-Age=2)
deactivate S
U->>S: Follow-up request with RedirectCount
activate S
S->>L: handleMaybeOrganizationSyncHandshake()
activate L
alt RedirectCount >= 3
L-->>S: Treat as loop → skip activation, warn
else RedirectCount < 3
L-->>S: Continue activation/redirect flow
end
deactivate L
deactivate S
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. ✨ Finishing Touches
🧪 Generate unit tests
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
| const newCounterValue = this.authenticateContext.handshakeRedirectLoopCounter + 1; | ||
| const cookieName = constants.Cookies.RedirectCount; | ||
| headers.append('Set-Cookie', `${cookieName}=${newCounterValue}; SameSite=Lax; HttpOnly; Max-Age=3`); | ||
| headers.append('Set-Cookie', `${cookieName}=${newCounterValue}; SameSite=Lax; HttpOnly; Max-Age=2`); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
3 was an arbitrary choice here, I'm reducing to 2 to mitigate the case where someone switches between orgs quickly when using org url sync
| return null; | ||
| } | ||
| if (authenticateContext.handshakeRedirectLoopCounter > 0) { | ||
| if (authenticateContext.handshakeRedirectLoopCounter >= 3) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Again, reducing the case where someone might be switching quickly. this should help, in addition to the max-age change, reduce false-positives of redirect loop detection
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
There was a problem hiding this 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 (5)
.changeset/grumpy-groups-run.md (1)
1-5: Broaden the changeset note to reflect all user-visible behavior changes.The note currently mentions the dev handshake trigger fix, but this PR also:
- Lowers the redirect loop cookie Max-Age to 2s.
- Raises the redirect-loop threshold for org activation to 3 redirects.
Consider expanding the description so downstream consumers understand the full behavioral impact.
Proposed wording:
--- -'@clerk/backend': patch --- -Fixes an issue where a handshake would trigger more than intended in development. +'@clerk/backend': patch +--- +Fixes excessive dev handshakes and adjusts redirect loop detection: +- Dev: remove the __clerk_db_jwt (DevBrowser) query param from the app URL after handshake resolution to avoid re-triggering. +- Loop detection: lower redirect counter cookie Max-Age to 2s and only consider a loop after ≥3 rapid redirects.packages/backend/src/tokens/handshake.ts (3)
221-228: Also strip LegacyDevBrowser in dev redirect, or reuse the existing helper for consistency.In dev, you delete Handshake, HandshakeHelp, and DevBrowser. We already have
removeDevBrowserFromURLwhich deletes bothDevBrowserandLegacyDevBrowser. Reusing it here prevents stale legacy params from keeping the loop alive.- if (this.authenticateContext.instanceType === 'development') { - const newUrl = new URL(this.authenticateContext.clerkUrl); - newUrl.searchParams.delete(constants.QueryParameters.Handshake); - newUrl.searchParams.delete(constants.QueryParameters.HandshakeHelp); - newUrl.searchParams.delete(constants.QueryParameters.DevBrowser); - headers.append(constants.Headers.Location, newUrl.toString()); - headers.set(constants.Headers.CacheControl, 'no-store'); - } + if (this.authenticateContext.instanceType === 'development') { + const newUrl = this.removeDevBrowserFromURL(this.authenticateContext.clerkUrl); + newUrl.searchParams.delete(constants.QueryParameters.Handshake); + newUrl.searchParams.delete(constants.QueryParameters.HandshakeHelp); + headers.append(constants.Headers.Location, newUrl.toString()); + headers.set(constants.Headers.CacheControl, 'no-store'); + }
321-323: Use a non-strict threshold (>= 3) to align with request.ts and harden against drift.
request.tstreats a loop as>= 3. Using>=here avoids off-by-one surprises if the counter gets out of sync.- if (this.authenticateContext.handshakeRedirectLoopCounter === 3) { + if (this.authenticateContext.handshakeRedirectLoopCounter >= 3) { return true; }
325-329: Ensure the RedirectCount cookie is scoped to the root pathAll occurrences of
Set-Cookiewith theRedirectCountname have been located only inhandshake.ts, so addingPath=/here will consistently apply across all routes without side effects.• File:
packages/backend/src/tokens/handshake.ts
Line 327 (zero-based index may differ):- headers.append('Set-Cookie', `${cookieName}=${newCounterValue}; SameSite=Lax; HttpOnly; Max-Age=2`); + headers.append('Set-Cookie', `${cookieName}=${newCounterValue}; Path=/; SameSite=Lax; HttpOnly; Max-Age=2`);No other
Set-Cookiecalls forRedirectCountwere found in the codebase, so this change is isolated and safe.packages/backend/src/tokens/request.ts (1)
389-398: LGTM on raising the org-activation loop threshold to ≥3. Consider centralizing the threshold.This matches the intent to allow a couple of redirects before considering it a loop. To avoid future drift with
HandshakeService.checkAndTrackRedirectLoop, consider extracting a shared constant (e.g.,REDIRECT_LOOP_THRESHOLD = 3) inconstants.tsand referencing it in both places.If you want, I can open a follow-up to introduce the shared constant and update both call-sites.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (3)
.changeset/grumpy-groups-run.md(1 hunks)packages/backend/src/tokens/handshake.ts(2 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/grumpy-groups-run.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/handshake.tspackages/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/handshake.tspackages/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/handshake.tspackages/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/handshake.tspackages/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
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor 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
Useconst assertionsfor literal types:as const
Usesatisfiesoperator 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 ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor 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/handshake.tspackages/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/handshake.tspackages/backend/src/tokens/request.ts
🧬 Code graph analysis (1)
packages/backend/src/tokens/handshake.ts (1)
packages/backend/src/constants.ts (1)
constants(79-85)
⏰ 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: Build Packages
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🦋 Changeset detectedLatest commit: db961af The changes in this PR will be included in the next version bump. This PR includes changesets to release 11 packages
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 |
There was a problem hiding this 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 (4)
integration/tests/handshake.test.ts (4)
1448-1451: Avoid parsing a missing Location header on 200 responsesOn 200, there should be no
Locationheader. Parsingnew URLSearchParams(res.headers.get('location'))relies on implementation quirks (e.g., treatingnullas a string) and is brittle across runtimes. Assert explicitly that the header is absent instead.Apply this diff:
- expect(res.status).toBe(200); - const redirectSearchParams = new URLSearchParams(res.headers.get('location')); - expect(redirectSearchParams.get('organization_id')).toBe(null); + expect(res.status).toBe(200); + expect(res.headers.get('location')).toBeNull();
1418-1421: Lock in the new cookie TTL: assert Max-Age=2Given the PR reduces the redirect-tracking cookie lifetime to 2 seconds, assert it in the test to prevent regressions. A regex keeps the assertion resilient to attribute ordering.
// read the set-cookie directives const setCookie = res.headers.get('set-cookie'); - expect(setCookie).toContain(`__clerk_redirect_count=1`); // <-- Critical + expect(setCookie).toContain(`__clerk_redirect_count=1`); // <-- Critical + // Also assert the new TTL + expect(setCookie).toMatch(/__clerk_redirect_count=1(?:;[^;]*)*;\s*Max-Age=2\b/i);
837-861: Add a follow-up request to ensure no post-handshake re-trigger in dev after __clerk_db_jwt resolutionOne objective is to stop retriggering a handshake in development after resolving a handshake that set
__clerk_db_jwt. You’re setting the cookie in “Handshake result - dev - new devbrowser”, but we don’t verify the very next navigation returns 200 without another handshake.Proposed test to add right after this block:
test('No re-handshake in dev immediately after handshake that set __clerk_db_jwt', async () => { const config = generateConfig({ mode: 'test' }); const { token } = config.generateToken({ state: 'active' }); // Simulate a handshake result that sets both session and devbrowser cookies const cookiesToSet = [`__session=${token};path=/`, '__clerk_db_jwt=asdf;path=/']; const handshake = await config.generateHandshakeToken(cookiesToSet); const res1 = await fetch(app.serverUrl + '/?__clerk_handshake=' + handshake, { headers: new Headers({ Cookie: `${devBrowserCookie}`, 'X-Publishable-Key': config.pk, 'X-Secret-Key': config.sk, 'Sec-Fetch-Dest': 'document', }), redirect: 'manual', }); expect(res1.status).toBe(307); expect(res1.headers.get('location')).toBe('/'); // Build Cookie header from Set-Cookie lines to mimic the browser carrying them forward const setCookieLines = [...res1.headers.entries()] .filter(([k]) => k.toLowerCase() === 'set-cookie') .map(([, v]) => v.split(';')[0]); // take "name=value" const carryCookies = setCookieLines.join('; '); // Next navigation to "/" should NOT handshake again const res2 = await fetch(app.serverUrl + '/', { headers: new Headers({ Cookie: `${carryCookies}`, 'X-Publishable-Key': config.pk, 'X-Secret-Key': config.sk, 'Sec-Fetch-Dest': 'document', }), redirect: 'manual', }); expect(res2.status).toBe(200); expect(res2.headers.get('location')).toBeNull(); });This asserts the fix end-to-end: once the devbrowser cookie is set from a resolved handshake, a subsequent visit does not re-enter the handshake path.
1339-1343: Remove stray console.log calls from the test suiteThese logs add noise to CI output and aren’t needed for assertions.
- if (testCase.name === 'Header-based auth should not handshake with expired auth') { - console.log(testCase.name); - console.log(res.headers.get('x-clerk-auth-status')); - console.log(res.headers.get('x-clerk-auth-reason')); - } + // (removed noisy debug logs)
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
integration/tests/handshake.test.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{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:
integration/tests/handshake.test.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:
integration/tests/handshake.test.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
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor 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
Useconst assertionsfor literal types:as const
Usesatisfiesoperator 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 ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor 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:
integration/tests/handshake.test.ts
integration/**
📄 CodeRabbit inference engine (.cursor/rules/global.mdc)
Framework integration templates and E2E tests should be placed under the integration/ directory
Files:
integration/tests/handshake.test.ts
integration/**/*
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
End-to-end tests and integration templates must be located in the 'integration/' directory.
Files:
integration/tests/handshake.test.ts
integration/**/*.{test,spec}.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Integration tests should use Playwright.
Files:
integration/tests/handshake.test.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:
integration/tests/handshake.test.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). (27)
- GitHub Check: Integration Tests (quickstart, chrome)
- GitHub Check: Integration Tests (vue, chrome)
- GitHub Check: Integration Tests (nextjs, chrome, 14)
- GitHub Check: Integration Tests (nextjs, chrome, 15)
- GitHub Check: Integration Tests (billing, chrome)
- GitHub Check: Integration Tests (localhost, chrome)
- GitHub Check: Integration Tests (tanstack-react-router, chrome)
- GitHub Check: Integration Tests (react-router, chrome)
- GitHub Check: Integration Tests (tanstack-react-start, chrome)
- GitHub Check: Integration Tests (nuxt, chrome)
- GitHub Check: Integration Tests (machine, chrome)
- GitHub Check: Integration Tests (expo-web, chrome)
- GitHub Check: Integration Tests (astro, chrome)
- GitHub Check: Integration Tests (sessions, chrome)
- GitHub Check: Integration Tests (elements, chrome)
- GitHub Check: Integration Tests (express, chrome)
- GitHub Check: Integration Tests (ap-flows, chrome)
- GitHub Check: Integration Tests (generic, chrome)
- GitHub Check: Publish with pkg-pr-new
- GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
- GitHub Check: Unit Tests (22, **)
- GitHub Check: Static analysis
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
integration/tests/handshake.test.ts (1)
1437-1441: Redirect-loop threshold updated to 3 — test change matches backend behaviorBumping
__clerk_redirect_countto3here aligns the test with the new ">= 3 redirects" loop-guard logic. Looks good.
| const newUrl = new URL(this.authenticateContext.clerkUrl); | ||
| newUrl.searchParams.delete(constants.QueryParameters.Handshake); | ||
| newUrl.searchParams.delete(constants.QueryParameters.HandshakeHelp); | ||
| newUrl.searchParams.delete(constants.QueryParameters.DevBrowser); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This looks good to me. Was there any reason we used to delete it from the clerk-js side only or just an omission?
Description
__clerk_db_jwtparametermax-ageof the redirect counter cookie to2to reduce false-positives during redirect detectionChecklist
pnpm testruns as expected.pnpm buildruns as expected.Type of change
Summary by CodeRabbit
Bug Fixes
Chores