Skip to content

fix(backend): Consider proxyUrl in determining frontendApi URL #6120

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 5 commits into
base: main
Choose a base branch
from

Conversation

jacekradko
Copy link
Member

@jacekradko jacekradko commented Jun 13, 2025

Description

Adding more comprehensive logic to ensure that we consider the proxy_url when creating the frontendApi url.

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 normalization for handshake redirects to prevent duplicate slashes and ensure correct handling of proxy URLs and frontend API formats.
  • Tests

    • Added extensive test coverage for handshake URL construction, including edge cases with proxy URLs, query parameters, environment-specific behaviors, and parameter inclusion.
  • Refactor

    • Updated internal logic for constructing handshake URLs to use more reliable URL handling and normalization methods.
    • Adjusted internal validation to compare tokens against the original API URL for improved accuracy.
    • Enhanced handling of publishable key parsing to preserve the original API URL separately from proxy overrides.

@jacekradko jacekradko requested review from aeliox, wobsoriano and a team as code owners June 13, 2025 20:37
Copy link

vercel bot commented Jun 13, 2025

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

Name Status Preview Comments Updated (UTC)
clerk-js-sandbox ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 14, 2025 1:38am

Copy link
Contributor

coderabbitai bot commented Jun 13, 2025

Warning

Rate limit exceeded

@jacekradko has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 1 minutes and 10 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between bc66f6d and 4b8f3d4.

📒 Files selected for processing (1)
  • packages/backend/src/tokens/__tests__/handshake.test.ts (4 hunks)
📝 Walkthrough
## Walkthrough

This change refactors the handshake URL construction logic to use the `URL` constructor with normalized base URLs, updates token issuer validation to reference the original frontend API, and significantly expands test coverage for handshake URL edge cases and query parameter handling. No exported API signatures are altered.

## Changes

| Files/Groups                                                                 | Change Summary                                                                                                      |
|-------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------|
| packages/backend/src/tokens/handshake.ts                                      | Refactored handshake URL construction to use the `URL` constructor with normalized base URLs.                       |
| packages/backend/src/tokens/authenticateContext.ts                            | Added `originalFrontendApi` property; updated token validation to use original frontend API; reordered interface fields. |
| packages/backend/src/tokens/__tests__/handshake.test.ts                       | Added extensive new tests for handshake URL construction edge cases, query parameters, and environment-specific logic. |

## Possibly related PRs

- clerk/javascript#6119: Introduced initial proxy URL usage in `buildRedirectToHandshake` and added basic proxy URL handling tests, which are directly expanded upon in this PR.

## Suggested reviewers

- wobsoriano
- aeliox
- brkalow
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 docstrings to generate docstrings for this 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

pkg-pr-new bot commented Jun 13, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 4b8f3d4

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (4)
packages/backend/src/tokens/handshake.ts (1)

138-146: Nice defensive URL normalisation – tiny readability nit

Re-assigning baseUrl in-place works, but creating a new const trimmedBaseUrl would keep the variable immutable and make the intent clearer:

- let baseUrl = this.authenticateContext.frontendApi.startsWith('http')
-   ? this.authenticateContext.frontendApi
-   : `https://${this.authenticateContext.frontendApi}`;
-
- baseUrl = baseUrl.replace(/\/+$/, '') + '/';
+ const trimmedBaseUrl =
+   (this.authenticateContext.frontendApi.startsWith('http')
+     ? this.authenticateContext.frontendApi
+     : `https://${this.authenticateContext.frontendApi}`)
+     .replace(/\/+$/, '') + '/';

No functional difference, just marginally easier to scan.

packages/backend/src/tokens/authenticateContext.ts (1)

49-54: Empty-string default for originalFrontendApi hides bad configuration

If parsing the publishable key were ever to fail (e.g. malformed env var in CI), originalFrontendApi would remain the default empty string and silently make every issuer comparison fail.
Consider initialising it as undefined and asserting shortly after parsePublishableKey succeeds, so mis-configurations surface immediately.

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

405-408: Remove non-null assertions to satisfy ESLint and keep tests strict-mode safe

- expect(() => new URL(location!)).not.toThrow();
- const url = new URL(location!);
+ expect(location).not.toBeNull();
+ const url = new URL(location as string);

Same pattern applies further down (lines 587-588).
The explicit runtime check removes the need for the ! operator and silences @typescript-eslint/no-non-null-assertion.

Also applies to: 582-588

🧰 Tools
🪛 ESLint

[error] 406-406: Forbidden non-null assertion.

(@typescript-eslint/no-non-null-assertion)


[error] 408-408: Forbidden non-null assertion.

(@typescript-eslint/no-non-null-assertion)


423-427: Hard-coding API version couples tests to implementation detail

expect(url.searchParams.get('__clerk_api_version')).toBe('2025-04-10');

When the backend bumps SUPPORTED_BAPI_VERSION, this test will fail noisily. Import the constant instead:

-import { constants } from '../../constants';
+import { constants, SUPPORTED_BAPI_VERSION } from '../../constants';-expect(url.searchParams.get('__clerk_api_version')).toBe('2025-04-10');
+expect(url.searchParams.get('__clerk_api_version')).toBe(SUPPORTED_BAPI_VERSION);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4319257 and 7701f84.

📒 Files selected for processing (3)
  • packages/backend/src/tokens/__tests__/handshake.test.ts (4 hunks)
  • packages/backend/src/tokens/authenticateContext.ts (4 hunks)
  • packages/backend/src/tokens/handshake.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/backend/src/tokens/authenticateContext.ts (1)
packages/shared/src/keys.ts (1)
  • parsePublishableKey (36-71)
🪛 ESLint
packages/backend/src/tokens/__tests__/handshake.test.ts

[error] 406-406: Forbidden non-null assertion.

(@typescript-eslint/no-non-null-assertion)


[error] 408-408: Forbidden non-null assertion.

(@typescript-eslint/no-non-null-assertion)


[error] 587-587: Forbidden non-null assertion.

(@typescript-eslint/no-non-null-assertion)

⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
packages/backend/src/tokens/authenticateContext.ts (1)

170-180: parsePublishableKey may still return null; guard before dereference

fatal: true currently throws on an invalid key, but future refactors could relax that. A minimal guard keeps this method future-proof:

- const originalPk = parsePublishableKey(this.publishableKey, { … });
- this.originalFrontendApi = originalPk.frontendApi;
+ const originalPk = parsePublishableKey(this.publishableKey, { … });
+ if (!originalPk) {
+   throw new Error('Failed to parse publishable key');
+ }
+ this.originalFrontendApi = originalPk.frontendApi;

Comment on lines 283 to 286
const tokenIssuer = data.payload.iss.replace(/https?:\/\//gi, '');
return this.frontendApi === tokenIssuer;
// Use original frontend API for token validation since tokens are issued by the actual Clerk API, not proxy
return this.originalFrontendApi === tokenIssuer;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Issuer check ignores trailing slashes / “/v1” – could produce false negatives

iss values coming from Clerk tokens usually end with /v1/ (or at least /v1).
Comparing the raw host against originalFrontendApi therefore fails for perfectly valid tokens behind a proxy.

- const tokenIssuer = data.payload.iss.replace(/https?:\/\//gi, '');
- return this.originalFrontendApi === tokenIssuer;
+ const tokenIssuer = data.payload.iss
+   .replace(/https?:\/\//gi, '')
+   .replace(/\/+v1\/?$/, '')   // strip “/v1” if present
+   .replace(/\/+$/, '');       // strip trailing slash(es)
+
+ return this.originalFrontendApi.replace(/\/+$/, '') === tokenIssuer;

This keeps proxy handling intact while tolerating the canonical Clerk issuer suffix.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const tokenIssuer = data.payload.iss.replace(/https?:\/\//gi, '');
return this.frontendApi === tokenIssuer;
// Use original frontend API for token validation since tokens are issued by the actual Clerk API, not proxy
return this.originalFrontendApi === tokenIssuer;
}
const tokenIssuer = data.payload.iss
.replace(/https?:\/\//gi, '')
.replace(/\/+v1\/?$/, '') // strip “/v1” if present
.replace(/\/+$/, ''); // strip trailing slash(es)
// Use original frontend API for token validation since tokens are issued by the actual Clerk API, not proxy
return this.originalFrontendApi
.replace(/\/+$/, '') === tokenIssuer;
}
🤖 Prompt for AI Agents
In packages/backend/src/tokens/authenticateContext.ts around lines 283 to 286,
the issuer check removes the protocol but does not account for trailing slashes
or path segments like "/v1", causing valid tokens to fail validation. Modify the
code to normalize the issuer by removing the protocol and any trailing slashes
or path suffixes such as "/v1" before comparing it to originalFrontendApi,
ensuring the comparison tolerates the canonical Clerk issuer suffix while
preserving proxy handling.

Copy link

changeset-bot bot commented Jun 14, 2025

🦋 Changeset detected

Latest commit: d144b7b

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

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

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

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link
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

🔭 Outside diff range comments (1)
packages/backend/src/tokens/__tests__/handshake.test.ts (1)

180-210: 🛠️ Refactor suggestion

Mutating the shared handshakeService risks hidden state leakage

Several tests (should use proxy URL when available, handle proxy URL …) mutate mockAuthenticateContext after handshakeService has been instantiated.
If HandshakeService caches any derived values (e.g. a pre-sanitised base URL) in its constructor, later mutations will not be reflected and these tests may give false positives.

A safer pattern is to rebuild the service inside each test that tweaks context-level URL fields:

- mockAuthenticateContext.proxyUrl = 'https://my-proxy.example.com';
- mockAuthenticateContext.frontendApi = 'https://my-proxy.example.com';
- const headers = handshakeService.buildRedirectToHandshake('test-reason');
+ const ctx = { ...mockAuthenticateContext,
+              proxyUrl: 'https://my-proxy.example.com',
+              frontendApi: 'https://my-proxy.example.com' } as AuthenticateContext;
+ const service = new HandshakeService(ctx, mockOptions, mockOrganizationMatcher);
+ const headers = service.buildRedirectToHandshake('test-reason');

Repeat for the other proxy-URL variations.
Prevents brittle tests and documents the real construction path.

Also applies to: 212-240, 242-268

🧹 Nitpick comments (3)
.changeset/common-beers-read.md (1)

5-5: Clarify changelog wording

Consider switching to the imperative mood and matching the actual casing used in the codebase:

-Add logic to ensure that we consider the proxy_url when creating the frontendApi url.
+Consider the `proxyUrl` when constructing the `frontendApi` URL.

Keeps the changeset short, action-oriented, and consistent with variable names.

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

548-566: Unit test duplicates production regex rather than exercising public behaviour

trailingSlashTestCases validates input.replace(/\/+$/, ''), which is a literal copy of the implementation detail you’re trying to guard. If the production code ever changes (e.g. switches to URL parsing), this test will still pass while the real behaviour breaks.

Prefer exercising the public API (buildRedirectToHandshake) with those inputs, or extract the slash-trimming helper and test that helper directly.


389-416: Reduce duplication with a helper to assert handshake URL invariants

The frontendApiFormats loop re-implements the same location retrieval and assertion sequence found in many earlier tests. Extracting a small helper, e.g. assertValidHandshake(headers, reason?), would:

  1. Eliminate copy-paste.
  2. Make future changes (e.g. new required query param) a one-liner.
  3. Shorten the test file by ~40 lines.

Pure readability win, no change in coverage.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7701f84 and bc66f6d.

📒 Files selected for processing (2)
  • .changeset/common-beers-read.md (1 hunks)
  • packages/backend/src/tokens/__tests__/handshake.test.ts (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)

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.

2 participants