Skip to content

Commit c2fb75e

Browse files
committed
[Fix] validate that arrays contain valid byte values
1 parent 2cf2a20 commit c2fb75e

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

index.js

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,14 +51,28 @@ module.exports = function toBuffer(data, encoding) {
5151
return Buffer.from(data);
5252
}
5353

54+
var isArr = isArray(data);
55+
if (isArr) {
56+
for (var i = 0; i < data.length; i += 1) {
57+
var x = data[i];
58+
if (
59+
typeof x !== 'number'
60+
|| x < 0
61+
|| x > 255
62+
|| ~~x !== x // NaN and integer check
63+
) {
64+
throw new RangeError('Array items must be numbers in the range 0-255.');
65+
}
66+
}
67+
}
68+
5469
/*
5570
* Old Buffer polyfill on an engine that doesn't have TypedArray support
5671
* Also, this is from a different Buffer polyfill implementation then we have, as instanceof check failed
5772
* Convert to our current Buffer implementation
5873
*/
5974
if (
60-
isArray(data)
61-
|| (
75+
isArr || (
6276
Buffer.isBuffer(data)
6377
&& data.constructor
6478
&& typeof data.constructor.isBuffer === 'function'

test/index.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,15 @@ test('string + enc returns buffer', function (t) {
2424

2525
test('array returns buffer', function (t) {
2626
t.deepEqual(toBuffer([104, 105]), new Buffer('hi'));
27+
28+
forEach([-1, 256, NaN, 4.2, Infinity], function (nonByte) {
29+
t['throws'](
30+
function () { toBuffer([0, 42, nonByte]); },
31+
RangeError,
32+
nonByte + ': arrays with out-of-bounds byte values throw'
33+
);
34+
});
35+
2736
t.end();
2837
});
2938

0 commit comments

Comments
 (0)