Skip to content

Commit

Permalink
fix: Handle malformed pathnames in middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
amannn committed Sep 19, 2024
1 parent b0f8024 commit 9de566c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
7 changes: 7 additions & 0 deletions packages/next-intl/src/middleware/middleware.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1075,6 +1075,13 @@ describe('prefix-based routing', () => {
);
});

it('handles malformed urls', () => {
middleware(createMockRequest('/a%'));
middleware(createMockRequest('/en/a%'));
middleware(createMockRequest('/en/about/a%'));
expect(MockedNextResponse.next).toHaveBeenCalledTimes(3);
});

describe('base path', () => {
it('redirects non-prefixed requests for the default locale', () => {
middleware(withBasePath(createMockRequest('/')));
Expand Down
11 changes: 9 additions & 2 deletions packages/next-intl/src/middleware/middleware.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,15 @@ export default function createMiddleware<
};

return function middleware(request: NextRequest) {
// Resolve potential foreign symbols (e.g. /ja/%E7%B4%84 → /ja/約))
const unsafeExternalPathname = decodeURI(request.nextUrl.pathname);
let unsafeExternalPathname: string;
try {
// Resolve potential foreign symbols (e.g. /ja/%E7%B4%84 → /ja/約))
unsafeExternalPathname = decodeURI(request.nextUrl.pathname);
} catch (e) {
// In case an invalid pathname is encountered, forward
// it to Next.js which in turn responds with a 400
return NextResponse.next();
}

// Sanitize malicious URIs to prevent open redirect attacks due to
// decodeURI doesn't escape encoded backslashes ('%5C' & '%5c')
Expand Down

0 comments on commit 9de566c

Please sign in to comment.