Skip to content

Commit e3bf7de

Browse files
committed
Fixup offset check
1 parent f41c6b6 commit e3bf7de

File tree

2 files changed

+15
-8
lines changed

2 files changed

+15
-8
lines changed

src/objectid.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -163,16 +163,16 @@ export class ObjectId extends BSONValue {
163163
// Generate a new id
164164
ObjectId.generate(typeof workingId === 'number' ? workingId : undefined, pool, offset);
165165
} else if (ArrayBuffer.isView(workingId)) {
166-
if (workingId.byteLength !== 12 && typeof inputIndex !== 'number') {
167-
throw new BSONError('Buffer length must be 12 or offset must be specified');
168-
}
169-
if (
170-
inputIndex &&
171-
(typeof inputIndex !== 'number' || inputIndex < 0 || workingId.byteLength < inputIndex + 12)
166+
if (workingId.byteLength === 12) {
167+
inputIndex = 0;
168+
} else if (
169+
typeof inputIndex !== 'number' ||
170+
inputIndex < 0 ||
171+
workingId.byteLength < inputIndex + 12 ||
172+
isNaN(inputIndex)
172173
) {
173-
throw new BSONError('Buffer offset must be a non-negative number less than buffer length');
174+
throw new BSONError('Buffer length must be 12 or a valid offset must be specified');
174175
}
175-
inputIndex ??= 0;
176176
for (let i = 0; i < 12; i++) pool[offset + i] = workingId[inputIndex + i];
177177
} else if (typeof workingId === 'string') {
178178
if (workingId.length === 24 && checkForHexRegExp.test(workingId)) {

test/node/object_id.test.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,6 +407,13 @@ describe('ObjectId', function () {
407407
it('should throw an error if invalid Buffer offset passed in', function () {
408408
const a = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]);
409409
expect(() => new ObjectId(a, 5)).to.throw(BSONError);
410+
expect(() => new ObjectId(a, -1)).to.throw(BSONError);
411+
expect(() => new ObjectId(a, 0n)).to.throw(BSONError);
412+
expect(() => new ObjectId(a, '')).to.throw(BSONError);
413+
expect(() => new ObjectId(a, NaN)).to.throw(BSONError);
414+
expect(() => new ObjectId(a, {})).to.throw(BSONError);
415+
expect(() => new ObjectId(a, false)).to.throw(BSONError);
416+
expect(() => new ObjectId(a, '' + 1)).to.throw(BSONError);
410417
});
411418

412419
it('should correctly allow for node.js inspect to work with ObjectId', function (done) {

0 commit comments

Comments
 (0)