Skip to content

Commit

Permalink
Fix 400 when upstream content-type: octet-stream
Browse files Browse the repository at this point in the history
  • Loading branch information
styfle committed Jun 28, 2021
1 parent 6a5279a commit 582ad80
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
10 changes: 5 additions & 5 deletions packages/next/next-server/server/image-optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -434,27 +434,27 @@ function parseCacheControl(str: string | null): Map<string, string> {
* https://en.wikipedia.org/wiki/List_of_file_signatures
*/
function detectContentType(buffer: Buffer) {
if ([0xff, 0xd8, 0xff].every((i, b) => buffer[i] === b)) {
if ([0xff, 0xd8, 0xff].every((b, i) => buffer[i] === b)) {
return JPEG
}
if (
[0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a].every(
(i, b) => buffer[i] === b
(b, i) => buffer[i] === b
)
) {
return PNG
}
if ([0x47, 0x49, 0x46, 0x38].every((i, b) => buffer[i] === b)) {
if ([0x47, 0x49, 0x46, 0x38].every((b, i) => buffer[i] === b)) {
return GIF
}
if (
[0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50].every(
(i, b) => buffer[i] === b
(b, i) => !b || buffer[i] === b
)
) {
return WEBP
}
if ([0x3c, 0x3f, 0x78, 0x6d, 0x6c].every((i, b) => buffer[i] === b)) {
if ([0x3c, 0x3f, 0x78, 0x6d, 0x6c].every((b, i) => buffer[i] === b)) {
return SVG
}
return null
Expand Down
26 changes: 25 additions & 1 deletion test/integration/image-optimizer/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,26 @@ function runTests({ w, isDev, domains }) {
expect(res.headers.get('etag')).toBeTruthy()
await expectWidth(res, w)
})

it('should automatically detect image type when content-type is octet-stream', async () => {
const url =
'https://image-optimization-test.vercel.app/png-as-octet-stream'
const resOrig = await fetch(url)
expect(resOrig.status).toBe(200)
expect(resOrig.headers.get('Content-Type')).toBe(
'application/octet-stream'
)
const query = { url, w, q: 80 }
const opts = { headers: { accept: 'image/webp' } }
const res = await fetchViaHTTP(appPort, '/_next/image', query, opts)
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toBe('image/webp')
expect(res.headers.get('cache-control')).toBe(
'public, max-age=0, must-revalidate'
)
expect(res.headers.get('etag')).toBeTruthy()
await expectWidth(res, w)
})
}

it('should fail when url has file protocol', async () => {
Expand Down Expand Up @@ -697,7 +717,11 @@ describe('Image Optimizer', () => {
})

// domains for testing
const domains = ['localhost', 'example.com']
const domains = [
'localhost',
'example.com',
'image-optimization-test.vercel.app',
]

describe('dev support w/o next.config.js', () => {
const size = 384 // defaults defined in server/config.ts
Expand Down

0 comments on commit 582ad80

Please sign in to comment.