Skip to content

fix(react-router): fix regex handling for URLs containing newline characters #13643

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 2 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions contributors.yml
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,7 @@
- rtmann
- rtzll
- rubeonline
- rururux
- ryanflorence
- ryanhiebert
- saengmotmi
Expand Down
11 changes: 11 additions & 0 deletions packages/react-router/__tests__/matchPath-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,17 @@ describe("matchPath *", () => {
pathnameBase: "/users/foo*",
});
});

it("matches a URL with %0A (a newline character)", () => {
expect(matchPath("*", "/%0A")).toMatchObject({
pathname: "/%0A",
pathnameBase: "/",
})
expect(matchPath("*", "/new%0Aline")).toMatchObject({
pathname: "/new%0Aline",
pathnameBase: "/",
})
})
});

describe("matchPath warnings", () => {
Expand Down
5 changes: 5 additions & 0 deletions packages/react-router/__tests__/matchRoutes-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,11 @@ describe("matchRoutes", () => {
expect(pickPaths(routes, "/hometypo")).toEqual(["*"]);
});

it("matches root * routes for URLs containing %0A (a newline character)", () => {
expect(pickPaths(routes, "/%0A")).toEqual(["*"]);
expect(pickPaths(routes, "/new%0Aline")).toEqual(["*"]);
});

it("matches index routes with path correctly", () => {
expect(pickPaths(routes, "/withpath")).toEqual(["/withpath"]);
});
Expand Down
7 changes: 6 additions & 1 deletion packages/react-router/lib/router/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1255,6 +1255,9 @@ export function compilePath(
return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
}
);
// If the URL contains %0A (a newline character),
// the regular expression will not match correctly unless the s (single line) flag is set.
let regexpFlags = ["s"];

if (path.endsWith("*")) {
params.push({ paramName: "*" });
Expand All @@ -1278,7 +1281,9 @@ export function compilePath(
// Nothing to match for "" or "/"
}

let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i");
if (!caseSensitive) regexpFlags.push("i");

let matcher = new RegExp(regexpSource, regexpFlags.join(""));

return [matcher, params];
}
Expand Down