Skip to content

fix(backend,nextjs): Allow satellite redirect to public route #6225

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

Open
wants to merge 9 commits into
base: main
Choose a base branch
from

Conversation

jacekradko
Copy link
Member

@jacekradko jacekradko commented Jun 30, 2025

Description

Updates the redirect logic in satellite applications to permit navigation to public routes after sign-in or sign-up. Previously, users were always redirected to the primary domain or a protected route, even when the original destination was public. This change improves support for more flexible redirect flows in multi-domain setups.

Fixes: USER-2109

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

Summary by CodeRabbit

  • New Features

    • Improved redirect handling for unauthenticated requests on satellite domains, ensuring users are returned to their intended destination after authentication.
    • Enhanced logging for satellite domain detection during authentication flows.
  • Refactor

    • Streamlined internal logic by making conditional checks more explicit, with no change to user-facing behavior.

Copy link

changeset-bot bot commented Jun 30, 2025

🦋 Changeset detected

Latest commit: 660e1a7

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/nextjs Patch
@clerk/astro Patch
@clerk/agent-toolkit Patch
@clerk/express Patch
@clerk/fastify 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 Jun 30, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
clerk-js-sandbox ⬜️ Skipped (Inspect) Jul 1, 2025 4:19pm

@jacekradko jacekradko marked this pull request as ready for review June 30, 2025 20:27
@jacekradko jacekradko changed the title fix: satellite redirect fix(backend,nextjs): Allow satellite redirect to public route Jun 30, 2025
Copy link
Contributor

coderabbitai bot commented Jun 30, 2025

📝 Walkthrough

Walkthrough

The changes refactor the handling of satellite domain authentication flows in the Next.js Clerk middleware. The middleware now detects unauthenticated requests on satellite domains and logs this scenario. Redirect logic for sign-in and sign-up is updated: when the request originates from a satellite domain, the redirect URL includes a redirect_url query parameter pointing back to the original satellite domain URL, ensuring users return to their initial destination after authentication. Function signatures for redirect creation are updated to accept the full request state. In a separate file, a redundant boolean variable is inlined without altering logic. Additionally, the Astro middleware call to createMiddlewareRedirectToSignIn is updated to pass the new requestState argument.

Assessment against linked issues

Objective Addressed Explanation
Include a redirect_url parameter to return to the Satellite domain when sign-in/sign-up from Satellite domain (USER-2109)
Use isSatellite value to determine when to include the redirect parameter (USER-2109)
Ensure redirection back to the satellite domain for both public and protected routes if isSatellite is true (USER-2109)

Suggested reviewers

  • wobsoriano
  • panteliselef

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5512ce4 and 660e1a7.

📒 Files selected for processing (1)
  • packages/nextjs/src/server/clerkMiddleware.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/nextjs/src/server/clerkMiddleware.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Build Packages
  • GitHub Check: Analyze (javascript-typescript)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between baac817 and 69ba85b.

📒 Files selected for processing (2)
  • packages/backend/src/tokens/request.ts (1 hunks)
  • packages/nextjs/src/server/clerkMiddleware.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
`**/*.{js,jsx,ts,tsx}`: All code must pass ESLint checks with the project's conf...

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Use Prettier for consistent code formatting
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
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Validate all inputs and sanitize outputs
Implement proper logging with different levels

📄 Source: CodeRabbit Inference Engine (.cursor/rules/development.mdc)

List of files the instruction was applied to:

  • packages/backend/src/tokens/request.ts
  • packages/nextjs/src/server/clerkMiddleware.ts
`packages/**/*.ts`: TypeScript is required for all packages

packages/**/*.ts: TypeScript is required for all packages

📄 Source: CodeRabbit Inference Engine (.cursor/rules/development.mdc)

List of files the instruction was applied to:

  • packages/backend/src/tokens/request.ts
  • packages/nextjs/src/server/clerkMiddleware.ts
`packages/**/*.{ts,tsx,d.ts}`: Packages should export TypeScript types alongside runtime code

packages/**/*.{ts,tsx,d.ts}: Packages should export TypeScript types alongside runtime code

📄 Source: CodeRabbit Inference Engine (.cursor/rules/development.mdc)

List of files the instruction was applied to:

  • packages/backend/src/tokens/request.ts
  • packages/nextjs/src/server/clerkMiddleware.ts
`**/*.{ts,tsx}`: Use proper TypeScript error types

**/*.{ts,tsx}: Use proper TypeScript error types

📄 Source: CodeRabbit Inference Engine (.cursor/rules/development.mdc)

List of files the instruction was applied to:

  • packages/backend/src/tokens/request.ts
  • packages/nextjs/src/server/clerkMiddleware.ts
`**/*.{ts,tsx}`: Always define explicit return types for functions, especially p...

**/*.{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
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
Document public functions and APIs with JSDoc-style comments including @param, @returns, @throws, and @example
Define custom error classes for domain-specific errors
Use the Result pattern for error handling instead of throwing exceptions
Use optional chaining and nullish coalescing for safe property access
Let TypeScript infer types when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use readonly arrays and objects for immutability
Use immutable update patterns (spread, etc.) for objects and arrays
Use lazy loading for large types
Prefer unknown over any for performance
Use type-only imports: import type { ... }
Use branded types for domain safety
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints in TypeScript generics
No unused type parameters in generics
Proper use of utility types instead of manual type construction
Type-only imports where possible for performance
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

📄 Source: CodeRabbit Inference Engine (.cursor/rules/typescript.mdc)

List of files the instruction was applied to:

  • packages/backend/src/tokens/request.ts
  • packages/nextjs/src/server/clerkMiddleware.ts
🧠 Learnings (3)
📓 Common learnings
Learnt from: dstaley
PR: clerk/javascript#6116
File: .changeset/tangy-garlics-say.md:1-2
Timestamp: 2025-06-13T16:09:53.061Z
Learning: In the Clerk JavaScript repository, contributors create intentionally empty changeset files (containing only the YAML delimiters) when a PR touches only non-published parts of the codebase (e.g., sandbox assets). This signals that no package release is required, so such changesets should not be flagged as missing content.
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/nextjs.mdc:0-0
Timestamp: 2025-06-30T10:31:43.578Z
Learning: Applies to app/**/*.tsx : Use redirect function for server-side redirects in Server Components
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/nextjs.mdc:0-0
Timestamp: 2025-06-30T10:31:43.578Z
Learning: Applies to {middleware.ts,src/middleware.ts} : Implement middleware for route-level authentication
Learnt from: wobsoriano
PR: clerk/javascript#6123
File: packages/nextjs/src/server/__tests__/getAuthDataFromRequest.test.ts:63-75
Timestamp: 2025-06-16T01:27:54.563Z
Learning: In packages/nextjs/src/server/data/getAuthDataFromRequest.ts, the tokenType behavior on mismatch is intentionally different between array and single acceptsToken values: when acceptsToken is an array and the token type doesn't match any in the array, tokenType returns null; when acceptsToken is a single value and the token type doesn't match, tokenType returns the requested single value. This design aligns with developer intent and provides a more ergonomic API for common use cases.
Learnt from: LauraBeatris
PR: clerk/javascript#6117
File: packages/clerk-js/src/ui/components/SessionTasks/index.tsx:64-83
Timestamp: 2025-06-18T16:33:36.764Z
Learning: In SessionTasks component at packages/clerk-js/src/ui/components/SessionTasks/index.tsx, the useEffect that checks for pending tasks should only run on mount (not react to currentTask/status changes) to handle browser back navigation edge cases without interfering with normal task completion flow managed by nextTask().
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/nextjs.mdc:0-0
Timestamp: 2025-06-30T10:31:43.578Z
Learning: Applies to pages/**/*.{js,ts,jsx,tsx} : Implement ISR (Incremental Static Regeneration) with revalidate option in Pages Router
packages/backend/src/tokens/request.ts (1)
Learnt from: wobsoriano
PR: clerk/javascript#6123
File: packages/nextjs/src/server/__tests__/getAuthDataFromRequest.test.ts:63-75
Timestamp: 2025-06-16T01:27:54.563Z
Learning: In packages/nextjs/src/server/data/getAuthDataFromRequest.ts, the tokenType behavior on mismatch is intentionally different between array and single acceptsToken values: when acceptsToken is an array and the token type doesn't match any in the array, tokenType returns null; when acceptsToken is a single value and the token type doesn't match, tokenType returns the requested single value. This design aligns with developer intent and provides a more ergonomic API for common use cases.
packages/nextjs/src/server/clerkMiddleware.ts (5)
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/nextjs.mdc:0-0
Timestamp: 2025-06-30T10:31:43.578Z
Learning: Applies to app/**/*.tsx : Use redirect function for server-side redirects in Server Components
Learnt from: LauraBeatris
PR: clerk/javascript#6117
File: packages/clerk-js/src/ui/components/SessionTasks/index.tsx:64-83
Timestamp: 2025-06-18T16:33:36.764Z
Learning: In SessionTasks component at packages/clerk-js/src/ui/components/SessionTasks/index.tsx, the useEffect that checks for pending tasks should only run on mount (not react to currentTask/status changes) to handle browser back navigation edge cases without interfering with normal task completion flow managed by nextTask().
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/nextjs.mdc:0-0
Timestamp: 2025-06-30T10:31:43.578Z
Learning: Applies to pages/**/*.{js,ts,jsx,tsx} : Implement ISR (Incremental Static Regeneration) with revalidate option in Pages Router
Learnt from: wobsoriano
PR: clerk/javascript#6123
File: packages/nextjs/src/server/__tests__/getAuthDataFromRequest.test.ts:63-75
Timestamp: 2025-06-16T01:27:54.563Z
Learning: In packages/nextjs/src/server/data/getAuthDataFromRequest.ts, the tokenType behavior on mismatch is intentionally different between array and single acceptsToken values: when acceptsToken is an array and the token type doesn't match any in the array, tokenType returns null; when acceptsToken is a single value and the token type doesn't match, tokenType returns the requested single value. This design aligns with developer intent and provides a more ergonomic API for common use cases.
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/nextjs.mdc:0-0
Timestamp: 2025-06-30T10:31:43.578Z
Learning: Applies to {middleware.ts,src/middleware.ts} : Implement middleware for route-level authentication
🧬 Code Graph Analysis (1)
packages/backend/src/tokens/request.ts (1)
packages/backend/src/tokens/authStatus.ts (2)
  • AuthErrorReason (105-121)
  • AuthErrorReason (123-123)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (2)
packages/backend/src/tokens/request.ts (1)

458-484: LGTM: Clean refactoring improves code readability.

The removal of the intermediate variable isRequestEligibleForMultiDomainSync and directly inlining the condition makes the code more straightforward while preserving the exact same logic. This refactoring aligns well with the broader satellite domain handling improvements in the PR.

packages/nextjs/src/server/clerkMiddleware.ts (1)

205-224: Enhanced satellite domain detection improves debugging.

The addition of satellite domain detection with logging is well-implemented and will help with debugging authentication flows. The logic correctly identifies unauthenticated requests on satellite domains and provides useful debug information.

Comment on lines +225 to +226
const redirectToSignIn = createMiddlewareRedirectToSignIn(clerkRequest, requestState);
const redirectToSignUp = createMiddlewareRedirectToSignUp(clerkRequest, requestState);
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify function signature changes across the codebase.

The function signatures for createMiddlewareRedirectToSignIn and createMiddlewareRedirectToSignUp have been updated to accept a requestState parameter. Ensure all callers of these functions have been updated accordingly.


🏁 Script executed:

#!/bin/bash
# Description: Search for any remaining calls to these functions that might not have been updated with the new signature.

# Search for function calls that might still use the old signature
rg -A 3 "createMiddlewareRedirectToSignIn|createMiddlewareRedirectToSignUp" --type ts --type tsx

Length of output: 126


🏁 Script executed:

#!/bin/bash
# Search for all calls to the redirect functions in .ts and .tsx files
rg -n "createMiddlewareRedirectToSignIn|createMiddlewareRedirectToSignUp" -g '*.ts' -g '*.tsx'

Length of output: 787


Update Astro middleware to use the new redirect signatures

The Astro middleware still invokes createMiddlewareRedirectToSignIn with only the old single‐argument signature. It must be updated to pass the new requestState parameter (and likewise for createMiddlewareRedirectToSignUp if used).

• packages/astro/src/server/clerk-middleware.ts:

  • Line 99: change
    const redirectToSignIn = createMiddlewareRedirectToSignIn(clerkRequest);
    to
    const redirectToSignIn = createMiddlewareRedirectToSignIn(clerkRequest, requestState);
  • (If present) update any createMiddlewareRedirectToSignUp(clerkRequest) calls in this file to also include requestState.
🤖 Prompt for AI Agents
In packages/astro/src/server/clerk-middleware.ts around line 99, update the call
to createMiddlewareRedirectToSignIn to include the second argument requestState,
changing it from createMiddlewareRedirectToSignIn(clerkRequest) to
createMiddlewareRedirectToSignIn(clerkRequest, requestState). Also, if there are
any calls to createMiddlewareRedirectToSignUp with only clerkRequest as an
argument, update those to include requestState as the second argument as well.

Comment on lines 384 to 422
const createMiddlewareRedirectToSignIn = (
clerkRequest: ClerkRequest,
requestState: RequestState,
): ClerkMiddlewareSessionAuthObject['redirectToSignIn'] => {
return (opts = {}) => {
const url = clerkRequest.clerkUrl.toString();
redirectToSignInError(url, opts.returnBackUrl);
const returnBackUrl = opts.returnBackUrl === null ? null : (opts.returnBackUrl || url).toString();

// For satellite domains, use the satellite domain sync flow instead of standard redirects
// This ensures proper cross-domain redirect handling similar to automatic satellite sync
if (requestState.isSatellite && requestState.signInUrl && returnBackUrl !== null) {
const redirectURL = new URL(requestState.signInUrl);
redirectURL.searchParams.set('redirect_url', returnBackUrl);
redirectToSignInError(redirectURL.toString(), returnBackUrl);
} else {
redirectToSignInError(url, returnBackUrl);
}
};
};

const createMiddlewareRedirectToSignUp = (
clerkRequest: ClerkRequest,
requestState: RequestState,
): ClerkMiddlewareSessionAuthObject['redirectToSignUp'] => {
return (opts = {}) => {
const url = clerkRequest.clerkUrl.toString();
redirectToSignUpError(url, opts.returnBackUrl);
const returnBackUrl = opts.returnBackUrl === null ? null : (opts.returnBackUrl || url).toString();

// For satellite domains, use the satellite domain sync flow instead of standard redirects
// This ensures proper cross-domain redirect handling similar to automatic satellite sync
if (requestState.isSatellite && requestState.signUpUrl && returnBackUrl !== null) {
const redirectURL = new URL(requestState.signUpUrl);
redirectURL.searchParams.set('redirect_url', returnBackUrl);
redirectToSignUpError(redirectURL.toString(), returnBackUrl);
} else {
redirectToSignUpError(url, returnBackUrl);
}
};
};
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Satellite domain redirect logic enhances cross-domain authentication flow.

The updated redirect functions correctly implement satellite domain sync flow by adding a redirect_url query parameter when redirecting from satellite domains. This ensures users return to their intended destination after authentication.

However, consider adding validation for the redirect_url parameter to prevent potential open redirect vulnerabilities.


🌐 Web query:

What are the security best practices for validating redirect URLs to prevent open redirect attacks in authentication flows?

💡 Result:

To prevent open redirect attacks in authentication flows, validating redirect URLs properly is crucial. Here are the best security practices for validating these URLs:

  1. Use a Whitelist of Allowed URLs or Domains
    Maintain a strict list of allowed redirect URLs or base domains. Only redirect to URLs that exactly match or reside within these trusted domains.

  2. Avoid Open Redirect Parameters Without Validation
    Never directly use user-supplied URLs for redirection without validation. Validate that the URL parameter strictly conforms to an allowed list or set of rules.

  3. Canonicalize and Normalize URLs
    Before validation, canonicalize URLs to resolve relative paths, remove encoding tricks (like escaped characters), and normalize the URL to prevent bypass using variations.

  4. Check URL Scheme and Host
    Ensure the URLs use safe schemes (e.g., only https or your valid schemes). Reject or sanitize URLs with suspicious schemes such as javascript:, data:, or file:.

  5. Use Relative Paths Instead of Full URLs Whenever Possible
    Prefer using relative paths within your domain for redirects. This avoids cross-domain redirection risks.

  6. Limit Redirects to Internal Paths
    Redirect only to internal paths or safe subdomains owned by your service. For external redirects, consider additional verification mechanisms or user approval.

  7. Use URL Parsing Libraries
    Use well-tested URL parsing libraries rather than regex or string operations to analyze URLs.

  8. Log and Monitor Redirects
    Log every redirect request and monitor for abnormal or suspicious redirect attempts.

  9. Fail Securely
    When validation fails, redirect users to a safe default location (such as your homepage or error page) instead of echoing back the original input.

  10. Implement Security Headers
    Use security headers like Content-Security-Policy and X-Content-Type-Options to further reduce risks from malicious redirects.

By implementing these best practices, you can significantly reduce the risk of open redirect vulnerabilities in your authentication flows.


Add strict validation for redirect_url to prevent open redirects

The current satellite-domain logic appends the user-supplied returnBackUrl directly into the redirect_url query parameter, which could be exploited for open-redirect attacks. Introduce URL validation before using it in both redirect functions.

• File: packages/nextjs/src/server/clerkMiddleware.ts (createMiddlewareRedirectToSignIn & createMiddlewareRedirectToSignUp, lines 384–422)

  • Canonicalize and parse returnBackUrl with a URL-parsing library.
  • Enforce allowed schemes (e.g., only https:).
  • Check host against a whitelist of trusted domains or restrict to internal paths.
  • Fall back to a safe default URL (e.g., home or sign-in page) if validation fails.

Implement these steps to ensure only legitimate URLs are used for redirection.

🤖 Prompt for AI Agents
In packages/nextjs/src/server/clerkMiddleware.ts between lines 384 and 422, the
redirect functions createMiddlewareRedirectToSignIn and
createMiddlewareRedirectToSignUp currently use the user-supplied returnBackUrl
directly in the redirect_url query parameter, risking open redirect
vulnerabilities. To fix this, parse and canonicalize returnBackUrl using a URL
parser, validate that its scheme is https, and verify its host against a
whitelist of trusted domains or restrict it to internal paths. If validation
fails, replace returnBackUrl with a safe default URL such as the home or sign-in
page URL before appending it to the redirect URL. This ensures only legitimate
URLs are used for redirection and prevents open redirect attacks.

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 69ba85b and dc8a887.

📒 Files selected for processing (1)
  • packages/astro/src/server/clerk-middleware.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
`**/*.{js,jsx,ts,tsx}`: All code must pass ESLint checks with the project's conf...

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Use Prettier for consistent code formatting
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
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Validate all inputs and sanitize outputs
Implement proper logging with different levels

📄 Source: CodeRabbit Inference Engine (.cursor/rules/development.mdc)

List of files the instruction was applied to:

  • packages/astro/src/server/clerk-middleware.ts
`packages/**/*.ts`: TypeScript is required for all packages

packages/**/*.ts: TypeScript is required for all packages

📄 Source: CodeRabbit Inference Engine (.cursor/rules/development.mdc)

List of files the instruction was applied to:

  • packages/astro/src/server/clerk-middleware.ts
`packages/**/*.{ts,tsx,d.ts}`: Packages should export TypeScript types alongside runtime code

packages/**/*.{ts,tsx,d.ts}: Packages should export TypeScript types alongside runtime code

📄 Source: CodeRabbit Inference Engine (.cursor/rules/development.mdc)

List of files the instruction was applied to:

  • packages/astro/src/server/clerk-middleware.ts
`**/*.{ts,tsx}`: Use proper TypeScript error types

**/*.{ts,tsx}: Use proper TypeScript error types

📄 Source: CodeRabbit Inference Engine (.cursor/rules/development.mdc)

List of files the instruction was applied to:

  • packages/astro/src/server/clerk-middleware.ts
`**/*.{ts,tsx}`: Always define explicit return types for functions, especially p...

**/*.{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
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
Document public functions and APIs with JSDoc-style comments including @param, @returns, @throws, and @example
Define custom error classes for domain-specific errors
Use the Result pattern for error handling instead of throwing exceptions
Use optional chaining and nullish coalescing for safe property access
Let TypeScript infer types when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use readonly arrays and objects for immutability
Use immutable update patterns (spread, etc.) for objects and arrays
Use lazy loading for large types
Prefer unknown over any for performance
Use type-only imports: import type { ... }
Use branded types for domain safety
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints in TypeScript generics
No unused type parameters in generics
Proper use of utility types instead of manual type construction
Type-only imports where possible for performance
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

📄 Source: CodeRabbit Inference Engine (.cursor/rules/typescript.mdc)

List of files the instruction was applied to:

  • packages/astro/src/server/clerk-middleware.ts
🧠 Learnings (2)
📓 Common learnings
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/nextjs.mdc:0-0
Timestamp: 2025-06-30T10:31:43.578Z
Learning: Applies to app/**/*.tsx : Use redirect function for server-side redirects in Server Components
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/nextjs.mdc:0-0
Timestamp: 2025-06-30T10:31:43.578Z
Learning: Applies to {middleware.ts,src/middleware.ts} : Implement middleware for route-level authentication
Learnt from: wobsoriano
PR: clerk/javascript#6123
File: packages/nextjs/src/server/__tests__/getAuthDataFromRequest.test.ts:63-75
Timestamp: 2025-06-16T01:27:54.563Z
Learning: In packages/nextjs/src/server/data/getAuthDataFromRequest.ts, the tokenType behavior on mismatch is intentionally different between array and single acceptsToken values: when acceptsToken is an array and the token type doesn't match any in the array, tokenType returns null; when acceptsToken is a single value and the token type doesn't match, tokenType returns the requested single value. This design aligns with developer intent and provides a more ergonomic API for common use cases.
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/nextjs.mdc:0-0
Timestamp: 2025-06-30T10:31:43.578Z
Learning: Applies to pages/**/*.{js,ts,jsx,tsx} : Implement ISR (Incremental Static Regeneration) with revalidate option in Pages Router
packages/astro/src/server/clerk-middleware.ts (3)
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/nextjs.mdc:0-0
Timestamp: 2025-06-30T10:31:43.578Z
Learning: Applies to {middleware.ts,src/middleware.ts} : Implement middleware for route-level authentication
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/nextjs.mdc:0-0
Timestamp: 2025-06-30T10:31:43.578Z
Learning: Applies to app/**/*.tsx : Use redirect function for server-side redirects in Server Components
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/nextjs.mdc:0-0
Timestamp: 2025-06-30T10:31:43.578Z
Learning: Applies to {middleware.ts,src/middleware.ts} : Place middleware.ts in project root or src directory
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)

Copy link

pkg-pr-new bot commented Jul 1, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 660e1a7

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

Successfully merging this pull request may close these issues.

2 participants