Add CORS support and improve error responses in fetch handler
This commit is contained in:
parent
dc05d722ea
commit
1e909f963f
15
src/index.js
15
src/index.js
@ -14,15 +14,24 @@ export default {
|
||||
async fetch(request, env, ctx) {
|
||||
const url = new URL(request.url);
|
||||
const rawKey = url.pathname.slice(1); // remove leading slash
|
||||
const corsHeaders = {
|
||||
'Access-Control-Allow-Origin': request.headers.get('Origin'),
|
||||
'Access-Control-Allow-Methods': '*',
|
||||
'Access-Control-Allow-Headers': '*',
|
||||
};
|
||||
|
||||
if (url.hostname !== '127.0.0.1' && url.protocol === 'http:') {
|
||||
return new Response(null, { status: 301, headers: {
|
||||
Location: url.toString().replace(/^(http:)/, 'https:')
|
||||
}});
|
||||
}
|
||||
|
||||
if (request.method === 'OPTIONS') {
|
||||
return new Response(null, { status: 200, headers: corsHeaders });
|
||||
}
|
||||
|
||||
if (!rawKey) {
|
||||
return new Response('Invalid key', { status: 400 });
|
||||
return new Response('Invalid key', { status: 400, headers: corsHeaders });
|
||||
}
|
||||
|
||||
let endpoint, accessKeyId, secretAccessKey, region, bucket;
|
||||
@ -57,7 +66,7 @@ export default {
|
||||
const pat = /^[a-zA-Z0-9]{1,64}$/;
|
||||
if (!expId || !participantId || expId.includes('/') || !participantId.match(pat)) {
|
||||
// prevent path traversal
|
||||
return new Response('Invalid expId or participantId', { status: 400 });
|
||||
return new Response('Invalid parameters', { status: 400, headers: corsHeaders });
|
||||
}
|
||||
|
||||
const client = new S3Client({
|
||||
@ -73,6 +82,6 @@ export default {
|
||||
Key: `${expId}/${participantId}/${rawKey}`
|
||||
});
|
||||
const signedUrl = await getSignedUrl(client, command, { expiresIn: 12*60*60 });
|
||||
return new Response(signedUrl);
|
||||
return new Response(signedUrl, { headers: corsHeaders });
|
||||
},
|
||||
};
|
Loading…
Reference in New Issue
Block a user