Skip to content
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
17 changes: 12 additions & 5 deletions plugin/src/helpers/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,18 @@ export const setupImageCdn = async ({
join(constants.INTERNAL_FUNCTIONS_SRC, '_ipx.ts'),
)

netlifyConfig.redirects.push({
from: '/_gatsby/image/*',
to: '/.netlify/builders/_ipx',
status: 200,
})
netlifyConfig.redirects.push(
{
from: '/_gatsby/image/*',
to: '/.netlify/builders/_ipx',
status: 200,
},
{
from: '/_gatsby/file/*',
to: '/.netlify/functions/_ipx',
status: 200,
},
)
}

export const deleteFunctions = async ({
Expand Down
42 changes: 41 additions & 1 deletion plugin/src/templates/ipx.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,47 @@
import { Buffer } from 'buffer'

import { Handler, HandlerResponse } from '@netlify/functions'
import { createIPXHandler } from '@netlify/ipx'

export const handler = createIPXHandler({
const ipxHandler = createIPXHandler({
propsEncoding: 'base64',
basePath: '/_gatsby/image/',
bypassDomainCheck: true,
})

// eslint-disable-next-line require-await
export const handler: Handler = async (event, ...rest) => {
const { pathname, host } = new URL(event.rawUrl)

const [, , type, encodedUrl] = pathname.split('/')

if (type === 'image') {
return ipxHandler(event, ...rest) as Promise<HandlerResponse>
}

try {
const urlString = Buffer.from(encodedUrl, 'base64').toString('utf8')
// Validate it by parsing it
const url = new URL(urlString)
if (url.host === host) {
return {
statusCode: 400,
body: 'File cannot be served from the same host as the original request',
}
}
console.log(`Redirecting to ${urlString}`)
return {
statusCode: 301,
headers: {
Location: url.toString(),
},
body: '',
}
} catch (error) {
console.error(error)
return {
statusCode: 400,
body: 'Invalid request',
}
}
}