mongoose 7.8.13 → 7.8.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cast.js CHANGED
@@ -111,6 +111,11 @@ module.exports = function cast(schema, obj, options, context) {
111
111
  } else if (path === '$comment' && !schema.paths.hasOwnProperty('$comment')) {
112
112
  val = castString(val, path);
113
113
  obj[path] = val;
114
+ } else if (isOperator(path)) {
115
+ // Pass through other top-level operators, like `$jsonSchema`, without casting.
116
+ // MongoDB doesn't allow querying top-level `$` fields, so these can't be paths
117
+ // and `strict` or `strictQuery` shouldn't strip them.
118
+ continue;
114
119
  } else {
115
120
  if (!schema) {
116
121
  // no casting for Mixed types
@@ -70,7 +70,14 @@ function QueryCursor(query) {
70
70
  this.listeners('error').length > 0 && this.emit('error', err);
71
71
  return;
72
72
  }
73
- Object.assign(this.options, query._optionsForExec());
73
+ // `_optionsForExec()` can throw, for example if casting the projection fails
74
+ try {
75
+ Object.assign(this.options, query._optionsForExec());
76
+ } catch (err) {
77
+ this._markError(err);
78
+ this.listeners('error').length > 0 && this.emit('error', err);
79
+ return;
80
+ }
74
81
  this._transforms = this._transforms.concat(query._transforms.slice());
75
82
  if (this.options.transform) {
76
83
  this._transforms.push(this.options.transform);
@@ -24,7 +24,7 @@ module.exports = function sanitizeFilter(filter) {
24
24
  if (key === '$and' || key === '$or' || key === '$nor') {
25
25
  sanitizeFilter(value);
26
26
  continue;
27
- } else if (key === '$jsonSchema' || key === '$where' || key === '$expr' || key === '$text') {
27
+ } else if (key[0] === '$') {
28
28
  throw new MongooseError(key + ' is not allowed with sanitizeFilter');
29
29
  }
30
30
 
@@ -7,7 +7,24 @@ module.exports = function sanitizeProjection(projection) {
7
7
 
8
8
  const keys = Object.keys(projection);
9
9
  for (let i = 0; i < keys.length; ++i) {
10
- if (typeof projection[keys[i]] === 'string') {
10
+ const value = projection[keys[i]];
11
+ if (typeof value === 'string') {
12
+ projection[keys[i]] = 1;
13
+ continue;
14
+ }
15
+ if (value == null || typeof value !== 'object') {
16
+ continue;
17
+ }
18
+ // Only allow `$meta: 'textScore'`, `$elemMatch`, and numeric `$slice`. Nested sub-projections, arrays, and
19
+ // expressions like `{ name: { $concat: ['$password'] } }` become `1`. Note that
20
+ // `{ $slice: ['$otherArray', 1] }` is an expression that can read another field, and
21
+ // `$meta: 'indexKey'` and `$meta: 'sortKey'` can return values of `select: false` paths.
22
+ const slice = value.$slice;
23
+ const isAllowedProjectionOperator = value.$meta === 'textScore' ||
24
+ value.$elemMatch != null ||
25
+ typeof slice === 'number' ||
26
+ (Array.isArray(slice) && slice.every(v => typeof v === 'number'));
27
+ if (!isAllowedProjectionOperator) {
11
28
  projection[keys[i]] = 1;
12
29
  }
13
30
  }
package/lib/query.js CHANGED
@@ -1100,6 +1100,11 @@ Query.prototype.select = function select() {
1100
1100
  }
1101
1101
  arg = parseProjection(arg, true); // we want to keep the minus and pluses, so add boolean arg.
1102
1102
  if (utils.isObject(arg)) {
1103
+ // `fields['__proto__'] = value` would re-point the projection's prototype
1104
+ if (Object.prototype.hasOwnProperty.call(arg, '__proto__')) {
1105
+ arg = { ...arg };
1106
+ delete arg['__proto__'];
1107
+ }
1103
1108
  if (this.selectedInclusively()) {
1104
1109
  Object.entries(arg).forEach(([key, value]) => {
1105
1110
  if (value) {
@@ -4977,11 +4982,7 @@ Query.prototype._castFields = function _castFields(fields) {
4977
4982
 
4978
4983
  if (selected) {
4979
4984
  // they passed $elemMatch, cast em
4980
- try {
4981
- out = this.cast(this.model, selected);
4982
- } catch (err) {
4983
- return err;
4984
- }
4985
+ out = this.cast(this.model, selected);
4985
4986
 
4986
4987
  // apply the casted field args
4987
4988
  for (let i = 0; i < elemMatchKeys.length; ++i) {
@@ -5003,6 +5004,20 @@ Query.prototype._applyPaths = function applyPaths() {
5003
5004
  return;
5004
5005
  }
5005
5006
  this._fields = this._fields || {};
5007
+
5008
+ let shouldSanitizeProjection = undefined;
5009
+ if (utils.hasUserDefinedProperty(this.model.db.options, 'sanitizeProjection')) {
5010
+ shouldSanitizeProjection = this.model.db.options.sanitizeProjection;
5011
+ } else if (utils.hasUserDefinedProperty(this.model.base.options, 'sanitizeProjection')) {
5012
+ shouldSanitizeProjection = this.model.base.options.sanitizeProjection;
5013
+ } else {
5014
+ shouldSanitizeProjection = this._mongooseOptions.sanitizeProjection;
5015
+ }
5016
+ // Strip expressions at exec time, because projections may be set before `sanitizeProjection`
5017
+ if (shouldSanitizeProjection) {
5018
+ sanitizeProjection(this._fields);
5019
+ }
5020
+
5006
5021
  helpers.applyPaths(this._fields, this.model.schema);
5007
5022
 
5008
5023
  let _selectPopulatedPaths = true;
@@ -11,6 +11,8 @@ const get = require('./helpers/get');
11
11
  const getDiscriminatorByValue =
12
12
  require('./helpers/discriminator/getDiscriminatorByValue');
13
13
  const isDefiningProjection = require('./helpers/projection/isDefiningProjection');
14
+ const isExclusive = require('./helpers/projection/isExclusive');
15
+ const isPOJO = require('./helpers/isPOJO');
14
16
  const clone = require('./helpers/clone');
15
17
  const isPathSelectedInclusive = require('./helpers/projection/isPathSelectedInclusive');
16
18
 
@@ -172,6 +174,7 @@ exports.applyPaths = function applyPaths(fields, schema) {
172
174
  }
173
175
 
174
176
  keys = Object.keys(fields);
177
+ let hasElemMatch = false;
175
178
  for (let keyIndex = 0; keyIndex < keys.length; ++keyIndex) {
176
179
  if (keys[keyIndex][0] === '+') {
177
180
  continue;
@@ -181,15 +184,32 @@ exports.applyPaths = function applyPaths(fields, schema) {
181
184
  if (!isDefiningProjection(field)) {
182
185
  continue;
183
186
  }
187
+ // `$elemMatch` is inclusive on its own, but MongoDB treats `{ arr: { $elemMatch }, name: 0 }` as exclusive
188
+ if (field?.$elemMatch != null) {
189
+ hasElemMatch = true;
190
+ continue;
191
+ }
184
192
  if (keys[keyIndex] === '_id' && keys.length > 1) {
185
193
  continue;
186
194
  }
187
195
  if (keys[keyIndex] === schema.options.discriminatorKey && keys.length > 1 && field != null && !field) {
188
196
  continue;
189
197
  }
198
+ // Nested sub-projections like `{ profile: { bio: 0 } }` are exclusive or inclusive based on their
199
+ // nested values, unlike expressions like `{ $concat: [...] }`, which are always inclusive
200
+ if (isPOJO(field) && !Object.keys(field).some(key => key.startsWith('$'))) {
201
+ exclude = isExclusive(field) ?? undefined;
202
+ if (exclude === undefined) {
203
+ continue;
204
+ }
205
+ break;
206
+ }
190
207
  exclude = !field;
191
208
  break;
192
209
  }
210
+ if (exclude === undefined && hasElemMatch) {
211
+ exclude = false;
212
+ }
193
213
 
194
214
  // Potentially add back minus paths based on schema-level path config
195
215
  // and whether the projection is inclusive
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mongoose",
3
3
  "description": "Mongoose MongoDB ODM",
4
- "version": "7.8.13",
4
+ "version": "7.8.14",
5
5
  "author": "Guillermo Rauch <guillermo@learnboost.com>",
6
6
  "keywords": [
7
7
  "mongodb",
package/types/query.d.ts CHANGED
@@ -146,7 +146,15 @@ declare module 'mongoose' {
146
146
  * (https://mongoosejs.com/docs/validation.html#update-validators). Defaults to false.
147
147
  */
148
148
  runValidators?: boolean;
149
- /* Set to `true` to automatically sanitize potentially unsafe user-generated query projections */
149
+ /**
150
+ * Set to `true` to automatically sanitize potentially unsafe user-generated query projections.
151
+ * Converts projection values that aren't numbers or booleans to `1`, including strings like `'$password'`
152
+ * and expressions like `{ $concat: ['$password'] }`, so projections can't copy one field's value into another.
153
+ * The only projection operators that are allowed are `$elemMatch`, `$slice` with numbers, and `$meta: 'textScore'`.
154
+ *
155
+ * In Mongoose 7, `sanitizeProjection` does **not** prevent projecting in fields that the schema deselects
156
+ * with `select: false`: `select('+password')` and `select({ password: 1 })` still include `password`.
157
+ */
150
158
  sanitizeProjection?: boolean;
151
159
  /**
152
160
  * Set to `true` to automatically sanitize potentially unsafe query filters by stripping out query selectors that