mongoose-query-find 4.0.2 → 5.0.1

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/dist/find.js CHANGED
@@ -9,43 +9,56 @@
9
9
  * QueryFind is a safe, allowlisted, and fully-featured query builder for
10
10
  * Mongoose that:
11
11
  * - Parses and sanitizes URL query parameters into Mongoose-friendly filters
12
- * - Coerces string booleans and date strings into proper types
13
- * - Supports safe top-level logical operators ($and / $or / $nor / $not)
12
+ * - Coerces string booleans and date strings into proper types (timezone-aware)
13
+ * - Supports safe top-level logical operators ($and / $or / $nor)
14
14
  * - Enforces an allowlist for fields that may be filtered, sorted, or selected
15
15
  * - Provides global (case-insensitive) regex search across specified fields
16
16
  * - Supports population, select (projection), sorting, and pagination
17
17
  * - Emits slow-query notifications when configured
18
18
  *
19
- * New: maxLimit option (customizable)
20
- * ----------------------------------
21
- * By default the per-page `limit` is capped at 100. You can override this
22
- * by passing `maxLimit` in the QueryFind options:
19
+ * ── Timezone handling ───────────────────────────────────────────────────────
20
+ * MongoDB always stores/compares dates in UTC. Clients think and filter in local
21
+ * time (e.g. ?createdAt=2026-09-01 means "Sept 1st in the caller's timezone",
22
+ * not UTC midnight). This builder resolves that with `date-fns-tz`:
23
23
  *
24
- * const result = await queryFind(User.find(), req.query, { maxLimit: 250 }).paginate();
24
+ * - fromZonedTime(localString, tz) -> the exact UTC instant for a wall-clock
25
+ * time in `tz`. Used to turn a client-supplied local date into the correct
26
+ * $gte/$lt UTC range.
25
27
  *
26
- * If the client requests ?limit=500 but maxLimit is 250, the effective limit
27
- * will be min(requestedLimit, maxLimit).
28
+ * The timezone is a per-request value, passed via the options object rather
29
+ * than hardcoded, typically sourced from a header:
30
+ *
31
+ * const timezone = (req.headers['x-timezone'] as string) ?? 'Asia/Dhaka';
32
+ * const result = await queryFind(User.find(), req.query, { timezone })...
33
+ *
34
+ * An invalid/unknown IANA timezone string never throws mid-query — it is
35
+ * validated once at construction time and falls back to the default.
36
+ *
37
+ * Date coercion rules (for date-like fields):
38
+ * - "YYYY-MM-DD" -> whole local day [00:00, next 00:00) in tz
39
+ * - "YYYY-MM-DDTHH:mm:ss[.sss]" -> local wall-clock time in tz
40
+ * - ISO string with Z / +06:00 -> absolute instant (timezone not applied)
41
+ * - ?createdAt[gte]=2026-09-01 -> start of that local day
42
+ * - ?createdAt[lte]=2026-09-30 -> last millisecond of that local day
43
+ * - ?createdAt[gt]=... [lt]=... -> end / start of that local day
44
+ * - ?createdAt[eq]=... / [ne]=...-> whole-day range / negated whole-day range
28
45
  *
29
46
  * Installation
30
47
  * ------------
31
- * npm:
32
- * npm install mongoose-query-find
33
- *
34
- * Yarn:
35
- * yarn add mongoose-query-find
48
+ * npm install mongoose-query-find date-fns-tz
36
49
  *
37
50
  * Usage
38
51
  * -----
39
- * Example typical usage inside an Express route handler:
40
- *
41
52
  * import { queryFind } from 'mongoose-query-find';
42
53
  * import User from './models/User';
43
54
  *
44
55
  * app.get('/users', async (req, res, next) => {
45
56
  * try {
57
+ * const timezone = (req.headers['x-timezone'] as string) ?? 'Asia/Dhaka';
46
58
  * const result = await queryFind(User.find(), req.query, {
59
+ * timezone,
47
60
  * maxTimeMS: 2000,
48
- * maxLimit: 250, // <- custom max limit per page
61
+ * maxLimit: 250,
49
62
  * onSlowQuery(info) {
50
63
  * console.warn('Slow query', info);
51
64
  * },
@@ -68,21 +81,15 @@
68
81
  * API (high-level)
69
82
  * ----------------
70
83
  * - queryFind(query, queryString, options?) -> QueryFind
71
- * Factory convenience wrapper around `new QueryFind(...)`.
72
- *
73
84
  * - new QueryFind(query, queryString, options?)
74
- * Constructor parameters:
75
- * - query: a Mongoose Query instance (e.g. Model.find())
76
- * - queryString: parsed URL query parameters (e.g. req.query)
77
- * - options (optional):
78
- * - maxTimeMS?: number (default: 5000)
85
+ * options (optional):
86
+ * - timezone?: string IANA tz (default: 'Asia/Dhaka')
87
+ * - maxTimeMS?: number (default: 5000)
79
88
  * - slowQueryThresholdMS?: number (defaults to maxTimeMS)
80
- * - maxLimit?: number (default: 100) <-- NEW
89
+ * - maxLimit?: number (default: 100)
81
90
  * - onSlowQuery?: (info: SlowQueryInfo) => void
82
91
  * - onSanitizeDrop?: (path: string, value: unknown) => void
83
- * - lean?: boolean (default: true)
84
- *
85
- * (rest of API documentation unchanged)
92
+ * - lean?: boolean (default: true)
86
93
  *
87
94
  * Copyright and License
88
95
  * ---------------------
@@ -90,17 +97,29 @@
90
97
  */
91
98
  Object.defineProperty(exports, "__esModule", { value: true });
92
99
  exports.queryFind = exports.QueryFind = exports.QueryFindValidationError = exports.QueryFindError = void 0;
100
+ const date_fns_tz_1 = require("date-fns-tz");
93
101
  // ─── Constants ────────────────────────────────────────────────────────────────
94
102
  const RESERVED_KEYS = new Set(['page', 'sort', 'limit', 'fields', 'q']);
95
103
  const DEFAULT_MAX_LIMIT = 100;
104
+ const DEFAULT_LIMIT = 10;
105
+ const MAX_PAGE = 1000000000;
96
106
  const MAX_NESTING_DEPTH = 5;
97
107
  const MAX_SEARCH_LENGTH = 200;
98
108
  const MAX_SORT_FIELDS = 5;
99
109
  const DEFAULT_MAX_TIME_MS = 5000;
110
+ const DEFAULT_TIMEZONE = 'Asia/Dhaka';
100
111
  // Matches only when the date-word is the LAST path segment (e.g. "createdAt",
101
112
  // "user.updatedAt") — not an arbitrary substring like "myUpdatedAt".
102
113
  const DATE_FIELD_RE = /(^|\.)(createdAt|updatedAt|deletedAt|date|birthDate|expiresAt)$/i;
103
114
  const PLAIN_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
115
+ // A string that already carries its own UTC offset ("Z" or "+06:00") is
116
+ // treated as an absolute instant rather than a local wall-clock time.
117
+ const HAS_OFFSET_RE = /([Zz]|[+-]\d{2}:?\d{2})$/;
118
+ const DANGEROUS_KEYS = new Set([
119
+ '__proto__',
120
+ 'constructor',
121
+ 'prototype',
122
+ ]);
104
123
  const COERCIBLE_OPS = new Set([
105
124
  'eq',
106
125
  'ne',
@@ -111,9 +130,10 @@ const COERCIBLE_OPS = new Set([
111
130
  'in',
112
131
  'nin',
113
132
  ]);
114
- const IN_LIKE_OPS = new Set(['in', '$in', 'nin', '$nin']);
133
+ const IN_LIKE_OPS = new Set(['in', 'nin']);
115
134
  const DEFAULT_SORT = { createdAt: -1 };
116
- const ALLOWED_TOP_LEVEL_OPS = new Set(['$and', '$or', '$nor', '$not']);
135
+ // NOTE: `$not` is not a valid top-level query operator in MongoDB, so it is not allowed here.
136
+ const ALLOWED_TOP_LEVEL_OPS = new Set(['$and', '$or', '$nor']);
117
137
  const BANNED_OPERATORS = new Set([
118
138
  '$where',
119
139
  '$expr',
@@ -139,24 +159,121 @@ class QueryFindValidationError extends QueryFindError {
139
159
  }
140
160
  exports.QueryFindValidationError = QueryFindValidationError;
141
161
  // ─── Input parsing ────────────────────────────────────────────────────────────
162
+ function asString(v) {
163
+ return typeof v === 'string' ? v : undefined;
164
+ }
142
165
  function parsePage(raw) {
143
- const n = parseInt(raw ?? '1', 10);
144
- return isNaN(n) || n < 1 ? 1 : n;
166
+ const n = parseInt(asString(raw) ?? '1', 10);
167
+ return !Number.isSafeInteger(n) || n < 1 || n > MAX_PAGE ? 1 : n;
145
168
  }
146
169
  function parseLimit(raw, maxLimit = DEFAULT_MAX_LIMIT) {
147
- const n = parseInt(raw ?? '10', 10);
148
- if (isNaN(n) || n < 1)
149
- return 10;
170
+ const n = parseInt(asString(raw) ?? String(DEFAULT_LIMIT), 10);
171
+ if (!Number.isFinite(n) || n < 1)
172
+ return Math.min(DEFAULT_LIMIT, maxLimit);
150
173
  return Math.min(n, maxLimit);
151
174
  }
175
+ const validTimezones = new Set();
176
+ function resolveTimezone(tz) {
177
+ const candidate = typeof tz === 'string' && tz.trim() && tz.length <= 64
178
+ ? tz.trim()
179
+ : DEFAULT_TIMEZONE;
180
+ if (validTimezones.has(candidate))
181
+ return candidate;
182
+ try {
183
+ // Throws RangeError on an invalid IANA zone — cheapest available validator.
184
+ new Intl.DateTimeFormat('en-US', { timeZone: candidate });
185
+ validTimezones.add(candidate);
186
+ return candidate;
187
+ }
188
+ catch {
189
+ if (process.env.NODE_ENV !== 'production') {
190
+ console.warn(`[query-find] Invalid timezone "${candidate}", falling back to "${DEFAULT_TIMEZONE}"`);
191
+ }
192
+ return DEFAULT_TIMEZONE;
193
+ }
194
+ }
195
+ // ─── Timezone-aware date helpers ───────────────────────────────────────────────
196
+ /** True only for a real calendar date in strict "YYYY-MM-DD" form (rejects "2026-02-31"). */
197
+ function isRealPlainDate(s) {
198
+ if (!PLAIN_DATE_RE.test(s))
199
+ return false;
200
+ const [y, m, d] = s.split('-').map(Number);
201
+ const dt = new Date(Date.UTC(y, m - 1, d));
202
+ return (dt.getUTCFullYear() === y &&
203
+ dt.getUTCMonth() === m - 1 &&
204
+ dt.getUTCDate() === d);
205
+ }
206
+ /** Shifts a "YYYY-MM-DD" string by N calendar days (pure UTC date math — DST-proof). */
207
+ function shiftLocalDateString(dateStr, days) {
208
+ const [y, m, d] = dateStr.split('-').map(Number);
209
+ const dt = new Date(Date.UTC(y, m - 1, d));
210
+ dt.setUTCDate(dt.getUTCDate() + days);
211
+ return dt.toISOString().slice(0, 10);
212
+ }
213
+ /** [start, end) UTC instants for a single local calendar date in `timezone`. */
214
+ function plainDateToUtcRange(dateStr, timezone) {
215
+ const start = (0, date_fns_tz_1.fromZonedTime)(`${dateStr}T00:00:00.000`, timezone);
216
+ const end = (0, date_fns_tz_1.fromZonedTime)(`${shiftLocalDateString(dateStr, 1)}T00:00:00.000`, timezone);
217
+ return { start, end };
218
+ }
219
+ /** Parses a single date/datetime string to a scalar UTC Date. */
220
+ function coerceDateScalar(value, timezone) {
221
+ let parsed;
222
+ if (PLAIN_DATE_RE.test(value)) {
223
+ if (!isRealPlainDate(value))
224
+ return undefined;
225
+ parsed = (0, date_fns_tz_1.fromZonedTime)(`${value}T00:00:00.000`, timezone);
226
+ }
227
+ else if (HAS_OFFSET_RE.test(value)) {
228
+ parsed = new Date(value);
229
+ }
230
+ else {
231
+ parsed = (0, date_fns_tz_1.fromZonedTime)(value, timezone);
232
+ }
233
+ return isNaN(parsed.getTime()) ? undefined : parsed;
234
+ }
235
+ /**
236
+ * Coerces a date string for a date-like field. `op` is the bare comparison
237
+ * operator ("gt", "lte", "in", ...) or undefined for a direct field value.
238
+ */
239
+ function coerceDateValue(value, op, timezone) {
240
+ if (op && IN_LIKE_OPS.has(op)) {
241
+ // $in/$nin require scalar values, not ranges.
242
+ return coerceDateScalar(value, timezone) ?? value;
243
+ }
244
+ if (isRealPlainDate(value)) {
245
+ const { start, end } = plainDateToUtcRange(value, timezone);
246
+ if (isNaN(start.getTime()) || isNaN(end.getTime()))
247
+ return value;
248
+ switch (op) {
249
+ case undefined:
250
+ return { $gte: start, $lt: end };
251
+ case 'gt':
252
+ return end;
253
+ case 'lte':
254
+ return new Date(end.getTime() - 1);
255
+ default: // gte / lt / eq / ne (eq/ne are normally intercepted earlier)
256
+ return start;
257
+ }
258
+ }
259
+ return coerceDateScalar(value, timezone) ?? value;
260
+ }
152
261
  // ─── Sanitization ─────────────────────────────────────────────────────────────
262
+ function isPlainObject(v) {
263
+ if (v === null || typeof v !== 'object' || Array.isArray(v))
264
+ return false;
265
+ if (v instanceof Date)
266
+ return false;
267
+ const proto = Object.getPrototypeOf(v);
268
+ return proto === Object.prototype || proto === null;
269
+ }
153
270
  /**
154
271
  * Recursively strips non-plain values (class instances, functions) from an
155
272
  * arbitrary object so only JSON-safe primitives/plain objects/Dates reach the
156
273
  * query pipeline. Notifies the caller via onDrop when values are removed.
157
274
  *
158
- * BUG FIX: Changed depth check from `>` to `>=` to properly enforce MAX_NESTING_DEPTH.
159
- * This prevents nesting deeper than 5 levels (0, 1, 2, 3, 4 are allowed; 5+ rejected).
275
+ * Depth check uses `>=` to properly enforce MAX_NESTING_DEPTH (levels 0–4
276
+ * allowed; 5+ rejected). Prototype-polluting keys are skipped.
160
277
  */
161
278
  function sanitize(value, depth = 0, path = '', onDrop) {
162
279
  if (depth >= MAX_NESTING_DEPTH) {
@@ -184,16 +301,16 @@ function sanitize(value, depth = 0, path = '', onDrop) {
184
301
  }
185
302
  return out;
186
303
  }
187
- if (t === 'object' && Object.getPrototypeOf(value) === Object.prototype) {
304
+ if (isPlainObject(value)) {
188
305
  const src = value;
189
306
  const out = {};
190
- for (const k in src) {
191
- if (Object.prototype.hasOwnProperty.call(src, k)) {
192
- const childPath = path ? `${path}.${k}` : k;
193
- const s = sanitize(src[k], depth + 1, childPath, onDrop);
194
- if (s !== undefined)
195
- out[k] = s;
196
- }
307
+ for (const k of Object.keys(src)) {
308
+ if (DANGEROUS_KEYS.has(k))
309
+ continue;
310
+ const childPath = path ? `${path}.${k}` : k;
311
+ const s = sanitize(src[k], depth + 1, childPath, onDrop);
312
+ if (s !== undefined)
313
+ out[k] = s;
197
314
  }
198
315
  return out;
199
316
  }
@@ -220,23 +337,28 @@ function isFieldAllowed(field, allowedLookup) {
220
337
  }
221
338
  /**
222
339
  * Removes any non-operator key not present in the allowlist. Operator keys
223
- * ($and/$or/$nor/$not and any nested operator) are recursed into so that a
340
+ * ($and/$or/$nor and any nested operator) are recursed into so that a
224
341
  * client cannot bypass the field allowlist by wrapping a disallowed field
225
342
  * inside a logical operator (e.g. ?$or[0][secretField]=x).
343
+ *
344
+ * Clauses that were fully stripped are dropped (an empty clause would
345
+ * otherwise match everything inside $or).
226
346
  */
227
347
  function enforceAllowlist(filter, allowedLookup, canonicalMap) {
228
348
  if (allowedLookup.size === 0)
229
349
  return filter;
230
350
  const out = {};
231
- for (const k in filter) {
232
- if (!Object.prototype.hasOwnProperty.call(filter, k))
233
- continue;
351
+ for (const k of Object.keys(filter)) {
234
352
  const v = filter[k];
235
353
  if (k.startsWith('$')) {
236
354
  if (Array.isArray(v)) {
237
- out[k] = v.map((item) => isPlainObject(item)
355
+ const items = v
356
+ .map((item) => isPlainObject(item)
238
357
  ? enforceAllowlist(item, allowedLookup, canonicalMap)
239
- : item);
358
+ : item)
359
+ .filter((item) => !(isPlainObject(item) && Object.keys(item).length === 0));
360
+ if (items.length > 0)
361
+ out[k] = items;
240
362
  }
241
363
  else if (isPlainObject(v)) {
242
364
  out[k] = enforceAllowlist(v, allowedLookup, canonicalMap);
@@ -252,27 +374,20 @@ function enforceAllowlist(filter, allowedLookup, canonicalMap) {
252
374
  }
253
375
  return out;
254
376
  }
255
- function isPlainObject(v) {
256
- return (v !== null &&
257
- typeof v === 'object' &&
258
- !Array.isArray(v) &&
259
- !(v instanceof Date) &&
260
- Object.getPrototypeOf(v) === Object.prototype);
261
- }
262
377
  // ─── Fused coercion pass ──────────────────────────────────────────────────────
263
378
  /**
264
379
  * Single-pass coercion:
265
380
  * - 'true' / 'false' strings → booleans
266
- * - Date-field strings → Date objects ($gte/$lt range for plain YYYY-MM-DD)
381
+ * - Date-field strings → Date objects, interpreted in `timezone`
382
+ * (plain YYYY-MM-DD → whole-local-day range or boundary depending on op)
267
383
  * - Shorthand operator keys (eq, ne, gt, …) → prefixed form ($eq, $ne, …)
384
+ * - ?field[in]=a,b,c → ['a','b','c']
268
385
  *
269
386
  * Inside an $in/$nin array, plain-date strings are coerced to a scalar Date
270
387
  * rather than a {$gte,$lt} range object, since $in/$nin require scalar values.
271
- *
272
- * OPTIMIZATION: Filter out undefined values before pushing to avoid bloating arrays
273
- * with undefined entries that would be skipped later anyway.
388
+ * `parentOp` is the BARE operator name (no leading "$").
274
389
  */
275
- function coerceAll(value, parentKey = '', parentOp) {
390
+ function coerceAll(value, timezone, parentKey = '', parentOp) {
276
391
  if (value === null)
277
392
  return null;
278
393
  if (typeof value === 'string') {
@@ -280,19 +395,9 @@ function coerceAll(value, parentKey = '', parentOp) {
280
395
  return true;
281
396
  if (value === 'false')
282
397
  return false;
283
- if (DATE_FIELD_RE.test(parentKey)) {
284
- const parsed = new Date(value);
285
- if (!isNaN(parsed.getTime())) {
286
- if (PLAIN_DATE_RE.test(value)) {
287
- if (parentOp && IN_LIKE_OPS.has(parentOp))
288
- return parsed;
289
- const start = new Date(value);
290
- const end = new Date(start);
291
- end.setUTCDate(end.getUTCDate() + 1);
292
- return { $gte: start, $lt: end };
293
- }
294
- return parsed;
295
- }
398
+ if (DATE_FIELD_RE.test(parentKey) &&
399
+ (!parentOp || COERCIBLE_OPS.has(parentOp))) {
400
+ return coerceDateValue(value, parentOp, timezone);
296
401
  }
297
402
  return value;
298
403
  }
@@ -300,8 +405,8 @@ function coerceAll(value, parentKey = '', parentOp) {
300
405
  return value;
301
406
  if (Array.isArray(value)) {
302
407
  const out = [];
303
- for (let i = 0; i < value.length; i++) {
304
- const coerced = coerceAll(value[i], parentKey, parentOp);
408
+ for (const item of value) {
409
+ const coerced = coerceAll(item, timezone, parentKey, parentOp);
305
410
  if (coerced !== undefined)
306
411
  out.push(coerced);
307
412
  }
@@ -309,55 +414,87 @@ function coerceAll(value, parentKey = '', parentOp) {
309
414
  }
310
415
  const src = value;
311
416
  const out = {};
312
- for (const k in src) {
313
- if (!Object.prototype.hasOwnProperty.call(src, k))
417
+ for (const k of Object.keys(src)) {
418
+ if (DANGEROUS_KEYS.has(k))
314
419
  continue;
315
- const newKey = COERCIBLE_OPS.has(k) ? `$${k}` : k;
420
+ const v = src[k];
316
421
  const isOp = k.startsWith('$') || COERCIBLE_OPS.has(k);
317
- const childPath = isOp ? parentKey : parentKey ? `${parentKey}.${k}` : k;
318
- // Reset parentOp when descending into a new field (isOp=false) so a
319
- // stale $in/$nin context from a sibling branch can't leak in.
320
- out[newKey] = coerceAll(src[k], childPath, isOp ? k : undefined);
422
+ if (!isOp) {
423
+ // Reset parentOp when descending into a new field so a stale
424
+ // $in/$nin context from a sibling branch can't leak in.
425
+ out[k] = coerceAll(v, timezone, parentKey ? `${parentKey}.${k}` : k, undefined);
426
+ continue;
427
+ }
428
+ const bare = k.startsWith('$') ? k.slice(1) : k;
429
+ const outKey = k.startsWith('$') ? k : `$${k}`;
430
+ // ?field[eq]=2026-09-01 / [ne]= on a date field -> whole-day range semantics.
431
+ if ((bare === 'eq' || bare === 'ne') &&
432
+ typeof v === 'string' &&
433
+ isRealPlainDate(v) &&
434
+ DATE_FIELD_RE.test(parentKey)) {
435
+ const { start, end } = plainDateToUtcRange(v, timezone);
436
+ if (!isNaN(start.getTime()) && !isNaN(end.getTime())) {
437
+ if (bare === 'eq') {
438
+ out.$gte = start;
439
+ out.$lt = end;
440
+ }
441
+ else {
442
+ out.$not = { $gte: start, $lt: end };
443
+ }
444
+ continue;
445
+ }
446
+ }
447
+ // ?field[in]=a,b,c -> ['a','b','c']
448
+ const child = IN_LIKE_OPS.has(bare) && typeof v === 'string'
449
+ ? v
450
+ .split(',')
451
+ .map((s) => s.trim())
452
+ .filter(Boolean)
453
+ : v;
454
+ out[outKey] = coerceAll(child, timezone, parentKey, bare);
321
455
  }
322
456
  return out;
323
457
  }
324
458
  // ─── Operator validation ──────────────────────────────────────────────────────
325
459
  /**
326
- * Throws on any BANNED_OPERATORS key at any depth, and on any top-level $ key
327
- * that isn't in ALLOWED_TOP_LEVEL_OPS.
460
+ * Throws on any BANNED_OPERATORS key at any depth. When `topLevelCheck` is true
461
+ * (client input) it also throws on any top-level $ key not in ALLOWED_TOP_LEVEL_OPS
462
+ * and requires logical operators to hold a non-empty array of plain objects.
328
463
  */
329
- function rejectDisallowedOperators(filter, depth = 0) {
330
- for (const k in filter) {
331
- if (!Object.prototype.hasOwnProperty.call(filter, k))
332
- continue;
464
+ function rejectDisallowedOperators(filter, depth = 0, topLevelCheck = true) {
465
+ for (const k of Object.keys(filter)) {
333
466
  if (BANNED_OPERATORS.has(k)) {
334
467
  throw new QueryFindValidationError(`Disallowed operator in query: "${k}"`);
335
468
  }
336
- if (depth === 0 && k.startsWith('$') && !ALLOWED_TOP_LEVEL_OPS.has(k)) {
337
- throw new QueryFindValidationError(`Disallowed top-level operator in query string: "${k}"`);
338
- }
339
469
  const v = filter[k];
470
+ if (topLevelCheck && depth === 0 && k.startsWith('$')) {
471
+ if (!ALLOWED_TOP_LEVEL_OPS.has(k)) {
472
+ throw new QueryFindValidationError(`Disallowed top-level operator in query string: "${k}"`);
473
+ }
474
+ if (!Array.isArray(v) || v.length === 0 || !v.every(isPlainObject)) {
475
+ throw new QueryFindValidationError(`Operator "${k}" requires a non-empty array of conditions`);
476
+ }
477
+ }
340
478
  if (Array.isArray(v)) {
341
479
  for (const item of v) {
342
480
  if (isPlainObject(item))
343
- rejectDisallowedOperators(item, depth + 1);
481
+ rejectDisallowedOperators(item, depth + 1, topLevelCheck);
344
482
  }
345
483
  }
346
484
  else if (isPlainObject(v)) {
347
- rejectDisallowedOperators(v, depth + 1);
485
+ rejectDisallowedOperators(v, depth + 1, topLevelCheck);
348
486
  }
349
487
  }
350
488
  }
351
489
  // ─── Filter builder ───────────────────────────────────────────────────────────
352
- function buildFilter(raw, allowedLookup, canonicalMap, onDrop) {
490
+ function buildFilter(raw, allowedLookup, canonicalMap, timezone, onDrop) {
353
491
  const stripped = {};
354
- for (const k in raw) {
355
- if (Object.prototype.hasOwnProperty.call(raw, k) && !RESERVED_KEYS.has(k)) {
492
+ for (const k of Object.keys(raw)) {
493
+ if (!RESERVED_KEYS.has(k) && !DANGEROUS_KEYS.has(k))
356
494
  stripped[k] = raw[k];
357
- }
358
495
  }
359
496
  const safe = sanitize(stripped, 0, '', onDrop);
360
- const coerced = coerceAll(safe);
497
+ const coerced = coerceAll(safe, timezone);
361
498
  const allowed = enforceAllowlist(coerced, allowedLookup, canonicalMap);
362
499
  rejectDisallowedOperators(allowed);
363
500
  return allowed;
@@ -379,7 +516,7 @@ function parseSort(sort, allowedLookup, canonicalMap) {
379
516
  continue;
380
517
  const desc = trimmed.startsWith('-');
381
518
  const field = desc ? trimmed.slice(1).trim() : trimmed;
382
- if (!field)
519
+ if (!field || field.startsWith('$') || DANGEROUS_KEYS.has(field))
383
520
  continue;
384
521
  if (allowedLookup.size > 0) {
385
522
  if (!isFieldAllowed(field, allowedLookup))
@@ -397,15 +534,18 @@ function parseSort(sort, allowedLookup, canonicalMap) {
397
534
  /**
398
535
  * Filters a space-separated projection string against the allowlist and
399
536
  * normalizes each field to its canonical case. _id and __v are always
400
- * permitted. Returns '' when every token is blocked — callers must handle
401
- * this explicitly to avoid an accidental "select everything".
537
+ * permitted. `+field` (force-select hidden fields) and `$` tokens are never
538
+ * accepted from the client. Returns '' when every token is blocked — callers
539
+ * must handle this explicitly to avoid an accidental "select everything".
402
540
  */
403
541
  function sanitizeProjection(projection, allowedLookup, canonicalMap) {
404
- if (allowedLookup.size === 0)
405
- return projection;
406
- return projection
542
+ const tokens = projection
407
543
  .split(/\s+/)
408
544
  .filter(Boolean)
545
+ .filter((token) => !token.startsWith('+') && !token.includes('$'));
546
+ if (allowedLookup.size === 0)
547
+ return tokens.join(' ');
548
+ return tokens
409
549
  .filter((token) => {
410
550
  const field = token.startsWith('-') ? token.slice(1) : token;
411
551
  return (field === '__v' ||
@@ -422,10 +562,11 @@ function sanitizeProjection(projection, allowedLookup, canonicalMap) {
422
562
  }
423
563
  // ─── QueryFind ────────────────────────────────────────────────────────────────
424
564
  /**
425
- * Fluent query builder / paginator for Mongoose 8/9.
565
+ * Fluent query builder / paginator for Mongoose 8/9, with timezone-aware
566
+ * date filtering.
426
567
  *
427
568
  * @example
428
- * const result = await new QueryFind(User.find(), req.query)
569
+ * const result = await new QueryFind(User.find(), req.query, { timezone })
429
570
  * .allowFields(['name', 'email', 'role', 'createdAt'])
430
571
  * .where({ orgId: req.user.orgId, deletedAt: null })
431
572
  * .filter()
@@ -441,11 +582,13 @@ class QueryFind {
441
582
  this._canonicalMap = new Map();
442
583
  /**
443
584
  * URL-derived filter and server conditions are kept separate so server
444
- * conditions (merged last, in buildFinalFilter) can never be overridden by
445
- * URL params, regardless of call order between where() and filter().
585
+ * conditions can never be overridden by URL params, regardless of call
586
+ * order between where() and filter(). Server conditions are a list
587
+ * (AND-ed together) so repeated where() calls on one field never
588
+ * overwrite each other.
446
589
  */
447
590
  this._urlFilter = {};
448
- this._serverConditions = {};
591
+ this._serverConditions = [];
449
592
  /** $or clauses from globalSearch(), assembled once in buildFinalFilter(). */
450
593
  this._searchOr = [];
451
594
  this._sort = { ...DEFAULT_SORT };
@@ -455,12 +598,33 @@ class QueryFind {
455
598
  this._defaultFields = null;
456
599
  this.model = query.model;
457
600
  this.qs = Object.freeze({ ...queryString });
601
+ // Conditions already present on the passed-in query (e.g. User.find({ orgId }))
602
+ // are kept as mandatory server conditions instead of being silently dropped.
603
+ try {
604
+ const base = query.getFilter?.();
605
+ if (base && Object.keys(base).length > 0) {
606
+ this._serverConditions.push({ ...base });
607
+ }
608
+ }
609
+ catch {
610
+ // Ignore — a query without a readable filter simply contributes nothing.
611
+ }
612
+ const maxLimit = typeof options.maxLimit === 'number' &&
613
+ Number.isFinite(options.maxLimit) &&
614
+ options.maxLimit >= 1
615
+ ? Math.floor(options.maxLimit)
616
+ : DEFAULT_MAX_LIMIT;
617
+ const maxTimeMS = typeof options.maxTimeMS === 'number' &&
618
+ Number.isFinite(options.maxTimeMS) &&
619
+ options.maxTimeMS >= 0
620
+ ? options.maxTimeMS
621
+ : DEFAULT_MAX_TIME_MS;
458
622
  this.options = {
459
- maxTimeMS: options.maxTimeMS ?? DEFAULT_MAX_TIME_MS,
623
+ timezone: resolveTimezone(options.timezone),
624
+ maxTimeMS,
460
625
  slowQueryThresholdMS: options.slowQueryThresholdMS ??
461
- options.maxTimeMS ??
462
- DEFAULT_MAX_TIME_MS,
463
- maxLimit: options.maxLimit ?? DEFAULT_MAX_LIMIT,
626
+ (maxTimeMS > 0 ? maxTimeMS : DEFAULT_MAX_TIME_MS),
627
+ maxLimit,
464
628
  lean: options.lean ?? true,
465
629
  onSlowQuery: options.onSlowQuery,
466
630
  onSanitizeDrop: options.onSanitizeDrop,
@@ -468,6 +632,10 @@ class QueryFind {
468
632
  this._page = parsePage(this.qs.page);
469
633
  this._limit = parseLimit(this.qs.limit, this.options.maxLimit);
470
634
  }
635
+ /** The resolved (validated) timezone this instance is using. */
636
+ get timezone() {
637
+ return this.options.timezone;
638
+ }
471
639
  // ── Configuration ─────────────────────────────────────────────────────────
472
640
  /**
473
641
  * Declares which fields the client may filter, sort, and select. Must be
@@ -484,22 +652,32 @@ class QueryFind {
484
652
  /**
485
653
  * Parses URL query params into a Mongoose filter and merges them into the
486
654
  * URL-derived filter store. Only allowlisted fields pass through (including
487
- * fields nested inside $and/$or/$nor/$not). Reserved keys are stripped first.
655
+ * fields nested inside $and/$or/$nor). Reserved keys are stripped first.
656
+ * Date strings are interpreted in this instance's timezone.
488
657
  */
489
658
  filter() {
490
- const parsed = buildFilter(this.qs, this._allowedLookup, this._canonicalMap, this.options.onSanitizeDrop);
659
+ const parsed = buildFilter(this.qs, this._allowedLookup, this._canonicalMap, this.options.timezone, this.options.onSanitizeDrop);
491
660
  Object.assign(this._urlFilter, parsed);
492
661
  return this;
493
662
  }
494
663
  /**
495
- * Mandatory server-side conditions the client cannot override — merged
496
- * into the final filter last. Values are not sanitized (ObjectIds, Dates,
497
- * etc. are valid); banned $ operators are still rejected.
664
+ * Mandatory server-side conditions the client cannot override — AND-ed
665
+ * with the final filter. Repeated calls are AND-ed together, never
666
+ * overwritten. Values are not sanitized (ObjectIds, Dates, etc. are
667
+ * valid); banned $ operators are still rejected, and `undefined` values
668
+ * throw (an undefined condition would silently match everything).
498
669
  */
499
670
  where(conditions) {
500
671
  const asRecord = conditions;
501
- rejectDisallowedOperators(asRecord);
502
- Object.assign(this._serverConditions, asRecord);
672
+ for (const k of Object.keys(asRecord)) {
673
+ if (asRecord[k] === undefined) {
674
+ throw new QueryFindValidationError(`where: condition for "${k}" is undefined`);
675
+ }
676
+ }
677
+ rejectDisallowedOperators(asRecord, 0, false);
678
+ if (Object.keys(asRecord).length === 0)
679
+ return this;
680
+ this._serverConditions.push({ ...asRecord });
503
681
  return this;
504
682
  }
505
683
  /**
@@ -508,7 +686,7 @@ class QueryFind {
508
686
  * multiple times — extends the $or list rather than re-wrapping the filter.
509
687
  */
510
688
  globalSearch(fields) {
511
- const raw = this.qs.q?.trim();
689
+ const raw = asString(this.qs.q)?.trim();
512
690
  if (!raw || raw.length > MAX_SEARCH_LENGTH || fields.length === 0)
513
691
  return this;
514
692
  const safeFields = this._allowedLookup.size > 0
@@ -527,8 +705,9 @@ class QueryFind {
527
705
  * Fields not in allowFields() are dropped; falls back to DEFAULT_SORT.
528
706
  */
529
707
  sort() {
530
- if (this.qs.sort) {
531
- this._sort = parseSort(this.qs.sort, this._allowedLookup, this._canonicalMap);
708
+ const raw = asString(this.qs.sort);
709
+ if (raw) {
710
+ this._sort = parseSort(raw, this._allowedLookup, this._canonicalMap);
532
711
  }
533
712
  return this;
534
713
  }
@@ -541,8 +720,9 @@ class QueryFind {
541
720
  limitFields(defaultFields) {
542
721
  if (defaultFields)
543
722
  this._defaultFields = defaultFields;
544
- if (this.qs.fields) {
545
- const raw = this.qs.fields
723
+ const fieldsRaw = asString(this.qs.fields);
724
+ if (fieldsRaw) {
725
+ const raw = fieldsRaw
546
726
  .split(',')
547
727
  .map((f) => f.trim())
548
728
  .filter(Boolean)
@@ -557,9 +737,10 @@ class QueryFind {
557
737
  }
558
738
  /**
559
739
  * Registers a populate path. `match` is sanitized (non-plain values
560
- * stripped) and boolean/date strings coerced, then checked for banned
561
- * operators — but NOT restricted to the main model's allowFields(), since
562
- * the populated model may have an entirely different schema.
740
+ * stripped) and boolean/date strings coerced (dates in this instance's
741
+ * timezone), then checked for banned operators — but NOT restricted to the
742
+ * main model's allowFields(), since the populated model may have an
743
+ * entirely different schema.
563
744
  */
564
745
  populate(path, select) {
565
746
  if (typeof path === 'string') {
@@ -568,8 +749,8 @@ class QueryFind {
568
749
  }
569
750
  if (path.match != null) {
570
751
  const safeMatch = sanitize(path.match, 0, 'populate.match', this.options.onSanitizeDrop);
571
- const coercedMatch = coerceAll(safeMatch);
572
- rejectDisallowedOperators(coercedMatch);
752
+ const coercedMatch = coerceAll(safeMatch, this.options.timezone);
753
+ rejectDisallowedOperators(coercedMatch, 0, false);
573
754
  this._populates.push({ ...path, match: coercedMatch });
574
755
  }
575
756
  else {
@@ -578,48 +759,47 @@ class QueryFind {
578
759
  return this;
579
760
  }
580
761
  // ── Private helpers ───────────────────────────────────────────────────────
762
+ /**
763
+ * Effective sort: the requested sort plus `_id` as a stable tiebreaker
764
+ * (prevents duplicate/missing rows across pages).
765
+ */
766
+ effectiveSort() {
767
+ if ('_id' in this._sort)
768
+ return { ...this._sort };
769
+ const dir = Object.values(this._sort)[0] ?? -1;
770
+ return { ...this._sort, _id: dir };
771
+ }
581
772
  /**
582
773
  * Assembles the final filter from three sources:
583
774
  * 1. URL-derived filter (client controlled)
584
775
  * 2. Global search $or clause
585
- * 3. Server conditions (highest priority)
776
+ * 3. Server conditions (each AND-ed, so they can never be overridden)
586
777
  *
587
778
  * Combined with $and rather than object-spread, so a server condition on
588
779
  * the same field as a URL filter narrows the query instead of silently
589
780
  * discarding one side.
590
- *
591
- * OPTIMIZATION: Eliminated unnecessary object spreads. Use direct assignment
592
- * to reduce garbage collection pressure.
593
781
  */
594
782
  buildFinalFilter() {
595
- let base;
596
- // Avoid spreading the URL filter; just use it directly initially
597
- const hasUrlFilter = Object.keys(this._urlFilter).length > 0;
598
- if (this._searchOr.length > 0) {
599
- if (hasUrlFilter) {
600
- base = { $and: [this._urlFilter, { $or: this._searchOr }] };
601
- }
602
- else {
603
- base = { $or: this._searchOr };
604
- }
605
- }
606
- else {
607
- base = hasUrlFilter ? this._urlFilter : {};
608
- }
609
- const hasServer = Object.keys(this._serverConditions).length > 0;
610
- if (Object.keys(base).length > 0 && hasServer) {
611
- return { $and: [base, this._serverConditions] };
612
- }
613
- if (hasServer) {
614
- return this._serverConditions;
783
+ const clauses = [];
784
+ if (Object.keys(this._urlFilter).length > 0)
785
+ clauses.push(this._urlFilter);
786
+ if (this._searchOr.length > 0)
787
+ clauses.push({ $or: this._searchOr });
788
+ for (const cond of this._serverConditions) {
789
+ if (Object.keys(cond).length > 0)
790
+ clauses.push(cond);
615
791
  }
616
- return base;
792
+ if (clauses.length === 0)
793
+ return {};
794
+ if (clauses.length === 1)
795
+ return clauses[0];
796
+ return { $and: clauses };
617
797
  }
618
798
  execFind(mongoFilter, skip) {
619
799
  const { maxTimeMS, lean } = this.options;
620
800
  const q = this.model
621
801
  .find(mongoFilter)
622
- .sort(this._sort)
802
+ .sort(this.effectiveSort())
623
803
  .skip(skip)
624
804
  .limit(this._limit);
625
805
  if (lean)
@@ -636,27 +816,41 @@ class QueryFind {
636
816
  async execCount(mongoFilter, hasFilter) {
637
817
  const { maxTimeMS } = this.options;
638
818
  if (!hasFilter) {
639
- return (await this.model
640
- .estimatedDocumentCount()
641
- .maxTimeMS(maxTimeMS)
642
- .exec());
819
+ const q = this.model.estimatedDocumentCount();
820
+ if (maxTimeMS > 0)
821
+ q.maxTimeMS(maxTimeMS);
822
+ return (await q.exec());
643
823
  }
644
- return (await this.model
645
- .countDocuments(mongoFilter)
646
- .maxTimeMS(maxTimeMS)
647
- .exec());
824
+ const q = this.model.countDocuments(mongoFilter);
825
+ if (maxTimeMS > 0)
826
+ q.maxTimeMS(maxTimeMS);
827
+ return (await q.exec());
648
828
  }
649
829
  async wrapTimed(fn, page, limit, filter) {
650
- const { onSlowQuery, slowQueryThresholdMS, maxTimeMS } = this.options;
830
+ const { onSlowQuery, slowQueryThresholdMS } = this.options;
651
831
  if (!onSlowQuery)
652
832
  return fn();
653
833
  const start = Date.now();
654
- const result = await fn();
655
- const elapsedMs = Date.now() - start;
656
- if (elapsedMs >= (slowQueryThresholdMS ?? maxTimeMS)) {
657
- onSlowQuery({ elapsedMs, filter, sort: this._sort, page, limit });
834
+ try {
835
+ return await fn();
836
+ }
837
+ finally {
838
+ const elapsedMs = Date.now() - start;
839
+ if (elapsedMs >= slowQueryThresholdMS) {
840
+ try {
841
+ onSlowQuery({
842
+ elapsedMs,
843
+ filter,
844
+ sort: this.effectiveSort(),
845
+ page,
846
+ limit,
847
+ });
848
+ }
849
+ catch {
850
+ // A faulty logging callback must never break the query.
851
+ }
852
+ }
658
853
  }
659
- return result;
660
854
  }
661
855
  // ── Terminal ───────────────────────────────────────────────────────────────
662
856
  /**
@@ -689,6 +883,9 @@ class QueryFind {
689
883
  };
690
884
  }
691
885
  if (cachedTotal !== undefined) {
886
+ if (!Number.isInteger(cachedTotal) || cachedTotal < 0) {
887
+ throw new QueryFindValidationError(`paginate: "cachedTotal" must be a non-negative integer, got ${cachedTotal}`);
888
+ }
692
889
  const totalPages = Math.max(Math.ceil(cachedTotal / limit), 1);
693
890
  const safePage = page > totalPages ? 1 : page;
694
891
  const data = await this.wrapTimed(() => this.execFind(mongoFilter, (safePage - 1) * limit), safePage, limit, finalFilter);