Skip to content

Conversation

@bratsos
Copy link
Contributor

@bratsos bratsos commented Oct 22, 2025

Description

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

    • Improved URL parameter cleanup during handshake redirects, ensuring additional parameters are properly removed for cleaner URLs.
  • Tests

    • Added comprehensive test coverage for handshake query parameter cleanup, including multiple scenarios in development and production environments with edge cases.

@changeset-bot
Copy link

changeset-bot bot commented Oct 22, 2025

🦋 Changeset detected

Latest commit: a176276

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 Oct 22, 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 Oct 23, 2025 9:57am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 22, 2025

Walkthrough

This change adds test coverage and implementation for cleaning up an additional URL parameter during handshake redirect handling. A new __clerk_handshake_nonce parameter is now removed from redirect URLs in development mode, with comprehensive test coverage added for parameter cleanup scenarios. A semantic-release changeset file marks the patch release.

Changes

Cohort / File(s) Summary
Handshake URL Parameter Cleanup
packages/backend/src/tokens/handshake.ts
Removes __clerk_handshake_nonce URL parameter from development redirects alongside existing cleanup operations
Handshake Tests
packages/backend/src/tokens/__tests__/handshake.test.ts
Adds comprehensive test coverage for Query Parameter Cleanup in both development and production modes, including parameter combinations, URL encoding, hash fragments, and error handling
Release Metadata
.changeset/spicy-queens-send.md
Adds semantic-release changeset entry for @clerk/backend patch release

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 A nonce in the URL hops away,
Our cleanup now works both night and day,
With tests written thorough, left and right,
The handshake redirects shine bright! ✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "fix(backend): Remove handshake nonce query param to prevent infinite loops" directly corresponds to the main change in the changeset. The primary code modification in packages/backend/src/tokens/handshake.ts removes the HandshakeNonce URL parameter from redirect URLs, which is exactly what the title describes. The title is specific and actionable, clearly indicating both what is being fixed (removal of the handshake nonce query parameter) and the reason (preventing infinite loops), allowing a developer scanning the repository history to immediately understand the intent of the change. The accompanying test additions and changeset file are supporting changes that align with the title's primary focus.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ 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 ab/fix-handshake-nonce-query-param

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

@pkg-pr-new
Copy link

pkg-pr-new bot commented Oct 22, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: a176276

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 (7)
.changeset/spicy-queens-send.md (1)

1-3: Add a human-friendly release note.

Include a short description of the change and its impact, e.g., “Remove nonce-based handshake query parameters from URLs to prevent redirect loops; behavior differs in dev vs prod.” This improves changelog clarity for consumers.

Apply this diff:

 ---
 '@clerk/backend': patch
 ---
+Remove nonce-based handshake query parameters from URLs after handshake resolution to prevent redirect loops.
+
+- Cleans `__clerk_handshake_nonce`, `__clerk_handshake`, `__clerk_help`, `__clerk_db_jwt` from redirect URLs
+- Dev: redirects to a clean URL and sets `Cache-Control: no-store`
+- Prod: sets cookies without server-side cleanup redirect
+
+No public API changes.
packages/backend/src/tokens/__tests__/handshake.test.ts (1)

605-937: Great coverage on cleanup paths; minor DRY + maintainability nits.

  • Coverage looks solid across nonce/token/help/dev-browser variants, URL encoding, fragments, dev/prod header differences, and error paths. LGTM.
  • Consider extracting a small helper to set up mockAuthenticateContext for nonce-handshake scenarios (repeated in multiple tests) and a constant array for the handshake param keys you’re cleaning to avoid typos across tests.

Example extraction:

+const HANDSHAKE_QS_KEYS = [
+  '__clerk_handshake_nonce',
+  '__clerk_handshake',
+  '__clerk_help',
+  '__clerk_db_jwt',
+] as const;

+function withNoncePayload(ctx: AuthenticateContext, nonce: string, directives: string[]) {
+  ctx.handshakeNonce = nonce;
+  ctx.apiClient = {
+    clients: { getHandshakePayload: vi.fn().mockResolvedValue({ directives }) },
+  } as any;
+}
integration/tests/handshake.test.ts (5)

1676-1699: Test name doesn’t match behavior (expects redirect).

Title says “no redirect needed” but the assertion expects 307. Rename to reflect actual behavior to avoid confusion during triage.

Apply this diff:

-test('development handshake with nonce in cookie (not query) - no redirect needed', async () => {
+test('development handshake with nonce only in cookie – redirects to the same URL (no query cleanup needed)', async () => {

1559-1619: Nice all-in-one cleanup assertion; suggest centralizing key names.

Good single-test validation that all handshake params are removed while unrelated params persist. To reduce duplication across suites, define a local const HANDSHAKE_QS_KEYS = [...] and reuse in expectations.


1723-1771: Loop-prevention test is effective; cap and diagnostics are good.

Bounded retry with explicit failure if nonce persists is clear. Consider logging requestCount and last location on failure to ease debugging in CI.

Apply this minimal addition inside the else branch before throwing:

-      } else {
-        throw new Error(`Unexpected status: ${res.status}`);
+      } else {
+        console.error('loop-prevention: requestCount=', requestCount);
+        console.error('loop-prevention: lastLocation=', res.headers.get('location'));
+        throw new Error(`Unexpected status: ${res.status}`);
       }

1510-1548: App/env bootstrap looks correct; add teardown hardening.

Setup/teardown is solid. Add mockHandshakePayloads.clear() in an afterEach to isolate tests if a test early-returns or fails before afterAll.

 test.afterAll(async () => {
   await app.teardown();
   await new Promise<void>(resolve => apiServer.close(() => resolve()));
-  mockHandshakePayloads.clear();
 });
+
+test.afterEach(() => {
+  mockHandshakePayloads.clear();
+});

1550-1581: Cookie assertions use getSetCookie(); confirm undici availability in CI.

headers.getSetCookie?.() depends on undici. If CI ever swaps fetch implementations, this may become undefined. Optional fallback: parse raw set-cookie headers via res.headers.get('set-cookie') to avoid flakiness.

Would you like me to add a small helper:

function getSetCookies(res: Response): string[] {
  // undici
  const arr = (res.headers as any).getSetCookie?.();
  if (Array.isArray(arr)) return arr;
  const raw = res.headers.get('set-cookie');
  return raw ? raw.split(/\r?\n(?=.+?=)/g) : [];
}
📜 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 ca00881 and ac1ef70.

📒 Files selected for processing (3)
  • .changeset/spicy-queens-send.md (1 hunks)
  • integration/tests/handshake.test.ts (1 hunks)
  • packages/backend/src/tokens/__tests__/handshake.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (12)
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/spicy-queens-send.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/__tests__/handshake.test.ts
  • 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:

  • packages/backend/src/tokens/__tests__/handshake.test.ts
  • integration/tests/handshake.test.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/backend/src/tokens/__tests__/handshake.test.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/__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
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/__tests__/handshake.test.ts
  • integration/tests/handshake.test.ts
packages/**/*.{test,spec}.{js,jsx,ts,tsx}

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

Unit tests should use Jest or Vitest as the test runner.

Files:

  • packages/backend/src/tokens/__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:

  • packages/backend/src/tokens/__tests__/handshake.test.ts
  • integration/tests/handshake.test.ts
**/__tests__/**/*.{ts,tsx}

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

**/__tests__/**/*.{ts,tsx}: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces

Files:

  • packages/backend/src/tokens/__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
🧬 Code graph analysis (2)
packages/backend/src/tokens/__tests__/handshake.test.ts (2)
packages/backend/src/constants.ts (1)
  • constants (79-85)
packages/backend/src/tokens/handshake.ts (1)
  • verifyHandshakeToken (53-82)
integration/tests/handshake.test.ts (2)
integration/models/application.ts (1)
  • Application (7-7)
integration/presets/index.ts (1)
  • appConfigs (15-32)
🪛 LanguageTool
.changeset/spicy-queens-send.md

[grammar] ~1-~1: Hier könnte ein Fehler sein.
Context: --- '@clerk/backend': patch ---

(QB_NEW_DE)

⏰ 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__/handshake.test.ts (1)

824-839: Dev cache policy assertion is precise.

Asserting Cache-Control: no-store in development mode is valuable and prevents regressions. No changes needed.

integration/tests/handshake.test.ts (1)

1459-1792: Repo-wide sanity check: ensure no runtime reads of __clerk_handshake_nonce remain.

Given the loop-prevention goal, confirm the nonce query param is not read in runtime code (only tests). Run:

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 (5)
packages/backend/src/tokens/handshake.ts (1)

219-227: Good fix: delete nonce to stop dev redirect loops; also delete LegacyDevBrowser for completeness

The added removal of constants.QueryParameters.HandshakeNonce in dev resolves the loop. To keep cleanup exhaustive and future‑proof, also remove LegacyDevBrowser here (it’s already handled in removeDevBrowserFromURL, but not in this post‑handshake cleanup), and consider centralizing the param cleanup.

Suggested minimal addition:

       newUrl.searchParams.delete(constants.QueryParameters.DevBrowser);
+      newUrl.searchParams.delete(constants.QueryParameters.LegacyDevBrowser);
       newUrl.searchParams.delete(constants.QueryParameters.HandshakeNonce);

Optionally, extract a small helper (private) to delete all handshake params in one place to avoid drift:

private sanitizeHandshakeParams(u: URL): void {
  [
    constants.QueryParameters.Handshake,
    constants.QueryParameters.HandshakeHelp,
    constants.QueryParameters.DevBrowser,
    constants.QueryParameters.LegacyDevBrowser,
    constants.QueryParameters.HandshakeNonce,
  ].forEach(k => u.searchParams.delete(k));
}

Then call this.sanitizeHandshakeParams(newUrl).

integration/tests/handshake.test.ts (3)

1510-1517: Avoid fixed test ports; use ephemeral to reduce CI flakiness

Binding the API mock to a hardcoded port can collide under parallel CI. Use an ephemeral port and feed it into the env after listen(0).

Apply this refactor:

-  const NONCE_TEST_PORT = 4299;
+  // Use ephemeral port to avoid collisions in CI
+  const NONCE_TEST_PORT = 0;
@@
-  test.beforeAll('setup local Clerk API mock for nonce tests', async () => {
+  test.beforeAll('setup local Clerk API mock for nonce tests', async () => {
@@
-    const env = appConfigs.envs.withEmailCodes
-      .clone()
-      .setEnvVariable('private', 'CLERK_API_URL', `http://localhost:${NONCE_TEST_PORT}`);
-
-    await new Promise<void>(resolve => apiServer.listen(NONCE_TEST_PORT, resolve));
+    await new Promise<void>(resolve => apiServer.listen(0, resolve));
+    const addr = apiServer.address();
+    const port = typeof addr === 'string' ? 0 : addr?.port;
+    const env = appConfigs.envs.withEmailCodes
+      .clone()
+      .setEnvVariable('private', 'CLERK_API_URL', `http://localhost:${port}`);
@@
-    await app.withEnv(env);
+    await app.withEnv(env);

Also applies to: 1518-1520, 1538-1541


1578-1580: Confirm Node/Undici supports Headers.getSetCookie() in the test runner

headers.getSetCookie() is Undici/Node‑fetch specific. Ensure the CI Node version supports it; otherwise parse set-cookie via a fallback.

Example fallback (only if needed):

const setCookieHeaders =
  res.headers.getSetCookie?.()
  ?? (res.headers.get('set-cookie') ? [res.headers.get('set-cookie')!] : []);

Also applies to: 1719-1721


1676-1699: Rename test for clarity

Title says “no redirect needed” but the expectation is 307 with a cleaned URL. Rename to avoid confusion, e.g., “nonce in cookie only — cleanup redirect issued”.

packages/backend/src/tokens/__tests__/handshake.test.ts (1)

623-839: Great coverage; add a case for LegacyDevBrowser and centralize test helpers

The dev cleanup tests cover nonce, handshake, help, and dev browser. Add a case asserting removal of LegacyDevBrowser as well, mirroring production/dev expectations. Also consider a tiny helper to build mockAuthenticateContext URLs and assert cleaned params to reduce duplication across tests.

📜 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 ac1ef70 and dd7acf8.

📒 Files selected for processing (4)
  • .changeset/spicy-queens-send.md (1 hunks)
  • integration/tests/handshake.test.ts (1 hunks)
  • packages/backend/src/tokens/__tests__/handshake.test.ts (1 hunks)
  • packages/backend/src/tokens/handshake.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (12)
**/*.{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
  • packages/backend/src/tokens/__tests__/handshake.test.ts
  • packages/backend/src/tokens/handshake.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
  • packages/backend/src/tokens/__tests__/handshake.test.ts
  • packages/backend/src/tokens/handshake.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:

  • integration/tests/handshake.test.ts
  • packages/backend/src/tokens/__tests__/handshake.test.ts
  • packages/backend/src/tokens/handshake.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
  • packages/backend/src/tokens/__tests__/handshake.test.ts
  • packages/backend/src/tokens/handshake.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/backend/src/tokens/__tests__/handshake.test.ts
  • packages/backend/src/tokens/handshake.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/__tests__/handshake.test.ts
  • packages/backend/src/tokens/handshake.ts
packages/**/*.{test,spec}.{js,jsx,ts,tsx}

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

Unit tests should use Jest or Vitest as the test runner.

Files:

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

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

**/__tests__/**/*.{ts,tsx}: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces

Files:

  • packages/backend/src/tokens/__tests__/handshake.test.ts
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/spicy-queens-send.md
🧬 Code graph analysis (3)
integration/tests/handshake.test.ts (2)
integration/models/application.ts (1)
  • Application (7-7)
integration/presets/index.ts (1)
  • appConfigs (15-32)
packages/backend/src/tokens/__tests__/handshake.test.ts (2)
packages/backend/src/constants.ts (1)
  • constants (79-85)
packages/backend/src/tokens/handshake.ts (1)
  • verifyHandshakeToken (53-82)
packages/backend/src/tokens/handshake.ts (2)
packages/backend/src/internal.ts (1)
  • constants (1-1)
packages/backend/src/constants.ts (1)
  • constants (79-85)
🪛 LanguageTool
.changeset/spicy-queens-send.md

[grammar] ~1-~1: Hier könnte ein Fehler sein.
Context: --- '@clerk/backend': patch ---

(QB_NEW_DE)

⏰ 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). (9)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (handshake, chrome)
  • GitHub Check: Integration Tests (sessions:staging, chrome)
  • GitHub Check: Integration Tests (handshake:staging, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
🔇 Additional comments (1)
.changeset/spicy-queens-send.md (1)

1-3: Changeset OK for @clerk/backend patch

Content is valid for a patch bump. Ensure the release note text (in the PR body) briefly calls out the loop-prevention fix so consumers understand the behavior change.

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

🧹 Nitpick comments (2)
integration/tests/handshake.test.ts (2)

1462-1463: Use an ephemeral port to avoid CI flakes from port collisions.

Binding to 4299 can intermittently fail in parallel CI. Listen on port 0 and inject the resolved port into CLERK_API_URL.

-  const NONCE_TEST_PORT = 4299;
+  // Use ephemeral port to avoid collisions
+  const NONCE_TEST_PORT = 0;
@@
-  test.beforeAll('setup local Clerk API mock for nonce tests', async () => {
+  test.beforeAll('setup local Clerk API mock for nonce tests', async () => {
     test.setTimeout(90_000);
-    const env = appConfigs.envs.withEmailCodes
-      .clone()
-      .setEnvVariable('private', 'CLERK_API_URL', `http://localhost:${NONCE_TEST_PORT}`);
-
-    await new Promise<void>(resolve => apiServer.listen(NONCE_TEST_PORT, resolve));
+    await new Promise<void>(resolve => apiServer.listen(NONCE_TEST_PORT, resolve));
+    const address = apiServer.address();
+    const port = typeof address === 'string' ? 0 : address?.port;
+    const env = appConfigs.envs.withEmailCodes
+      .clone()
+      .setEnvVariable('private', 'CLERK_API_URL', `http://localhost:${port}`);

Also applies to: 1511-1517


1592-1619: Optional: add a case with nonce present in both cookie and query.

Validates precedence and ensures both sources are cleaned from the URL, further guarding against loop edge cases.

Would you like me to draft this additional test?

📜 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 dd7acf8 and e24f7f6.

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

  • 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
🧬 Code graph analysis (1)
integration/tests/handshake.test.ts (2)
integration/models/application.ts (1)
  • Application (7-7)
integration/presets/index.ts (1)
  • appConfigs (15-32)
⏰ 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 (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (custom, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (handshake:staging, chrome)
  • GitHub Check: Integration Tests (handshake, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (sessions:staging, chrome)
  • GitHub Check: Integration Tests (sessions, 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: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
integration/tests/handshake.test.ts (1)

1459-1792: Strong coverage and realistic mocks.

The suite thoroughly verifies nonce cleanup, URL preservation, and loop prevention across modes. Nice use of single‑use payloads and explicit assertions.

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 (1)
.changeset/spicy-queens-send.md (1)

1-3: Changeset structure is correct.

The file follows the standard Changesets format with proper YAML front matter. The patch bump type aligns with the bug fix classification in the PR objectives.

Consider optionally adding a brief description between the --- delimiters to provide more context in the generated changelog. For example:

---
'@clerk/backend': patch
---
+Remove __clerk_handshake_nonce query parameter from redirect URLs in development mode to prevent infinite loops.
📜 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 e24f7f6 and 7cc0a8a.

📒 Files selected for processing (3)
  • .changeset/spicy-queens-send.md (1 hunks)
  • packages/backend/src/tokens/__tests__/handshake.test.ts (1 hunks)
  • packages/backend/src/tokens/handshake.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/backend/src/tokens/handshake.ts
  • packages/backend/src/tokens/tests/handshake.test.ts
🧰 Additional context used
📓 Path-based instructions (1)
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/spicy-queens-send.md
🪛 LanguageTool
.changeset/spicy-queens-send.md

[grammar] ~1-~1: Hier könnte ein Fehler sein.
Context: --- '@clerk/backend': patch ---

(QB_NEW_DE)

⏰ 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

Copy link
Member

@octoper octoper left a comment

Choose a reason for hiding this comment

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

🔥

@bratsos bratsos merged commit f2644c2 into main Oct 23, 2025
44 checks passed
@bratsos bratsos deleted the ab/fix-handshake-nonce-query-param branch October 23, 2025 10:38
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.

4 participants