@memberjunction/generic-database-provider 6.2.2 → 6.3.0-edge.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.
Files changed (42) hide show
  1. package/dist/GenericDatabaseProvider.d.ts +198 -20
  2. package/dist/GenericDatabaseProvider.d.ts.map +1 -1
  3. package/dist/GenericDatabaseProvider.js +1318 -157
  4. package/dist/GenericDatabaseProvider.js.map +1 -1
  5. package/dist/NodeAsyncServerOperationScopeTracker.d.ts +20 -0
  6. package/dist/NodeAsyncServerOperationScopeTracker.d.ts.map +1 -0
  7. package/dist/NodeAsyncServerOperationScopeTracker.js +30 -0
  8. package/dist/NodeAsyncServerOperationScopeTracker.js.map +1 -0
  9. package/dist/UserCache.d.ts +32 -0
  10. package/dist/UserCache.d.ts.map +1 -1
  11. package/dist/UserCache.js +111 -12
  12. package/dist/UserCache.js.map +1 -1
  13. package/dist/clientClauseScreen.d.ts +62 -0
  14. package/dist/clientClauseScreen.d.ts.map +1 -1
  15. package/dist/clientClauseScreen.js +800 -2
  16. package/dist/clientClauseScreen.js.map +1 -1
  17. package/dist/concurrency/fieldConflictDetector.d.ts +82 -0
  18. package/dist/concurrency/fieldConflictDetector.d.ts.map +1 -0
  19. package/dist/concurrency/fieldConflictDetector.js +285 -0
  20. package/dist/concurrency/fieldConflictDetector.js.map +1 -0
  21. package/dist/countOnlyBatch.d.ts +5 -1
  22. package/dist/countOnlyBatch.d.ts.map +1 -1
  23. package/dist/countOnlyBatch.js +6 -2
  24. package/dist/countOnlyBatch.js.map +1 -1
  25. package/dist/index.d.ts +9 -0
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +5 -0
  28. package/dist/index.js.map +1 -1
  29. package/dist/recordChangeSnapshot.d.ts +28 -0
  30. package/dist/recordChangeSnapshot.d.ts.map +1 -1
  31. package/dist/recordChangeSnapshot.js +66 -0
  32. package/dist/recordChangeSnapshot.js.map +1 -1
  33. package/dist/rowFilterParameters.d.ts +22 -0
  34. package/dist/rowFilterParameters.d.ts.map +1 -0
  35. package/dist/rowFilterParameters.js +23 -0
  36. package/dist/rowFilterParameters.js.map +1 -0
  37. package/dist/serverPrincipal.d.ts +45 -0
  38. package/dist/serverPrincipal.d.ts.map +1 -0
  39. package/dist/serverPrincipal.js +46 -0
  40. package/dist/serverPrincipal.js.map +1 -0
  41. package/dist/tsconfig.tsbuildinfo +1 -0
  42. package/package.json +14 -14
@@ -1,6 +1,7 @@
1
- import { CurrentFieldSecurityGeneration, EntityPermissionType, IsPlatformSQL } from '@memberjunction/core';
2
- import { FindForbiddenFunctionCalls, IsKeyword, LexSQL, SignificantTokens, SQLParser, StrictFragmentValidator, } from '@memberjunction/sql-parser';
1
+ import { CurrentFieldSecurityGeneration, EntityPermissionType, IsPlatformSQL, IsPostRunViewProtectedEntity } from '@memberjunction/core';
2
+ import { FindForbiddenFunctionCalls, IsKeyword, LexSQL, SignificantTokens, SqlDocument, SQLParser, StrictFragmentValidator, } from '@memberjunction/sql-parser';
3
3
  import { PostgreSQLDialect, SQLServerDialect } from '@memberjunction/sql-dialect';
4
+ import { FindProjectionStars } from './fieldSecurity/projectionStars.js';
4
5
  /** True when `provider` can screen client SQL clauses. */
5
6
  export function IsClientClauseScreeningProvider(provider) {
6
7
  return !!provider && 'ScreenClientClause' in provider && typeof provider.ScreenClientClause === 'function';
@@ -275,6 +276,9 @@ export class ClientClauseScreen {
275
276
  * does. For any other entity, a granted read covers every row and field of its base view.
276
277
  */
277
278
  static AssertUnscopedRead(entity, user, label) {
279
+ if (IsPostRunViewProtectedEntity(entity.Name)) {
280
+ throw new Error(`Invalid ${label}: entity '${entity.Name}' enforces row-level access via server RunView hooks — SQL that reads its base view directly cannot apply those hooks; read that entity with RunView`);
281
+ }
278
282
  if (entity.GetEffectiveRowFilterWhereClause(user, EntityPermissionType.Read, '').length > 0) {
279
283
  throw new Error(`Invalid ${label}: entity '${entity.Name}' is row-level-security filtered for you — SQL that reads its base view directly cannot apply that filter; read that entity with RunView`);
280
284
  }
@@ -302,6 +306,800 @@ export class ClientClauseScreen {
302
306
  ClientClauseScreen.AssertUnscopedRead(entity, user, label);
303
307
  }
304
308
  }
309
+ /**
310
+ * Parses a read-only SQL statement and resolves every non-CTE FROM/JOIN relation to its
311
+ * corresponding {@link EntityInfo} (matching entity base views, usable alternate base views,
312
+ * or entity base tables). Throws if the statement is not a single read-only SELECT, if any
313
+ * subquery cannot be accounted for, or if any relation does not resolve unambiguously to an
314
+ * entity in `entities`.
315
+ */
316
+ static ResolveStatementEntities(sql, entities, dialect, label = 'SQL') {
317
+ ClientClauseScreen.AssertNoIdentifierAliasNames(sql, dialect, label);
318
+ ClientClauseScreen.AssertNoForbiddenFunctionCalls(sql, dialect, label);
319
+ const reads = ClientClauseScreen.readOnlyStatementReads(sql, dialect, label);
320
+ ClientClauseScreen.AssertEverySelectAccountedFor(sql, dialect, reads, label);
321
+ const viewAllowList = ClientClauseScreen.BuildEntityBaseViewAllowList(entities);
322
+ const tableAllowList = ClientClauseScreen.buildBaseTableAllowList(entities);
323
+ const resolved = new Map();
324
+ for (const relation of reads.Relations) {
325
+ if (relation.IsCTEReference)
326
+ continue;
327
+ if (!relation.TableName) {
328
+ const fnName = relation.FunctionName;
329
+ if (fnName && !relation.SchemaName && ClientClauseScreen.ARGUMENT_ONLY_TABLE_FUNCTIONS.has(fnName.toLowerCase())) {
330
+ continue;
331
+ }
332
+ const source = fnName ? `the table function '${[relation.SchemaName, fnName].filter(Boolean).join('.')}'` : 'a row source it cannot identify';
333
+ throw new Error(`Invalid ${label}: query may read only registered entities, not ${source}`);
334
+ }
335
+ const entity = ClientClauseScreen.resolveEntityRelation(viewAllowList, tableAllowList, relation.SchemaName, relation.TableName, label);
336
+ resolved.set(entity.ID || entity.Name, entity);
337
+ }
338
+ return Array.from(resolved.values());
339
+ }
340
+ /**
341
+ * Returns all bare/unquoted word and quoted-identifier tokens appearing in `sql` (quotes stripped),
342
+ * excluding string literals and comments. Used by agent data-policy guards to refuse ad-hoc SQL
343
+ * that references denied field names via column aliases or WHERE predicates.
344
+ */
345
+ static ExtractStatementIdentifierTokens(sql, dialect) {
346
+ const tokens = LexSQL(sql, dialect);
347
+ const names = new Set();
348
+ for (const token of tokens) {
349
+ if (token.Kind === 'word' || token.Kind === 'identifier') {
350
+ const stripped = ClientClauseScreen.StripIdentifierQuotes(token.Text).trim();
351
+ if (stripped.length > 0) {
352
+ names.add(stripped);
353
+ }
354
+ }
355
+ }
356
+ return Array.from(names);
357
+ }
358
+ /**
359
+ * Refuses statement separators, comments, or unbalanced parentheses outside string literals
360
+ * and quoted identifiers. Prevents `(${agentFilter}) AND (${policy})` breakout payloads such
361
+ * as `1=1) OR (1=1` where parenthesis depth drops below zero mid-fragment.
362
+ */
363
+ static AssertBalancedSingleFragment(clause, label, dialect) {
364
+ if (clause == null || clause === '')
365
+ return;
366
+ ClientClauseScreen.AssertSingleStatementFragment(clause, label, dialect);
367
+ let depth = 0;
368
+ for (const token of LexSQL(clause, dialect)) {
369
+ if (token.Kind === 'open') {
370
+ depth++;
371
+ }
372
+ else if (token.Kind === 'close') {
373
+ depth--;
374
+ if (depth < 0) {
375
+ throw new Error(`Invalid ${label}: unbalanced closing parenthesis in SQL fragment`);
376
+ }
377
+ }
378
+ }
379
+ if (depth !== 0) {
380
+ throw new Error(`Invalid ${label}: unbalanced opening parenthesis in SQL fragment`);
381
+ }
382
+ }
383
+ /**
384
+ * Screens an agent-supplied `Filter` or `OrderBy` fragment (requiring balanced parentheses,
385
+ * a single read-only fragment, no forbidden functions, and only readable entity base views in
386
+ * any subqueries) and returns every subquery {@link EntityInfo} referenced so callers can
387
+ * additionally enforce agent-level entity policies on subquery targets.
388
+ */
389
+ static ScreenAgentClause(clause, label, entities, dialect, user) {
390
+ if (!clause?.trim())
391
+ return [];
392
+ ClientClauseScreen.AssertBalancedSingleFragment(clause, label, dialect);
393
+ if (SQLParser.HasStackedStatements(clause, dialect)) {
394
+ throw new Error(`Invalid ${label}: multiple statements are not permitted in filters or sort clauses`);
395
+ }
396
+ const fragment = ClientClauseScreen.toDialectQuoting(clause, dialect);
397
+ ClientClauseScreen.AssertNoIdentifierAliasNames(fragment, dialect, label);
398
+ ClientClauseScreen.AssertNoForbiddenFunctionCalls(fragment, dialect, label);
399
+ const result = label === 'OrderBy'
400
+ ? StrictFragmentValidator.ValidateOrderBy(fragment, dialect, { CollectReads: true })
401
+ : StrictFragmentValidator.ValidateFilter(fragment, dialect, { CollectReads: true });
402
+ const reads = ClientClauseScreen.safeReadsOf(result, `Invalid ${label}: not a safe read-only ${label === 'OrderBy' ? 'sort' : 'filter'} fragment — refusing under uncertainty`, label);
403
+ ClientClauseScreen.AssertEverySelectAccountedFor(result.ParsedSQL, dialect, reads, label);
404
+ if (reads.Relations.length === 0) {
405
+ return [];
406
+ }
407
+ const allowed = ClientClauseScreen.BuildEntityBaseViewAllowList(entities);
408
+ const referenced = new Map();
409
+ for (const relation of reads.Relations) {
410
+ const entity = ClientClauseScreen.AssertRelationReadable(allowed, relation, label, user);
411
+ if (entity) {
412
+ if (user) {
413
+ ClientClauseScreen.AssertUnscopedRead(entity, user, label);
414
+ }
415
+ referenced.set(entity.ID || entity.Name, entity);
416
+ }
417
+ }
418
+ return Array.from(referenced.values());
419
+ }
420
+ static { this.WHOLE_ROW_SERIALIZATION_FUNCTIONS = new Set([
421
+ 'to_json',
422
+ 'to_jsonb',
423
+ 'row_to_json',
424
+ 'json_agg',
425
+ 'jsonb_agg',
426
+ 'record_to_json',
427
+ 'checksum',
428
+ 'binary_checksum',
429
+ ]); }
430
+ /**
431
+ * Refuses SQL constructs that rename, serialize, or sort by columns without naming the underlying
432
+ * source column when field-level masking is active:
433
+ * 1. CTE explicit column-alias lists (`WITH c(a, b) AS (SELECT * FROM ...)` at any depth)
434
+ * 2. Derived-table column-alias lists (`FROM (SELECT * FROM ...) AS t(a, b)`)
435
+ * 3. Set operations (`UNION` / `INTERSECT` / `EXCEPT`) combined with wildcard (`*`) projections
436
+ * 4. Whole-row constructs (`FOR JSON`, `FOR XML`, `NATURAL JOIN`, `to_jsonb(e)` / `row_to_json(e)`,
437
+ * bare whole-row relation references, non-projection `*` / `alias.*` wildcards inside subqueries
438
+ * or expressions, and ordinal `ORDER BY` / `GROUP BY`).
439
+ */
440
+ static AssertNoPositionalColumnRenames(sql, dialect, label = 'SQL') {
441
+ const tokens = SignificantTokens(LexSQL(sql, dialect));
442
+ if (tokens.length === 0)
443
+ return;
444
+ const keywordAllowedBeforeOpenAfterClose = new Set([
445
+ 'and', 'or', 'in', 'not', 'over', 'filter', 'within', 'values',
446
+ 'where', 'on', 'having', 'when', 'then', 'else', 'between',
447
+ 'union', 'intersect', 'except', 'select', 'from', 'join',
448
+ ]);
449
+ let depth = 0;
450
+ const depths = [];
451
+ for (const tok of tokens) {
452
+ if (tok.Kind === 'close') {
453
+ depth = Math.max(0, depth - 1);
454
+ }
455
+ depths.push(depth);
456
+ if (tok.Kind === 'open') {
457
+ depth++;
458
+ }
459
+ }
460
+ // 1. Check CTE header column lists at ANY nesting depth: `<cte_name> ( ... ) AS [ [NOT] MATERIALIZED ] (`
461
+ for (let i = 0; i < tokens.length; i++) {
462
+ if ((tokens[i].Kind === 'word' || tokens[i].Kind === 'identifier') && tokens[i + 1]?.Kind === 'open') {
463
+ const isCteHeaderKeyword = IsKeyword(tokens[i], 'AS') ||
464
+ IsKeyword(tokens[i], 'WITH') ||
465
+ IsKeyword(tokens[i], 'SELECT') ||
466
+ IsKeyword(tokens[i], 'MATERIALIZED') ||
467
+ IsKeyword(tokens[i], 'NOT');
468
+ if (!isCteHeaderKeyword) {
469
+ const targetDepth = depths[i];
470
+ let closeIdx = -1;
471
+ for (let j = i + 2; j < tokens.length; j++) {
472
+ if (tokens[j].Kind === 'close' && depths[j] === targetDepth) {
473
+ closeIdx = j;
474
+ break;
475
+ }
476
+ }
477
+ if (closeIdx > i + 1 && closeIdx + 1 < tokens.length && IsKeyword(tokens[closeIdx + 1], 'AS')) {
478
+ let afterAs = closeIdx + 2;
479
+ if (afterAs < tokens.length && IsKeyword(tokens[afterAs], 'NOT')) {
480
+ afterAs++;
481
+ }
482
+ if (afterAs < tokens.length && IsKeyword(tokens[afterAs], 'MATERIALIZED')) {
483
+ afterAs++;
484
+ }
485
+ if (afterAs < tokens.length && tokens[afterAs].Kind === 'open') {
486
+ throw new Error(`Invalid ${label}: CTE column-alias lists are not permitted when field-level masking is active`);
487
+ }
488
+ }
489
+ }
490
+ }
491
+ }
492
+ // 2. Check derived-table column lists, set operations + *, FOR JSON/XML, whole-row functions, and ordinal ORDER/GROUP BY
493
+ let hasSetOp = false;
494
+ let hasWildcardStar = false;
495
+ for (let i = 0; i < tokens.length; i++) {
496
+ const tok = tokens[i];
497
+ if (IsKeyword(tok, 'UNION') || IsKeyword(tok, 'INTERSECT') || IsKeyword(tok, 'EXCEPT')) {
498
+ hasSetOp = true;
499
+ }
500
+ if (IsKeyword(tok, 'FOR') && tokens[i + 1] && (IsKeyword(tokens[i + 1], 'JSON') || IsKeyword(tokens[i + 1], 'XML'))) {
501
+ throw new Error(`Invalid ${label}: FOR ${tokens[i + 1].Text.toUpperCase()} is not permitted when field-level masking is active`);
502
+ }
503
+ if (IsKeyword(tok, 'NATURAL') && tokens[i + 1] && IsKeyword(tokens[i + 1], 'JOIN')) {
504
+ throw new Error(`Invalid ${label}: NATURAL JOIN is not permitted when field-level masking is active`);
505
+ }
506
+ if ((tok.Kind === 'word' || tok.Kind === 'identifier') && tokens[i + 1]?.Kind === 'open') {
507
+ const fnLower = ClientClauseScreen.StripIdentifierQuotes(tok.Text).trim().toLowerCase();
508
+ if (ClientClauseScreen.WHOLE_ROW_SERIALIZATION_FUNCTIONS.has(fnLower)) {
509
+ throw new Error(`Invalid ${label}: whole-row function ${tok.Text}() is not permitted when field-level masking is active`);
510
+ }
511
+ }
512
+ if ((IsKeyword(tok, 'ORDER') || IsKeyword(tok, 'GROUP')) && tokens[i + 1] && IsKeyword(tokens[i + 1], 'BY')) {
513
+ const clauseDepth = depths[i];
514
+ let itemStart = true;
515
+ for (let j = i + 2; j < tokens.length; j++) {
516
+ if (depths[j] < clauseDepth && tokens[j].Kind === 'close') {
517
+ break;
518
+ }
519
+ if (depths[j] === clauseDepth) {
520
+ if (IsKeyword(tokens[j], 'OFFSET') ||
521
+ IsKeyword(tokens[j], 'FETCH') ||
522
+ IsKeyword(tokens[j], 'LIMIT') ||
523
+ IsKeyword(tokens[j], 'FOR') ||
524
+ IsKeyword(tokens[j], 'HAVING') ||
525
+ IsKeyword(tokens[j], 'ORDER') ||
526
+ IsKeyword(tokens[j], 'UNION') ||
527
+ IsKeyword(tokens[j], 'INTERSECT') ||
528
+ IsKeyword(tokens[j], 'EXCEPT')) {
529
+ break;
530
+ }
531
+ if (itemStart) {
532
+ const isSignedNum = tokens[j].Kind === 'operator' &&
533
+ (tokens[j].Text === '+' || tokens[j].Text === '-') &&
534
+ tokens[j + 1]?.Kind === 'number';
535
+ if (tokens[j].Kind === 'number' || isSignedNum) {
536
+ throw new Error(`Invalid ${label}: ordinal ${tok.Text.toUpperCase()} BY is not permitted when field-level masking is active`);
537
+ }
538
+ }
539
+ itemStart = tokens[j].Kind === 'comma';
540
+ }
541
+ else {
542
+ itemStart = false;
543
+ }
544
+ }
545
+ }
546
+ if (tok.Text === '*' || (tok.Kind === 'operator' && tok.Text.includes('*'))) {
547
+ const prev = i > 0 ? tokens[i - 1] : undefined;
548
+ if (!prev ||
549
+ prev.Kind === 'comma' ||
550
+ prev.Kind === 'dot' ||
551
+ IsKeyword(prev, 'SELECT') ||
552
+ IsKeyword(prev, 'DISTINCT') ||
553
+ IsKeyword(prev, 'ALL')) {
554
+ hasWildcardStar = true;
555
+ }
556
+ }
557
+ if (tok.Kind === 'close') {
558
+ const next1 = tokens[i + 1];
559
+ const next2 = tokens[i + 2];
560
+ const next3 = tokens[i + 3];
561
+ if (next1 &&
562
+ IsKeyword(next1, 'AS') &&
563
+ next2 &&
564
+ (next2.Kind === 'word' || next2.Kind === 'identifier') &&
565
+ next3?.Kind === 'open') {
566
+ throw new Error(`Invalid ${label}: derived-table column-alias lists are not permitted when field-level masking is active`);
567
+ }
568
+ if (next1 &&
569
+ (next1.Kind === 'word' || next1.Kind === 'identifier') &&
570
+ !keywordAllowedBeforeOpenAfterClose.has(ClientClauseScreen.StripIdentifierQuotes(next1.Text).trim().toLowerCase()) &&
571
+ next2?.Kind === 'open') {
572
+ throw new Error(`Invalid ${label}: derived-table column-alias lists are not permitted when field-level masking is active`);
573
+ }
574
+ }
575
+ }
576
+ // 3. Check set operations with wildcard projections
577
+ if (hasSetOp && hasWildcardStar) {
578
+ throw new Error(`Invalid ${label}: set operations (UNION/INTERSECT/EXCEPT) with wildcard (*) projections are not permitted when field-level masking is active`);
579
+ }
580
+ // 4. Parse with SqlDocument and check CTEs() + WholeRowConstructs() + FindProjectionStars()
581
+ const parserDialect = 'Key' in dialect && 'Lexical' in dialect && 'Grammar' in dialect
582
+ ? dialect
583
+ : dialect.QuoteIdentifier('x').startsWith('[')
584
+ ? new SQLServerDialect()
585
+ : new PostgreSQLDialect();
586
+ const doc = SqlDocument.Parse(sql, parserDialect);
587
+ const ctes = doc.CTEs();
588
+ if (ctes.Complete && ctes.Value.some((c) => c.ColumnList !== null && c.ColumnList.length > 0)) {
589
+ throw new Error(`Invalid ${label}: CTE column-alias lists are not permitted when field-level masking is active`);
590
+ }
591
+ const wholeRow = doc.WholeRowConstructs();
592
+ if (!wholeRow.Complete) {
593
+ throw new Error(`Invalid ${label}: whole-row construct analysis could not complete safely when field-level masking is active`);
594
+ }
595
+ if (wholeRow.Value.length > 0) {
596
+ const projectionStars = FindProjectionStars(sql, parserDialect);
597
+ for (const construct of wholeRow.Value) {
598
+ switch (construct.Kind) {
599
+ case 'ForDocument':
600
+ throw new Error(`Invalid ${label}: ${construct.Detail} is not permitted when field-level masking is active`);
601
+ case 'RowFunction':
602
+ case 'RowReference':
603
+ throw new Error(`Invalid ${label}: whole-row construct (${construct.Detail}) is not permitted when field-level masking is active`);
604
+ case 'NaturalJoin':
605
+ throw new Error(`Invalid ${label}: NATURAL JOIN is not permitted when field-level masking is active`);
606
+ case 'OrdinalOrderBy':
607
+ throw new Error(`Invalid ${label}: ordinal ${construct.Detail} is not permitted when field-level masking is active`);
608
+ case 'Star':
609
+ case 'QualifiedStar': {
610
+ const starOffset = sql.lastIndexOf('*', construct.Span.End - 1);
611
+ const isExistsSelectStar = construct.Kind === 'Star' &&
612
+ /\bEXISTS\s*\(\s*SELECT\s*$/i.test(sql.slice(0, construct.Span.Start));
613
+ if (!isExistsSelectStar && (starOffset < construct.Span.Start || !projectionStars.has(starOffset))) {
614
+ throw new Error(`Invalid ${label}: non-projection wildcard (${construct.Detail}) is not permitted when field-level masking is active`);
615
+ }
616
+ break;
617
+ }
618
+ default:
619
+ break;
620
+ }
621
+ }
622
+ }
623
+ }
624
+ /**
625
+ * Refuses whole-row constructs (`FOR JSON`/`FOR XML`, `to_jsonb(e)` / `row_to_json(e)`,
626
+ * subquery `*`/`alias.*`, CTE/derived-table column lists) and ordinal `ORDER BY` inside a
627
+ * `Filter` or `OrderBy` fragment when the target entity or any subquery entity has denied fields.
628
+ */
629
+ static AssertNoWholeRowOrOrdinalInClause(clause, label, dialect) {
630
+ if (!clause?.trim())
631
+ return;
632
+ const fragment = ClientClauseScreen.toDialectQuoting(clause, dialect);
633
+ const quotedSchema = dialect.QuoteIdentifier('__mj');
634
+ const quotedView = dialect.QuoteIdentifier('vw_clause_check');
635
+ const wrappedSql = label === 'OrderBy'
636
+ ? `SELECT 1 FROM ${quotedSchema}.${quotedView} ORDER BY ${fragment}`
637
+ : `SELECT 1 FROM ${quotedSchema}.${quotedView} WHERE ${fragment}`;
638
+ ClientClauseScreen.AssertNoPositionalColumnRenames(wrappedSql, dialect, label);
639
+ }
640
+ /**
641
+ * Inspects a stored query's rendered SQL and returns any denied field identifiers that appear
642
+ * anywhere OTHER than a pure, unaliased top-level `SELECT` projection column (`Col`, `t.Col`,
643
+ * or `s.t.Col`). Pure unaliased top-level columns preserve their field name in the result set
644
+ * and are stripped by `AgentDataPolicyGuard.MaskRows`; aliases (`Salary AS Contact`),
645
+ * expressions/aggregates (`MAX(Salary)`), predicates (`WHERE Salary > ...`), and sorts
646
+ * (`ORDER BY Salary`) cannot be stripped safely by output column name and are therefore refused.
647
+ */
648
+ static FindUnmaskableStoredQueryDeniedFields(sql, dialect, isFieldDenied) {
649
+ const tokens = SignificantTokens(LexSQL(sql, dialect));
650
+ if (tokens.length === 0)
651
+ return [];
652
+ let depth = 0;
653
+ const depths = [];
654
+ for (const tok of tokens) {
655
+ if (tok.Kind === 'close') {
656
+ depth = Math.max(0, depth - 1);
657
+ }
658
+ depths.push(depth);
659
+ if (tok.Kind === 'open') {
660
+ depth++;
661
+ }
662
+ }
663
+ const topSelectIdx = tokens.findIndex((t, i) => depths[i] === 0 && IsKeyword(t, 'SELECT'));
664
+ if (topSelectIdx < 0) {
665
+ return ClientClauseScreen.ExtractStatementIdentifierTokens(sql, dialect).filter(isFieldDenied);
666
+ }
667
+ let projStart = topSelectIdx + 1;
668
+ if (projStart < tokens.length &&
669
+ depths[projStart] === 0 &&
670
+ (IsKeyword(tokens[projStart], 'DISTINCT') || IsKeyword(tokens[projStart], 'ALL'))) {
671
+ projStart++;
672
+ }
673
+ if (projStart < tokens.length && depths[projStart] === 0 && IsKeyword(tokens[projStart], 'TOP')) {
674
+ projStart++;
675
+ if (projStart < tokens.length && tokens[projStart].Kind === 'open') {
676
+ projStart++;
677
+ while (projStart < tokens.length && !(tokens[projStart].Kind === 'close' && depths[projStart] === 0)) {
678
+ projStart++;
679
+ }
680
+ if (projStart < tokens.length)
681
+ projStart++;
682
+ }
683
+ else if (projStart < tokens.length && tokens[projStart].Kind === 'number') {
684
+ projStart++;
685
+ }
686
+ if (projStart < tokens.length && depths[projStart] === 0 && IsKeyword(tokens[projStart], 'PERCENT')) {
687
+ projStart++;
688
+ }
689
+ }
690
+ let projEnd = tokens.length;
691
+ for (let i = projStart; i < tokens.length; i++) {
692
+ if (depths[i] === 0 &&
693
+ (IsKeyword(tokens[i], 'FROM') ||
694
+ IsKeyword(tokens[i], 'INTO') ||
695
+ IsKeyword(tokens[i], 'WHERE') ||
696
+ IsKeyword(tokens[i], 'GROUP') ||
697
+ IsKeyword(tokens[i], 'HAVING') ||
698
+ IsKeyword(tokens[i], 'ORDER') ||
699
+ IsKeyword(tokens[i], 'UNION') ||
700
+ IsKeyword(tokens[i], 'INTERSECT') ||
701
+ IsKeyword(tokens[i], 'EXCEPT'))) {
702
+ projEnd = i;
703
+ break;
704
+ }
705
+ }
706
+ const unmaskable = new Set();
707
+ const checkToken = (tok) => {
708
+ if (tok.Kind === 'word' || tok.Kind === 'identifier') {
709
+ const name = ClientClauseScreen.StripIdentifierQuotes(tok.Text).trim();
710
+ if (name.length > 0 && isFieldDenied(name)) {
711
+ unmaskable.add(name);
712
+ }
713
+ }
714
+ };
715
+ // Any denied field before projStart (e.g., inside WITH CTEs or TOP expression) is unmaskable
716
+ for (let i = 0; i < projStart; i++) {
717
+ checkToken(tokens[i]);
718
+ }
719
+ // Split top-level projection items by comma at depth 0
720
+ const items = [];
721
+ let current = [];
722
+ for (let i = projStart; i < projEnd; i++) {
723
+ if (depths[i] === 0 && tokens[i].Kind === 'comma') {
724
+ items.push(current);
725
+ current = [];
726
+ }
727
+ else {
728
+ current.push(tokens[i]);
729
+ }
730
+ }
731
+ if (current.length > 0) {
732
+ items.push(current);
733
+ }
734
+ const isPlainColumnIdent = (tok) => (tok.Kind === 'word' || tok.Kind === 'identifier') &&
735
+ !IsKeyword(tok, 'AS') &&
736
+ !IsKeyword(tok, 'NULL') &&
737
+ !IsKeyword(tok, 'TRUE') &&
738
+ !IsKeyword(tok, 'FALSE') &&
739
+ !IsKeyword(tok, 'CASE') &&
740
+ !IsKeyword(tok, 'DISTINCT');
741
+ for (const item of items) {
742
+ const isPureUnaliasedColumn = (item.length === 1 && isPlainColumnIdent(item[0])) ||
743
+ (item.length === 3 &&
744
+ isPlainColumnIdent(item[0]) &&
745
+ item[1].Kind === 'dot' &&
746
+ isPlainColumnIdent(item[2])) ||
747
+ (item.length === 5 &&
748
+ isPlainColumnIdent(item[0]) &&
749
+ item[1].Kind === 'dot' &&
750
+ isPlainColumnIdent(item[2]) &&
751
+ item[3].Kind === 'dot' &&
752
+ isPlainColumnIdent(item[4]));
753
+ if (!isPureUnaliasedColumn) {
754
+ for (const tok of item) {
755
+ checkToken(tok);
756
+ }
757
+ }
758
+ }
759
+ // Any denied field at or after projEnd (FROM/JOIN/WHERE/GROUP/HAVING/ORDER/UNION) is unmaskable
760
+ // (skipping the immediate relation name right after FROM or JOIN so view names don't false-positive)
761
+ for (let i = projEnd; i < tokens.length; i++) {
762
+ if (IsKeyword(tokens[i], 'FROM') || IsKeyword(tokens[i], 'JOIN')) {
763
+ let relIdx = i + 1;
764
+ while (relIdx + 1 < tokens.length &&
765
+ (tokens[relIdx].Kind === 'word' || tokens[relIdx].Kind === 'identifier') &&
766
+ tokens[relIdx + 1].Kind === 'dot') {
767
+ relIdx += 2;
768
+ }
769
+ if (relIdx < tokens.length &&
770
+ (tokens[relIdx].Kind === 'word' || tokens[relIdx].Kind === 'identifier')) {
771
+ i = relIdx;
772
+ continue;
773
+ }
774
+ }
775
+ checkToken(tokens[i]);
776
+ }
777
+ return Array.from(unmaskable);
778
+ }
779
+ /**
780
+ * Evaluates a simple SQL `WHERE` predicate against an in-memory record map for lightweight
781
+ * providers that do not expose a live SQL execution engine (e.g. unit-test metadata mocks).
782
+ * Fails closed (`false`) on any subquery, function call, or unrecognized SQL construct.
783
+ */
784
+ static EvaluateSimpleSqlWherePredicate(whereClause, record, dialect) {
785
+ const trimmed = whereClause.trim();
786
+ if (trimmed.length === 0)
787
+ return true;
788
+ try {
789
+ ClientClauseScreen.AssertBalancedSingleFragment(trimmed, 'PolicyWhereClause', dialect);
790
+ }
791
+ catch {
792
+ return false;
793
+ }
794
+ const tokens = SignificantTokens(LexSQL(trimmed, dialect));
795
+ if (tokens.length === 0)
796
+ return true;
797
+ const recordByLowerKey = new Map();
798
+ for (const [k, v] of Object.entries(record)) {
799
+ recordByLowerKey.set(k.trim().toLowerCase(), v);
800
+ }
801
+ let pos = 0;
802
+ const peek = () => tokens[pos];
803
+ const consume = () => tokens[pos++];
804
+ const readLiteral = () => {
805
+ const tok = peek();
806
+ if (!tok)
807
+ return { ok: false };
808
+ if (tok.Kind === 'string') {
809
+ consume();
810
+ const raw = tok.Text.replace(/^[NnEe]'/, "'");
811
+ if (raw.startsWith("'") && raw.endsWith("'")) {
812
+ return { ok: true, value: raw.slice(1, -1).replace(/''/g, "'") };
813
+ }
814
+ return { ok: false };
815
+ }
816
+ if (tok.Kind === 'operator' && (tok.Text === '-' || tok.Text === '+')) {
817
+ const sign = tok.Text === '-' ? -1 : 1;
818
+ consume();
819
+ const numTok = peek();
820
+ if (!numTok || numTok.Kind !== 'number')
821
+ return { ok: false };
822
+ consume();
823
+ const parsed = Number(numTok.Text);
824
+ return Number.isFinite(parsed) ? { ok: true, value: sign * parsed } : { ok: false };
825
+ }
826
+ if (tok.Kind === 'number') {
827
+ consume();
828
+ const parsed = Number(tok.Text);
829
+ return Number.isFinite(parsed) ? { ok: true, value: parsed } : { ok: false };
830
+ }
831
+ if (tok.Kind === 'word') {
832
+ if (IsKeyword(tok, 'NULL')) {
833
+ consume();
834
+ return { ok: true, value: null };
835
+ }
836
+ if (IsKeyword(tok, 'TRUE')) {
837
+ consume();
838
+ return { ok: true, value: true };
839
+ }
840
+ if (IsKeyword(tok, 'FALSE')) {
841
+ consume();
842
+ return { ok: true, value: false };
843
+ }
844
+ }
845
+ return { ok: false };
846
+ };
847
+ const compareValues = (actual, op, expected) => {
848
+ if (actual === null || actual === undefined || expected === null) {
849
+ return false;
850
+ }
851
+ if (typeof expected === 'number' || typeof actual === 'number') {
852
+ const leftNum = typeof actual === 'boolean' ? (actual ? 1 : 0) : Number(actual);
853
+ const rightNum = typeof expected === 'boolean' ? (expected ? 1 : 0) : Number(expected);
854
+ if (!Number.isFinite(leftNum) || !Number.isFinite(rightNum))
855
+ return false;
856
+ switch (op) {
857
+ case '=': return leftNum === rightNum;
858
+ case '!=':
859
+ case '<>': return leftNum !== rightNum;
860
+ case '<': return leftNum < rightNum;
861
+ case '<=': return leftNum <= rightNum;
862
+ case '>': return leftNum > rightNum;
863
+ case '>=': return leftNum >= rightNum;
864
+ default: return false;
865
+ }
866
+ }
867
+ if (typeof expected === 'boolean' || typeof actual === 'boolean') {
868
+ const leftBool = typeof actual === 'boolean' ? actual : String(actual).toLowerCase() === 'true' || actual === '1';
869
+ const rightBool = typeof expected === 'boolean' ? expected : String(expected).toLowerCase() === 'true' || expected === '1';
870
+ if (op === '=')
871
+ return leftBool === rightBool;
872
+ if (op === '!=' || op === '<>')
873
+ return leftBool !== rightBool;
874
+ return false;
875
+ }
876
+ const leftStr = actual instanceof Date ? actual.toISOString() : String(actual);
877
+ const rightStr = String(expected);
878
+ const leftLower = leftStr.toLowerCase();
879
+ const rightLower = rightStr.toLowerCase();
880
+ switch (op) {
881
+ case '=': return leftLower === rightLower;
882
+ case '!=':
883
+ case '<>': return leftLower !== rightLower;
884
+ case '<': return leftLower < rightLower;
885
+ case '<=': return leftLower <= rightLower;
886
+ case '>': return leftLower > rightLower;
887
+ case '>=': return leftLower >= rightLower;
888
+ default: return false;
889
+ }
890
+ };
891
+ const parseOr = () => {
892
+ let left = parseAnd();
893
+ if (!left.ok)
894
+ return left;
895
+ while (peek() && IsKeyword(peek(), 'OR')) {
896
+ consume();
897
+ const right = parseAnd();
898
+ if (!right.ok)
899
+ return right;
900
+ left = { ok: true, value: left.value || right.value };
901
+ }
902
+ return left;
903
+ };
904
+ const parseAnd = () => {
905
+ let left = parseNot();
906
+ if (!left.ok)
907
+ return left;
908
+ while (peek() && IsKeyword(peek(), 'AND')) {
909
+ consume();
910
+ const right = parseNot();
911
+ if (!right.ok)
912
+ return right;
913
+ left = { ok: true, value: left.value && right.value };
914
+ }
915
+ return left;
916
+ };
917
+ const parseNot = () => {
918
+ if (peek() && IsKeyword(peek(), 'NOT')) {
919
+ consume();
920
+ const inner = parseNot();
921
+ return inner.ok ? { ok: true, value: !inner.value } : inner;
922
+ }
923
+ return parsePrimary();
924
+ };
925
+ const parsePrimary = () => {
926
+ const first = peek();
927
+ if (!first)
928
+ return { ok: false };
929
+ if (first.Kind === 'open') {
930
+ consume();
931
+ if (peek() && IsKeyword(peek(), 'SELECT')) {
932
+ return { ok: false };
933
+ }
934
+ const inner = parseOr();
935
+ if (!inner.ok)
936
+ return inner;
937
+ if (peek()?.Kind !== 'close')
938
+ return { ok: false };
939
+ consume();
940
+ return inner;
941
+ }
942
+ // Support literal 1=1 / 1=0 guards
943
+ if (first.Kind === 'number') {
944
+ const leftLit = readLiteral();
945
+ if (!leftLit.ok)
946
+ return { ok: false };
947
+ const opTok = consume();
948
+ if (!opTok || opTok.Kind !== 'operator')
949
+ return { ok: false };
950
+ const rightLit = readLiteral();
951
+ if (!rightLit.ok)
952
+ return { ok: false };
953
+ return { ok: true, value: compareValues(leftLit.value, opTok.Text, rightLit.value) };
954
+ }
955
+ if (first.Kind !== 'word' && first.Kind !== 'identifier') {
956
+ return { ok: false };
957
+ }
958
+ let colTok = consume();
959
+ if (peek()?.Kind === 'dot') {
960
+ consume();
961
+ const nextIdent = consume();
962
+ if (!nextIdent || (nextIdent.Kind !== 'word' && nextIdent.Kind !== 'identifier')) {
963
+ return { ok: false };
964
+ }
965
+ colTok = nextIdent;
966
+ }
967
+ // Reject function calls `fn(...)`
968
+ if (peek()?.Kind === 'open') {
969
+ return { ok: false };
970
+ }
971
+ const colName = ClientClauseScreen.StripIdentifierQuotes(colTok.Text).trim().toLowerCase();
972
+ const actualVal = recordByLowerKey.get(colName);
973
+ const next = peek();
974
+ if (!next)
975
+ return { ok: false };
976
+ if (IsKeyword(next, 'IS')) {
977
+ consume();
978
+ let negated = false;
979
+ if (peek() && IsKeyword(peek(), 'NOT')) {
980
+ negated = true;
981
+ consume();
982
+ }
983
+ if (!peek() || !IsKeyword(peek(), 'NULL'))
984
+ return { ok: false };
985
+ consume();
986
+ const isNull = actualVal === null || actualVal === undefined;
987
+ return { ok: true, value: negated ? !isNull : isNull };
988
+ }
989
+ let negatedOp = false;
990
+ if (IsKeyword(next, 'NOT')) {
991
+ negatedOp = true;
992
+ consume();
993
+ }
994
+ const afterNot = peek();
995
+ if (!afterNot)
996
+ return { ok: false };
997
+ if (IsKeyword(afterNot, 'IN')) {
998
+ consume();
999
+ if (peek()?.Kind !== 'open')
1000
+ return { ok: false };
1001
+ consume();
1002
+ if (peek() && IsKeyword(peek(), 'SELECT'))
1003
+ return { ok: false };
1004
+ const items = [];
1005
+ while (peek() && peek().Kind !== 'close') {
1006
+ const lit = readLiteral();
1007
+ if (!lit.ok)
1008
+ return { ok: false };
1009
+ items.push(lit.value);
1010
+ if (peek()?.Kind === 'comma') {
1011
+ consume();
1012
+ }
1013
+ else if (peek()?.Kind !== 'close') {
1014
+ return { ok: false };
1015
+ }
1016
+ }
1017
+ if (peek()?.Kind !== 'close')
1018
+ return { ok: false };
1019
+ consume();
1020
+ const matched = items.some((item) => compareValues(actualVal, '=', item));
1021
+ return { ok: true, value: negatedOp ? !matched : matched };
1022
+ }
1023
+ if (IsKeyword(afterNot, 'LIKE')) {
1024
+ consume();
1025
+ const patLit = readLiteral();
1026
+ if (!patLit.ok || typeof patLit.value !== 'string')
1027
+ return { ok: false };
1028
+ if (actualVal === null || actualVal === undefined)
1029
+ return { ok: true, value: false };
1030
+ const regexSrc = '^' +
1031
+ patLit.value
1032
+ .replace(/[.+?^${}()|[\]\\]/g, '\\$&')
1033
+ .replace(/%/g, '.*')
1034
+ .replace(/_/g, '.') +
1035
+ '$';
1036
+ const matched = new RegExp(regexSrc, 'is').test(String(actualVal));
1037
+ return { ok: true, value: negatedOp ? !matched : matched };
1038
+ }
1039
+ if (negatedOp)
1040
+ return { ok: false };
1041
+ if (afterNot.Kind === 'operator') {
1042
+ // Compound operators like `<>`, `!=`, `<=`, `>=` may lex as 1 or 2 operator tokens
1043
+ let opText = consume().Text;
1044
+ if ((opText === '<' && (peek()?.Text === '>' || peek()?.Text === '=')) ||
1045
+ (opText === '>' && peek()?.Text === '=') ||
1046
+ (opText === '!' && peek()?.Text === '=')) {
1047
+ opText += consume().Text;
1048
+ }
1049
+ if (!['=', '!=', '<>', '<', '<=', '>', '>='].includes(opText)) {
1050
+ return { ok: false };
1051
+ }
1052
+ const right = readLiteral();
1053
+ if (!right.ok)
1054
+ return { ok: false };
1055
+ return { ok: true, value: compareValues(actualVal, opText, right.value) };
1056
+ }
1057
+ return { ok: false };
1058
+ };
1059
+ const parsed = parseOr();
1060
+ if (!parsed.ok || pos !== tokens.length) {
1061
+ return false;
1062
+ }
1063
+ return parsed.value;
1064
+ }
1065
+ static buildBaseTableAllowList(entities) {
1066
+ const qualified = new Map();
1067
+ const bare = new Map();
1068
+ for (const e of entities) {
1069
+ const table = ClientClauseScreen.StripIdentifierQuotes(e.BaseTable);
1070
+ if (!table)
1071
+ continue;
1072
+ const schema = ClientClauseScreen.StripIdentifierQuotes(e.SchemaName);
1073
+ const bareKey = table.toLowerCase();
1074
+ bare.set(bareKey, bare.has(bareKey) ? (bare.get(bareKey) === e ? e : null) : e);
1075
+ if (schema) {
1076
+ const qualKey = `${schema}.${table}`.toLowerCase();
1077
+ const existing = qualified.get(qualKey);
1078
+ qualified.set(qualKey, existing === undefined || existing === e ? e : null);
1079
+ }
1080
+ }
1081
+ return { Qualified: qualified, Bare: bare };
1082
+ }
1083
+ static resolveEntityRelation(viewAllowList, tableAllowList, schema, table, label) {
1084
+ const unqualified = ClientClauseScreen.IsUnqualifiedSchema(schema);
1085
+ const key = unqualified ? table.toLowerCase() : `${schema}.${table}`.toLowerCase();
1086
+ const fromView = unqualified ? viewAllowList.Bare.get(key) : viewAllowList.Qualified.get(key);
1087
+ const reference = `${schema ? schema + '.' : ''}${table}`;
1088
+ if (fromView === null) {
1089
+ throw new Error(`Invalid ${label}: '${reference}' matches multiple entities — qualify it unambiguously`);
1090
+ }
1091
+ if (fromView) {
1092
+ return fromView;
1093
+ }
1094
+ const fromTable = unqualified ? tableAllowList.Bare.get(key) : tableAllowList.Qualified.get(key);
1095
+ if (fromTable === null) {
1096
+ throw new Error(`Invalid ${label}: '${reference}' matches multiple entity base tables — qualify it unambiguously`);
1097
+ }
1098
+ if (fromTable) {
1099
+ return fromTable;
1100
+ }
1101
+ throw new Error(`Invalid ${label}: '${reference}' does not resolve to a registered MemberJunction entity`);
1102
+ }
305
1103
  /**
306
1104
  * Every FROM item in a parsed statement, and the number of SELECT nodes, from a walk of the
307
1105
  * whole parse tree with CTE scope ({@link StatementRelation.IsCTEReference}); see