Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
The bson npm package is a library that allows you to serialize and deserialize data in BSON format. BSON, short for Binary JSON, is a binary-encoded serialization of JSON-like documents. It is designed to be efficient in both storage space and scan-speed. The bson package is commonly used when working with MongoDB, as MongoDB uses BSON as its document storage format.
Serialization
This feature allows you to convert a JavaScript object into a BSON formatted buffer. This is useful for storing and transmitting data in a compact binary form.
{"const BSON = require('bson'); const bson = new BSON(); const doc = { hello: 'world' }; const data = bson.serialize(doc); console.log(data); // <Buffer 16 00 00 00 02 68 65 6c 6c 6f 00 06 00 00 00 77 6f 72 6c 64 00 00>"}
Deserialization
This feature allows you to convert BSON data back into a JavaScript object. This is useful when you need to read data that was stored or transmitted in BSON format.
{"const BSON = require('bson'); const bson = new BSON(); const data = Buffer.from('160000000268656c6c6f0006000000776f726c640000', 'hex'); const doc = bson.deserialize(data); console.log(doc); // { hello: 'world' }"}
msgpack5 is a package that implements the MessagePack serialization format. MessagePack is an efficient binary serialization format that is similar to BSON but is not tied to MongoDB. It aims to be more compact and faster than JSON.
protobufjs is a package that allows you to serialize and deserialize data using Google's Protocol Buffers. Protocol Buffers are similar to BSON in that they provide a way to encode structured data in an efficient binary format, but they require a predefined schema and are more focused on cross-language compatibility.
cbor is a package that implements the CBOR (Concise Binary Object Representation) data format. Like BSON, CBOR is a binary format that can serialize and deserialize JavaScript objects. However, CBOR is designed to be more compact and to have a wider range of data types than BSON.
BSON is short for "Binary JSON," and is the binary-encoded serialization of JSON-like documents. You can learn more about it in the specification.
Releases are created automatically and signed using the Node team's GPG key. This applies to the git tag as well as all release packages provided as part of a GitHub release. To verify the provided packages, download the key and import it using gpg:
gpg --import node-driver.asc
The GitHub release contains a detached signature file for the NPM package (named
bson-X.Y.Z.tgz.sig
).
The following command returns the link npm package.
npm view bson@vX.Y.Z dist.tarball
Using the result of the above command, a curl
command can return the official npm package for the release.
To verify the integrity of the downloaded package, run the following command:
gpg --verify bson-X.Y.Z.tgz.sig bson-X.Y.Z.tgz
[!Note] No verification is done when using npm to install the package. The contents of the Github tarball and npm's tarball are identical.
Think you've found a bug? Want to see a new feature in bson
? Please open a case in our issue management tool, JIRA:
Bug reports in JIRA for the NODE driver project are public.
To build a new version perform the following operations:
npm install
npm run build
When using a bundler or Node.js you can import bson using the package name:
import { BSON, EJSON, ObjectId } from 'bson';
// or:
// const { BSON, EJSON, ObjectId } = require('bson');
const bytes = BSON.serialize({ _id: new ObjectId() });
console.log(bytes);
const doc = BSON.deserialize(bytes);
console.log(EJSON.stringify(doc));
// {"_id":{"$oid":"..."}}
If you are working directly in the browser without a bundler please use the .mjs
bundle like so:
<script type="module">
import { BSON, EJSON, ObjectId } from './lib/bson.mjs';
const bytes = BSON.serialize({ _id: new ObjectId() });
console.log(bytes);
const doc = BSON.deserialize(bytes);
console.log(EJSON.stringify(doc));
// {"_id":{"$oid":"..."}}
</script>
npm install bson
Only the following version combinations with the MongoDB Node.js Driver are considered stable.
bson@1.x | bson@4.x | bson@5.x | bson@6.x | |
---|---|---|---|---|
mongodb@6.x | N/A | N/A | N/A | ✓ |
mongodb@5.x | N/A | N/A | ✓ | N/A |
mongodb@4.x | N/A | ✓ | N/A | N/A |
mongodb@3.x | ✓ | N/A | N/A | N/A |
Param | Type | Default | Description |
---|---|---|---|
text | string | ||
[options] | object | Optional settings | |
[options.relaxed] | boolean | true | Attempt to return native JS types where possible, rather than BSON types (if true) |
Parse an Extended JSON string, constructing the JavaScript value or object described by that string.
Example
const { EJSON } = require('bson');
const text = '{ "int32": { "$numberInt": "10" } }';
// prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }
console.log(EJSON.parse(text, { relaxed: false }));
// prints { int32: 10 }
console.log(EJSON.parse(text));
Param | Type | Default | Description |
---|---|---|---|
value | object | The value to convert to extended JSON | |
[replacer] | function | array | A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string | |
[space] | string | number | A String or Number object that's used to insert white space into the output JSON string for readability purposes. | |
[options] | object | Optional settings | |
[options.relaxed] | boolean | true | Enabled Extended JSON's relaxed mode |
[options.legacy] | boolean | true | Output in Extended JSON v1 |
Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
Example
const { EJSON } = require('bson');
const Int32 = require('mongodb').Int32;
const doc = { int32: new Int32(10) };
// prints '{"int32":{"$numberInt":"10"}}'
console.log(EJSON.stringify(doc, { relaxed: false }));
// prints '{"int32":10}'
console.log(EJSON.stringify(doc));
Param | Type | Description |
---|---|---|
bson | object | The object to serialize |
[options] | object | Optional settings passed to the stringify function |
Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.
Param | Type | Description |
---|---|---|
ejson | object | The Extended JSON object to deserialize |
[options] | object | Optional settings passed to the parse method |
Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types
It is our recommendation to use BSONError.isBSONError()
checks on errors and to avoid relying on parsing error.message
and error.name
strings in your code. We guarantee BSONError.isBSONError()
checks will pass according to semver guidelines, but errors may be sub-classed or their messages may change at any time, even patch releases, as we see fit to increase the helpfulness of the errors.
Any new errors we add to the driver will directly extend an existing error class and no existing error will be moved to a different parent class outside of a major release.
This means BSONError.isBSONError()
will always be able to accurately capture the errors that our BSON library throws.
Hypothetical example: A collection in our Db has an issue with UTF-8 data:
let documentCount = 0;
const cursor = collection.find({}, { utf8Validation: true });
try {
for await (const doc of cursor) documentCount += 1;
} catch (error) {
if (BSONError.isBSONError(error)) {
console.log(`Found the troublemaker UTF-8!: ${documentCount} ${error.message}`);
return documentCount;
}
throw error;
}
BSON vendors the required polyfills for TextEncoder
, TextDecoder
, atob
, btoa
imported from React Native and therefore doesn't expect users to polyfill these. One additional polyfill, crypto.getRandomValues
is recommended and can be installed with the following command:
npm install --save react-native-get-random-values
The following snippet should be placed at the top of the entrypoint (by default this is the root index.js
file) for React Native projects using the BSON library. These lines must be placed for any code that imports BSON
.
// Required Polyfills For ReactNative
import 'react-native-get-random-values';
Finally, import the BSON
library like so:
import { BSON, EJSON } from 'bson';
This will cause React Native to import the node_modules/bson/lib/bson.rn.cjs
bundle (see the "react-native"
setting we have in the "exports"
section of our package.json.)
The "exports"
definition in our package.json
will result in BSON's CommonJS bundle being imported in a React Native project instead of the ES module bundle. Importing the CommonJS bundle is necessary because BSON's ES module bundle of BSON uses top-level await, which is not supported syntax in React Native's runtime hermes.
undefined
get converted to null
?The undefined
BSON type has been deprecated for many years, so this library has dropped support for it. Use the ignoreUndefined
option (for example, from the driver ) to instead remove undefined
keys.
This library looks for toBSON()
functions on every path, and calls the toBSON()
function to get the value to serialize.
const BSON = require('bson');
class CustomSerialize {
toBSON() {
return 42;
}
}
const obj = { answer: new CustomSerialize() };
// "{ answer: 42 }"
console.log(BSON.deserialize(BSON.serialize(obj)));
FAQs
A bson parser for node.js and the browser
The npm package bson receives a total of 7,199,055 weekly downloads. As such, bson popularity was classified as popular.
We found that bson demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 8 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.