From 1827b5d5e2a58567d4bf7bed092693666f91c9c7 Mon Sep 17 00:00:00 2001 From: Jackson Tian Date: Thu, 7 Jan 2016 15:01:54 +0800 Subject: [PATCH] buffer: introduce Buffer.encode() method Buffer constructor has too much behaviour. it is usual to convert string to Buffer in the form of new Buffer(str). If don't check type of first argument, new Buffer(number) can lead Buffer vulnerability. For example: - https://github.com/websockets/ws/releases/tag/1.0.1 - https://github.com/qiniu/nodejs-sdk.v6/issues/123 Introduce Buffer.encode() method to be explicit abort encoding. --- doc/api/buffer.markdown | 19 +++++++++++++++++++ lib/buffer.js | 7 +++++++ 2 files changed, 26 insertions(+) diff --git a/doc/api/buffer.markdown b/doc/api/buffer.markdown index 090a3eef51acbd..93e4baceffd984 100644 --- a/doc/api/buffer.markdown +++ b/doc/api/buffer.markdown @@ -290,6 +290,25 @@ Example: build a single Buffer from a list of three Buffers: // // 42 +### Class Method: Buffer.encode(str[, encoding]) + +* `str` {String} string to encode. +* `encoding` {String} encoding to use, Optional. +* Return: Buffer + +Encoding a string with more safely. + + const str = '100'; + const number = 100; + const buf1 = new Buffer(str); // allocate 3 bytes + const buf2 = new Buffer(number); // allocate 100 bytes + + const value = ? // when value is come from outside + + const buf3 = new Buffer(value); // wtf? + + const buf4 = Buffer.encode(value); // allocate bytes safely + ### Class Method: Buffer.isBuffer(obj) * `obj` Object diff --git a/lib/buffer.js b/lib/buffer.js index 00be048d4a6e0b..a8d9bc1c452d34 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -195,6 +195,13 @@ Buffer.compare = function compare(a, b) { return binding.compare(a, b); }; +Buffer.encode = function(str, encoding) { + // convert string safely + if (typeof str !== 'string') { + str = '' + str; + } + return new Buffer(str, encoding); +}; Buffer.isEncoding = function(encoding) { var loweredCase = false;