Commit 25f810b5 authored by Zack Tanner's avatar Zack Tanner Committed by JJ Kasper

exclude images and static media from dev origin check (#77417)

Excludes `/_next/image` and `/_next/static/media` as they don't contain sensitive information and prevents complications loading them in cases where they are inlined in CSS, as they'll be requested with `sec-fetch-mode: no-cors`. 

x-ref: https://github.com/vercel/next.js/issues/77344
parent d9bcb833
...@@ -31,6 +31,25 @@ function warnOrBlockRequest( ...@@ -31,6 +31,25 @@ function warnOrBlockRequest(
return true return true
} }
function isInternalDevEndpoint(req: IncomingMessage): boolean {
if (!req.url) return false
try {
// TODO: We should standardize on a single prefix for this
const isMiddlewareRequest = req.url.includes('/__nextjs')
const isInternalAsset = req.url.includes('/_next')
// Static media requests are excluded, as they might be loaded via CSS and would fail
// CORS checks.
const isIgnoredRequest =
req.url.includes('/_next/image') ||
req.url.includes('/_next/static/media')
return !isIgnoredRequest && (isInternalAsset || isMiddlewareRequest)
} catch (err) {
return false
}
}
export const blockCrossSite = ( export const blockCrossSite = (
req: IncomingMessage, req: IncomingMessage,
res: ServerResponse | Duplex, res: ServerResponse | Duplex,
...@@ -51,8 +70,7 @@ export const blockCrossSite = ( ...@@ -51,8 +70,7 @@ export const blockCrossSite = (
} }
// only process internal URLs/middleware // only process internal URLs/middleware
// TODO: We should standardize on a single prefix for this if (!isInternalDevEndpoint(req)) {
if (!req.url?.includes('/_next') && !req.url?.includes('/__nextjs')) {
return false return false
} }
// block non-cors request from cross-site e.g. script tag on // block non-cors request from cross-site e.g. script tag on
......
...@@ -318,6 +318,37 @@ describe.each([['', '/docs']])( ...@@ -318,6 +318,37 @@ describe.each([['', '/docs']])(
server.close() server.close()
} }
}) })
it('should load images regardless of allowed origins', async () => {
const { server, port } = await createHostServer()
try {
const browser = await webdriver(`http://127.0.0.1:${port}`, '/about')
const imageSnippet = `(() => {
const statusEl = document.createElement('p')
statusEl.id = 'status'
document.querySelector('body').appendChild(statusEl)
const image = document.createElement('img')
image.src = "${next.url}/_next/image?url=%2Fimage.png&w=256&q=75"
document.querySelector('body').appendChild(image)
image.onload = () => {
statusEl.innerText = 'OK'
}
image.onerror = () => {
statusEl.innerText = 'Unauthorized'
}
})()`
await browser.eval(imageSnippet)
await retry(async () => {
expect(await browser.elementByCss('#status').text()).toBe('OK')
})
} finally {
server.close()
}
})
}) })
} }
) )
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