Skip to content
Open
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
37 changes: 35 additions & 2 deletions lib/s3-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,31 @@
// Require AWS SDK
const { S3Client, GetObjectCommand } = require('@aws-sdk/client-s3'); // AWS SDK
const { getSignedUrl } = require('@aws-sdk/s3-request-presigner');
const { streamToBuffer } = require('./utils');
const MAX_BUFFERED_OBJECT_SIZE = parseInt(
process.env.AWS_S3_MAX_BUFFERED_OBJECT_SIZE ||
process.env.AWS_S3_MAX_OBJECT_SIZE ||
10485760,
10
);
Comment on lines +11 to +16
Comment on lines +11 to +16

const streamToBufferWithLimit = async (stream, maxSize) => {
const chunks = [];
let size = 0;

for await (const chunk of stream) {
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
size += buffer.length;

if (size > maxSize) {
if (typeof stream.destroy === 'function') stream.destroy();
throw new Error('S3 object exceeds maximum allowed buffered size');
}

chunks.push(buffer);
}

return Buffer.concat(chunks);
};
Comment on lines +18 to +35

// Export
exports.client = new S3Client();
Expand All @@ -21,9 +45,18 @@ exports.getObject = (params) => {

if (!res.Body) return res;

if (
Number.isFinite(MAX_BUFFERED_OBJECT_SIZE) &&
MAX_BUFFERED_OBJECT_SIZE > 0 &&
typeof res.ContentLength === 'number' &&
res.ContentLength > MAX_BUFFERED_OBJECT_SIZE
) {
throw new Error('S3 object exceeds maximum allowed buffered size');
Comment on lines 28 to +54
}

return {
...res,
Body: await streamToBuffer(res.Body),
Body: await streamToBufferWithLimit(res.Body, MAX_BUFFERED_OBJECT_SIZE),
};
},
};
Expand Down
Loading