Skip to content

Commit

Permalink
Fixes escaping port number in absolute urls (#1028)
Browse files Browse the repository at this point in the history
* fix(coercePath): escape the port number

* fix(coercePath): remove the "g" modifier from port/protocol regexp

Co-authored-by: Artem Zakharchenko <kettanaito@gmail.com>
  • Loading branch information
tdeekens and kettanaito committed Dec 14, 2021
1 parent d8bd81a commit 2e7ecd8
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 11 deletions.
35 changes: 25 additions & 10 deletions src/utils/matching/matchRequestUrl.test.ts
Expand Up @@ -64,6 +64,31 @@ describe('matchRequestUrl', () => {
})

describe('coercePath', () => {
test('escapes the colon in protocol', () => {
expect(coercePath('https://example.com')).toEqual('https\\://example.com')
expect(coercePath('https://example.com/:userId')).toEqual(
'https\\://example.com/:userId',
)
expect(coercePath('http://localhost:3000')).toEqual(
'http\\://localhost\\:3000',
)
})

test('escapes the colon before the port number', () => {
expect(coercePath('localhost:8080')).toEqual('localhost\\:8080')
expect(coercePath('http://127.0.0.1:8080')).toEqual(
'http\\://127.0.0.1\\:8080',
)
expect(coercePath('https://example.com:1234')).toEqual(
'https\\://example.com\\:1234',
)

expect(coercePath('localhost:8080/:5678')).toEqual('localhost\\:8080/:5678')
expect(coercePath('https://example.com:8080/:5678')).toEqual(
'https\\://example.com\\:8080/:5678',
)
})

test('replaces wildcard with an unnnamed capturing group', () => {
expect(coercePath('*')).toEqual('(.*)')
expect(coercePath('**')).toEqual('(.*)')
Expand All @@ -86,14 +111,4 @@ describe('coercePath', () => {
'/foo/:first/bar/:second*/(.*)',
)
})

test('escapes the semicolon in protocol', () => {
expect(coercePath('https://example.com')).toEqual('https\\://example.com')
expect(coercePath('https://example.com/:userId')).toEqual(
'https\\://example.com/:userId',
)
expect(coercePath('http://localhost:3000')).toEqual(
'http\\://localhost:3000',
)
})
})
7 changes: 6 additions & 1 deletion src/utils/matching/matchRequestUrl.ts
Expand Up @@ -36,12 +36,17 @@ export function coercePath(path: string): string {
: `${parameterName}${expression}`
},
)
/**
* Escape the port so that "path-to-regexp" can match
* absolute URLs including port numbers.
*/
.replace(/([^\/])(:)(?=\d+)/, '$1\\$2')
/**
* Escape the protocol so that "path-to-regexp" could match
* absolute URL.
* @see https://github.com/pillarjs/path-to-regexp/issues/259
*/
.replace(/^([^\/]+)(:)(?=\/\/)/g, '$1\\$2')
.replace(/^([^\/]+)(:)(?=\/\/)/, '$1\\$2')
)
}

Expand Down

0 comments on commit 2e7ecd8

Please sign in to comment.