Unverified Commit 4ab41efd authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add handling for repeated slashes (#27738)

This adds handling for repeated forward/back slashes in Next.js, when these slashes are detected in a request to Next.js we will automatically remove the additional slashes redirecting with a 308 status code which prevents duplicate content when being crawled by search engines. 

Fixes: https://github.com/vercel/next.js/issues/13011
Fixes: https://github.com/vercel/next.js/issues/23772
Closes: https://github.com/vercel/next.js/pull/15171
Closes: https://github.com/vercel/next.js/pull/25745
parent 61586eda
......@@ -188,12 +188,7 @@ class Container extends React.Component<{
// the asPath unexpectedly e.g. adding basePath when
// it wasn't originally present
page !== '/404' &&
!(
page === '/_error' &&
hydrateProps &&
hydrateProps.pageProps &&
hydrateProps.pageProps.statusCode === 404
) &&
page !== '/_error' &&
(isFallback ||
(data.nextExport &&
(isDynamicRoute(router.pathname) ||
......
......@@ -46,6 +46,7 @@ import {
isResSent,
NextApiRequest,
NextApiResponse,
normalizeRepeatedSlashes,
} from '../shared/lib/utils'
import {
apiResolver,
......@@ -313,6 +314,18 @@ export default class Server {
res: ServerResponse,
parsedUrl?: UrlWithParsedQuery
): Promise<void> {
const urlParts = (req.url || '').split('?')
const urlNoQuery = urlParts[0]
if (urlNoQuery?.match(/(\\|\/\/)/)) {
const cleanUrl = normalizeRepeatedSlashes(req.url!)
res.setHeader('Location', cleanUrl)
res.setHeader('Refresh', `0;url=${cleanUrl}`)
res.statusCode = 308
res.end(cleanUrl)
return
}
setLazyProp({ req: req as any }, 'cookies', getCookieParser(req.headers))
// Parse url if parsedUrl not provided
......@@ -811,7 +824,13 @@ export default class Server {
parsedDestination.search = stringifyQuery(req, query)
const updatedDestination = formatUrl(parsedDestination)
let updatedDestination = formatUrl(parsedDestination)
if (updatedDestination.startsWith('/')) {
updatedDestination = normalizeRepeatedSlashes(
updatedDestination
)
}
res.setHeader('Location', updatedDestination)
res.statusCode = getRedirectStatus(redirectRoute as Redirect)
......@@ -822,7 +841,7 @@ export default class Server {
res.setHeader('Refresh', `0;url=${updatedDestination}`)
}
res.end()
res.end(updatedDestination)
return {
finished: true,
}
......@@ -1519,6 +1538,10 @@ export default class Server {
redirect.destination = `${basePath}${redirect.destination}`
}
if (redirect.destination.startsWith('/')) {
redirect.destination = normalizeRepeatedSlashes(redirect.destination)
}
if (statusCode === PERMANENT_REDIRECT_STATUS) {
res.setHeader('Refresh', `0;url=${redirect.destination}`)
}
......
......@@ -23,6 +23,7 @@ import {
getLocationOrigin,
getURL,
loadGetInitialProps,
normalizeRepeatedSlashes,
NextPageContext,
ST,
NEXT_DATA,
......@@ -274,8 +275,29 @@ export function resolveHref(
): string {
// we use a dummy base url for relative urls
let base: URL
const urlAsString =
typeof href === 'string' ? href : formatWithValidation(href)
let urlAsString = typeof href === 'string' ? href : formatWithValidation(href)
// repeated slashes and backslashes in the URL are considered
// invalid and will never match a Next.js page/file
const urlProtoMatch = urlAsString.match(/^[a-zA-Z]{1,}:\/\//)
const urlAsStringNoProto = urlProtoMatch
? urlAsString.substr(urlProtoMatch[0].length)
: urlAsString
const urlParts = urlAsStringNoProto.split('?')
if ((urlParts[0] || '').match(/(\/\/|\\)/)) {
console.error(
`Invalid href passed to next/router: ${urlAsString}, repeated forward-slashes (//) or backslashes \\ are not valid in the href`
)
const normalizedUrl = normalizeRepeatedSlashes(urlAsStringNoProto)
urlAsString = (urlProtoMatch ? urlProtoMatch[0] : '') + normalizedUrl
}
// Return because it cannot be routed by the Next.js router
if (!isLocalURL(urlAsString)) {
return (resolveAs ? [urlAsString] : urlAsString) as string
}
try {
base = new URL(
......@@ -286,10 +308,6 @@ export function resolveHref(
// fallback to / for invalid asPath values e.g. //
base = new URL('/', 'http://n')
}
// Return because it cannot be routed by the Next.js router
if (!isLocalURL(urlAsString)) {
return (resolveAs ? [urlAsString] : urlAsString) as string
}
try {
const finalUrl = new URL(urlAsString, base)
finalUrl.pathname = normalizePathTrailingSlash(finalUrl.pathname)
......
......@@ -328,6 +328,20 @@ export function isResSent(res: ServerResponse) {
return res.finished || res.headersSent
}
export function normalizeRepeatedSlashes(url: string) {
const urlParts = url.split('?')
const urlNoQuery = urlParts[0]
return (
urlNoQuery
// first we replace any non-encoded backslashes with forward
// then normalize repeated forward slashes
.replace(/\\/g, '/')
.replace(/\/\/+/g, '/') +
(urlParts[1] ? `?${urlParts.slice(1).join('?')}` : '')
)
}
export async function loadGetInitialProps<
C extends BaseContext,
IP = {},
......
......@@ -15,7 +15,6 @@ import {
getPageFileFromPagesManifest,
getPagesManifest,
updatePagesManifest,
check,
} from 'next-test-utils'
jest.setTimeout(1000 * 60 * 2)
......@@ -245,11 +244,6 @@ describe('500 Page Support', () => {
const browser = await webdriver(appPort, '/err?hello=world')
const initialTitle = await browser.eval('document.title')
await check(async () => {
const query = await browser.eval(`window.next.router.query`)
return query.hello === 'world' ? 'success' : 'not yet'
}, 'success')
const currentTitle = await browser.eval('document.title')
expect(initialTitle).toBe(currentTitle)
......
/* eslint-env jest */
/* eslint-disable jest/no-identical-title */
import url from 'url'
import fs from 'fs-extra'
import { join } from 'path'
import {
......@@ -22,19 +22,32 @@ let app
const expectStatus = async (path) => {
const containRegex = /(This page could not be found|Bad Request)/
// test base mount point `public/`
const res = await fetchViaHTTP(appPort, path)
expect(res.status === 400 || res.status === 404).toBe(true)
expect(await res.text()).toMatch(containRegex)
const checkRes = async (res) => {
if (res.status === 308) {
const redirectDest = res.headers.get('location')
const parsedUrl = url.parse(redirectDest, true)
expect(parsedUrl.hostname).toBe('localhost')
} else {
expect(res.status === 400 || res.status === 404).toBe(true)
expect(await res.text()).toMatch(containRegex)
}
}
const res = await fetchViaHTTP(appPort, path, undefined, {
redirect: 'manual',
})
await checkRes(res)
// test `/_next` mount point
const res2 = await fetchViaHTTP(appPort, `/_next/${path}`)
expect(res2.status === 400 || res2.status === 404).toBe(true)
expect(await res2.text()).toMatch(containRegex)
const res2 = await fetchViaHTTP(appPort, `/_next/${path}`, undefined, {
redirect: 'manual',
})
await checkRes(res2)
// test `/static` mount point
const res3 = await fetchViaHTTP(appPort, `/static/${path}`)
expect(res3.status === 400 || res3.status === 404).toBe(true)
expect(await res3.text()).toMatch(containRegex)
const res3 = await fetchViaHTTP(appPort, `/static/${path}`, undefined, {
redirect: 'manual',
})
await checkRes(res3)
}
const runTests = () => {
......
module.exports = {
redirects() {
return [
{
source: '/redirect-forward-slashes',
destination: '/test//google.com',
permanent: false,
},
{
source: '/redirect-back-slashes',
destination: '/test\\/google.com',
permanent: false,
},
]
},
}
if (typeof window !== 'undefined') {
window.errorLoad = true
}
export default function Page() {
return <p id="error">custom error</p>
}
export default function Another() {
return <p id="another">another page</p>
}
export default function Index(props) {
return <p id="index">index page</p>
}
import Link from 'next/link'
if (typeof window !== 'undefined') {
window.caughtErrors = []
const origError = window.console.error
window.console.error = function (...args) {
window.caughtErrors.push(args.join(' '))
return origError(...args)
}
}
export default function Invalid() {
return (
<>
<p id="invalid">invalid page</p>
<Link href="/another" as="//google.com">
<a id="page-with-as-slashes">to /another as //google.com</a>
</Link>
<br />
<Link href="//google.com">
<a id="href-with-slashes">to //google.com</a>
</Link>
<br />
<Link href="//google.com?hello=1">
<a id="href-with-slashes-query">to //google.com?hello=1</a>
</Link>
<br />
<Link href="//google.com#hello">
<a id="href-with-slashes-hash">to //google.com#hello</a>
</Link>
<br />
<Link href="/another" as="\/\/google.com">
<a id="page-with-as-backslashes">to /another as \\/\\/google.com</a>
</Link>
<br />
<Link href="\/\/google.com">
<a id="href-with-backslashes">to \\/\\/google.com</a>
</Link>
<br />
<Link href="\/\/google.com?hello=1">
<a id="href-with-backslashes-query">to \\/\\/google.com?hello=1</a>
</Link>
<br />
<Link href="\/\/google.com#hello">
<a id="href-with-backslashes-hash">to \\/\\/google.com#hello</a>
</Link>
<br />
</>
)
}
/* eslint-env jest */
import { join } from 'path'
import fs from 'fs-extra'
import url from 'url'
import webdriver from 'next-webdriver'
import escapeRegex from 'escape-string-regexp'
import {
nextBuild,
findPort,
nextStart,
killApp,
waitFor,
nextExport,
stopApp,
startStaticServer,
launchApp,
fetchViaHTTP,
check,
} from 'next-test-utils'
jest.setTimeout(60 * 1000)
const appDir = join(__dirname, '../app')
const outdir = join(appDir, 'out')
let appPort
let app
function runTests({ isDev = false, isExport = false, isPages404 = false }) {
let notFoundContent = 'custom error'
// let badRequestContent = 'custom error'
if (isPages404) {
// badRequestContent = 'Bad Request'
notFoundContent = 'custom 404'
}
if (isExport && isPages404) {
notFoundContent = 'custom 404'
// badRequestContent = 'custom 404'
}
const didNotReload = async (browser) => {
for (let i = 0; i < 4; i++) {
await waitFor(500)
const result = await browser.eval('window.errorLoad')
if (result !== true) {
throw new Error(
`did not find window.errorLoad, current url: ${await browser.url()}`
)
}
if (isDev) break
}
}
if (!isExport) {
it('should normalize repeated slashes in redirects correctly', async () => {
const res = await fetchViaHTTP(
appPort,
'/redirect-forward-slashes',
undefined,
{
redirect: 'manual',
}
)
expect(res.status).toBe(307)
const parsedUrl = url.parse(res.headers.get('location'), true)
expect(parsedUrl.hostname).toBe('localhost')
expect(parsedUrl.pathname).toBe('/test/google.com')
expect(parsedUrl.query).toEqual({})
expect(await res.text()).toBe('/test/google.com')
const res2 = await fetchViaHTTP(
appPort,
'/redirect-back-slashes',
undefined,
{
redirect: 'manual',
}
)
expect(res2.status).toBe(307)
const parsedUrl2 = url.parse(res2.headers.get('location'), true)
expect(parsedUrl2.hostname).toBe('localhost')
expect(parsedUrl2.pathname).toBe('/test/google.com')
expect(parsedUrl2.query).toEqual({})
expect(await res2.text()).toBe('/test/google.com')
})
}
it('should handle double slashes correctly', async () => {
if (!isExport) {
const res = await fetchViaHTTP(appPort, '//google.com', undefined, {
redirect: 'manual',
})
expect(res.status).toBe(308)
const parsedUrl = url.parse(res.headers.get('location'), true)
expect(parsedUrl.pathname).toBe('/google.com')
expect(parsedUrl.hostname).toBe('localhost')
expect(parsedUrl.query).toEqual({})
}
const browser = await webdriver(appPort, '//google.com')
await didNotReload(browser)
expect(await browser.eval('window.location.pathname')).toBe(
isExport ? '//google.com' : '/google.com'
)
expect(await browser.eval('window.location.search')).toBe('')
expect(await browser.eval('window.location.hash')).toBe('')
expect(await browser.eval('document.documentElement.innerHTML')).toContain(
notFoundContent
)
})
it('should handle double slashes correctly with query', async () => {
if (!isExport) {
const res = await fetchViaHTTP(
appPort,
'//google.com',
{ h: '1' },
{
redirect: 'manual',
}
)
expect(res.status).toBe(308)
const parsedUrl = url.parse(res.headers.get('location'), true)
expect(parsedUrl.pathname).toBe('/google.com')
expect(parsedUrl.hostname).toBe('localhost')
expect(parsedUrl.query).toEqual({ h: '1' })
}
const browser = await webdriver(appPort, '//google.com?h=1')
await didNotReload(browser)
expect(await browser.eval('window.location.pathname')).toBe(
isExport ? '//google.com' : '/google.com'
)
expect(await browser.eval('window.location.search')).toBe('?h=1')
expect(await browser.eval('window.location.hash')).toBe('')
expect(await browser.eval('document.documentElement.innerHTML')).toContain(
notFoundContent
)
})
it('should handle double slashes correctly with hash', async () => {
if (!isExport) {
const res = await fetchViaHTTP(appPort, '//google.com', undefined, {
redirect: 'manual',
})
expect(res.status).toBe(308)
const parsedUrl = url.parse(res.headers.get('location'), true)
expect(parsedUrl.pathname).toBe('/google.com')
expect(parsedUrl.hostname).toBe('localhost')
expect(parsedUrl.query).toEqual({})
}
const browser = await webdriver(appPort, '//google.com#hello')
await didNotReload(browser)
expect(await browser.eval('window.location.pathname')).toBe(
isExport ? '//google.com' : '/google.com'
)
expect(await browser.eval('window.location.hash')).toBe('#hello')
expect(await browser.eval('window.location.search')).toBe('')
expect(await browser.eval('document.documentElement.innerHTML')).toContain(
notFoundContent
)
})
it('should handle double slashes correctly with encoded', async () => {
if (!isExport) {
const res = await fetchViaHTTP(appPort, '/%2Fgoogle.com', undefined, {
redirect: 'manual',
})
expect(res.status).toBe(404)
expect(await res.text()).toContain(notFoundContent)
}
const browser = await webdriver(appPort, '/%2Fgoogle.com')
await didNotReload(browser)
expect(await browser.eval('window.location.pathname')).toBe(
'/%2Fgoogle.com'
)
expect(await browser.eval('document.documentElement.innerHTML')).toContain(
notFoundContent
)
})
it('should handle double slashes correctly with encoded and query', async () => {
if (!isExport) {
const res = await fetchViaHTTP(
appPort,
'/%2Fgoogle.com',
{ hello: '1' },
{
redirect: 'manual',
}
)
expect(res.status).toBe(404)
expect(await res.text()).toContain(notFoundContent)
}
const browser = await webdriver(appPort, '/%2Fgoogle.com?hello=1')
await didNotReload(browser)
expect(await browser.eval('window.location.pathname')).toBe(
'/%2Fgoogle.com'
)
expect(await browser.eval('window.location.search')).toBe('?hello=1')
expect(await browser.eval('document.documentElement.innerHTML')).toContain(
notFoundContent
)
})
it('should handle double slashes correctly with encoded and hash', async () => {
if (!isExport) {
const res = await fetchViaHTTP(appPort, '/%2Fgoogle.com', undefined, {
redirect: 'manual',
})
expect(res.status).toBe(404)
expect(await res.text()).toContain(notFoundContent)
}
const browser = await webdriver(appPort, '/%2Fgoogle.com#hello')
await didNotReload(browser)
expect(await browser.eval('window.location.pathname')).toBe(
'/%2Fgoogle.com'
)
expect(await browser.eval('window.location.hash')).toBe('#hello')
expect(await browser.eval('document.documentElement.innerHTML')).toContain(
notFoundContent
)
})
it('should handle backslashes correctly', async () => {
if (!isExport) {
const res = await fetchViaHTTP(appPort, '/\\google.com', undefined, {
redirect: 'manual',
})
expect(res.status).toBe(308)
const parsedUrl = url.parse(res.headers.get('location'), true)
expect(parsedUrl.pathname).toBe('/google.com')
expect(parsedUrl.hostname).toBe('localhost')
expect(parsedUrl.query).toEqual({})
expect(await res.text()).toBe('/google.com')
}
const browser = await webdriver(appPort, '/\\google.com')
await didNotReload(browser)
expect(await browser.eval('window.location.pathname')).toBe(
isExport ? '//google.com' : '/google.com'
)
expect(await browser.eval('window.location.hash')).toBe('')
expect(await browser.eval('window.location.search')).toBe('')
expect(await browser.eval('document.documentElement.innerHTML')).toContain(
notFoundContent
)
})
it('should handle mixed backslashes/forward slashes correctly', async () => {
if (!isExport) {
const res = await fetchViaHTTP(appPort, '/\\/google.com', undefined, {
redirect: 'manual',
})
expect(res.status).toBe(308)
const parsedUrl = url.parse(res.headers.get('location'), true)
expect(parsedUrl.pathname).toBe(isExport ? '//google.com' : '/google.com')
expect(parsedUrl.hostname).toBe('localhost')
expect(parsedUrl.query).toEqual({})
expect(await res.text()).toBe('/google.com')
}
const browser = await webdriver(appPort, '/\\/google.com#hello')
await didNotReload(browser)
expect(await browser.eval('window.location.pathname')).toBe(
isExport ? '///google.com' : '/google.com'
)
expect(await browser.eval('window.location.hash')).toBe('#hello')
expect(await browser.eval('window.location.search')).toBe('')
expect(await browser.eval('document.documentElement.innerHTML')).toContain(
notFoundContent
)
})
it('should handle slashes in next/link correctly', async () => {
const browser = await webdriver(
appPort,
`/invalid${isExport ? '.html' : ''}`
)
const invalidHrefs = [
'//google.com',
'//google.com?hello=1',
'//google.com#hello',
'\\/\\/google.com',
'\\/\\/google.com?hello=1',
'\\/\\/google.com#hello',
]
for (const href of invalidHrefs) {
await check(
() =>
browser.eval(
'window.caughtErrors.map(err => typeof err !== "string" ? err.message : err).join(", ")'
),
new RegExp(escapeRegex(`Invalid href passed to next/router: ${href}`))
)
}
})
it('should handle slashes in router push correctly', async () => {
const browser = await webdriver(appPort, '/')
for (const item of [
{
page: '/another',
href: '/another',
as: '//google.com',
pathname: '/google.com',
},
{
page: isPages404 ? '/404' : '/_error',
href: '//google.com',
pathname: '/google.com',
},
{
page: isPages404 ? '/404' : '/_error',
href: '//google.com?hello=1',
pathname: '/google.com',
search: '?hello=1',
},
{
page: isPages404 ? '/404' : '/_error',
href: '//google.com#hello',
pathname: '/google.com',
hash: '#hello',
},
]) {
await browser.eval(
`window.next.router.push("${item.href}"${
item.as ? `, "${item.as}"` : ''
})`
)
expect(await browser.eval('window.location.pathname')).toBe(item.pathname)
expect(await browser.eval('window.location.search')).toBe(
item.search || ''
)
expect(await browser.eval('window.location.hash')).toBe(item.hash || '')
expect(await browser.eval('window.next.router.pathname')).toBe(item.page)
}
})
it('should have no error from encoded slashes in router push', async () => {
const browser = await webdriver(appPort, '/')
for (const item of [
{
page: '/another',
href: '/another',
as: '/%2Fgoogle.com',
shouldHardNav: false,
},
{
page: isPages404 ? '/404' : '/_error',
href: '/%2Fgoogle.com',
},
{
page: isPages404 ? '/404' : '/_error',
href: '/%2F%2Fgoogle.com?hello=1',
pathname: '/%2F%2Fgoogle.com',
search: '?hello=1',
},
{
page: isPages404 ? '/404' : '/_error',
href: '/%5C%5C%2Fgoogle.com#hello',
pathname: '/%5C%5C%2Fgoogle.com',
hash: '#hello',
},
]) {
await browser.eval(`(function() {
window.beforeNav = 1
window.next.router.push("${item.href}"${
item.as ? `, "${item.as}"` : ''
})
})()`)
await check(
() => browser.eval('window.location.pathname'),
item.pathname || item.as || item.href
)
expect(await browser.eval('window.location.search')).toBe(
item.search || ''
)
expect(await browser.eval('window.location.hash')).toBe(item.hash || '')
expect(await browser.eval('window.next.router.pathname')).toBe(item.page)
expect(await browser.eval('window.next.router.asPath')).toBe(
item.as || item.href
)
expect(await browser.eval('window.beforeNav')).toBe(
item.shouldHardNav !== false ? null : 1
)
}
})
}
describe('404 handling', () => {
let nextOpts = {}
beforeAll(async () => {
const hasLocalNext = await fs.exists(join(appDir, 'node_modules/next'))
if (hasLocalNext) {
nextOpts = {
nextBin: join(appDir, 'node_modules/next/dist/bin/next'),
cwd: appDir,
}
console.log('Using next options', nextOpts)
}
})
const devStartAndExport = (isPages404) => {
describe('next dev', () => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort, nextOpts)
})
afterAll(() => killApp(app))
runTests({
isPages404,
isDev: true,
})
})
describe('production', () => {
beforeAll(async () => {
await nextBuild(appDir, [], nextOpts)
})
describe('next start', () => {
beforeAll(async () => {
appPort = await findPort()
app = await nextStart(appDir, appPort, nextOpts)
})
afterAll(() => killApp(app))
runTests({
isPages404,
})
})
describe('next export', () => {
beforeAll(async () => {
await nextExport(appDir, { outdir }, nextOpts)
app = await startStaticServer(outdir, join(outdir, '404.html'))
appPort = app.address().port
})
afterAll(() => {
stopApp(app)
})
runTests({
isPages404,
isExport: true,
})
})
})
}
describe('custom _error', () => {
devStartAndExport(false)
})
describe('pages/404', () => {
const pagesErr = join(appDir, 'pages/_error.js')
const pages404 = join(appDir, 'pages/404.js')
beforeAll(async () => {
await fs.move(pagesErr, pagesErr + '.bak')
await fs.writeFile(
pages404,
`
if (typeof window !== 'undefined') {
window.errorLoad = true
}
export default function Page() {
return <p id='error'>custom 404</p>
}
`
)
await nextBuild(appDir, [], nextOpts)
})
afterAll(async () => {
await fs.move(pagesErr + '.bak', pagesErr)
await fs.remove(pages404)
})
devStartAndExport(true)
})
})
import spawn from 'cross-spawn'
import express from 'express'
import { existsSync, readFileSync, unlinkSync, writeFileSync } from 'fs'
import {
existsSync,
readFileSync,
unlinkSync,
writeFileSync,
createReadStream,
} from 'fs'
import { writeFile } from 'fs-extra'
import getPort from 'get-port'
import http from 'http'
......@@ -363,11 +369,17 @@ export function waitFor(millis) {
return new Promise((resolve) => setTimeout(resolve, millis))
}
export async function startStaticServer(dir) {
export async function startStaticServer(dir, notFoundFile) {
const app = express()
const server = http.createServer(app)
app.use(express.static(dir))
if (notFoundFile) {
app.use((req, res) => {
createReadStream(notFoundFile).pipe(res)
})
}
await promiseCall(server, 'listen')
return server
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment