Skip to content

Commit

Permalink
Add additional test for image extension when returning a 400 based on…
Browse files Browse the repository at this point in the history
… Content-Type
  • Loading branch information
nring committed Apr 27, 2021
1 parent fff183c commit 4526dfe
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion packages/next/next-server/server/image-optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,15 @@ const PNG = 'image/png'
const JPEG = 'image/jpeg'
const GIF = 'image/gif'
const SVG = 'image/svg+xml'
const FILE_TYPES = [
/* avif, */ 'webp',
'png',
'jpg',
'jpeg',
'gif',
'svg',
'ico',
]
const CACHE_VERSION = 2
const MODERN_TYPES = [/* AVIF, */ WEBP]
const ANIMATABLE_TYPES = [WEBP, PNG, GIF]
Expand Down Expand Up @@ -266,7 +275,10 @@ export async function imageOptimizer(
}

// If upstream type is not a valid image type, return 400 error.
if (!upstreamType.startsWith('image/')) {
if (
!upstreamType.startsWith('image/') &&
!endsWithImageExtension(href, FILE_TYPES)
) {
res.statusCode = 400
res.end("The requested resource isn't a valid image.")
return { finished: true }
Expand Down Expand Up @@ -379,6 +391,12 @@ function sendResponse(
res.end(buffer)
}

function endsWithImageExtension(href: string, fileTypes: string[]): boolean {
return fileTypes.some((fileType) => {
return href.toLowerCase().endsWith(fileType)
})
}

function getSupportedMimeType(options: string[], accept = ''): string {
const mimeType = mediaType(accept, options)
return accept.includes(mimeType) ? mimeType : ''
Expand Down

1 comment on commit 4526dfe

@bumpah
Copy link

@bumpah bumpah commented on 4526dfe Apr 29, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this looks good, tho I would probably check that filename ends with .${fileType} to exclude any filename without extension and the actual filename ends with string same as one of the values in FILE_TYPES -array.

Other than that, great work I think.

Please sign in to comment.