@clearrecord/check 1.2.0 → 1.3.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/bin/check.js CHANGED
@@ -107,7 +107,7 @@ var require_path = __commonJS({
107
107
  Object.defineProperty(exports2, "__esModule", { value: true });
108
108
  exports2.convertPosixPathToPattern = exports2.convertWindowsPathToPattern = exports2.convertPathToPattern = exports2.escapePosixPath = exports2.escapeWindowsPath = exports2.escape = exports2.removeLeadingDotSegment = exports2.makeAbsolute = exports2.unixify = void 0;
109
109
  var os = require("os");
110
- var path3 = require("path");
110
+ var path7 = require("path");
111
111
  var IS_WINDOWS_PLATFORM = os.platform() === "win32";
112
112
  var LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2;
113
113
  var POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g;
@@ -119,7 +119,7 @@ var require_path = __commonJS({
119
119
  }
120
120
  exports2.unixify = unixify;
121
121
  function makeAbsolute(cwd, filepath) {
122
- return path3.resolve(cwd, filepath);
122
+ return path7.resolve(cwd, filepath);
123
123
  }
124
124
  exports2.makeAbsolute = makeAbsolute;
125
125
  function removeLeadingDotSegment(entry) {
@@ -1416,7 +1416,7 @@ var require_braces = __commonJS({
1416
1416
  var require_constants2 = __commonJS({
1417
1417
  "node_modules/micromatch/node_modules/picomatch/lib/constants.js"(exports2, module2) {
1418
1418
  "use strict";
1419
- var path3 = require("path");
1419
+ var path7 = require("path");
1420
1420
  var WIN_SLASH = "\\\\/";
1421
1421
  var WIN_NO_SLASH = `[^${WIN_SLASH}]`;
1422
1422
  var DEFAULT_MAX_EXTGLOB_RECURSION = 0;
@@ -1590,7 +1590,7 @@ var require_constants2 = __commonJS({
1590
1590
  /* | */
1591
1591
  CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
1592
1592
  /* \uFEFF */
1593
- SEP: path3.sep,
1593
+ SEP: path7.sep,
1594
1594
  /**
1595
1595
  * Create EXTGLOB_CHARS
1596
1596
  */
@@ -1617,7 +1617,7 @@ var require_constants2 = __commonJS({
1617
1617
  var require_utils2 = __commonJS({
1618
1618
  "node_modules/micromatch/node_modules/picomatch/lib/utils.js"(exports2) {
1619
1619
  "use strict";
1620
- var path3 = require("path");
1620
+ var path7 = require("path");
1621
1621
  var win32 = process.platform === "win32";
1622
1622
  var {
1623
1623
  REGEX_BACKSLASH,
@@ -1646,7 +1646,7 @@ var require_utils2 = __commonJS({
1646
1646
  if (options && typeof options.windows === "boolean") {
1647
1647
  return options.windows;
1648
1648
  }
1649
- return win32 === true || path3.sep === "\\";
1649
+ return win32 === true || path7.sep === "\\";
1650
1650
  };
1651
1651
  exports2.escapeLast = (input, char, lastIdx) => {
1652
1652
  const idx = input.lastIndexOf(char, lastIdx);
@@ -2510,9 +2510,9 @@ var require_parse2 = __commonJS({
2510
2510
  const idx = prev.value.lastIndexOf("[");
2511
2511
  const pre = prev.value.slice(0, idx);
2512
2512
  const rest2 = prev.value.slice(idx + 2);
2513
- const posix = POSIX_REGEX_SOURCE[rest2];
2514
- if (posix) {
2515
- prev.value = pre + posix;
2513
+ const posix2 = POSIX_REGEX_SOURCE[rest2];
2514
+ if (posix2) {
2515
+ prev.value = pre + posix2;
2516
2516
  state.backtrack = true;
2517
2517
  advance();
2518
2518
  if (!bos.output && tokens.indexOf(prev) === 1) {
@@ -3010,7 +3010,7 @@ var require_parse2 = __commonJS({
3010
3010
  var require_picomatch = __commonJS({
3011
3011
  "node_modules/micromatch/node_modules/picomatch/lib/picomatch.js"(exports2, module2) {
3012
3012
  "use strict";
3013
- var path3 = require("path");
3013
+ var path7 = require("path");
3014
3014
  var scan = require_scan();
3015
3015
  var parse = require_parse2();
3016
3016
  var utils = require_utils2();
@@ -3033,7 +3033,7 @@ var require_picomatch = __commonJS({
3033
3033
  throw new TypeError("Expected pattern to be a non-empty string");
3034
3034
  }
3035
3035
  const opts = options || {};
3036
- const posix = utils.isWindows(options);
3036
+ const posix2 = utils.isWindows(options);
3037
3037
  const regex = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true);
3038
3038
  const state = regex.state;
3039
3039
  delete regex.state;
@@ -3043,8 +3043,8 @@ var require_picomatch = __commonJS({
3043
3043
  isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
3044
3044
  }
3045
3045
  const matcher = (input, returnObject = false) => {
3046
- const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
3047
- const result = { glob, state, regex, posix, input, output, match, isMatch };
3046
+ const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix: posix2 });
3047
+ const result = { glob, state, regex, posix: posix2, input, output, match, isMatch };
3048
3048
  if (typeof opts.onResult === "function") {
3049
3049
  opts.onResult(result);
3050
3050
  }
@@ -3069,7 +3069,7 @@ var require_picomatch = __commonJS({
3069
3069
  }
3070
3070
  return matcher;
3071
3071
  };
3072
- picomatch.test = (input, regex, options, { glob, posix } = {}) => {
3072
+ picomatch.test = (input, regex, options, { glob, posix: posix2 } = {}) => {
3073
3073
  if (typeof input !== "string") {
3074
3074
  throw new TypeError("Expected input to be a string");
3075
3075
  }
@@ -3077,7 +3077,7 @@ var require_picomatch = __commonJS({
3077
3077
  return { isMatch: false, output: "" };
3078
3078
  }
3079
3079
  const opts = options || {};
3080
- const format = opts.format || (posix ? utils.toPosixSlashes : null);
3080
+ const format = opts.format || (posix2 ? utils.toPosixSlashes : null);
3081
3081
  let match = input === glob;
3082
3082
  let output = match && format ? format(input) : input;
3083
3083
  if (match === false) {
@@ -3086,16 +3086,16 @@ var require_picomatch = __commonJS({
3086
3086
  }
3087
3087
  if (match === false || opts.capture === true) {
3088
3088
  if (opts.matchBase === true || opts.basename === true) {
3089
- match = picomatch.matchBase(input, regex, options, posix);
3089
+ match = picomatch.matchBase(input, regex, options, posix2);
3090
3090
  } else {
3091
3091
  match = regex.exec(output);
3092
3092
  }
3093
3093
  }
3094
3094
  return { isMatch: Boolean(match), match, output };
3095
3095
  };
3096
- picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
3096
+ picomatch.matchBase = (input, glob, options, posix2 = utils.isWindows(options)) => {
3097
3097
  const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
3098
- return regex.test(path3.basename(input));
3098
+ return regex.test(path7.basename(input));
3099
3099
  };
3100
3100
  picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
3101
3101
  picomatch.parse = (pattern, options) => {
@@ -3282,9 +3282,9 @@ var require_micromatch = __commonJS({
3282
3282
  return [].concat(patterns).every((p) => picomatch(p, options)(str));
3283
3283
  };
3284
3284
  micromatch.capture = (glob, input, options) => {
3285
- let posix = utils.isWindows(options);
3285
+ let posix2 = utils.isWindows(options);
3286
3286
  let regex = picomatch.makeRe(String(glob), { ...options, capture: true });
3287
- let match = regex.exec(posix ? utils.toPosixSlashes(input) : input);
3287
+ let match = regex.exec(posix2 ? utils.toPosixSlashes(input) : input);
3288
3288
  if (match) {
3289
3289
  return match.slice(1).map((v) => v === void 0 ? "" : v);
3290
3290
  }
@@ -3322,7 +3322,7 @@ var require_pattern = __commonJS({
3322
3322
  "use strict";
3323
3323
  Object.defineProperty(exports2, "__esModule", { value: true });
3324
3324
  exports2.isAbsolute = exports2.partitionAbsoluteAndRelative = exports2.removeDuplicateSlashes = exports2.matchAny = exports2.convertPatternsToRe = exports2.makeRe = exports2.getPatternParts = exports2.expandBraceExpansion = exports2.expandPatternsWithBraceExpansion = exports2.isAffectDepthOfReadingPattern = exports2.endsWithSlashGlobStar = exports2.hasGlobStar = exports2.getBaseDirectory = exports2.isPatternRelatedToParentDirectory = exports2.getPatternsOutsideCurrentDirectory = exports2.getPatternsInsideCurrentDirectory = exports2.getPositivePatterns = exports2.getNegativePatterns = exports2.isPositivePattern = exports2.isNegativePattern = exports2.convertToNegativePattern = exports2.convertToPositivePattern = exports2.isDynamicPattern = exports2.isStaticPattern = void 0;
3325
- var path3 = require("path");
3325
+ var path7 = require("path");
3326
3326
  var globParent = require_glob_parent();
3327
3327
  var micromatch = require_micromatch();
3328
3328
  var GLOBSTAR = "**";
@@ -3417,8 +3417,8 @@ var require_pattern = __commonJS({
3417
3417
  }
3418
3418
  exports2.endsWithSlashGlobStar = endsWithSlashGlobStar;
3419
3419
  function isAffectDepthOfReadingPattern(pattern) {
3420
- const basename2 = path3.basename(pattern);
3421
- return endsWithSlashGlobStar(pattern) || isStaticPattern(basename2);
3420
+ const basename3 = path7.basename(pattern);
3421
+ return endsWithSlashGlobStar(pattern) || isStaticPattern(basename3);
3422
3422
  }
3423
3423
  exports2.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
3424
3424
  function expandPatternsWithBraceExpansion(patterns) {
@@ -3463,19 +3463,19 @@ var require_pattern = __commonJS({
3463
3463
  exports2.removeDuplicateSlashes = removeDuplicateSlashes;
3464
3464
  function partitionAbsoluteAndRelative(patterns) {
3465
3465
  const absolute = [];
3466
- const relative = [];
3466
+ const relative2 = [];
3467
3467
  for (const pattern of patterns) {
3468
3468
  if (isAbsolute(pattern)) {
3469
3469
  absolute.push(pattern);
3470
3470
  } else {
3471
- relative.push(pattern);
3471
+ relative2.push(pattern);
3472
3472
  }
3473
3473
  }
3474
- return [absolute, relative];
3474
+ return [absolute, relative2];
3475
3475
  }
3476
3476
  exports2.partitionAbsoluteAndRelative = partitionAbsoluteAndRelative;
3477
3477
  function isAbsolute(pattern) {
3478
- return path3.isAbsolute(pattern);
3478
+ return path7.isAbsolute(pattern);
3479
3479
  }
3480
3480
  exports2.isAbsolute = isAbsolute;
3481
3481
  }
@@ -3652,8 +3652,8 @@ var require_utils3 = __commonJS({
3652
3652
  exports2.errno = errno;
3653
3653
  var fs3 = require_fs();
3654
3654
  exports2.fs = fs3;
3655
- var path3 = require_path();
3656
- exports2.path = path3;
3655
+ var path7 = require_path();
3656
+ exports2.path = path7;
3657
3657
  var pattern = require_pattern();
3658
3658
  exports2.pattern = pattern;
3659
3659
  var stream = require_stream();
@@ -3765,8 +3765,8 @@ var require_async = __commonJS({
3765
3765
  "use strict";
3766
3766
  Object.defineProperty(exports2, "__esModule", { value: true });
3767
3767
  exports2.read = void 0;
3768
- function read(path3, settings, callback) {
3769
- settings.fs.lstat(path3, (lstatError, lstat) => {
3768
+ function read(path7, settings, callback) {
3769
+ settings.fs.lstat(path7, (lstatError, lstat) => {
3770
3770
  if (lstatError !== null) {
3771
3771
  callFailureCallback(callback, lstatError);
3772
3772
  return;
@@ -3775,7 +3775,7 @@ var require_async = __commonJS({
3775
3775
  callSuccessCallback(callback, lstat);
3776
3776
  return;
3777
3777
  }
3778
- settings.fs.stat(path3, (statError, stat) => {
3778
+ settings.fs.stat(path7, (statError, stat) => {
3779
3779
  if (statError !== null) {
3780
3780
  if (settings.throwErrorOnBrokenSymbolicLink) {
3781
3781
  callFailureCallback(callback, statError);
@@ -3807,13 +3807,13 @@ var require_sync = __commonJS({
3807
3807
  "use strict";
3808
3808
  Object.defineProperty(exports2, "__esModule", { value: true });
3809
3809
  exports2.read = void 0;
3810
- function read(path3, settings) {
3811
- const lstat = settings.fs.lstatSync(path3);
3810
+ function read(path7, settings) {
3811
+ const lstat = settings.fs.lstatSync(path7);
3812
3812
  if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
3813
3813
  return lstat;
3814
3814
  }
3815
3815
  try {
3816
- const stat = settings.fs.statSync(path3);
3816
+ const stat = settings.fs.statSync(path7);
3817
3817
  if (settings.markSymbolicLink) {
3818
3818
  stat.isSymbolicLink = () => true;
3819
3819
  }
@@ -3884,17 +3884,17 @@ var require_out = __commonJS({
3884
3884
  var sync = require_sync();
3885
3885
  var settings_1 = require_settings();
3886
3886
  exports2.Settings = settings_1.default;
3887
- function stat(path3, optionsOrSettingsOrCallback, callback) {
3887
+ function stat(path7, optionsOrSettingsOrCallback, callback) {
3888
3888
  if (typeof optionsOrSettingsOrCallback === "function") {
3889
- async.read(path3, getSettings(), optionsOrSettingsOrCallback);
3889
+ async.read(path7, getSettings(), optionsOrSettingsOrCallback);
3890
3890
  return;
3891
3891
  }
3892
- async.read(path3, getSettings(optionsOrSettingsOrCallback), callback);
3892
+ async.read(path7, getSettings(optionsOrSettingsOrCallback), callback);
3893
3893
  }
3894
3894
  exports2.stat = stat;
3895
- function statSync(path3, optionsOrSettings) {
3895
+ function statSync(path7, optionsOrSettings) {
3896
3896
  const settings = getSettings(optionsOrSettings);
3897
- return sync.read(path3, settings);
3897
+ return sync.read(path7, settings);
3898
3898
  }
3899
3899
  exports2.statSync = statSync;
3900
3900
  function getSettings(settingsOrOptions = {}) {
@@ -4110,16 +4110,16 @@ var require_async2 = __commonJS({
4110
4110
  return;
4111
4111
  }
4112
4112
  const tasks = names.map((name) => {
4113
- const path3 = common.joinPathSegments(directory, name, settings.pathSegmentSeparator);
4113
+ const path7 = common.joinPathSegments(directory, name, settings.pathSegmentSeparator);
4114
4114
  return (done) => {
4115
- fsStat.stat(path3, settings.fsStatSettings, (error, stats) => {
4115
+ fsStat.stat(path7, settings.fsStatSettings, (error, stats) => {
4116
4116
  if (error !== null) {
4117
4117
  done(error);
4118
4118
  return;
4119
4119
  }
4120
4120
  const entry = {
4121
4121
  name,
4122
- path: path3,
4122
+ path: path7,
4123
4123
  dirent: utils.fs.createDirentFromStats(name, stats)
4124
4124
  };
4125
4125
  if (settings.stats) {
@@ -4237,7 +4237,7 @@ var require_settings2 = __commonJS({
4237
4237
  "node_modules/@nodelib/fs.scandir/out/settings.js"(exports2) {
4238
4238
  "use strict";
4239
4239
  Object.defineProperty(exports2, "__esModule", { value: true });
4240
- var path3 = require("path");
4240
+ var path7 = require("path");
4241
4241
  var fsStat = require_out();
4242
4242
  var fs3 = require_fs4();
4243
4243
  var Settings = class {
@@ -4245,7 +4245,7 @@ var require_settings2 = __commonJS({
4245
4245
  this._options = _options;
4246
4246
  this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false);
4247
4247
  this.fs = fs3.createFileSystemAdapter(this._options.fs);
4248
- this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path3.sep);
4248
+ this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path7.sep);
4249
4249
  this.stats = this._getValue(this._options.stats, false);
4250
4250
  this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
4251
4251
  this.fsStatSettings = new fsStat.Settings({
@@ -4272,17 +4272,17 @@ var require_out2 = __commonJS({
4272
4272
  var sync = require_sync2();
4273
4273
  var settings_1 = require_settings2();
4274
4274
  exports2.Settings = settings_1.default;
4275
- function scandir(path3, optionsOrSettingsOrCallback, callback) {
4275
+ function scandir(path7, optionsOrSettingsOrCallback, callback) {
4276
4276
  if (typeof optionsOrSettingsOrCallback === "function") {
4277
- async.read(path3, getSettings(), optionsOrSettingsOrCallback);
4277
+ async.read(path7, getSettings(), optionsOrSettingsOrCallback);
4278
4278
  return;
4279
4279
  }
4280
- async.read(path3, getSettings(optionsOrSettingsOrCallback), callback);
4280
+ async.read(path7, getSettings(optionsOrSettingsOrCallback), callback);
4281
4281
  }
4282
4282
  exports2.scandir = scandir;
4283
- function scandirSync(path3, optionsOrSettings) {
4283
+ function scandirSync(path7, optionsOrSettings) {
4284
4284
  const settings = getSettings(optionsOrSettings);
4285
- return sync.read(path3, settings);
4285
+ return sync.read(path7, settings);
4286
4286
  }
4287
4287
  exports2.scandirSync = scandirSync;
4288
4288
  function getSettings(settingsOrOptions = {}) {
@@ -4930,7 +4930,7 @@ var require_settings3 = __commonJS({
4930
4930
  "node_modules/@nodelib/fs.walk/out/settings.js"(exports2) {
4931
4931
  "use strict";
4932
4932
  Object.defineProperty(exports2, "__esModule", { value: true });
4933
- var path3 = require("path");
4933
+ var path7 = require("path");
4934
4934
  var fsScandir = require_out2();
4935
4935
  var Settings = class {
4936
4936
  constructor(_options = {}) {
@@ -4940,7 +4940,7 @@ var require_settings3 = __commonJS({
4940
4940
  this.deepFilter = this._getValue(this._options.deepFilter, null);
4941
4941
  this.entryFilter = this._getValue(this._options.entryFilter, null);
4942
4942
  this.errorFilter = this._getValue(this._options.errorFilter, null);
4943
- this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path3.sep);
4943
+ this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path7.sep);
4944
4944
  this.fsScandirSettings = new fsScandir.Settings({
4945
4945
  followSymbolicLinks: this._options.followSymbolicLinks,
4946
4946
  fs: this._options.fs,
@@ -5002,7 +5002,7 @@ var require_reader2 = __commonJS({
5002
5002
  "node_modules/fast-glob/out/readers/reader.js"(exports2) {
5003
5003
  "use strict";
5004
5004
  Object.defineProperty(exports2, "__esModule", { value: true });
5005
- var path3 = require("path");
5005
+ var path7 = require("path");
5006
5006
  var fsStat = require_out();
5007
5007
  var utils = require_utils3();
5008
5008
  var Reader = class {
@@ -5015,7 +5015,7 @@ var require_reader2 = __commonJS({
5015
5015
  });
5016
5016
  }
5017
5017
  _getFullEntryPath(filepath) {
5018
- return path3.resolve(this._settings.cwd, filepath);
5018
+ return path7.resolve(this._settings.cwd, filepath);
5019
5019
  }
5020
5020
  _makeEntry(stats, pattern) {
5021
5021
  const entry = {
@@ -5431,7 +5431,7 @@ var require_provider = __commonJS({
5431
5431
  "node_modules/fast-glob/out/providers/provider.js"(exports2) {
5432
5432
  "use strict";
5433
5433
  Object.defineProperty(exports2, "__esModule", { value: true });
5434
- var path3 = require("path");
5434
+ var path7 = require("path");
5435
5435
  var deep_1 = require_deep();
5436
5436
  var entry_1 = require_entry();
5437
5437
  var error_1 = require_error();
@@ -5445,7 +5445,7 @@ var require_provider = __commonJS({
5445
5445
  this.entryTransformer = new entry_2.default(this._settings);
5446
5446
  }
5447
5447
  _getRootDirectory(task) {
5448
- return path3.resolve(this._settings.cwd, task.base);
5448
+ return path7.resolve(this._settings.cwd, task.base);
5449
5449
  }
5450
5450
  _getReaderOptions(task) {
5451
5451
  const basePath = task.base === "." ? "" : task.base;
@@ -5736,19 +5736,19 @@ var require_out4 = __commonJS({
5736
5736
  return utils.path.convertPathToPattern(source);
5737
5737
  }
5738
5738
  FastGlob2.convertPathToPattern = convertPathToPattern;
5739
- let posix;
5740
- (function(posix2) {
5739
+ let posix2;
5740
+ (function(posix3) {
5741
5741
  function escapePath2(source) {
5742
5742
  assertPatternsInput(source);
5743
5743
  return utils.path.escapePosixPath(source);
5744
5744
  }
5745
- posix2.escapePath = escapePath2;
5745
+ posix3.escapePath = escapePath2;
5746
5746
  function convertPathToPattern2(source) {
5747
5747
  assertPatternsInput(source);
5748
5748
  return utils.path.convertPosixPathToPattern(source);
5749
5749
  }
5750
- posix2.convertPathToPattern = convertPathToPattern2;
5751
- })(posix = FastGlob2.posix || (FastGlob2.posix = {}));
5750
+ posix3.convertPathToPattern = convertPathToPattern2;
5751
+ })(posix2 = FastGlob2.posix || (FastGlob2.posix = {}));
5752
5752
  let win32;
5753
5753
  (function(win322) {
5754
5754
  function escapePath2(source) {
@@ -5790,11 +5790,12 @@ __export(local_cli_exports, {
5790
5790
  parseCliArgs: () => parseCliArgs
5791
5791
  });
5792
5792
  module.exports = __toCommonJS(local_cli_exports);
5793
- var path2 = __toESM(require("path"));
5793
+ var path6 = __toESM(require("path"));
5794
5794
  var fs2 = __toESM(require("fs/promises"));
5795
5795
 
5796
5796
  // src/engine.ts
5797
5797
  var fs = __toESM(require("fs/promises"));
5798
+ var path5 = __toESM(require("path"));
5798
5799
 
5799
5800
  // src/crawler.ts
5800
5801
  var import_fast_glob = __toESM(require_out4());
@@ -5805,8 +5806,21 @@ var Crawler = class {
5805
5806
  "**/node_modules/**",
5806
5807
  "**/.next/**",
5807
5808
  "**/.git/**",
5809
+ "**/.turbo/**",
5810
+ "**/.vercel/**",
5808
5811
  "**/dist/**",
5809
- "**/build/**"
5812
+ "**/build/**",
5813
+ "**/coverage/**",
5814
+ "**/out/**",
5815
+ "**/__tests__/**",
5816
+ "**/tests/**",
5817
+ "**/test/**",
5818
+ "**/__mocks__/**",
5819
+ "**/mocks/**",
5820
+ "**/fixtures/**",
5821
+ "**/*.test.*",
5822
+ "**/*.spec.*",
5823
+ "**/*.stories.*"
5810
5824
  ];
5811
5825
  constructor(rootDir) {
5812
5826
  this.rootDir = rootDir;
@@ -5820,14 +5834,19 @@ var Crawler = class {
5820
5834
  "dependency-triage": [],
5821
5835
  "route-auth-analyzer": []
5822
5836
  };
5823
- const allFiles = await (0, import_fast_glob.default)(["**/*.{ts,tsx,js,jsx,mjs,sql,prisma,json}"], {
5824
- cwd: this.rootDir,
5825
- ignore: this.ignorePatterns,
5826
- absolute: true
5827
- });
5837
+ const allFiles = await (0, import_fast_glob.default)(
5838
+ ["**/*.{ts,tsx,js,jsx,mjs,cjs,sql,prisma,json,toml}", "**/.env*"],
5839
+ {
5840
+ cwd: this.rootDir,
5841
+ ignore: this.ignorePatterns,
5842
+ absolute: true,
5843
+ dot: true
5844
+ }
5845
+ );
5828
5846
  for (const filePath of allFiles) {
5829
- const ext = import_path.default.extname(filePath);
5847
+ const ext = import_path.default.extname(filePath).toLowerCase();
5830
5848
  const fileName = import_path.default.basename(filePath);
5849
+ const lowerFileName = fileName.toLowerCase();
5831
5850
  const normalized = filePath.replace(/\\/g, "/").toLowerCase();
5832
5851
  if (ext === ".sql") {
5833
5852
  manifest["rls-analyzer"].push(filePath);
@@ -5836,9 +5855,14 @@ var Crawler = class {
5836
5855
  if (ext === ".prisma") {
5837
5856
  manifest["index-detector"].push(filePath);
5838
5857
  }
5839
- if ([".ts", ".tsx", ".js", ".jsx", ".mjs"].includes(ext)) {
5858
+ if ([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"].includes(ext)) {
5840
5859
  manifest["secret-scanner"].push(filePath);
5841
5860
  manifest["route-auth-analyzer"].push(filePath);
5861
+ } else if (/^\.env(?:\.[a-z0-9_-]+)?$/i.test(lowerFileName) && !/(?:example|template|sample)/i.test(lowerFileName)) {
5862
+ manifest["secret-scanner"].push(filePath);
5863
+ }
5864
+ if (lowerFileName === "config.toml" && normalized.includes("supabase")) {
5865
+ manifest["route-auth-analyzer"].push(filePath);
5842
5866
  }
5843
5867
  if (normalized.includes("webhook")) {
5844
5868
  manifest["billing-auditor"].push(filePath);
@@ -5859,11 +5883,13 @@ var ReportSynthesizer = class {
5859
5883
  }
5860
5884
  const counts = { CRITICAL: 0, HIGH: 0, MEDIUM: 0, LOW: 0 };
5861
5885
  findings.forEach((f) => counts[f.severity]++);
5862
- let output = "--- CLEAR RECORD SCAN SUMMARY ---\\n";
5863
- output += `CRITICAL: ${counts.CRITICAL} | HIGH: ${counts.HIGH} | MEDIUM: ${counts.MEDIUM} | LOW: ${counts.LOW}\\n`;
5864
- output += "---------------------------------\\n";
5886
+ let output = "--- CLEAR RECORD SCAN SUMMARY ---\n";
5887
+ output += `CRITICAL: ${counts.CRITICAL} | HIGH: ${counts.HIGH} | MEDIUM: ${counts.MEDIUM} | LOW: ${counts.LOW}
5888
+ `;
5889
+ output += "---------------------------------\n";
5865
5890
  findings.forEach((f) => {
5866
- output += `[${f.severity}] ${f.title} - ${f.location.filePath}\\n`;
5891
+ output += `[${f.severity}] ${f.title} - ${f.location.filePath}
5892
+ `;
5867
5893
  });
5868
5894
  return output;
5869
5895
  }
@@ -5919,123 +5945,212 @@ ${f.remediation.fixScript}
5919
5945
  };
5920
5946
 
5921
5947
  // src/analyzers/rls-analyzer.ts
5948
+ var IGNORED_SYSTEM_TABLES = /* @__PURE__ */ new Set([
5949
+ "_prisma_migrations",
5950
+ "__drizzle_migrations",
5951
+ "schema_migrations"
5952
+ ]);
5953
+ var PUBLIC_CATALOG_TABLES = /* @__PURE__ */ new Set([
5954
+ "plans",
5955
+ "products",
5956
+ "prices",
5957
+ "categories",
5958
+ "tags",
5959
+ "countries"
5960
+ ]);
5961
+ var SERVER_ONLY_DENY_ALL_TABLES = /* @__PURE__ */ new Set([
5962
+ "customers",
5963
+ "webhook_events",
5964
+ "stripe_events",
5965
+ "audit_logs",
5966
+ "rate_limits"
5967
+ ]);
5968
+ function stripSqlCommentsPreservingLines(sql) {
5969
+ const withoutBlock = sql.replace(
5970
+ /\/\*[\s\S]*?\*\//g,
5971
+ (block) => block.replace(/[^\r\n]/g, " ")
5972
+ );
5973
+ return withoutBlock.split(/\r?\n/).map((line) => line.replace(/--.*$/, "")).join("\n");
5974
+ }
5975
+ function getLineNumberAtIndex(content, index) {
5976
+ return content.slice(0, Math.max(0, index)).split(/\r?\n/).length;
5977
+ }
5922
5978
  var RlsAnalyzer = class {
5923
5979
  async analyze(filePath, content) {
5980
+ return this.analyzeMigrationSuite([{ filePath, content }]);
5981
+ }
5982
+ analyzeMigrationSuite(files, options) {
5983
+ if (options?.isNonSupabaseOrmOnly || files.length === 0) {
5984
+ return [];
5985
+ }
5924
5986
  const findings = [];
5925
- const lines = content.split(/\r?\n/);
5926
- const tables = [];
5927
- const enabledRls = /* @__PURE__ */ new Set();
5928
- const tablesWithPolicies = /* @__PURE__ */ new Set();
5929
- const publicPolicies = /* @__PURE__ */ new Map();
5930
- const createTableRegex = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:public\.)?(\w+)/i;
5931
- const enableRlsRegex = /ALTER\s+TABLE\s+(?:public\.)?(\w+)\s+ENABLE\s+ROW\s+LEVEL\s+SECURITY/i;
5932
- const anyPolicyRegex = /CREATE\s+POLICY\s+["']?[^"'\n]+["']?\s+ON\s+(?:public\.)?(\w+)/i;
5933
- const publicPolicyRegex = /CREATE\s+POLICY\s+".*?"\s+ON\s+(?:public\.)?(\w+)\s+FOR\s+SELECT\s+TO\s+public/i;
5934
- lines.forEach((line, idx) => {
5935
- const lineNumber = idx + 1;
5936
- const tableMatch = line.match(createTableRegex);
5937
- if (tableMatch) tables.push({ name: tableMatch[1], line: lineNumber });
5938
- const rlsMatch = line.match(enableRlsRegex);
5939
- if (rlsMatch) enabledRls.add(rlsMatch[1]);
5940
- const anyPolicyMatch = line.match(anyPolicyRegex);
5941
- if (anyPolicyMatch) tablesWithPolicies.add(anyPolicyMatch[1]);
5942
- const policyMatch = line.match(publicPolicyRegex);
5943
- if (policyMatch && !publicPolicies.has(policyMatch[1])) {
5944
- publicPolicies.set(policyMatch[1], lineNumber);
5987
+ const createdTables = /* @__PURE__ */ new Map();
5988
+ const rlsEnabledTables = /* @__PURE__ */ new Map();
5989
+ const intentionalNoPolicyTables = /* @__PURE__ */ new Set();
5990
+ const policyTables = /* @__PURE__ */ new Set();
5991
+ const permissivePolicies = [];
5992
+ for (const { filePath, content } of files) {
5993
+ const rawLines = content.split(/\r?\n/);
5994
+ const sqlClean = stripSqlCommentsPreservingLines(content);
5995
+ const createTableRegex = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:([a-zA-Z0-9_]+)\.)?["`]?([a-zA-Z0-9_]+)["`]?/gi;
5996
+ let ctMatch;
5997
+ while ((ctMatch = createTableRegex.exec(sqlClean)) !== null) {
5998
+ const schemaName = (ctMatch[1] || "public").toLowerCase();
5999
+ const rawName = ctMatch[2] || "";
6000
+ const tbl = rawName.toLowerCase();
6001
+ if (schemaName === "public" && tbl && !IGNORED_SYSTEM_TABLES.has(tbl)) {
6002
+ if (!createdTables.has(tbl)) {
6003
+ createdTables.set(tbl, {
6004
+ rawName,
6005
+ filePath,
6006
+ line: getLineNumberAtIndex(sqlClean, ctMatch.index)
6007
+ });
6008
+ }
6009
+ }
5945
6010
  }
5946
- });
5947
- for (const { name: table, line: createLine } of tables) {
5948
- if (!enabledRls.has(table)) {
6011
+ const enableRlsRegex = /ALTER\s+TABLE\s+(?:ONLY\s+)?(?:IF\s+EXISTS\s+)?(?:([a-zA-Z0-9_]+)\.)?["`]?([a-zA-Z0-9_]+)["`]?\s+ENABLE\s+ROW\s+LEVEL\s+SECURITY/gi;
6012
+ let rlsMatch;
6013
+ while ((rlsMatch = enableRlsRegex.exec(sqlClean)) !== null) {
6014
+ const schemaName = (rlsMatch[1] || "public").toLowerCase();
6015
+ const rawName = rlsMatch[2] || "";
6016
+ const tbl = rawName.toLowerCase();
6017
+ if (schemaName === "public" && tbl && !rlsEnabledTables.has(tbl)) {
6018
+ const line = getLineNumberAtIndex(sqlClean, rlsMatch.index);
6019
+ rlsEnabledTables.set(tbl, {
6020
+ rawName,
6021
+ filePath,
6022
+ line
6023
+ });
6024
+ const nearbyRaw = rawLines.slice(Math.max(0, line - 6), Math.min(rawLines.length, line + 4)).join("\n");
6025
+ if (/no\s+policies|private\s+table|service_role\s+only/i.test(nearbyRaw)) {
6026
+ intentionalNoPolicyTables.add(tbl);
6027
+ }
6028
+ }
6029
+ }
6030
+ const policyStmtRegex = /CREATE\s+POLICY\s+([^;]+?)\bON\s+(?:([a-zA-Z0-9_]+)\.)?["`]?([a-zA-Z0-9_]+)["`]?([^;]*);/gis;
6031
+ const paddedSql = `${sqlClean};`;
6032
+ let polMatch;
6033
+ while ((polMatch = policyStmtRegex.exec(paddedSql)) !== null) {
6034
+ const polName = polMatch[1] || "";
6035
+ const schemaName = (polMatch[2] || "public").toLowerCase();
6036
+ const rawName = polMatch[3] || "";
6037
+ const tbl = rawName.toLowerCase();
6038
+ const polBody = polMatch[4] || "";
6039
+ if (schemaName !== "public" || !tbl) continue;
6040
+ policyTables.add(tbl);
6041
+ const hasToServiceRole = /\bTO\s+service_role\b/i.test(polBody);
6042
+ const hasToPublicSelect = /\bFOR\s+SELECT\s+TO\s+public\b/i.test(polBody);
6043
+ const hasTrueExpr = /\b(?:USING|WITH\s+CHECK)\s*\(\s*true\s*\)/i.test(polBody);
6044
+ const isReadOnlySelect = /\bFOR\s+SELECT\b/i.test(polBody);
6045
+ const isServiceNamedWithoutRole = /service[_\s-]?role/i.test(polName) && !hasToServiceRole;
6046
+ const isPermissive = hasToPublicSelect || hasTrueExpr && !hasToServiceRole && (!isReadOnlySelect || !PUBLIC_CATALOG_TABLES.has(tbl) || isServiceNamedWithoutRole);
6047
+ if (isPermissive) {
6048
+ permissivePolicies.push({
6049
+ rawName,
6050
+ filePath,
6051
+ line: getLineNumberAtIndex(sqlClean, polMatch.index),
6052
+ isToPublic: hasToPublicSelect
6053
+ });
6054
+ }
6055
+ }
6056
+ }
6057
+ for (const [tbl, info] of createdTables.entries()) {
6058
+ if (!rlsEnabledTables.has(tbl)) {
5949
6059
  findings.push({
5950
6060
  id: "CR-ARCH-02",
5951
6061
  moduleId: "rls-analyzer",
5952
6062
  title: "Anonymous Table Dump",
5953
6063
  severity: "CRITICAL",
5954
- cvssScore: 9.1,
6064
+ cvssScore: 9.5,
5955
6065
  location: {
5956
- filePath,
5957
- startLine: createLine,
5958
- endLine: createLine,
6066
+ filePath: info.filePath,
6067
+ startLine: info.line,
6068
+ endLine: info.line,
5959
6069
  startCol: 1,
5960
6070
  endCol: 100,
5961
- snippet: `CREATE TABLE public.${table}`
6071
+ snippet: `CREATE TABLE public.${info.rawName}`
5962
6072
  },
5963
6073
  analysis: {
5964
- description: `The '${table}' table is created without Row Level Security enabled.`,
5965
- aiContrast: "Generic LLMs often assume RLS is handled globally. They fail to verify the explicit ENABLE ROW LEVEL SECURITY command.",
5966
- empiricalProof: `curl -X GET 'https://[PROJECT].supabase.co/rest/v1/${table}?select=*' -H 'apikey: [ANON_KEY]'`
6074
+ description: `The '${info.rawName}' table is created without Row Level Security enabled across SQL migrations.`,
6075
+ aiContrast: "Generic LLMs often assume RLS is handled globally or check a single file in isolation.",
6076
+ empiricalProof: `curl -X GET 'https://[PROJECT].supabase.co/rest/v1/${info.rawName}?select=*' -H 'apikey: [ANON_KEY]'`
5967
6077
  },
5968
6078
  remediation: {
5969
6079
  summary: "Enable RLS and restrict access to authenticated users.",
5970
- fixScript: `ALTER TABLE public.${table} ENABLE ROW LEVEL SECURITY;
5971
- CREATE POLICY "Users can read own" ON public.${table} FOR SELECT TO authenticated USING (auth.uid() = id);`,
5972
- prTitle: `Security: Enable RLS on ${table} table`
6080
+ fixScript: `ALTER TABLE public.${info.rawName} ENABLE ROW LEVEL SECURITY;
6081
+ CREATE POLICY "Users can read own" ON public.${info.rawName} FOR SELECT TO authenticated USING (auth.uid() = id);`,
6082
+ prTitle: `Security: Enable RLS on ${info.rawName} table`
5973
6083
  },
5974
6084
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
5975
6085
  });
5976
- } else if (!tablesWithPolicies.has(table)) {
6086
+ }
6087
+ }
6088
+ for (const [tbl, info] of rlsEnabledTables.entries()) {
6089
+ const isIntentionalDenyAll = intentionalNoPolicyTables.has(tbl) || policyTables.size > 0 && SERVER_ONLY_DENY_ALL_TABLES.has(tbl);
6090
+ if (!policyTables.has(tbl) && !isIntentionalDenyAll) {
5977
6091
  findings.push({
5978
6092
  id: "CR-ARCH-03",
5979
6093
  moduleId: "rls-analyzer",
5980
6094
  title: "RLS Enabled Without Policy (CVE-2025-48757 Zero-Policy Trap)",
5981
6095
  severity: "HIGH",
5982
- cvssScore: 8.2,
6096
+ cvssScore: 8.8,
5983
6097
  location: {
5984
- filePath,
5985
- startLine: createLine,
5986
- endLine: createLine,
6098
+ filePath: info.filePath,
6099
+ startLine: info.line,
6100
+ endLine: info.line,
5987
6101
  startCol: 1,
5988
6102
  endCol: 100,
5989
- snippet: `ALTER TABLE public.${table} ENABLE ROW LEVEL SECURITY (0 policies)`
6103
+ snippet: `ALTER TABLE public.${info.rawName} ENABLE ROW LEVEL SECURITY (0 policies)`
5990
6104
  },
5991
6105
  analysis: {
5992
- description: `The '${table}' table enables RLS without defining explicit CREATE POLICY rules.`,
5993
- aiContrast: "Many scanners stop once ENABLE ROW LEVEL SECURITY appears, missing incomplete/untested policy coverage.",
5994
- empiricalProof: `SELECT tablename, policyname FROM pg_policies WHERE tablename = '${table}';`
6106
+ description: `The '${info.rawName}' table enables RLS without defining explicit CREATE POLICY rules across SQL migrations.`,
6107
+ aiContrast: "Many scanners stop once ENABLE ROW LEVEL SECURITY appears, missing incomplete policy coverage.",
6108
+ empiricalProof: `SELECT tablename, policyname FROM pg_policies WHERE tablename = '${info.rawName}';`
5995
6109
  },
5996
6110
  remediation: {
5997
6111
  summary: "Define explicit authenticated tenant policies on the RLS-enabled table.",
5998
- fixScript: `CREATE POLICY "Authenticated Read" ON public.${table} FOR SELECT TO authenticated USING (auth.uid() = user_id);`,
5999
- prTitle: `Security: Add explicit RLS policies to ${table}`
6000
- },
6001
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
6002
- });
6003
- } else if (publicPolicies.has(table)) {
6004
- const policyLine = publicPolicies.get(table) || createLine;
6005
- findings.push({
6006
- id: "CR-ARCH-03",
6007
- moduleId: "rls-analyzer",
6008
- title: "Publicly Accessible Data",
6009
- severity: "CRITICAL",
6010
- cvssScore: 8.5,
6011
- location: {
6012
- filePath,
6013
- startLine: policyLine,
6014
- endLine: policyLine,
6015
- startCol: 1,
6016
- endCol: 100,
6017
- snippet: `CREATE POLICY ... TO public`
6018
- },
6019
- analysis: {
6020
- description: `The '${table}' table has a SELECT policy that explicitly allows 'public' access.`,
6021
- aiContrast: "Agents see a policy exists and assume it is secure. They fail to check the target role (public vs authenticated).",
6022
- empiricalProof: `curl -X GET 'https://[PROJECT].supabase.co/rest/v1/${table}?select=*' -H 'apikey: [ANON_KEY]'`
6023
- },
6024
- remediation: {
6025
- summary: "Restrict the policy to authenticated users only.",
6026
- fixScript: `DROP POLICY "Public Read" ON public.${table};
6027
- CREATE POLICY "Authenticated Read" ON public.${table} FOR SELECT TO authenticated USING (auth.uid() = id);`,
6028
- prTitle: `Security: Restrict ${table} access to authenticated users`
6112
+ fixScript: `CREATE POLICY "Authenticated Read" ON public.${info.rawName} FOR SELECT TO authenticated USING (auth.uid() = user_id);`,
6113
+ prTitle: `Security: Add explicit RLS policies to ${info.rawName}`
6029
6114
  },
6030
6115
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
6031
6116
  });
6032
6117
  }
6033
6118
  }
6119
+ for (const perm of permissivePolicies) {
6120
+ findings.push({
6121
+ id: "CR-ARCH-03",
6122
+ moduleId: "rls-analyzer",
6123
+ title: "Publicly Accessible Data",
6124
+ severity: "CRITICAL",
6125
+ cvssScore: 9.1,
6126
+ location: {
6127
+ filePath: perm.filePath,
6128
+ startLine: perm.line,
6129
+ endLine: perm.line,
6130
+ startCol: 1,
6131
+ endCol: 100,
6132
+ snippet: perm.isToPublic ? "CREATE POLICY ... TO public" : "CREATE POLICY ... USING (true)"
6133
+ },
6134
+ analysis: {
6135
+ description: `The '${perm.rawName}' table has an overly permissive RLS policy (TO public or USING (true) without TO service_role).`,
6136
+ aiContrast: "Agents see a policy exists and assume it is secure without inspecting role and predicate bounds.",
6137
+ empiricalProof: `curl -X GET 'https://[PROJECT].supabase.co/rest/v1/${perm.rawName}?select=*' -H 'apikey: [ANON_KEY]'`
6138
+ },
6139
+ remediation: {
6140
+ summary: "Restrict the policy to authenticated users or service_role only.",
6141
+ fixScript: `DROP POLICY IF EXISTS "Public Read" ON public.${perm.rawName};
6142
+ CREATE POLICY "Authenticated Read" ON public.${perm.rawName} FOR SELECT TO authenticated USING (auth.uid() = user_id);`,
6143
+ prTitle: `Security: Restrict ${perm.rawName} access to authenticated users`
6144
+ },
6145
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
6146
+ });
6147
+ }
6034
6148
  return findings;
6035
6149
  }
6036
6150
  };
6037
6151
 
6038
6152
  // src/analyzers/secret-scanner.ts
6153
+ var import_path2 = __toESM(require("path"));
6039
6154
  var SecretScanner = class {
6040
6155
  secretPatterns = [
6041
6156
  {
@@ -6051,7 +6166,7 @@ var SecretScanner = class {
6051
6166
  {
6052
6167
  id: "CR-SEC-02",
6053
6168
  title: "Supabase Service Role Leak",
6054
- regex: /(?:sb_admin_[a-zA-Z0-9]+|sb_secret_[a-zA-Z0-9_-]{16,}|SUPABASE_SERVICE_ROLE_KEY\s*[:=]\s*['"][^'"]{12,}['"])/g,
6169
+ regex: /(?:sb_admin_[a-zA-Z0-9]+|sb_secret_[a-zA-Z0-9_-]{16,}|SUPABASE_SERVICE_ROLE_KEY\s*[:=]\s*['"](?:eyJ[a-zA-Z0-9_-]+|sb_admin_[a-zA-Z0-9]+|sb_secret_[a-zA-Z0-9_-]+|[^'"]{24,})['"])/g,
6055
6170
  severity: "CRITICAL",
6056
6171
  cvssScore: 9.8,
6057
6172
  aiContrast: "General LLMs often ignore strings starting with sb_admin_ / sb_secret_ as they look like internal IDs. They fail to recognize this as the bypass-all-RLS master key.",
@@ -6081,7 +6196,7 @@ var SecretScanner = class {
6081
6196
  {
6082
6197
  id: "CR-SEC-05",
6083
6198
  title: "RSA / PEM Private Key Leak",
6084
- regex: /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/g,
6199
+ regex: /-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----/g,
6085
6200
  severity: "CRITICAL",
6086
6201
  cvssScore: 9.5,
6087
6202
  aiContrast: "Private cryptographic keys inside source files allow token forgery or MITM compromise.",
@@ -6091,37 +6206,40 @@ var SecretScanner = class {
6091
6206
  {
6092
6207
  id: "CR-SEC-06",
6093
6208
  title: "Client-Exposed Secret Env Prefix (NEXT_PUBLIC_ / VITE_)",
6094
- regex: /(?:NEXT_PUBLIC_|VITE_)[A-Z0-9_]*(?:SERVICE_ROLE|SECRET_KEY|WEBHOOK_SECRET|PRIVATE_KEY|ADMIN_KEY)/g,
6209
+ regex: /(?:NEXT_PUBLIC_|VITE_)[A-Z0-9_]*(?:SERVICE_ROLE|SECRET_KEY|SECRET|WEBHOOK_SECRET|PRIVATE_KEY|PRIVATE|ADMIN_KEY)[A-Z0-9_]*/g,
6095
6210
  severity: "CRITICAL",
6096
6211
  cvssScore: 9.3,
6097
6212
  aiContrast: "Frameworks inline NEXT_PUBLIC_* and VITE_* variables verbatim into browser bundles.",
6098
6213
  empiricalProof: "Any visitor can inspect compiled browser JS chunks to read the credential.",
6099
6214
  remediation: "Remove the NEXT_PUBLIC_ / VITE_ prefix so the key stays strictly on the server."
6100
- },
6101
- {
6102
- id: "CR-SEC-07",
6103
- title: "Browser-Exposed AI SDK (dangerouslyAllowBrowser)",
6104
- regex: /dangerouslyAllowBrowser\s*:\s*true/g,
6105
- severity: "CRITICAL",
6106
- cvssScore: 9,
6107
- aiContrast: "Shipping dangerouslyAllowBrowser: true exposes your OpenAI/Anthropic billing key to every visitor.",
6108
- empiricalProof: "Browser network tab exposes Authorization: Bearer sk-... on client LLM calls.",
6109
- remediation: "Move AI SDK calls into a Next.js App Router API Route (/api/ai) and remove dangerouslyAllowBrowser."
6110
6215
  }
6111
6216
  ];
6112
6217
  async analyze(filePath, content) {
6113
6218
  const findings = [];
6114
6219
  const normalized = filePath.replace(/\\/g, "/");
6115
- if (/(?:^|\/)(?:__tests__|tests?|mocks?|fixtures?)\//i.test(normalized) || /\.(?:test|spec)\.[jt]sx?$/i.test(normalized)) {
6220
+ const baseName = import_path2.default.basename(normalized);
6221
+ const lowerBaseName = baseName.toLowerCase();
6222
+ if (/(?:^|\/)(?:__tests__|tests?|__mocks__|mocks?|fixtures?)\//i.test(normalized) || /\.(?:test|spec|stories)\.[jt]sx?$/i.test(normalized)) {
6116
6223
  return [];
6117
6224
  }
6225
+ const isEnvTemplateFile = lowerBaseName.includes(".env") && /(?:example|template|sample)/i.test(lowerBaseName);
6226
+ if (isEnvTemplateFile) {
6227
+ return [];
6228
+ }
6229
+ const isTrackedDotEnvSecretFile = /^\.env(?:\.[a-z0-9_-]+)?$/i.test(lowerBaseName) && !isEnvTemplateFile;
6230
+ const codeOnly = content.replace(/\/\*[\s\S]*?\*\//g, (b) => b.replace(/[^\r\n]/g, " ")).replace(/\/\/.*$/gm, "");
6231
+ const isClientComponentFile = /^\s*['"]use client['"]/m.test(codeOnly);
6118
6232
  for (const pattern of this.secretPatterns) {
6233
+ if (pattern.id === "CR-SEC-01" && content.includes("authDomain") && content.includes("projectId")) {
6234
+ continue;
6235
+ }
6119
6236
  const matches = content.matchAll(pattern.regex);
6120
6237
  for (const match of matches) {
6121
6238
  const secret = match[0];
6122
6239
  if (secret.toUpperCase().includes("EXAMPLE")) {
6123
6240
  continue;
6124
6241
  }
6242
+ const line = this.getLineNumber(content, match.index ?? 0);
6125
6243
  findings.push({
6126
6244
  id: pattern.id,
6127
6245
  moduleId: "secret-scanner",
@@ -6130,8 +6248,8 @@ var SecretScanner = class {
6130
6248
  cvssScore: pattern.cvssScore,
6131
6249
  location: {
6132
6250
  filePath,
6133
- startLine: this.getLineNumber(content, match.index),
6134
- endLine: this.getLineNumber(content, match.index + secret.length),
6251
+ startLine: line,
6252
+ endLine: this.getLineNumber(content, (match.index ?? 0) + secret.length),
6135
6253
  startCol: 1,
6136
6254
  endCol: 100,
6137
6255
  snippet: secret
@@ -6143,13 +6261,115 @@ var SecretScanner = class {
6143
6261
  },
6144
6262
  remediation: {
6145
6263
  summary: pattern.remediation,
6146
- fixScript: "// Remove hardcoded secret and use process.env.SERVICE_ROLE_KEY",
6264
+ fixScript: "// Remove hardcoded secret and load from server-only environment variable",
6147
6265
  prTitle: `Security: Remove leaked secret from ${filePath}`
6148
6266
  },
6149
6267
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
6150
6268
  });
6151
6269
  }
6152
6270
  }
6271
+ const hasAlreadyFlaggedSec02 = findings.some((f) => f.id === "CR-SEC-02");
6272
+ if (!hasAlreadyFlaggedSec02) {
6273
+ const trackedEnvMatch = isTrackedDotEnvSecretFile ? content.match(/^\s*(?:export\s+)?SUPABASE_SERVICE_ROLE_KEY\s*=\s*\S+/m) : null;
6274
+ const clientRefMatch = isClientComponentFile ? codeOnly.match(
6275
+ /(?:process\.env|import\.meta\.env)(?:\.SUPABASE_SERVICE_ROLE_KEY|\[\s*['"]SUPABASE_SERVICE_ROLE_KEY['"]\s*\])/i
6276
+ ) : null;
6277
+ const leakMatch = trackedEnvMatch || clientRefMatch;
6278
+ if (leakMatch && leakMatch.index !== void 0) {
6279
+ const line = this.getLineNumber(content, leakMatch.index);
6280
+ findings.push({
6281
+ id: "CR-SEC-02",
6282
+ moduleId: "secret-scanner",
6283
+ title: "Supabase Service Role Leak",
6284
+ severity: "CRITICAL",
6285
+ cvssScore: 9.8,
6286
+ location: {
6287
+ filePath,
6288
+ startLine: line,
6289
+ endLine: line,
6290
+ startCol: 1,
6291
+ endCol: 100,
6292
+ snippet: leakMatch[0].trim()
6293
+ },
6294
+ analysis: {
6295
+ description: 'SUPABASE_SERVICE_ROLE_KEY is committed in a tracked .env file or referenced directly inside a "use client" component.',
6296
+ aiContrast: "Client-bundled or git-tracked service role keys grant full RLS bypass across all tables.",
6297
+ empiricalProof: "curl -X GET 'https://[PROJECT].supabase.co/rest/v1/any_table?select=*' -H 'apikey: [SERVICE_ROLE_KEY]'"
6298
+ },
6299
+ remediation: {
6300
+ summary: "Keep SUPABASE_SERVICE_ROLE_KEY strictly in gitignored server environment variables with server-only module guards.",
6301
+ fixScript: "import 'server-only';",
6302
+ prTitle: `Security: Isolate SUPABASE_SERVICE_ROLE_KEY from client/git in ${filePath}`
6303
+ },
6304
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
6305
+ });
6306
+ }
6307
+ }
6308
+ if (/\.(?:ts|tsx|js|jsx|mjs|cjs)$/i.test(baseName)) {
6309
+ const dangerousBrowserMatch = codeOnly.match(/dangerouslyAllowBrowser\s*:\s*true/);
6310
+ const clientAiMatch = isClientComponentFile ? codeOnly.match(/\bnew\s+(?:OpenAI|Anthropic)\s*\(/) : null;
6311
+ const aiLeakMatch = dangerousBrowserMatch || clientAiMatch;
6312
+ if (aiLeakMatch && aiLeakMatch.index !== void 0) {
6313
+ const line = this.getLineNumber(codeOnly, aiLeakMatch.index);
6314
+ findings.push({
6315
+ id: "CR-SEC-07",
6316
+ moduleId: "secret-scanner",
6317
+ title: "Browser-Exposed AI SDK (dangerouslyAllowBrowser)",
6318
+ severity: "CRITICAL",
6319
+ cvssScore: 9,
6320
+ location: {
6321
+ filePath,
6322
+ startLine: line,
6323
+ endLine: line,
6324
+ startCol: 1,
6325
+ endCol: 100,
6326
+ snippet: aiLeakMatch[0]
6327
+ },
6328
+ analysis: {
6329
+ description: "OpenAI or Anthropic SDK is instantiated in a browser client component or with dangerouslyAllowBrowser: true.",
6330
+ aiContrast: "Shipping dangerouslyAllowBrowser: true exposes your OpenAI/Anthropic billing key to every visitor.",
6331
+ empiricalProof: "Browser network tab exposes Authorization: Bearer sk-... on client LLM calls."
6332
+ },
6333
+ remediation: {
6334
+ summary: "Move AI SDK calls into a Next.js App Router API Route (/api/ai) and remove dangerouslyAllowBrowser.",
6335
+ fixScript: "// Move OpenAI/Anthropic SDK instantiation to server-only route.ts",
6336
+ prTitle: `Security: Move browser-exposed AI SDK to server route in ${filePath}`
6337
+ },
6338
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
6339
+ });
6340
+ }
6341
+ const rawSqlRegex = /\$(?:queryRawUnsafe|executeRawUnsafe)\s*\(|\.(?:query|execute)\s*\(\s*`[^`]*(?:SELECT|INSERT|UPDATE|DELETE)[^`]*\$\{/i;
6342
+ const sqlMatch = codeOnly.match(rawSqlRegex);
6343
+ if (sqlMatch && sqlMatch.index !== void 0) {
6344
+ const line = this.getLineNumber(codeOnly, sqlMatch.index);
6345
+ findings.push({
6346
+ id: "CR-DB-01",
6347
+ moduleId: "rls-analyzer",
6348
+ title: "Unparameterized Raw SQL Query / Injection Vector",
6349
+ severity: "CRITICAL",
6350
+ cvssScore: 9.4,
6351
+ location: {
6352
+ filePath,
6353
+ startLine: line,
6354
+ endLine: line,
6355
+ startCol: 1,
6356
+ endCol: 100,
6357
+ snippet: sqlMatch[0].slice(0, 80)
6358
+ },
6359
+ analysis: {
6360
+ description: "Database query uses $queryRawUnsafe or raw template literal interpolation (${...}) inside SQL statements, exposing the database to SQL injection.",
6361
+ aiContrast: "AI code generators frequently emit $queryRawUnsafe(`SELECT ... ${input}`) instead of parameterized tagged templates.",
6362
+ empiricalProof: "email=' OR '1'='1' -- dumps unauthorized rows via unparameterized SQL"
6363
+ },
6364
+ remediation: {
6365
+ summary: "Replace $queryRawUnsafe / string-interpolated queries with parameterized $queryRaw tagged templates or $1 placeholders.",
6366
+ fixScript: "await pool.query('SELECT * FROM users WHERE email = $1', [email]);",
6367
+ prTitle: `Security: Parameterize raw SQL query in ${filePath}`
6368
+ },
6369
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
6370
+ });
6371
+ }
6372
+ }
6153
6373
  return findings;
6154
6374
  }
6155
6375
  getLineNumber(content, index) {
@@ -6158,12 +6378,27 @@ var SecretScanner = class {
6158
6378
  };
6159
6379
 
6160
6380
  // src/analyzers/billing-auditor.ts
6381
+ var import_path3 = __toESM(require("path"));
6161
6382
  var BillingAuditor = class {
6162
6383
  async analyze(filePath, content) {
6163
6384
  const findings = [];
6164
- const lowerPath = filePath.replace(/\\/g, "/").toLowerCase();
6165
- if (lowerPath.includes("lemon")) {
6166
- const hasLemonVerify = content.toLowerCase().includes("x-signature") || content.includes("createHmac") || content.includes("timingSafeEqual");
6385
+ const normalizedPath = filePath.replace(/\\/g, "/");
6386
+ const lowerPath = normalizedPath.toLowerCase();
6387
+ const baseName = import_path3.default.basename(normalizedPath);
6388
+ if (/(?:^|\/)(?:__tests__|tests?|__mocks__|mocks?|fixtures?)\//i.test(normalizedPath) || /\.(?:test|spec|stories)\.[jt]sx?$/i.test(normalizedPath)) {
6389
+ return [];
6390
+ }
6391
+ const codeOnly = content.replace(/\/\*[\s\S]*?\*\//g, (b) => b.replace(/[^\r\n]/g, " ")).replace(/\/\/.*$/gm, "");
6392
+ const isHttpWebhookEndpoint = lowerPath.includes("webhook") && (baseName === "route.ts" || baseName === "route.js" || /\/pages\/api\/.+\.(?:ts|js|mjs)$/i.test(normalizedPath) || /\/supabase\/functions\/[^/]+\/index\.(?:ts|js)$/i.test(normalizedPath) || /\bapp\.post\s*\(/.test(codeOnly));
6393
+ const isPureReExportRoute = /^\s*export\s+(?:\*|\{[^}]+\})\s+from\s+['"][^'"]+['"]/m.test(codeOnly) && !/\b(?:async\s+function|function\s+\w+|const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=)/.test(
6394
+ codeOnly
6395
+ );
6396
+ if (!isHttpWebhookEndpoint || isPureReExportRoute) {
6397
+ return [];
6398
+ }
6399
+ const isLemonRoute = lowerPath.includes("lemon") || /lemonsqueezy|x-signature/i.test(codeOnly);
6400
+ if (isLemonRoute) {
6401
+ const hasLemonVerify = codeOnly.toLowerCase().includes("x-signature") || codeOnly.includes("createHmac") || codeOnly.includes("timingSafeEqual");
6167
6402
  if (!hasLemonVerify) {
6168
6403
  findings.push({
6169
6404
  id: "CR-BIL-02",
@@ -6194,8 +6429,9 @@ var BillingAuditor = class {
6194
6429
  }
6195
6430
  return findings;
6196
6431
  }
6197
- if (lowerPath.includes("paddle")) {
6198
- const hasPaddleVerify = content.toLowerCase().includes("paddle-signature") || content.includes("webhooks.unmarshal") || content.includes("createHmac");
6432
+ const isPaddleRoute = lowerPath.includes("paddle") || /paddle-signature|paddle\.webhooks/i.test(codeOnly);
6433
+ if (isPaddleRoute) {
6434
+ const hasPaddleVerify = codeOnly.toLowerCase().includes("paddle-signature") || codeOnly.includes("webhooks.unmarshal") || codeOnly.includes("createHmac");
6199
6435
  if (!hasPaddleVerify) {
6200
6436
  findings.push({
6201
6437
  id: "CR-BIL-03",
@@ -6226,66 +6462,76 @@ var BillingAuditor = class {
6226
6462
  }
6227
6463
  return findings;
6228
6464
  }
6229
- const hasConstructEvent = content.includes("stripe.webhooks.constructEvent");
6230
- const processesPayment = /update.*subscriptions|create.*customer|grant.*access|db\..*update|prisma\..*update|supabase\..*update/i.test(content);
6231
- if (processesPayment && !hasConstructEvent) {
6232
- findings.push({
6233
- id: "CR-BIL-01",
6234
- moduleId: "billing-auditor",
6235
- title: "Unsigned Stripe Webhook",
6236
- severity: "CRITICAL",
6237
- cvssScore: 9.5,
6238
- location: {
6239
- filePath,
6240
- startLine: 1,
6241
- endLine: 1,
6242
- startCol: 1,
6243
- endCol: 100,
6244
- snippet: "Logic found updating subscription without signature verification."
6245
- },
6246
- analysis: {
6247
- description: "The Stripe webhook handler processes payment events without verifying the Stripe-Signature header.",
6248
- aiContrast: "General AI agents often check if a webhook exists, but they rarely verify that the event was actually sent by Stripe and not forged by a malicious user.",
6249
- empiricalProof: `curl -X POST https://[PROJECT].com/api/webhooks/stripe -d '{"type": "checkout.session.completed", "data": {"object": {"customer": "attacker_id"}}} '`
6250
- },
6251
- remediation: {
6252
- summary: "Use stripe.webhooks.constructEvent() to verify the webhook signature.",
6253
- fixScript: "const event = stripe.webhooks.constructEvent(payload, sig, process.env.STRIPE_WEBHOOK_SECRET);",
6254
- prTitle: "Security: Add Stripe signature verification"
6255
- },
6256
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
6257
- });
6258
- }
6259
- if (hasConstructEvent) {
6260
- const secretMatch = content.match(/constructEvent\s*\(\s*[^,]+,\s*[^,]+,\s*['"]([^'"]*)['"]/);
6261
- if (secretMatch && (secretMatch[1] === "" || secretMatch[1].toLowerCase().includes("placeholder"))) {
6465
+ const isStripeRoute = lowerPath.includes("stripe") || /\bnew\s+Stripe\b|stripe\.webhooks/i.test(codeOnly) || /update.*subscriptions|create.*customer|grant.*access|db\..*update|prisma\..*update|supabase\..*update/i.test(
6466
+ codeOnly
6467
+ );
6468
+ if (isStripeRoute) {
6469
+ const hasConstructEvent = codeOnly.includes("constructEvent") || codeOnly.includes("constructEventAsync") || codeOnly.toLowerCase().includes("stripe-signature");
6470
+ const hasPostHandlerOrMutation = /\bexport\s+(?:async\s+)?(?:function|const)\s+POST\b/.test(codeOnly) || /\bexport\s+default\b/.test(codeOnly) || /\bapp\.post\s*\(/.test(codeOnly) || /update.*subscriptions|create.*customer|grant.*access|db\..*update|prisma\..*update|supabase\..*update/i.test(
6471
+ codeOnly
6472
+ );
6473
+ if (hasPostHandlerOrMutation && !hasConstructEvent) {
6262
6474
  findings.push({
6263
- id: "CR-BIL-02",
6475
+ id: "CR-BIL-01",
6264
6476
  moduleId: "billing-auditor",
6265
- title: "Missing Webhook Secret",
6266
- severity: "HIGH",
6267
- cvssScore: 7.2,
6477
+ title: "Unsigned Stripe Webhook",
6478
+ severity: "CRITICAL",
6479
+ cvssScore: 9.5,
6268
6480
  location: {
6269
6481
  filePath,
6270
6482
  startLine: 1,
6271
6483
  endLine: 1,
6272
6484
  startCol: 1,
6273
6485
  endCol: 100,
6274
- snippet: `constructEvent(..., '${secretMatch ? secretMatch[1] : ""}')`
6486
+ snippet: "Stripe webhook handler parses POST payload without signature verification."
6275
6487
  },
6276
6488
  analysis: {
6277
- description: "The Stripe webhook secret is either empty or uses a placeholder value.",
6278
- aiContrast: 'AI agents see a call to constructEvent and mark it "secure". They fail to check if the actual secret being passed is an empty string.',
6279
- empiricalProof: "The webhook secret is empty; any signature will be rejected, or a trivial bypass may exist depending on the SDK version."
6489
+ description: "The Stripe webhook handler processes payment events without verifying the Stripe-Signature header.",
6490
+ aiContrast: "General AI agents often check if a webhook exists, but fail to verify stripe.webhooks.constructEvent().",
6491
+ empiricalProof: `curl -X POST https://[PROJECT].com/api/webhooks/stripe -d '{"type": "checkout.session.completed", "data": {"object": {"customer": "attacker_id"}}}'`
6280
6492
  },
6281
6493
  remediation: {
6282
- summary: "Inject the webhook secret from environment variables.",
6283
- fixScript: "stripe.webhooks.constructEvent(payload, sig, process.env.STRIPE_WEBHOOK_SECRET);",
6284
- prTitle: "Security: Fix empty webhook secret"
6494
+ summary: "Use stripe.webhooks.constructEvent() to verify the webhook signature.",
6495
+ fixScript: "const event = stripe.webhooks.constructEvent(payload, sig, process.env.STRIPE_WEBHOOK_SECRET);",
6496
+ prTitle: "Security: Add Stripe signature verification"
6285
6497
  },
6286
6498
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
6287
6499
  });
6288
6500
  }
6501
+ if (codeOnly.includes("constructEvent")) {
6502
+ const secretMatch = codeOnly.match(
6503
+ /constructEvent\s*\(\s*[^,]+,\s*[^,]+,\s*['"]([^'"]*)['"]/
6504
+ );
6505
+ const secretVal = secretMatch?.[1] ?? null;
6506
+ if (secretVal !== null && (secretVal === "" || secretVal.toLowerCase().includes("placeholder"))) {
6507
+ findings.push({
6508
+ id: "CR-BIL-02",
6509
+ moduleId: "billing-auditor",
6510
+ title: "Missing Webhook Secret",
6511
+ severity: "HIGH",
6512
+ cvssScore: 7.2,
6513
+ location: {
6514
+ filePath,
6515
+ startLine: 1,
6516
+ endLine: 1,
6517
+ startCol: 1,
6518
+ endCol: 100,
6519
+ snippet: `constructEvent(..., '${secretVal}')`
6520
+ },
6521
+ analysis: {
6522
+ description: "The Stripe webhook secret is either empty or uses a placeholder value.",
6523
+ aiContrast: 'AI agents see a call to constructEvent and mark it "secure" without checking if the secret is an empty string.',
6524
+ empiricalProof: "The webhook secret is empty; signature verification is inoperable."
6525
+ },
6526
+ remediation: {
6527
+ summary: "Inject the webhook secret from environment variables.",
6528
+ fixScript: "stripe.webhooks.constructEvent(payload, sig, process.env.STRIPE_WEBHOOK_SECRET);",
6529
+ prTitle: "Security: Fix empty webhook secret"
6530
+ },
6531
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
6532
+ });
6533
+ }
6534
+ }
6289
6535
  }
6290
6536
  return findings;
6291
6537
  }
@@ -6298,62 +6544,85 @@ var IndexDetector = class {
6298
6544
  if (filePath.endsWith(".prisma")) {
6299
6545
  const modelBlocks = content.split(/^model\s+(\w+)\s*\{/m);
6300
6546
  for (let i = 1; i < modelBlocks.length; i += 2) {
6301
- const modelName = modelBlocks[i];
6547
+ const modelName = modelBlocks[i] || "Model";
6302
6548
  const body = (modelBlocks[i + 1] || "").split(/\n\}/)[0] || "";
6303
- const relationMatches = Array.from(body.matchAll(/@relation\([^)]*fields:\s*\[([^\]]+)\]/g));
6549
+ const indexedFields = /* @__PURE__ */ new Set();
6550
+ const blockIndexRegex = /@@(?:index|unique|id)\s*\(\s*\[([^\]]+)\]/g;
6551
+ let idxMatch;
6552
+ while ((idxMatch = blockIndexRegex.exec(body)) !== null) {
6553
+ const rawGroup = idxMatch[1] || "";
6554
+ for (const rawField of rawGroup.split(",")) {
6555
+ const cleanField = rawField.trim().split(/[\s(:]/)[0];
6556
+ if (cleanField) indexedFields.add(cleanField);
6557
+ }
6558
+ }
6559
+ const relationMatches = Array.from(
6560
+ body.matchAll(/@relation\s*\([^)]*fields:\s*\[([^\]]+)\]/g)
6561
+ );
6304
6562
  for (const match of relationMatches) {
6305
- const fkFields = match[1].split(",").map((s) => s.trim()).filter(Boolean);
6306
- const firstField = fkFields[0];
6307
- if (!firstField) continue;
6308
- const hasIndex = new RegExp(`@@(?:index|unique)\\([^)]*\\b${firstField}\\b`).test(body);
6309
- if (!hasIndex) {
6310
- findings.push({
6311
- id: "CR-PERF-01",
6312
- moduleId: "index-detector",
6313
- title: "Missing Prisma Relation Index",
6314
- severity: "MEDIUM",
6315
- cvssScore: 4.5,
6316
- location: {
6317
- filePath,
6318
- startLine: 1,
6319
- endLine: 1,
6320
- startCol: 1,
6321
- endCol: 100,
6322
- snippet: `model ${modelName} FK ${firstField}`
6323
- },
6324
- analysis: {
6325
- description: `Prisma model ${modelName} defines a foreign-key relation on '${firstField}' without an @@index([${firstField}]) directive.`,
6326
- aiContrast: "Deterministic Prisma schema inspection catches missing relation indexes that trigger full-table scans on joins.",
6327
- empiricalProof: `model ${modelName} { ... @@index([${firstField}]) }`
6328
- },
6329
- remediation: {
6330
- summary: `Add @@index([${firstField}]) to Prisma model ${modelName}.`,
6331
- fixScript: ` @@index([${firstField}])`,
6332
- prTitle: `Perf: Add Prisma index on ${modelName}.${firstField}`
6333
- },
6334
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
6335
- });
6563
+ const group = match[1] || "";
6564
+ const fkFields = group.split(",").map((s) => s.trim()).filter(Boolean);
6565
+ for (const fkField of fkFields) {
6566
+ if (indexedFields.has(fkField)) continue;
6567
+ const fieldAlreadyIndexedRegex = new RegExp(
6568
+ `^\\s*${fkField}\\b[^\\n]*@(?:id|unique)\\b`,
6569
+ "m"
6570
+ );
6571
+ if (!fieldAlreadyIndexedRegex.test(body)) {
6572
+ findings.push({
6573
+ id: "CR-PERF-01",
6574
+ moduleId: "index-detector",
6575
+ title: "Missing Prisma Relation Index",
6576
+ severity: "MEDIUM",
6577
+ cvssScore: 4.5,
6578
+ location: {
6579
+ filePath,
6580
+ startLine: 1,
6581
+ endLine: 1,
6582
+ startCol: 1,
6583
+ endCol: 100,
6584
+ snippet: `model ${modelName} FK ${fkField}`
6585
+ },
6586
+ analysis: {
6587
+ description: `Prisma model ${modelName} defines a foreign-key relation on '${fkField}' without an @@index([${fkField}]) directive.`,
6588
+ aiContrast: "Deterministic Prisma schema inspection catches missing relation indexes that trigger full-table scans on joins.",
6589
+ empiricalProof: `model ${modelName} { ... @@index([${fkField}]) }`
6590
+ },
6591
+ remediation: {
6592
+ summary: `Add @@index([${fkField}]) to Prisma model ${modelName}.`,
6593
+ fixScript: ` @@index([${fkField}])`,
6594
+ prTitle: `Perf: Add Prisma index on ${modelName}.${fkField}`
6595
+ },
6596
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
6597
+ });
6598
+ break;
6599
+ }
6336
6600
  }
6337
6601
  }
6338
6602
  }
6339
6603
  return findings;
6340
6604
  }
6341
6605
  const indices = /* @__PURE__ */ new Set();
6342
- const indexRegex = /CREATE\s+INDEX\s+[\w_]+\s+ON\s+(?:public\.)?(\w+)\((\w+)\)/gi;
6606
+ const indexRegex = /CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?[\w"_]+\s+ON\s+(?:public\.)?["`]?(\w+)["`]?(?:\s+USING\s+\w+)?\s*\(\s*["`]?(\w+)["`]?/gi;
6343
6607
  let indexMatch;
6344
6608
  while ((indexMatch = indexRegex.exec(content)) !== null) {
6345
- indices.add(`${indexMatch[1]}.${indexMatch[2]}`);
6609
+ const tbl = indexMatch[1];
6610
+ const col = indexMatch[2];
6611
+ if (tbl && col) {
6612
+ indices.add(`${tbl}.${col}`);
6613
+ }
6346
6614
  }
6347
6615
  const tableBlocks = content.split(/CREATE\s+TABLE/i);
6348
6616
  for (let i = 1; i < tableBlocks.length; i++) {
6349
- const block = tableBlocks[i];
6350
- const tableNameMatch = block.match(/^\s*(?:public\.)?(\w+)/i);
6351
- if (!tableNameMatch) continue;
6352
- const tableName = tableNameMatch[1];
6617
+ const block = tableBlocks[i] || "";
6618
+ const tableNameMatch = block.match(/^\s*(?:IF\s+NOT\s+EXISTS\s+)?(?:public\.)?["`]?(\w+)["`]?/i);
6619
+ const tableName = tableNameMatch?.[1];
6620
+ if (!tableName) continue;
6353
6621
  const fkRegex = /(\w+)\s+uuid\s+REFERENCES/gi;
6354
6622
  let fkMatch;
6355
6623
  while ((fkMatch = fkRegex.exec(block)) !== null) {
6356
6624
  const columnName = fkMatch[1];
6625
+ if (!columnName) continue;
6357
6626
  const key = `${tableName}.${columnName}`;
6358
6627
  if (!indices.has(key)) {
6359
6628
  findings.push({
@@ -6392,26 +6661,51 @@ var IndexDetector = class {
6392
6661
  // src/analyzers/dependency-triage.ts
6393
6662
  var DependencyTriage = class {
6394
6663
  safeVersions = {
6395
- "next": "14.0.0",
6396
- "react": "18.0.0"
6664
+ next: "14.0.0",
6665
+ react: "18.0.0"
6397
6666
  };
6398
6667
  async analyze(filePath, content) {
6399
6668
  const findings = [];
6400
6669
  let pkg;
6401
6670
  try {
6402
6671
  pkg = JSON.parse(content);
6403
- } catch (e) {
6672
+ } catch {
6404
6673
  return [];
6405
6674
  }
6406
- const dependencies = {
6407
- ...pkg?.dependencies ?? {},
6408
- ...pkg?.devDependencies ?? {}
6409
- };
6410
- for (const [lib, version] of Object.entries(dependencies)) {
6411
- if (this.safeVersions[lib] && typeof version === "string") {
6412
- const currentMajor = parseInt(version.replace(/[^0-9.]/, "").split(".")[0]);
6413
- const safeMajor = parseInt(this.safeVersions[lib].split(".")[0]);
6414
- if (currentMajor < safeMajor) {
6675
+ if (pkg?.deprecated) {
6676
+ findings.push({
6677
+ id: "CR-MAIN-01",
6678
+ moduleId: "dependency-triage",
6679
+ title: "Package is explicitly deprecated",
6680
+ severity: "MEDIUM",
6681
+ cvssScore: 6,
6682
+ location: {
6683
+ filePath,
6684
+ startLine: 1,
6685
+ endLine: 1,
6686
+ startCol: 1,
6687
+ endCol: 100,
6688
+ snippet: `"deprecated": ${JSON.stringify(pkg.deprecated)}`
6689
+ },
6690
+ analysis: {
6691
+ description: "Package manifest marks this module as deprecated, signaling unpatched upstream CVEs during M&A diligence.",
6692
+ aiContrast: "Automated code generators rarely check whether the package manifest itself is marked deprecated.",
6693
+ empiricalProof: 'Inspect "deprecated" field in package.json.'
6694
+ },
6695
+ remediation: {
6696
+ summary: "Migrate away from deprecated package manifests and update dependencies."
6697
+ },
6698
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
6699
+ });
6700
+ }
6701
+ const prodDependencies = pkg?.dependencies && typeof pkg.dependencies === "object" ? pkg.dependencies : {};
6702
+ for (const [lib, version] of Object.entries(prodDependencies)) {
6703
+ const safeVer = this.safeVersions[lib];
6704
+ if (safeVer && typeof version === "string") {
6705
+ const majorToken = version.replace(/[^0-9.]/g, "").split(".")[0] || "";
6706
+ const currentMajor = parseInt(majorToken, 10);
6707
+ const safeMajor = parseInt(safeVer.split(".")[0] || "0", 10);
6708
+ if (!Number.isNaN(currentMajor) && currentMajor < safeMajor) {
6415
6709
  findings.push({
6416
6710
  id: "CR-DEBT-01",
6417
6711
  moduleId: "dependency-triage",
@@ -6427,12 +6721,12 @@ var DependencyTriage = class {
6427
6721
  snippet: `"${lib}": "${version}"`
6428
6722
  },
6429
6723
  analysis: {
6430
- description: `The project is using ${lib} v${version}, but v${this.safeVersions[lib]} is the current baseline.`,
6431
- aiContrast: "Standard audit tools list all outdated packages. We specifically highlight those that impact the exit multiple by affecting LCP, SEO, and maintainability.",
6724
+ description: `The project is using ${lib} v${version}, but v${safeVer} is the current baseline.`,
6725
+ aiContrast: "Standard audit tools list all outdated packages. We specifically highlight production runtimes that impact the exit multiple.",
6432
6726
  empiricalProof: `Check the changelog for ${lib} v${safeMajor}.0.0 to see the critical architectural shifts missed.`
6433
6727
  },
6434
6728
  remediation: {
6435
- summary: `Upgrade ${lib} to v${this.safeVersions[lib]} or higher.`
6729
+ summary: `Upgrade ${lib} to v${safeVer} or higher.`
6436
6730
  },
6437
6731
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
6438
6732
  });
@@ -6444,40 +6738,101 @@ var DependencyTriage = class {
6444
6738
  };
6445
6739
 
6446
6740
  // src/analyzers/route-auth-analyzer.ts
6741
+ var import_path4 = __toESM(require("path"));
6447
6742
  var RouteAuthAnalyzer = class {
6448
6743
  async analyze(filePath, content, options) {
6449
6744
  const findings = [];
6450
6745
  const normalizedPath = filePath.replace(/\\/g, "/");
6451
6746
  const lowerPath = normalizedPath.toLowerCase();
6452
- if (/(?:^|\/)(?:__tests__|tests?|mocks?|fixtures?)\//i.test(normalizedPath) || /\.(?:test|spec)\.[jt]sx?$/i.test(normalizedPath)) {
6747
+ const baseName = import_path4.default.basename(normalizedPath);
6748
+ const lowerName = baseName.toLowerCase();
6749
+ if (/(?:^|\/)(?:__tests__|tests?|__mocks__|mocks?|fixtures?)\//i.test(normalizedPath) || /\.(?:test|spec|stories)\.[jt]sx?$/i.test(normalizedPath)) {
6453
6750
  return [];
6454
6751
  }
6455
- const baseName = normalizedPath.split("/").pop() || "";
6752
+ if (lowerName === "config.toml" && lowerPath.includes("supabase")) {
6753
+ const uncommented = content.split(/\r?\n/).map((line) => line.replace(/#.*$/, "")).join("\n");
6754
+ const fnSectionRegex = /\[functions\.([a-zA-Z0-9_-]+)\]([\s\S]*?)(?=\n\[|$)/g;
6755
+ let fnMatch;
6756
+ while ((fnMatch = fnSectionRegex.exec(uncommented)) !== null) {
6757
+ const fnName = fnMatch[1] || "";
6758
+ const sectionBody = fnMatch[2] || "";
6759
+ const isWebhookOrPublicFn = /(?:webhook|stripe|lemon|paddle|public|health)/i.test(fnName);
6760
+ if (!isWebhookOrPublicFn && /verify_jwt\s*=\s*false/i.test(sectionBody)) {
6761
+ const line = uncommented.slice(0, fnMatch.index).split(/\r?\n/).length;
6762
+ findings.push({
6763
+ id: "CR-ARCH-01",
6764
+ moduleId: "route-auth-analyzer",
6765
+ title: `Unauthenticated Supabase Edge Function in config.toml (${fnName})`,
6766
+ severity: "CRITICAL",
6767
+ cvssScore: 9.2,
6768
+ location: {
6769
+ filePath,
6770
+ startLine: line,
6771
+ endLine: line,
6772
+ startCol: 1,
6773
+ endCol: 100,
6774
+ snippet: `[functions.${fnName}] verify_jwt = false`
6775
+ },
6776
+ analysis: {
6777
+ description: `supabase/config.toml disables JWT authentication (verify_jwt = false) on non-webhook Edge Function "${fnName}".`,
6778
+ aiContrast: "Developers often set verify_jwt = false during debugging and ship unauthenticated Edge Functions to production.",
6779
+ empiricalProof: `curl -X POST https://[PROJECT].supabase.co/functions/v1/${fnName}`
6780
+ },
6781
+ remediation: {
6782
+ summary: "Re-enable JWT verification on non-webhook Supabase Edge Functions.",
6783
+ fixScript: `[functions.${fnName}]
6784
+ verify_jwt = true`,
6785
+ prTitle: `Security: Enable verify_jwt on Edge Function ${fnName}`
6786
+ },
6787
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
6788
+ });
6789
+ }
6790
+ }
6791
+ return findings;
6792
+ }
6456
6793
  const isAppRouterEndpoint = baseName === "route.ts" || baseName === "route.js";
6457
6794
  const isPagesRouterEndpoint = /\/pages\/api\/.+\.(?:ts|js|mjs)$/i.test(normalizedPath) && (content.includes("export default") || content.includes("module.exports"));
6458
- if (!isAppRouterEndpoint && !isPagesRouterEndpoint) {
6795
+ const isRemixActionEndpoint = /\/app\/routes\/.+\.(?:tsx|ts|jsx|js)$/i.test(normalizedPath) && /export\s+(?:async\s+)?function\s+action\b/.test(content);
6796
+ const isSupabaseEdgeFunction = /\/supabase\/functions\/[^/]+\/index\.(?:ts|js)$/i.test(normalizedPath) && (/\bserve\s*\(/.test(content) || /\bDeno\.serve\s*\(/.test(content));
6797
+ const isNextServerActionFile = /\.(?:ts|tsx|js|jsx)$/i.test(baseName) && !isAppRouterEndpoint && !isPagesRouterEndpoint && !isSupabaseEdgeFunction && (/^\s*['"]use server['"]/m.test(content) || /export\s+async\s+function\s+\w+\s*\([^)]*\)\s*\{\s*['"]use server['"]/m.test(content)) && /\bexport\s+async\s+function\b/.test(content);
6798
+ if (!isAppRouterEndpoint && !isPagesRouterEndpoint && !isRemixActionEndpoint && !isSupabaseEdgeFunction && !isNextServerActionFile) {
6459
6799
  return [];
6460
6800
  }
6461
- const codeOnly = content.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/.*$/gm, "");
6462
- const isPublicAuthOrWebhookPath = /\/(?:\(auth\)\/)?(?:auth\/)?(?:callback|confirm|login|signin|signup|register|logout|signout|reset-password|forgot-password|verify|magic-link)\b/i.test(
6801
+ const codeOnly = content.replace(/\/\*[\s\S]*?\*\//g, (b) => b.replace(/[^\r\n]/g, " ")).replace(/\/\/.*$/gm, "");
6802
+ const isPureReExportRoute = /^\s*export\s+(?:\*|\{[^}]+\})\s+from\s+['"][^'"]+['"]/m.test(codeOnly) && !/\b(?:async\s+function|function\s+\w+|const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=)/.test(
6803
+ codeOnly
6804
+ );
6805
+ const isPublicAuthOrWebhookPath = isPureReExportRoute || /\/(?:\(auth\)\/)?(?:auth\/)?(?:\([^/]+\)\/)?(?:callback|confirm|login|signin|sign-in|signup|sign-up|register|logout|signout|sign-out|reset-password|forgot-password|verify|magic-link)\b/i.test(
6806
+ normalizedPath
6807
+ ) || /(?:^|\/)(?:auth[-_.]?actions?|actions\/auth|sign[-_]?in\.actions?|sign[-_]?up\.actions?)\.[jt]sx?$/i.test(
6808
+ normalizedPath
6809
+ ) || normalizedPath.includes("[...nextauth]") || normalizedPath.includes("/api/auth/") || /\/pages\/api\/hello\.[jt]s$/i.test(normalizedPath) || lowerPath.includes("webhook") || /\/api\/(?:health|status|ping|public|og)\b/i.test(normalizedPath) || /\/api\/(?:[^/]+\/)*(?:pixel|track|beacon|collect|ingest|telemetry|csp-report|unsubscribe)\b/i.test(
6463
6810
  normalizedPath
6464
- ) || normalizedPath.includes("[...nextauth]") || normalizedPath.includes("/api/auth/") || lowerPath.includes("webhook") || /\/api\/(?:health|status|ping|public|og)\b/i.test(normalizedPath) || codeOnly.includes("NextAuth(") || codeOnly.includes("ImageResponse") || codeOnly.includes("exchangeCodeForSession");
6811
+ ) || /\/api\/(?:[^/]+\/)*(?:slack|discord|telegram|twilio|svix|qstash|inngest|trigger|intercom|zendesk|linear|cal|calendly|hubspot|zapier|loops|resend)\//i.test(
6812
+ normalizedPath
6813
+ ) || codeOnly.includes("COMMON_CORS_HEADERS") || /['"]Access-Control-Allow-Origin['"]\s*:\s*['"]\*['"]/i.test(codeOnly) || codeOnly.includes("NextAuth(") || codeOnly.includes("toNextJsHandler(") || codeOnly.includes("ImageResponse") || codeOnly.includes("exchangeCodeForSession") || codeOnly.includes("verifyOtp") || codeOnly.includes("signInWithPassword") || codeOnly.includes("signInWithOAuth") || codeOnly.includes("signInWithOtp") || codeOnly.includes("resetPasswordForEmail") || codeOnly.includes("signUp(") || codeOnly.includes("signOut(");
6465
6814
  if (isPublicAuthOrWebhookPath) {
6466
6815
  return [];
6467
6816
  }
6468
- if (options?.middlewareProtectsApi) {
6817
+ if ((isAppRouterEndpoint || isPagesRouterEndpoint) && (options?.middlewareProtectsApi || options?.hasImportedAuthHelper)) {
6469
6818
  return [];
6470
6819
  }
6471
6820
  const hasMutatingAppMethod = /\bexport\s+(?:async\s+)?function\s+(?:POST|PUT|DELETE|PATCH)\b/.test(codeOnly) || /\bexport\s+const\s+(?:POST|PUT|DELETE|PATCH)\b/.test(codeOnly);
6472
6821
  if (isAppRouterEndpoint && !hasMutatingAppMethod) {
6473
6822
  return [];
6474
6823
  }
6475
- const hasAuth = codeOnly.includes("auth()") || codeOnly.includes("auth.getUser") || codeOnly.includes("auth.getSession") || codeOnly.includes("getServerSession") || codeOnly.includes("getSession") || codeOnly.includes("requireUser") || codeOnly.includes("currentUser") || codeOnly.includes("protectedProcedure") || codeOnly.includes("constructEvent") || codeOnly.includes("createHmac") || codeOnly.includes("unmarshal") || /headers(?:\(\))?\.get\s*\(\s*['"](?:authorization|x-api-key|stripe-signature|x-signature|paddle-signature)['"]\s*\)/i.test(
6824
+ const hasAuth = codeOnly.includes("auth()") || codeOnly.includes("auth.getUser") || codeOnly.includes("auth.getSession") || codeOnly.includes("auth.api.getSession") || codeOnly.includes("getServerSession") || codeOnly.includes("getSession") || codeOnly.includes("requireUser") || codeOnly.includes("currentUser") || codeOnly.includes("authenticator") || codeOnly.includes("protectedProcedure") || codeOnly.includes("createProtectedRoute") || codeOnly.includes("constructEvent") || codeOnly.includes("createHmac") || codeOnly.includes("unmarshal") || codeOnly.includes("timingSafeEqual") || codeOnly.includes("timingSafeCompare") || /\b(?:getUser|getCurrentUser|validateRequest|getKindeServerSession)\s*\(/.test(codeOnly) || /headers(?:\(\))?\.get\s*\(\s*['"](?:authorization|x-api-key|stripe-signature|x-signature|paddle-signature|x-slack-signature|svix-signature|upstash-signature|x-hub-signature-256|x-shopify-hmac-sha256|x-hubspot-signature|webhook-signature)['"]\s*\)/i.test(
6825
+ codeOnly
6826
+ ) || /req\.headers\[['"](?:authorization|x-api-key|stripe-signature|x-slack-signature|svix-signature|upstash-signature)['"]\]/i.test(
6476
6827
  codeOnly
6477
- ) || /\b(?:verify|authenticate|validate|require|checkAuth|withAuth|ensureAuth|requireSession)[A-Za-z0-9_]*\s*\(/.test(
6828
+ ) || /\b(?:verify|authenticate|validate|require|assert|checkAuth|withAuth|withSession|withCron|withWorkspace|withAdmin|withSuperAdmin|withToken|withCustomer|withPartner|ensureAuth|requireSession|authActionClient)[A-Za-z0-9_]*\s*(?:\(|\.)/.test(
6478
6829
  codeOnly
6479
6830
  );
6480
6831
  if (!hasAuth) {
6832
+ const fnMatch = codeOnly.match(
6833
+ isSupabaseEdgeFunction ? /serve\s*\(/ : /export\s+(?:default\s+)?(?:async\s+)?(?:function|const)/
6834
+ );
6835
+ const startLine = fnMatch && fnMatch.index !== void 0 ? codeOnly.slice(0, fnMatch.index).split(/\r?\n/).length : 1;
6481
6836
  findings.push({
6482
6837
  id: "CR-ARCH-01",
6483
6838
  moduleId: "route-auth-analyzer",
@@ -6486,8 +6841,8 @@ var RouteAuthAnalyzer = class {
6486
6841
  cvssScore: 9.2,
6487
6842
  location: {
6488
6843
  filePath,
6489
- startLine: 1,
6490
- endLine: 1,
6844
+ startLine,
6845
+ endLine: startLine,
6491
6846
  startCol: 1,
6492
6847
  endCol: 100,
6493
6848
  snippet: "Mutating route handler lacks session verification or API signature check."
@@ -6511,6 +6866,23 @@ var RouteAuthAnalyzer = class {
6511
6866
 
6512
6867
  // src/auditor/risk-matrix.ts
6513
6868
  var RISK_MATRIX = {
6869
+ "CR-ARCH-01": {
6870
+ findingId: "CR-ARCH-01",
6871
+ moduleId: "route-auth-analyzer",
6872
+ technicalTitle: "Unprotected API Route",
6873
+ impact: {
6874
+ category: "DATA_BREACH_LIABILITY",
6875
+ summary: "Mutating server endpoint executes database or paid API operations without verifying caller session or authorization credentials.",
6876
+ worstCaseScenario: "Unauthenticated attackers invoke production mutation routes directly to modify tenant records, spoof state, or drain paid AI/API quotas.",
6877
+ buyerObjection: "Technical diligence audit flags unauthenticated server endpoints exposed to the public internet, triggering immediate security remediation holdbacks."
6878
+ },
6879
+ valuation: {
6880
+ dealSeverity: "DEAL_KILLER",
6881
+ multipleImpact: "-1.5x to -2.0x ARR Haircut or LOI Security Gate",
6882
+ mnaCategory: "Access Control & API Boundary Security",
6883
+ executiveVerdict: "Critical authentication boundary failure. Buyers require authenticated session guards on every mutating server endpoint prior to closing."
6884
+ }
6885
+ },
6514
6886
  "CR-ARCH-02": {
6515
6887
  findingId: "CR-ARCH-02",
6516
6888
  moduleId: "rls-analyzer",
@@ -6534,15 +6906,49 @@ var RISK_MATRIX = {
6534
6906
  technicalTitle: "Publicly Accessible Data",
6535
6907
  impact: {
6536
6908
  category: "DATA_BREACH_LIABILITY",
6537
- summary: "Table RLS policy explicitly targets 'public' role for SELECT, granting open world read permissions.",
6909
+ summary: "Table RLS policy is missing or explicitly targets 'public' / USING (true), granting open world access or zero-policy lockout.",
6538
6910
  worstCaseScenario: "Automated web scrapers extract complete application state; proprietary data sets and user lists leaked and weaponized by competitors.",
6539
- buyerObjection: "Diligence team identifies intentional policy opening data to the public internet. Demands proof of past access logs to confirm no historic exfiltration occurred before proceeding."
6911
+ buyerObjection: "Diligence team identifies incomplete or permissive RLS policies opening data to the public internet and demands proof of tenant isolation."
6540
6912
  },
6541
6913
  valuation: {
6542
6914
  dealSeverity: "DEAL_KILLER",
6543
6915
  multipleImpact: "-1.5x ARR Discount & 30-day Diligence Freeze",
6544
6916
  mnaCategory: "Access Control & Tenant Isolation",
6545
- executiveVerdict: "Severe compliance failure. The existence of permissive public policies signals undisciplined engineering, triggering deep forensics and deal retrades."
6917
+ executiveVerdict: "Severe compliance failure. Incomplete or permissive RLS policies signal undisciplined engineering, triggering deep forensics and deal retrades."
6918
+ }
6919
+ },
6920
+ "CR-DB-01": {
6921
+ findingId: "CR-DB-01",
6922
+ moduleId: "rls-analyzer",
6923
+ technicalTitle: "Unparameterized Raw SQL Injection Vector",
6924
+ impact: {
6925
+ category: "DATA_BREACH_LIABILITY",
6926
+ summary: "Application interpolates untrusted input directly into raw SQL queries ($queryRawUnsafe / template literals), enabling SQL injection.",
6927
+ worstCaseScenario: "Attacker injects arbitrary SQL payloads to exfiltrate full production tables, escalate privileges, or drop tenant schemas.",
6928
+ buyerObjection: "Classic OWASP SQL Injection vulnerability discovered in data layer; acquirer security counsel blocks closing until parameterized queries are verified."
6929
+ },
6930
+ valuation: {
6931
+ dealSeverity: "DEAL_KILLER",
6932
+ multipleImpact: "Immediate LOI Freeze & Mandatory Forensic Audit",
6933
+ mnaCategory: "Database Security & Injection Prevention",
6934
+ executiveVerdict: "Non-negotiable deal killer. Raw SQL injection vectors represent catastrophic data breach exposure and must be parameterized immediately."
6935
+ }
6936
+ },
6937
+ "CR-SEC-01": {
6938
+ findingId: "CR-SEC-01",
6939
+ moduleId: "secret-scanner",
6940
+ technicalTitle: "Google / Cloud Server API Key Leak",
6941
+ impact: {
6942
+ category: "FINANCIAL_REVENUE_FRAUD",
6943
+ summary: "Hardcoded Google Cloud server credential committed to source control exposes cloud and AI billing quotas.",
6944
+ worstCaseScenario: "Automated GitHub scrapers abuse leaked API credentials within minutes, generating five-figure cloud/LLM billing charges.",
6945
+ buyerObjection: "Hardcoded cloud credentials indicate weak secret hygiene; buyer demands full credential rotation before handover."
6946
+ },
6947
+ valuation: {
6948
+ dealSeverity: "DEAL_KILLER",
6949
+ multipleImpact: "Mandatory Key Rotation Gate Prior to Closing",
6950
+ mnaCategory: "Cloud Credential Hygiene",
6951
+ executiveVerdict: "Immediate credential hygiene blocker requiring server environment isolation and key rotation prior to handover."
6546
6952
  }
6547
6953
  },
6548
6954
  "CR-SEC-02": {
@@ -6579,6 +6985,74 @@ var RISK_MATRIX = {
6579
6985
  executiveVerdict: "Immediate financial deal killer. Live payment keys in source control contaminate financial statements and expose the business to direct capital loss."
6580
6986
  }
6581
6987
  },
6988
+ "CR-SEC-04": {
6989
+ findingId: "CR-SEC-04",
6990
+ moduleId: "secret-scanner",
6991
+ technicalTitle: "AWS IAM Access Key ID Leak",
6992
+ impact: {
6993
+ category: "DATA_BREACH_LIABILITY",
6994
+ summary: "Long-lived AWS IAM Access Key ID (AKIA*) committed to repository, exposing cloud infrastructure to unauthorized access.",
6995
+ worstCaseScenario: "Attackers enumerate S3 buckets, Secrets Manager, and EC2/RDS snapshots or spin up unauthorized compute infrastructure.",
6996
+ buyerObjection: "Cloud IAM root/programmatic credentials committed to git trigger mandatory CloudTrail compromise review."
6997
+ },
6998
+ valuation: {
6999
+ dealSeverity: "DEAL_KILLER",
7000
+ multipleImpact: "Immediate Cloud Security Freeze & IAM Audit",
7001
+ mnaCategory: "Cloud IAM & Infrastructure Security",
7002
+ executiveVerdict: "Critical cloud credential exposure. Revoke leaked IAM keys immediately and transition to short-lived OIDC roles."
7003
+ }
7004
+ },
7005
+ "CR-SEC-05": {
7006
+ findingId: "CR-SEC-05",
7007
+ moduleId: "secret-scanner",
7008
+ technicalTitle: "RSA / PEM Private Key Leak",
7009
+ impact: {
7010
+ category: "DATA_BREACH_LIABILITY",
7011
+ summary: "Unencrypted PEM/RSA/OpenSSH private key committed directly in source control.",
7012
+ worstCaseScenario: "Anyone with repository access can forge cryptographic JWTs/webhooks or impersonate production servers via SSH/TLS.",
7013
+ buyerObjection: "Compromised cryptographic signing keys require full history scrubbing and certificate re-issuance before closing."
7014
+ },
7015
+ valuation: {
7016
+ dealSeverity: "DEAL_KILLER",
7017
+ multipleImpact: "Immediate Cryptographic Key Revocation Gate",
7018
+ mnaCategory: "Cryptographic Key Hygiene",
7019
+ executiveVerdict: "Fatal cryptographic key leak. Revoke key pair immediately and purge PEM material from git history."
7020
+ }
7021
+ },
7022
+ "CR-SEC-06": {
7023
+ findingId: "CR-SEC-06",
7024
+ moduleId: "secret-scanner",
7025
+ technicalTitle: "Client-Exposed Secret Env Prefix",
7026
+ impact: {
7027
+ category: "DATA_BREACH_LIABILITY",
7028
+ summary: "Server secret variable uses NEXT_PUBLIC_ or VITE_ prefix, forcing Next.js/Vite to inline the credential into public browser JS.",
7029
+ worstCaseScenario: "Every website visitor receives privileged backend API or database secrets inside compiled client JavaScript chunks.",
7030
+ buyerObjection: "Frontend bundle inspection reveals leaked server secrets; acquirer halts diligence until secrets are rotated and isolated."
7031
+ },
7032
+ valuation: {
7033
+ dealSeverity: "DEAL_KILLER",
7034
+ multipleImpact: "-2.0x ARR Haircut & Mandatory Secret Rotation",
7035
+ mnaCategory: "Client/Server Bundle Isolation",
7036
+ executiveVerdict: "Critical client-bundle leak. Strip NEXT_PUBLIC_/VITE_ prefixes from all private keys and rotate exposed credentials."
7037
+ }
7038
+ },
7039
+ "CR-SEC-07": {
7040
+ findingId: "CR-SEC-07",
7041
+ moduleId: "secret-scanner",
7042
+ technicalTitle: "Browser-Exposed AI SDK",
7043
+ impact: {
7044
+ category: "FINANCIAL_REVENUE_FRAUD",
7045
+ summary: "OpenAI or Anthropic SDK initialized in browser bundle or with dangerouslyAllowBrowser: true.",
7046
+ worstCaseScenario: "Visitors extract live LLM API keys from browser DevTools and rack up thousands of dollars in unauthorized inference spend.",
7047
+ buyerObjection: "Unit economics and COGS are exposed to uncapped API key abuse from client-side LLM instantiation."
7048
+ },
7049
+ valuation: {
7050
+ dealSeverity: "DEAL_KILLER",
7051
+ multipleImpact: "-1.5x ARR Margin Risk & Key Rotation Gate",
7052
+ mnaCategory: "AI Infrastructure & COGS Protection",
7053
+ executiveVerdict: "Immediate COGS and credential exposure. Proxy all LLM calls through authenticated server-only route handlers."
7054
+ }
7055
+ },
6582
7056
  "CR-BIL-01": {
6583
7057
  findingId: "CR-BIL-01",
6584
7058
  moduleId: "billing-auditor",
@@ -6602,9 +7076,9 @@ var RISK_MATRIX = {
6602
7076
  technicalTitle: "Missing Webhook Secret",
6603
7077
  impact: {
6604
7078
  category: "FINANCIAL_REVENUE_FRAUD",
6605
- summary: "Stripe webhook signature validation invoked with an empty string or placeholder secret, rendering verification completely inoperable.",
6606
- worstCaseScenario: "Webhook verification fails intermittently or falls back to insecure parsing depending on SDK, dropping legitimate subscription renewal events and churning paid users.",
6607
- buyerObjection: "Billing integration is poorly configured and brittle. Buyer's engineering lead will flag revenue collection risk during code review."
7079
+ summary: "Webhook signature validation is missing (Lemon Squeezy X-Signature) or invoked with an empty/placeholder secret, rendering verification inoperable.",
7080
+ worstCaseScenario: "Spoofed subscription payloads unlock paid tiers for free or legitimate renewal webhooks fail verification.",
7081
+ buyerObjection: "Billing integration is unverified or brittle. Buyer's engineering lead will flag revenue collection risk during code review."
6608
7082
  },
6609
7083
  valuation: {
6610
7084
  dealSeverity: "ESCROW_HOLDBACK",
@@ -6613,13 +7087,30 @@ var RISK_MATRIX = {
6613
7087
  executiveVerdict: "Operational due diligence flag. Causes transaction delay while buyer demands proof of revenue reconciliation and webhook delivery logs."
6614
7088
  }
6615
7089
  },
7090
+ "CR-BIL-03": {
7091
+ findingId: "CR-BIL-03",
7092
+ moduleId: "billing-auditor",
7093
+ technicalTitle: "Unverified Paddle Webhook Handler",
7094
+ impact: {
7095
+ category: "FINANCIAL_REVENUE_FRAUD",
7096
+ summary: "Paddle billing webhook processes subscription lifecycle events without verifying Paddle-Signature via paddle.webhooks.unmarshal.",
7097
+ worstCaseScenario: "Attackers POST forged subscription.activated events to provision paid seats without paying.",
7098
+ buyerObjection: "Subscription state in database cannot be trusted without cryptographic Paddle webhook verification."
7099
+ },
7100
+ valuation: {
7101
+ dealSeverity: "VALUATION_HAIRCUT",
7102
+ multipleImpact: "-1.0x to -1.5x ARR Valuation Haircut",
7103
+ mnaCategory: "Revenue Recognition & Fraud Prevention",
7104
+ executiveVerdict: "Material billing integrity flaw requiring cryptographic webhook signature verification before financial diligence."
7105
+ }
7106
+ },
6616
7107
  "CR-PERF-01": {
6617
7108
  findingId: "CR-PERF-01",
6618
7109
  moduleId: "index-detector",
6619
7110
  technicalTitle: "Missing Foreign Key Index",
6620
7111
  impact: {
6621
7112
  category: "INFRASTRUCTURE_COLLAPSE",
6622
- summary: "Relational foreign key column lacks an index, forcing PostgreSQL sequential table scans on every joined query.",
7113
+ summary: "Relational foreign key column lacks an index, forcing sequential table scans on every joined query.",
6623
7114
  worstCaseScenario: "As tenant data reaches 50k+ rows, database CPU saturates at 100%, cascading query timeouts crash the API, and customer churn accelerates.",
6624
7115
  buyerObjection: "Database architecture will not scale post-acquisition without refactoring. Buyer discounts purchase price to cover necessary engineering re-architecture."
6625
7116
  },
@@ -6630,6 +7121,23 @@ var RISK_MATRIX = {
6630
7121
  executiveVerdict: "Classic post-LOI re-trade weapon. Acquirers leverage predictable latency spikes to negotiate a haircut on the agreed multiple."
6631
7122
  }
6632
7123
  },
7124
+ "CR-MAIN-01": {
7125
+ findingId: "CR-MAIN-01",
7126
+ moduleId: "dependency-triage",
7127
+ technicalTitle: "Deprecated Package Manifest",
7128
+ impact: {
7129
+ category: "TECHNICAL_DEBT_REWRITE",
7130
+ summary: "Package manifest is explicitly marked deprecated, signaling unmaintained upstream dependencies.",
7131
+ worstCaseScenario: "Deprecated modules accumulate unpatched CVEs and break clean production builds on modern Node runtimes.",
7132
+ buyerObjection: "Buyer deducts engineering remediation hours required to replace deprecated packages post-acquisition."
7133
+ },
7134
+ valuation: {
7135
+ dealSeverity: "RENEGOTIATION_TRIGGER",
7136
+ multipleImpact: "-$15,000 to -$40,000 Technical Debt Deduction",
7137
+ mnaCategory: "Maintainability & Tech Debt",
7138
+ executiveVerdict: "Replace deprecated packages prior to listing to eliminate avoidable buyer re-trade leverage."
7139
+ }
7140
+ },
6633
7141
  "CR-DEBT-01": {
6634
7142
  findingId: "CR-DEBT-01",
6635
7143
  moduleId: "dependency-triage",
@@ -6910,6 +7418,9 @@ var ExecutiveAuditor = class {
6910
7418
  };
6911
7419
 
6912
7420
  // src/engine.ts
7421
+ function stripCodeExt(relPath) {
7422
+ return relPath.replace(/\.(?:tsx|ts|jsx|js|mjs|cjs)$/i, "").replace(/\/index$/i, "");
7423
+ }
6913
7424
  var ClearRecordEngine = class {
6914
7425
  constructor(rootDir) {
6915
7426
  this.rootDir = rootDir;
@@ -6917,8 +7428,9 @@ var ClearRecordEngine = class {
6917
7428
  this.synthesizer = new ReportSynthesizer();
6918
7429
  this.enrichmentService = new EnrichmentService();
6919
7430
  this.executiveAuditor = new ExecutiveAuditor();
7431
+ this.rlsAnalyzer = new RlsAnalyzer();
6920
7432
  this.analyzers = {
6921
- "rls-analyzer": new RlsAnalyzer(),
7433
+ "rls-analyzer": this.rlsAnalyzer,
6922
7434
  "secret-scanner": new SecretScanner(),
6923
7435
  "billing-auditor": new BillingAuditor(),
6924
7436
  "index-detector": new IndexDetector(),
@@ -6931,40 +7443,245 @@ var ClearRecordEngine = class {
6931
7443
  synthesizer;
6932
7444
  enrichmentService;
6933
7445
  executiveAuditor;
7446
+ rlsAnalyzer;
6934
7447
  analyzers;
6935
7448
  async run() {
6936
7449
  const manifest = await this.crawler.crawl();
6937
7450
  const allFindings = [];
7451
+ const contentCache = /* @__PURE__ */ new Map();
7452
+ const readCached = async (filePath) => {
7453
+ const existing = contentCache.get(filePath);
7454
+ if (existing !== void 0) return existing;
7455
+ const text = await fs.readFile(filePath, "utf8");
7456
+ contentCache.set(filePath, text);
7457
+ return text;
7458
+ };
6938
7459
  let middlewareProtectsApi = false;
6939
- for (const filePath of manifest.files["secret-scanner"] || []) {
7460
+ let sawSupabaseMarker = false;
7461
+ let sawNonSupabaseOrm = false;
7462
+ const clientModuleRelPaths = /* @__PURE__ */ new Set();
7463
+ const authHelperModules = /* @__PURE__ */ new Set();
7464
+ const moduleImportEdges = /* @__PURE__ */ new Map();
7465
+ const serverServiceRoleModules = /* @__PURE__ */ new Map();
7466
+ const uniqueProjectFiles = new Set(Object.values(manifest.files).flat());
7467
+ for (const filePath of uniqueProjectFiles) {
6940
7468
  const normalized = filePath.replace(/\\/g, "/");
6941
- if (/(?:^|\/)(?:src\/)?middleware\.(?:ts|js|mjs)$/i.test(normalized)) {
7469
+ const relPath = path5.relative(this.rootDir, filePath).replace(/\\/g, "/");
7470
+ const lowerRel = `/${relPath.toLowerCase()}`;
7471
+ const baseName = path5.basename(normalized);
7472
+ if (lowerRel.includes("/supabase/")) {
7473
+ sawSupabaseMarker = true;
7474
+ }
7475
+ if (lowerRel.includes("/prisma/") || lowerRel.includes("/drizzle/") || baseName.endsWith(".prisma")) {
7476
+ sawNonSupabaseOrm = true;
7477
+ }
7478
+ let content = "";
7479
+ try {
7480
+ content = await readCached(filePath);
7481
+ } catch {
7482
+ continue;
7483
+ }
7484
+ if (/@supabase\/(?:supabase-js|ssr|auth-helpers)|NEXT_PUBLIC_SUPABASE_URL|SUPABASE_SERVICE_ROLE_KEY|\bauth\.uid\s*\(|\bENABLE\s+ROW\s+LEVEL\s+SECURITY\b|\bTO\s+(?:authenticated|service_role)\b/i.test(
7485
+ content
7486
+ )) {
7487
+ sawSupabaseMarker = true;
7488
+ }
7489
+ if (baseName === "package.json") {
6942
7490
  try {
6943
- const mw = await fs.readFile(filePath, "utf8");
6944
- const codeOnly = mw.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/.*$/gm, "");
6945
- const enforcesAuth = /\b(?:withAuth|authMiddleware|clerkMiddleware|updateSession|getServerSession|getToken)\b/.test(codeOnly) || codeOnly.includes("auth.getUser") || codeOnly.includes("auth.getSession");
6946
- const excludesAllApi = /\(\?\![^)]*\bapi\b/i.test(codeOnly) && !/['"]\/api\/:path\*['"]/i.test(codeOnly);
6947
- if (enforcesAuth && !excludesAllApi) {
6948
- middlewareProtectsApi = true;
6949
- break;
7491
+ const pkg = JSON.parse(content);
7492
+ const allDeps = {
7493
+ ...pkg?.dependencies && typeof pkg.dependencies === "object" ? pkg.dependencies : {},
7494
+ ...pkg?.devDependencies && typeof pkg.devDependencies === "object" ? pkg.devDependencies : {}
7495
+ };
7496
+ for (const dep of Object.keys(allDeps)) {
7497
+ if (/^@supabase\/|^supabase$/i.test(dep)) sawSupabaseMarker = true;
7498
+ if (/^@prisma\/client$|^prisma$|^drizzle-orm$|^mysql2$|^@planetscale\/database$|^typeorm$|^knex$|^kysely$/i.test(
7499
+ dep
7500
+ )) {
7501
+ sawNonSupabaseOrm = true;
7502
+ }
6950
7503
  }
6951
7504
  } catch {
6952
7505
  }
6953
7506
  }
7507
+ if (baseName.endsWith(".sql")) {
7508
+ if (/CREATE\s+TABLE\s+`/i.test(content) || /ENGINE\s*=\s*InnoDB/i.test(content)) {
7509
+ sawNonSupabaseOrm = true;
7510
+ }
7511
+ }
7512
+ if (/(?:^|\/)(?:src\/)?(?:middleware|proxy)\.(?:ts|js|mjs)$/i.test(normalized)) {
7513
+ const codeOnly = content.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/.*$/gm, "");
7514
+ const enforcesAuth = /\b(?:withAuth|authMiddleware|clerkMiddleware|updateSession|getServerSession|getToken)\b/.test(
7515
+ codeOnly
7516
+ ) || codeOnly.includes("auth.getUser") || codeOnly.includes("auth.getSession") || codeOnly.includes("cookies.get") && (codeOnly.includes("401") || codeOnly.includes("redirect"));
7517
+ const excludesAllApi = /\(\?\![^)]*\bapi\b/i.test(codeOnly) && !/['"]\/api\/:path\*['"]/i.test(codeOnly);
7518
+ if (enforcesAuth && !excludesAllApi) {
7519
+ middlewareProtectsApi = true;
7520
+ }
7521
+ }
7522
+ if (/\.(?:ts|tsx|js|jsx|mjs|cjs)$/i.test(baseName)) {
7523
+ const codeOnly = content.replace(/\/\*[\s\S]*?\*\//g, (b) => b.replace(/[^\r\n]/g, " ")).replace(/\/\/.*$/gm, "");
7524
+ const isClientFile = /^\s*['"]use client['"]/m.test(codeOnly);
7525
+ const isTopLevelUseServer = /^\s*['"]use server['"]/m.test(codeOnly);
7526
+ const hasServerOnlyGuard = isTopLevelUseServer || codeOnly.includes("'server-only'") || codeOnly.includes('"server-only"') || /\bcreateEnv\s*\(\s*\{[\s\S]*?\bserver\s*:/.test(codeOnly);
7527
+ const modKey = stripCodeExt(relPath);
7528
+ if (isClientFile) {
7529
+ clientModuleRelPaths.add(modKey);
7530
+ }
7531
+ const isStrictCallerAuthHelper = codeOnly.includes("auth()") || codeOnly.includes("auth.getUser") || codeOnly.includes("auth.getSession") || codeOnly.includes("auth.api.getSession") || codeOnly.includes("getServerSession") || codeOnly.includes("requireUser") || codeOnly.includes("currentUser") || codeOnly.includes("constructEvent") || codeOnly.includes("timingSafeEqual") || codeOnly.includes("timingSafeCompare") || /\b(?:getCurrentUser|validateRequest|getKindeServerSession|verifySlackSignature|verifyQstashSignature|verifySignature|verifyWebhook|verifyRequestSignature|checkAuth|withAuth|withSession|withCron|withWorkspace|withAdmin|withSuperAdmin|withToken|withCustomer|withPartner|ensureAuth|requireSession|authActionClient)\s*\(/.test(
7532
+ codeOnly
7533
+ ) || /headers(?:\(\))?\.get\s*\(\s*['"](?:authorization|x-api-key|stripe-signature|x-signature|paddle-signature|x-slack-signature|svix-signature|upstash-signature|x-hub-signature-256|x-shopify-hmac-sha256|x-hubspot-signature|webhook-signature)['"]\s*\)/i.test(
7534
+ codeOnly
7535
+ );
7536
+ if (isStrictCallerAuthHelper) {
7537
+ authHelperModules.add(modKey);
7538
+ }
7539
+ if (!isTopLevelUseServer) {
7540
+ const edges = moduleImportEdges.get(modKey) || /* @__PURE__ */ new Set();
7541
+ const workspacePrefixMatch = relPath.match(/^((?:apps|packages)\/[^/]+)\//);
7542
+ const workspacePrefix = workspacePrefixMatch ? workspacePrefixMatch[1] : null;
7543
+ const importSpecRegex = /(?:import|export)\s+(?!type\b)(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]|import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
7544
+ let impMatch;
7545
+ while ((impMatch = importSpecRegex.exec(codeOnly)) !== null) {
7546
+ const spec = impMatch[1] || impMatch[2];
7547
+ if (!spec) continue;
7548
+ if (spec.startsWith("@/") || spec.startsWith("~/")) {
7549
+ const sub = stripCodeExt(spec.slice(2));
7550
+ edges.add(sub);
7551
+ edges.add(`src/${sub}`);
7552
+ if (workspacePrefix) {
7553
+ edges.add(`${workspacePrefix}/${sub}`);
7554
+ edges.add(`${workspacePrefix}/src/${sub}`);
7555
+ }
7556
+ } else if (spec.startsWith("./") || spec.startsWith("../")) {
7557
+ const baseDir = path5.posix.dirname(relPath);
7558
+ const resolved = stripCodeExt(path5.posix.normalize(path5.posix.join(baseDir, spec)));
7559
+ edges.add(resolved);
7560
+ }
7561
+ }
7562
+ moduleImportEdges.set(modKey, edges);
7563
+ }
7564
+ if (!isClientFile && !hasServerOnlyGuard) {
7565
+ const refMatch = codeOnly.match(
7566
+ /(?:process\.env|import\.meta\.env)(?:\.SUPABASE_SERVICE_ROLE_KEY|\[\s*['"]SUPABASE_SERVICE_ROLE_KEY['"]\s*\])|\bgetEnvVar\s*\(\s*['"]SUPABASE_SERVICE_ROLE_KEY['"]/i
7567
+ );
7568
+ if (refMatch && refMatch.index !== void 0) {
7569
+ const line = codeOnly.slice(0, refMatch.index).split(/\r?\n/).length;
7570
+ serverServiceRoleModules.set(modKey, { filePath, line });
7571
+ }
7572
+ }
7573
+ }
7574
+ }
7575
+ const isNonSupabaseOrmOnly = !sawSupabaseMarker && sawNonSupabaseOrm;
7576
+ const sqlInputs = [];
7577
+ for (const sqlPath of (manifest.files["rls-analyzer"] || []).slice().sort()) {
7578
+ const lowerSql = sqlPath.replace(/\\/g, "/").toLowerCase();
7579
+ if (lowerSql.includes("/prisma/migrations/") || lowerSql.includes("/drizzle/")) {
7580
+ continue;
7581
+ }
7582
+ try {
7583
+ const content = await readCached(sqlPath);
7584
+ sqlInputs.push({ filePath: sqlPath, content });
7585
+ } catch (err) {
7586
+ console.error(`Error reading SQL ${sqlPath}:`, err);
7587
+ }
7588
+ }
7589
+ if (sqlInputs.length > 0) {
7590
+ allFindings.push(
7591
+ ...this.rlsAnalyzer.analyzeMigrationSuite(sqlInputs, { isNonSupabaseOrmOnly })
7592
+ );
6954
7593
  }
6955
7594
  for (const [moduleId, files] of Object.entries(manifest.files)) {
7595
+ if (moduleId === "rls-analyzer") continue;
6956
7596
  const analyzer = this.analyzers[moduleId];
6957
7597
  if (!analyzer) continue;
6958
7598
  for (const filePath of files) {
6959
7599
  try {
6960
- const content = await fs.readFile(filePath, "utf8");
6961
- const findings = moduleId === "route-auth-analyzer" ? await analyzer.analyze(filePath, content, { middlewareProtectsApi }) : await analyzer.analyze(filePath, content);
7600
+ const content = await readCached(filePath);
7601
+ let hasImportedAuthHelper = false;
7602
+ if (moduleId === "route-auth-analyzer") {
7603
+ const relRoute = stripCodeExt(path5.relative(this.rootDir, filePath).replace(/\\/g, "/"));
7604
+ const hop1Set = moduleImportEdges.get(relRoute);
7605
+ if (hop1Set) {
7606
+ for (const hop1 of hop1Set) {
7607
+ if (authHelperModules.has(hop1)) {
7608
+ hasImportedAuthHelper = true;
7609
+ break;
7610
+ }
7611
+ const hop2Set = moduleImportEdges.get(hop1);
7612
+ if (hop2Set) {
7613
+ for (const hop2 of hop2Set) {
7614
+ if (authHelperModules.has(hop2)) {
7615
+ hasImportedAuthHelper = true;
7616
+ break;
7617
+ }
7618
+ }
7619
+ }
7620
+ if (hasImportedAuthHelper) break;
7621
+ }
7622
+ }
7623
+ }
7624
+ const findings = moduleId === "route-auth-analyzer" ? await analyzer.analyze(filePath, content, {
7625
+ middlewareProtectsApi,
7626
+ hasImportedAuthHelper
7627
+ }) : await analyzer.analyze(filePath, content);
6962
7628
  allFindings.push(...findings);
6963
7629
  } catch (err) {
6964
7630
  console.error(`Error analyzing ${filePath}:`, err);
6965
7631
  }
6966
7632
  }
6967
7633
  }
7634
+ if (clientModuleRelPaths.size > 0 && serverServiceRoleModules.size > 0) {
7635
+ const reachableFromClient = new Set(clientModuleRelPaths);
7636
+ const queue = Array.from(clientModuleRelPaths);
7637
+ while (queue.length > 0) {
7638
+ const cur = queue.shift();
7639
+ if (!cur) continue;
7640
+ const targets = moduleImportEdges.get(cur);
7641
+ if (!targets) continue;
7642
+ for (const nextMod of targets) {
7643
+ if (!reachableFromClient.has(nextMod)) {
7644
+ reachableFromClient.add(nextMod);
7645
+ queue.push(nextMod);
7646
+ }
7647
+ }
7648
+ }
7649
+ for (const [modKey, info] of serverServiceRoleModules.entries()) {
7650
+ if (reachableFromClient.has(modKey)) {
7651
+ const alreadyFlagged = allFindings.some(
7652
+ (f) => f.id === "CR-SEC-02" && f.location.filePath === info.filePath
7653
+ );
7654
+ if (!alreadyFlagged) {
7655
+ allFindings.push({
7656
+ id: "CR-SEC-02",
7657
+ moduleId: "secret-scanner",
7658
+ title: "Supabase Service Role Helper Imported Into Client Component Graph",
7659
+ severity: "CRITICAL",
7660
+ cvssScore: 9.8,
7661
+ location: {
7662
+ filePath: info.filePath,
7663
+ startLine: info.line,
7664
+ endLine: info.line,
7665
+ startCol: 1,
7666
+ endCol: 100,
7667
+ snippet: 'process.env.SUPABASE_SERVICE_ROLE_KEY (reachable from "use client")'
7668
+ },
7669
+ analysis: {
7670
+ description: 'Module referencing SUPABASE_SERVICE_ROLE_KEY lacks a "server-only" guard and is imported into a "use client" component dependency graph.',
7671
+ aiContrast: "Single-file scanners miss cross-file client imports that pull server admin modules into browser bundles.",
7672
+ empiricalProof: 'Next.js client bundle includes module referencing SUPABASE_SERVICE_ROLE_KEY without import "server-only".'
7673
+ },
7674
+ remediation: {
7675
+ summary: 'Add import "server-only" and move privileged Supabase calls behind an authenticated server route handler.',
7676
+ fixScript: "import 'server-only';",
7677
+ prTitle: `Security: Isolate ${path5.basename(info.filePath)} from client bundle`
7678
+ },
7679
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
7680
+ });
7681
+ }
7682
+ }
7683
+ }
7684
+ }
6968
7685
  const enrichmentResult = this.enrichmentService.enrich(allFindings);
6969
7686
  const auditorMemo = this.executiveAuditor.generateMemo(enrichmentResult);
6970
7687
  return {
@@ -7127,11 +7844,11 @@ var CertificateGenerator = class {
7127
7844
  };
7128
7845
 
7129
7846
  // src/local-cli.ts
7130
- var CLI_VERSION = "1.2.0";
7847
+ var CLI_VERSION = "1.3.1";
7131
7848
  function parseCliArgs(args) {
7132
7849
  const options = {
7133
7850
  targetDir: process.cwd(),
7134
- reportPath: path2.join(process.cwd(), "clear-record-audit.md"),
7851
+ reportPath: path6.join(process.cwd(), "clear-record-audit.md"),
7135
7852
  saveReport: true,
7136
7853
  certificate: false,
7137
7854
  json: false,
@@ -7157,19 +7874,21 @@ function parseCliArgs(args) {
7157
7874
  const nextArg = args[i + 1];
7158
7875
  if (nextArg) {
7159
7876
  i += 1;
7160
- options.targetDir = path2.resolve(nextArg);
7877
+ options.targetDir = path6.resolve(nextArg);
7161
7878
  }
7162
7879
  } else if (arg === "--output" || arg === "-o") {
7163
7880
  const nextArg = args[i + 1];
7164
7881
  if (nextArg) {
7165
7882
  i += 1;
7166
- options.reportPath = path2.resolve(nextArg);
7883
+ options.reportPath = path6.resolve(nextArg);
7167
7884
  }
7885
+ } else if (arg && !arg.startsWith("-")) {
7886
+ options.targetDir = path6.resolve(arg);
7168
7887
  }
7169
7888
  }
7170
7889
  if (options.certificate) {
7171
- options.certificatePath = path2.join(
7172
- path2.dirname(options.reportPath),
7890
+ options.certificatePath = path6.join(
7891
+ path6.dirname(options.reportPath),
7173
7892
  "clear-record-certificate.md"
7174
7893
  );
7175
7894
  }
@@ -7204,7 +7923,7 @@ async function executeCli(options) {
7204
7923
  let certificate;
7205
7924
  const certGen = new CertificateGenerator();
7206
7925
  if (options.certificate) {
7207
- const repoBase = path2.basename(options.targetDir);
7926
+ const repoBase = path6.basename(options.targetDir);
7208
7927
  certificate = certGen.generate(result.auditorMemo, {
7209
7928
  repositoryName: repoBase
7210
7929
  });