Skip to content

Commit

Permalink
fix: improve ArrayBuffer brand check in ensureBuffer (#429)
Browse files Browse the repository at this point in the history
`instanceof` is notoriously unreliable in JS, because it can
be fooled by prototype manipulation and breaks down entirely
for cross-realm brand checks.

Using `Object.prototype.toString` is generally a better choice
for this.

This also adds `SharedArrayBuffer` as an alternative, as both
should be treated the same under most circumstances.
  • Loading branch information
addaleax committed Apr 9, 2021
1 parent f60c404 commit 99722f6
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
6 changes: 5 additions & 1 deletion src/ensure_buffer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ export function ensureBuffer(potentialBuffer: Buffer | ArrayBufferView | ArrayBu
return Buffer.from(potentialBuffer.buffer);
}

if (potentialBuffer instanceof ArrayBuffer) {
if (
['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(
Object.prototype.toString.call(potentialBuffer)
)
) {
return Buffer.from(potentialBuffer);
}

Expand Down
31 changes: 30 additions & 1 deletion test/node/ensure_buffer_test.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* global SharedArrayBuffer */
'use strict';

const { Buffer } = require('buffer');
Expand All @@ -19,7 +20,7 @@ describe('ensureBuffer tests', function () {
expect(bufferOut).to.equal(bufferIn);
});

it('should wrap a UInt8Array with a buffer', function () {
it('should wrap a Uint8Array with a buffer', function () {
const arrayIn = Uint8Array.from([1, 2, 3]);
let bufferOut;

Expand All @@ -31,6 +32,34 @@ describe('ensureBuffer tests', function () {
expect(bufferOut.buffer).to.equal(arrayIn.buffer);
});

it('should wrap a ArrayBuffer with a buffer', function () {
const arrayBufferIn = Uint8Array.from([1, 2, 3]).buffer;
let bufferOut;

expect(function () {
bufferOut = ensureBuffer(arrayBufferIn);
}).to.not.throw(Error);

expect(bufferOut).to.be.an.instanceOf(Buffer);
expect(bufferOut.buffer).to.equal(arrayBufferIn);
});

it('should wrap a SharedArrayBuffer with a buffer', function () {
if (typeof SharedArrayBuffer === 'undefined') {
this.skip();
return;
}
const arrayBufferIn = new SharedArrayBuffer(3);
let bufferOut;

expect(function () {
bufferOut = ensureBuffer(arrayBufferIn);
}).to.not.throw(Error);

expect(bufferOut).to.be.an.instanceOf(Buffer);
expect(bufferOut.buffer).to.equal(arrayBufferIn);
});

[0, 12, -1, '', 'foo', null, undefined, ['list'], {}, /x/].forEach(function (item) {
it(`should throw if input is ${typeof item}: ${item}`, function () {
expect(function () {
Expand Down

0 comments on commit 99722f6

Please sign in to comment.