Skip to content

fix(backend): validate token exchange resource components and sparse scopes - #10893

Draft
wyattjoh wants to merge 3 commits into
mainfrom
wyattjoh/repair-backend-d6-d2
Draft

wyattjoh wants to merge 3 commits into
mainfrom
wyattjoh/repair-backend-d6-d2

Conversation

@wyattjoh

Copy link
Copy Markdown
Contributor

Description

What: Reject malformed resource URI components and sparse or non-string scope entries in oauthApplications.__experimental_exchangeToken() before making a request.

Why: The client currently accepts raw brackets in resource paths and can serialize sparse scope arrays into invalid values such as read , forwarding requests that do not meet the token-exchange parameter grammar.

How:

  • Validate raw URI components before URL parsing while preserving valid resource strings, IPv6 hosts, query parameters, and the existing HTTPS/loopback policy. This enforces the absolute-URI requirement in RFC 8693 §2.1 and the component grammar in RFC 3986 §3.2 and §3.3.
  • Visit every scope position and reject missing or non-string entries rather than skipping holes or coercing values into tokens, preserving the scope grammar in RFC 6749 §3.3 and the existing invalid_request error contract.

Checklist

  • pnpm test runs as expected (backend Node and edge suites).
  • pnpm build runs as expected (backend and its dependencies).
  • (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:

@vercel

vercel Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
clerk-js-sandbox Ready Ready Preview Nov 20, 2026 5:10am UTC
mosaic-docs Ready Ready Preview Nov 20, 2026 5:10am UTC
swingset Ready Ready Preview Nov 20, 2026 5:10am UTC

Request Review

@changeset-bot

changeset-bot Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 2909af6

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/astro Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/hono Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/tanstack-react-start Patch
@clerk/testing Patch
@clerk/swingset 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

@coderabbitai

coderabbitai Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@pkg-pr-new

pkg-pr-new Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/electron

npm i https://pkg.pr.new/@clerk/electron@10893

@clerk/electron-passkeys

npm i https://pkg.pr.new/@clerk/electron-passkeys@10893

@clerk/eslint-plugin

npm i https://pkg.pr.new/@clerk/eslint-plugin@10893

@clerk/expo

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

@clerk/expo-biometrics

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

@clerk/expo-google-signin

npm i https://pkg.pr.new/@clerk/expo-google-signin@10893

@clerk/expo-native-components

npm i https://pkg.pr.new/@clerk/expo-native-components@10893

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/hono

npm i https://pkg.pr.new/@clerk/hono@10893

@clerk/localizations

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

@clerk/mosaic

npm i https://pkg.pr.new/@clerk/mosaic@10893

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/react

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

@clerk/react-router

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/ui

npm i https://pkg.pr.new/@clerk/ui@10893

@clerk/upgrade

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

@clerk/vue

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

commit: 2909af6

throw tokenExchangeRequestError(
'Each `scope` element must be a non-empty scope token without spaces, `"`, `\\`, or non-ASCII characters.',
);
for (const token of scope ?? []) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

for...of accepts any iterable, so a JavaScript caller passing scope: new Set(['read']) now passes this check. tokenExchangeBody then sees scope.length === undefined and omits scope entirely, so the exchange is sent asking for the authorization server's default scopes instead of read. Before this change, scope?.some(...) threw a TypeError for a Set, so the silent drop is new.

A plain string has a related problem: scope: 'read' passes here because each character is a valid token, and then fails in tokenExchangeBody with TypeError: params.scope.join is not a function rather than invalid_request. That mistake seems plausible because CreateOAuthApplicationParams.scopes in this file is a space-separated string.

Since this check exists to reject runtime values the types don't cover, please reject anything that isn't an array (Array.isArray(scope)) before the loop, and add a Set and a string case to the rejection tests.

~ 🤖

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in ee3bc70. assertValidTokenExchangeScope now returns early only for a missing scope and throws invalid_request for anything where Array.isArray(scope) is false, before it checks the elements (

function assertValidTokenExchangeScope(scope: string[] | undefined) {
if (scope == null) {
return;
}
if (!Array.isArray(scope)) {
throw tokenExchangeRequestError('`scope` must be an array of scope tokens.');
). A Set or a plain string now fails with an OAuthTokenExchangeError instead of being dropped or reaching join. This keeps the request's scope as the space-delimited token list from RFC 6749 §3.3. I added both cases to the rejection table (
['a Set instead of an array', new Set(['read']) as unknown as string[]],
['a string instead of an array', 'read' as unknown as string[]],
).


const rfc3986AbsoluteUriPattern =
/^[A-Za-z][A-Za-z0-9+.-]*:\/\/(?:[A-Za-z0-9\-._~:/?@!$&'()*+,;=[\]]|%[0-9A-Fa-f]{2})*$/;
/^[A-Za-z][A-Za-z0-9+.-]*:\/\/(?:(?:[A-Za-z0-9\-._~!$&'()*+,;=:]|%[0-9A-Fa-f]{2})*@)?(?:\[[0-9A-Fa-f:.]+\]|(?:[A-Za-z0-9\-._~!$&'()*+,;=]|%[0-9A-Fa-f]{2})*)(?::[0-9]*)?(?:\/(?:[A-Za-z0-9\-._~!$&'()*+,;=:@/]|%[0-9A-Fa-f]{2})*)?(?:\?(?:[A-Za-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9A-Fa-f]{2})*)?$/;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Optional hardening: the plain-http exception is decided on the WHATWG-normalized hostname, but resource is sent as written. The reg-name branch here accepts digits and percent-encoding, so http://2130706433/, http://0x7f.1/, and http://%6c%6fcalhost/ all pass as loopback (new URL normalizes them to 127.0.0.1 or localhost) and are sent over plain http in their raw form, which the authorization server won't read as a loopback host.

This predates the PR, but since the change is about keeping the raw string and the parsed URL in agreement, consider matching the loopback case against the raw host instead, so only a literal localhost, 127.0.0.1, or [::1] (case-insensitive) qualifies.

~ 🤖

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 2909af6. isAllowedResourceUrl now reads the host from the raw resource (rawResourceHost: the authority with any userinfo and port removed, lowercased) and allows plain http only when that host is literally localhost, 127.0.0.1, or [::1] and equals the WHATWG hostname (

function rawResourceHost(resource: string) {
const authority = resource.slice(resource.indexOf('//') + 2).split(/[/?]/, 1)[0];
return authority.slice(authority.lastIndexOf('@') + 1).replace(/:[0-9]*$/, '');
}
function isAllowedResourceUrl({ protocol, hostname }: URL, resource: string) {
const host = rawResourceHost(resource).toLowerCase();
return protocol === 'https:' || (protocol === 'http:' && loopbackHostnames.has(host) && host === hostname);
}
). http://2130706433/, http://0x7f.1/, and http://%6c%6fcalhost/ are now rejected, and HTTP://LOCALHOST:3000/api and http://user:pass@localhost/... still pass, since the host is case-insensitive per RFC 3986 §3.2.2. Tests:
['uses plain http for a decimal loopback address', 'http://2130706433/'],
['uses plain http for a shorthand hex loopback address', 'http://0x7f.1/'],
['uses plain http for a percent-encoded localhost', 'http://%6c%6fcalhost/'],
and #L567-L568. The changeset now mentions the narrower loopback rule.

This branch was successfully deployed

2 active deployments
Preview – swingset — 2909af6f Deployed Nov 20, 2026 by vercel[bot]
Preview – clerk-js-sandbox — 2909af6f Deployed Nov 20, 2026 by vercel[bot]
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