Skip to content
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

fix(middleware): consider localhost variations #31603

Merged
merged 7 commits into from
Nov 19, 2021
Merged
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
21 changes: 15 additions & 6 deletions packages/next/server/web/next-url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ interface Options {
trailingSlash?: boolean
}

const REGEX_LOCALHOST_HOSTNAME =
/(?!^https?:\/\/)(127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}|::1)/

export class NextURL extends URL {
private _basePath: string
private _locale?: {
Expand All @@ -33,11 +36,12 @@ export class NextURL extends URL {
private _options: Options
private _url: URL

constructor(url: string, options: Options = {}) {
super(formatRelative(url))
constructor(input: string, options: Options = {}) {
const url = createWHATWGURL(input)
super(url)
this._options = options
this._basePath = ''
this._url = formatRelative(url)
this._url = url
this.analyzeUrl()
}

Expand Down Expand Up @@ -163,7 +167,7 @@ export class NextURL extends URL {
}

set href(url: string) {
this._url = formatRelative(url)
this._url = createWHATWGURL(url)
this.analyzeUrl()
}

Expand Down Expand Up @@ -228,8 +232,13 @@ export class NextURL extends URL {
}
}

function formatRelative(url: string) {
return url.startsWith('/')
function createWHATWGURL(url: string) {
url = url.replace(REGEX_LOCALHOST_HOSTNAME, 'localhost')
return isRelativeURL(url)
? new URL(url.replace(/^\/+/, '/'), new URL('https://localhost'))
: new URL(url)
}

function isRelativeURL(url: string) {
return url.startsWith('/')
}
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,15 @@ it('parses and formats the default locale', () => {
expect(url.locale).toEqual('fr')
expect(url.toString()).toEqual('/root/fr/bar')
})

it('consider 127.0.0.1 and variations as localhost', () => {
const httpUrl = new NextURL('http://localhost:3000/hello')
expect(new NextURL('http://127.0.0.1:3000/hello')).toStrictEqual(httpUrl)
expect(new NextURL('http://127.0.1.0:3000/hello')).toStrictEqual(httpUrl)
expect(new NextURL('http://::1:3000/hello')).toStrictEqual(httpUrl)

const httpsUrl = new NextURL('https://localhost:3000/hello')
expect(new NextURL('https://127.0.0.1:3000/hello')).toStrictEqual(httpsUrl)
expect(new NextURL('https://127.0.1.0:3000/hello')).toStrictEqual(httpsUrl)
expect(new NextURL('https://::1:3000/hello')).toStrictEqual(httpsUrl)
})