masterrecord 1.3.3 → 1.5.6

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.
@@ -4,6 +4,23 @@ import entityTrackerModel from '../Entity/entityTrackerModel.js';
4
4
  import tools from '../Tools.js';
5
5
  import queryScript from './queryScript.js';
6
6
 
7
+ // Security: `.take()`/`.skip()` values are interpolated directly into
8
+ // LIMIT/OFFSET (these clauses cannot be parameterized on SQLite/MySQL/Postgres).
9
+ // Pagination values are the single most common place an application forwards
10
+ // raw user input (e.g. `?page=`, `?limit=`), so a non-numeric value here is a
11
+ // direct SQL-injection vector. Coerce to a safe, non-negative integer and throw
12
+ // loudly on anything else rather than letting it reach the SQL string.
13
+ function validateRowCount(value, method){
14
+ if(value === null || value === undefined){
15
+ return 0; // treated as "not set"
16
+ }
17
+ const n = typeof value === 'number' ? value : Number(value);
18
+ if(!Number.isInteger(n) || n < 0 || !Number.isSafeInteger(n)){
19
+ throw new Error(`.${method}() requires a non-negative integer, received: ${JSON.stringify(value)}`);
20
+ }
21
+ return n;
22
+ }
23
+
7
24
  class queryMethods{
8
25
 
9
26
  constructor(entity, context) {
@@ -198,12 +215,12 @@ class queryMethods{
198
215
  }
199
216
 
200
217
  take(number){
201
- this.__queryObject.script.take = number;
218
+ this.__queryObject.script.take = validateRowCount(number, 'take');
202
219
  return this;
203
220
  }
204
221
 
205
222
  skip(number){
206
- this.__queryObject.script.skip = number;
223
+ this.__queryObject.script.skip = validateRowCount(number, 'skip');
207
224
  return this;
208
225
  }
209
226
 
@@ -522,7 +539,13 @@ class queryMethods{
522
539
  throw new Error('No database type configured. Ensure context.env() or context.useMySql()/useSqlite() has been called and awaited.');
523
540
  }
524
541
 
525
- // Store in cache
542
+ // Store in cache — but never cache a "not found" (null) result. A
543
+ // negative result is poisoned the instant any concurrent writer inserts
544
+ // the matching row: a reader that filled the cache with the pre-commit
545
+ // empty would keep serving it (the writer's invalidateTable ran before
546
+ // this set, or on a different context instance's cache entirely). This
547
+ // is the "claimed idempotency key reads back empty" bug — re-run the
548
+ // cheap lookup against the database instead of trusting a cached miss.
526
549
  if (this.__useCache && result) {
527
550
  this.__context._queryCache.set(cacheKey, result, tableName);
528
551
  }
@@ -572,8 +595,14 @@ class queryMethods{
572
595
  throw new Error('No database type configured. Ensure context.env() or context.useMySql()/useSqlite() has been called and awaited.');
573
596
  }
574
597
 
575
- // Store in cache
576
- if (this.__useCache && result) {
598
+ // Store in cache — but NOT an empty result set. An empty array is
599
+ // truthy, so the old `&& result` guard cached `[]`, which is negative
600
+ // caching: the moment a concurrent writer inserts a matching row the
601
+ // cached `[]` is stale, yet a reader that filled it just before the
602
+ // writer's commit (or on a different context instance, whose cache the
603
+ // writer's invalidateTable never touches) keeps serving empty. Skipping
604
+ // empty sets means a "no rows yet" lookup always re-checks the database.
605
+ if (this.__useCache && result && result.length > 0) {
577
606
  this.__context._queryCache.set(cacheKey, result, tableName);
578
607
  }
579
608
 
package/SQLLiteEngine.js CHANGED
@@ -136,8 +136,12 @@ class SQLLiteEngine {
136
136
  }
137
137
  return Promise.resolve(null);
138
138
  } catch (err) {
139
- console.error(err);
140
- return Promise.resolve(null);
139
+ // Loud failure: never swallow a query error into a silent null.
140
+ // A missing table (the classic "SQLite dev worked, MySQL broke"
141
+ // drift) becomes a clear, actionable error naming the table.
142
+ const missing = tools.missingTableError(err);
143
+ if (missing) { throw missing; }
144
+ throw err;
141
145
  }
142
146
  }
143
147
 
@@ -209,8 +213,12 @@ class SQLLiteEngine {
209
213
  }
210
214
  return Promise.resolve(null);
211
215
  } catch (err) {
212
- console.error(err);
213
- return Promise.resolve(null);
216
+ // Loud failure: never swallow a query error into a silent null.
217
+ // A missing table (the classic "SQLite dev worked, MySQL broke"
218
+ // drift) becomes a clear, actionable error naming the table.
219
+ const missing = tools.missingTableError(err);
220
+ if (missing) { throw missing; }
221
+ throw err;
214
222
  }
215
223
  }
216
224
 
@@ -236,8 +244,12 @@ class SQLLiteEngine {
236
244
  }
237
245
  return Promise.resolve(null);
238
246
  } catch (err) {
239
- console.error(err);
240
- return Promise.resolve(null);
247
+ // Loud failure: never swallow a query error into a silent null.
248
+ // A missing table (the classic "SQLite dev worked, MySQL broke"
249
+ // drift) becomes a clear, actionable error naming the table.
250
+ const missing = tools.missingTableError(err);
251
+ if (missing) { throw missing; }
252
+ throw err;
241
253
  }
242
254
  }
243
255
 
@@ -365,7 +377,10 @@ class SQLLiteEngine {
365
377
 
366
378
  buildTake(query){
367
379
  if(query.take){
368
- return `LIMIT ${query.take}`
380
+ // Defense-in-depth: coerce to an integer at the SQL boundary. The
381
+ // `.take()` setter already validates, but LIMIT cannot be
382
+ // parameterized, so we never interpolate anything but a number.
383
+ return `LIMIT ${this._safeRowCount(query.take, 'take')}`
369
384
  }
370
385
  else{
371
386
  return "";
@@ -379,13 +394,25 @@ class SQLLiteEngine {
379
394
  // "no upper bound") so the OFFSET is valid SQL instead of a syntax
380
395
  // error. Now that .toList() no longer injects a default LIMIT 1000,
381
396
  // this is the path a bare .skip() takes.
382
- return query.take ? `OFFSET ${query.skip}` : `LIMIT -1 OFFSET ${query.skip}`;
397
+ const skip = this._safeRowCount(query.skip, 'skip');
398
+ return query.take ? `OFFSET ${skip}` : `LIMIT -1 OFFSET ${skip}`;
383
399
  }
384
400
  else{
385
401
  return "";
386
402
  }
387
403
  }
388
404
 
405
+ // Coerce a LIMIT/OFFSET value to a non-negative integer or throw. OFFSET
406
+ // and LIMIT are not parameterizable, so this is the last line of defense
407
+ // against a non-numeric (injection) value reaching the SQL string.
408
+ _safeRowCount(value, label){
409
+ const n = typeof value === 'number' ? value : Number(value);
410
+ if(!Number.isInteger(n) || n < 0 || !Number.isSafeInteger(n)){
411
+ throw new Error(`Invalid ${label} value for LIMIT/OFFSET: ${JSON.stringify(value)} (expected a non-negative integer)`);
412
+ }
413
+ return n;
414
+ }
415
+
389
416
  buildAnd(query, mainQuery){
390
417
  // loop through the AND
391
418
  // loop update ther where .expr
@@ -423,14 +450,16 @@ class SQLLiteEngine {
423
450
  }
424
451
  }
425
452
  if(item.expressions[exp].arg === "null"){
453
+ tools.assertSafeOperator(item.expressions[exp].func);
426
454
  expressions.push(`${entity}.${field} ${item.expressions[exp].func} ${item.expressions[exp].arg}`);
427
455
  }else{
428
456
  // Check if arg is a parameterized placeholder
429
457
  const isPlaceholder = (item.expressions[exp].arg === '?' || /^\$\d+$/.test(item.expressions[exp].arg));
458
+ tools.assertSafeOperator(item.expressions[exp].func);
430
459
  if(isPlaceholder){
431
460
  expressions.push(`${entity}.${field} ${item.expressions[exp].func} ${item.expressions[exp].arg}`);
432
461
  }else{
433
- expressions.push(`${entity}.${field} ${item.expressions[exp].func} '${item.expressions[exp].arg}'`);
462
+ expressions.push(`${entity}.${field} ${item.expressions[exp].func} '${tools.escapeSqlLiteral(item.expressions[exp].arg)}'`);
434
463
  }
435
464
  }
436
465
  }
@@ -490,18 +519,22 @@ class SQLLiteEngine {
490
519
  if(arg === "null"){
491
520
  if(func === "=") func = "is";
492
521
  if(func === "!=") func = "is not";
522
+ tools.assertSafeOperator(func);
493
523
  return `${ent}.${field} ${func} ${arg}`;
494
524
  }
495
525
  if(func === "IN"){
496
526
  return `${ent}.${field} ${func} ${arg}`;
497
527
  }
528
+ tools.assertSafeOperator(func);
498
529
  // Check if arg is a parameterized placeholder (? for MySQL/SQLite, $1/$2/etc for Postgres)
499
530
  const isPlaceholder = (arg === '?' || /^\$\d+$/.test(arg));
500
531
  if(isPlaceholder){
501
532
  // Don't quote placeholders - they must remain as bare ? or $1
502
533
  return `${ent}.${field} ${func} ${arg}`;
503
534
  }
504
- return `${ent}.${field} ${func} '${arg}'`;
535
+ // Literal (inline lambda constant). Escape the single quote so a
536
+ // value containing `'` can't break out of the string literal.
537
+ return `${ent}.${field} ${func} '${tools.escapeSqlLiteral(arg)}'`;
505
538
  }
506
539
 
507
540
  const pieces = [];
@@ -738,6 +771,30 @@ class SQLLiteEngine {
738
771
  );
739
772
  }
740
773
 
774
+ // True while a transaction is open. Used by saveChanges' batch fallbacks
775
+ // to decide whether to protect a bulk attempt with a SAVEPOINT.
776
+ inTransaction(){
777
+ return !!(this.db && this.db.inTransaction);
778
+ }
779
+
780
+ // Nested-rollback primitives so a failed bulk write can be undone without
781
+ // aborting the whole enclosing transaction. `name` is an internally
782
+ // generated identifier (`mr_sp_<n>`), never user input.
783
+ async savepoint(name){
784
+ return Promise.resolve(this.db.prepare(`SAVEPOINT ${name}`).run());
785
+ }
786
+
787
+ async releaseSavepoint(name){
788
+ return Promise.resolve(this.db.prepare(`RELEASE SAVEPOINT ${name}`).run());
789
+ }
790
+
791
+ async rollbackToSavepoint(name){
792
+ // ROLLBACK TO leaves the savepoint defined; RELEASE removes it so the
793
+ // savepoint stack doesn't grow across repeated fallbacks.
794
+ this.db.prepare(`ROLLBACK TO SAVEPOINT ${name}`).run();
795
+ return Promise.resolve(this.db.prepare(`RELEASE SAVEPOINT ${name}`).run());
796
+ }
797
+
741
798
  _buildSQLEqualTo(model){
742
799
  const $that = this;
743
800
  let argument = null;
package/Tools.js CHANGED
@@ -212,6 +212,82 @@ class Tools{
212
212
  num = num === 'true' ? true : (num === 'false' ? false : num);
213
213
  return num ? 1 : 0;
214
214
  }
215
+
216
+ // ---------------------------------------------------------------------
217
+ // Security helpers shared by every SQL engine (SQLite / MySQL / Postgres)
218
+ // ---------------------------------------------------------------------
219
+
220
+ // The complete set of comparison operators the query builders are allowed
221
+ // to emit into a WHERE/AND clause. `func` is derived from parsing the
222
+ // lambda source (queryScript's OPERATORS_REGEX already restricts it), but
223
+ // we re-assert the whitelist at the SQL boundary so a hand-built query
224
+ // string or a future parser change can never emit an arbitrary operator
225
+ // (which would allow SQL to be smuggled in after the column name).
226
+ static SAFE_SQL_OPERATORS = new Set([
227
+ '=', '!=', '<>', '<', '>', '<=', '>=',
228
+ 'is', 'is not', 'in', 'like', 'not like'
229
+ ]);
230
+
231
+ // Validate an operator against the whitelist. Returns the operator
232
+ // unchanged (case/whitespace-normalized) or throws. Comparison is
233
+ // case-insensitive so engines that upper-case (`IS`, `IN`) still pass.
234
+ static assertSafeOperator(func){
235
+ if(typeof func !== 'string'){
236
+ throw new Error(`Unsupported SQL operator: ${JSON.stringify(func)}`);
237
+ }
238
+ const normalized = func.trim().replace(/\s+/g, ' ').toLowerCase();
239
+ if(!Tools.SAFE_SQL_OPERATORS.has(normalized)){
240
+ throw new Error(`Unsupported SQL operator: '${func}'. Allowed: ${[...Tools.SAFE_SQL_OPERATORS].join(', ')}`);
241
+ }
242
+ return func;
243
+ }
244
+
245
+ // Detect a "table/relation does not exist" error across all three engines
246
+ // and extract the table name. Returns the name, or null if `err` is not a
247
+ // missing-table error. Signatures:
248
+ // - Postgres (42P01) : relation "x" does not exist
249
+ // - MySQL (ER_NO_SUCH_TABLE) : Table 'db.tbl' doesn't exist
250
+ // - SQLite (better-sqlite3) : no such table: tbl
251
+ static missingTableName(err){
252
+ if(!err) return null;
253
+ const msg = String(err.message || err);
254
+ let m = /relation "([^"]+)" does not exist/i.exec(msg);
255
+ if(m) return m[1];
256
+ m = /Table '(?:[^.']*\.)?([^']+)' doesn't exist/i.exec(msg);
257
+ if(m) return m[1];
258
+ m = /no such table:?\s*([A-Za-z0-9_]+)/i.exec(msg);
259
+ if(m) return m[1];
260
+ return null;
261
+ }
262
+
263
+ // Turn a missing-table driver error into a loud, actionable masterrecord
264
+ // error, or null if `err` isn't one. This is what stops schema drift from
265
+ // accumulating silently: a query against a not-yet-migrated table fails
266
+ // with a clear message on EVERY engine instead of quietly returning null
267
+ // (which made SQLite dev "just work" while MySQL/Postgres broke later).
268
+ static missingTableError(err){
269
+ const name = Tools.missingTableName(err);
270
+ if(!name) return null;
271
+ const friendly = new Error(
272
+ `masterrecord: table '${name}' does not exist. If this is a new entity, ` +
273
+ `generate and run a migration first ` +
274
+ `(npx masterrecord add-migration <name> <context> && npx masterrecord update-database <context>). ` +
275
+ `Original error: ${err.message || err}`
276
+ );
277
+ friendly.cause = err;
278
+ friendly.missingTable = name;
279
+ return friendly;
280
+ }
281
+
282
+ // Escape a value for safe interpolation inside a single-quoted SQL string
283
+ // literal. Doubling the single quote is the ANSI-standard escape and is
284
+ // correct on SQLite, MySQL, and Postgres (with standard_conforming_strings,
285
+ // the default). Runtime user values should still go through `$$`/`$`
286
+ // parameter binding; this protects the literal path (inline lambda
287
+ // constants, string-built queries) as defense-in-depth.
288
+ static escapeSqlLiteral(value){
289
+ return String(value).replace(/'/g, "''");
290
+ }
215
291
  }
216
292
 
217
293
  export default Tools;