diff --git a/packages/query-parser/src/index.spec.ts b/packages/query-parser/src/index.spec.ts index c7165dea5..676b21583 100644 --- a/packages/query-parser/src/index.spec.ts +++ b/packages/query-parser/src/index.spec.ts @@ -426,6 +426,24 @@ e s`, "{a:{name:'multi-line with s p a c\\n \\ne s'}}", ); }); + + it('escapes quotes, backslashes and newlines in Code', function () { + const code = `a "b" 'c' \\d\ne`; + const jsString = toJSString({ a: new bson.Code(code) }) as string; + assert.deepEqual(parseFilter(jsString), { + a: new bson.Code(code), + }); + }); + + it('escapes Code with a scope', function () { + const code = `');process.exit(1);('`; + const jsString = toJSString({ + a: new bson.Code(code, { b: 1 }), + }) as string; + assert.deepEqual(parseFilter(jsString), { + a: new bson.Code(code, { b: 1 }), + }); + }); }); describe('stringify', function () { diff --git a/packages/query-parser/src/stringify.ts b/packages/query-parser/src/stringify.ts index 30a9ee50f..4014e7ab7 100644 --- a/packages/query-parser/src/stringify.ts +++ b/packages/query-parser/src/stringify.ts @@ -48,10 +48,11 @@ function getTypeDescriptorForValue(value: BSONValue) { const BSON_TO_JS_STRING = { Code: function (v: Code) { + const code = JSON.stringify(v.code); if (v.scope) { - return `Code('${v.code}',${JSON.stringify(v.scope)})`; + return `Code(${code},${JSON.stringify(v.scope)})`; } - return `Code('${v.code}')`; + return `Code(${code})`; }, ObjectID: function (v: ObjectId) { return `ObjectId('${v.toString('hex')}')`;