Skip to content

Commit 6f30b4e

Browse files
committed
fix(ObjectId): will now throw if an invalid character is passed
If a non-hex string of length 12 is passed into the ObjectId constructor, we generate a hexString based off of the character codes of the passed in id. This requires that the passed id consist entirely of characters with values < 256 in utf-16. Previously, we let this silently fail and generated invalid hex string. Now, we throw a TypeError Fixes NODE-1737 BREAKING CHANGE: Where code was previously silently erroring, users may now experience TypeErrors
1 parent c6701fc commit 6f30b4e

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

Diff for: lib/objectid.js

+14-1
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,15 @@ function convertToHex(bytes) {
3434
return bytes.toString('hex');
3535
}
3636

37+
function makeObjectIdError(invalidString, index) {
38+
const invalidCharacter = invalidString[index];
39+
return new TypeError(
40+
`ObjectId string "${invalidString}" contains invalid character "${invalidCharacter}" with character code (${invalidString.charCodeAt(
41+
index
42+
)}). All character codes for a non-hex string must be less than 256.`
43+
);
44+
}
45+
3746
/**
3847
* A class representation of the BSON ObjectId type.
3948
*/
@@ -111,7 +120,11 @@ class ObjectId {
111120
}
112121

113122
for (let i = 0; i < this.id.length; i++) {
114-
hexString += hexTable[this.id.charCodeAt(i)];
123+
const hexChar = hexTable[this.id.charCodeAt(i)];
124+
if (typeof hexChar !== 'string') {
125+
throw makeObjectIdError(this.id, i);
126+
}
127+
hexString += hexChar;
115128
}
116129

117130
if (ObjectId.cacheHexString) this.__id = hexString;

Diff for: test/node/object_id_tests.js

+5
Original file line numberDiff line numberDiff line change
@@ -94,4 +94,9 @@ describe('ObjectId', function() {
9494
expect(ObjectId.isValid(buff12Bytes)).to.be.true;
9595
done();
9696
});
97+
98+
it('should throw if a 12-char string is passed in with character codes greater than 256', function() {
99+
expect(() => new ObjectId('abcdefghijkl').toHexString()).to.not.throw();
100+
expect(() => new ObjectId('abcdefŽhijkl').toHexString()).to.throw(TypeError);
101+
});
97102
});

0 commit comments

Comments
 (0)