prodlint 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -240,6 +240,81 @@ function findLoopsAST(ast) {
240
240
  });
241
241
  return loops;
242
242
  }
243
+ function isUserInputNode(node) {
244
+ if (node.type === "MemberExpression") {
245
+ const mem = node;
246
+ if (mem.object.type === "MemberExpression") {
247
+ const inner = mem.object;
248
+ if (inner.object.type === "Identifier") {
249
+ const objName = inner.object.name;
250
+ if (objName === "req" || objName === "request") {
251
+ if (inner.property.type === "Identifier") {
252
+ const prop = inner.property.name;
253
+ if (prop === "query" || prop === "body" || prop === "params") return true;
254
+ }
255
+ }
256
+ }
257
+ }
258
+ }
259
+ if (node.type === "CallExpression") {
260
+ const call = node;
261
+ if (call.callee.type === "MemberExpression") {
262
+ const callee = call.callee;
263
+ if (callee.property.type === "Identifier" && callee.property.name === "get") {
264
+ if (callee.object.type === "Identifier") {
265
+ const name = callee.object.name;
266
+ if (name === "searchParams" || name === "formData") return true;
267
+ }
268
+ if (callee.object.type === "MemberExpression") {
269
+ const inner = callee.object;
270
+ if (inner.property.type === "Identifier" && inner.property.name === "searchParams") {
271
+ return true;
272
+ }
273
+ }
274
+ }
275
+ }
276
+ }
277
+ return false;
278
+ }
279
+ function isStaticString(node) {
280
+ if (node.type === "StringLiteral") return true;
281
+ if (node.type === "TemplateLiteral") {
282
+ return node.expressions.length === 0;
283
+ }
284
+ return false;
285
+ }
286
+ function findUseEffectRanges(ast) {
287
+ const ranges = [];
288
+ walkAST(ast.program, (node) => {
289
+ if (node.type !== "CallExpression") return;
290
+ const call = node;
291
+ if (call.callee.type !== "Identifier" || call.callee.name !== "useEffect") return;
292
+ const callback = call.arguments[0];
293
+ if (!callback || !callback.loc) return;
294
+ ranges.push({
295
+ start: callback.loc.start.line - 1,
296
+ end: callback.loc.end.line - 1
297
+ });
298
+ });
299
+ return ranges;
300
+ }
301
+ function subtreeContains(node, predicate) {
302
+ if (predicate(node)) return true;
303
+ for (const key of Object.keys(node)) {
304
+ if (key === "start" || key === "end" || key === "loc" || key === "type") continue;
305
+ const val = node[key];
306
+ if (Array.isArray(val)) {
307
+ for (const item of val) {
308
+ if (item && typeof item === "object" && item.type) {
309
+ if (subtreeContains(item, predicate)) return true;
310
+ }
311
+ }
312
+ } else if (val && typeof val === "object" && val.type) {
313
+ if (subtreeContains(val, predicate)) return true;
314
+ }
315
+ }
316
+ return false;
317
+ }
243
318
 
244
319
  // src/utils/frameworks.ts
245
320
  var FRAMEWORK_SAFE_METHODS = {
@@ -309,7 +384,8 @@ var SCAN_EXTENSIONS = [
309
384
  "jsx",
310
385
  "mjs",
311
386
  "cjs",
312
- "json"
387
+ "json",
388
+ "sql"
313
389
  ];
314
390
  var AST_EXTENSIONS = /* @__PURE__ */ new Set(["ts", "tsx", "js", "jsx", "mjs", "cjs"]);
315
391
  var MAX_FILE_SIZE = 1024 * 1024;
@@ -1141,6 +1217,81 @@ var unsafeHtmlRule = {
1141
1217
  fileExtensions: ["ts", "tsx", "js", "jsx"],
1142
1218
  check(file, _project) {
1143
1219
  const findings = [];
1220
+ if (file.ast) {
1221
+ try {
1222
+ walkAST(file.ast.program, (node) => {
1223
+ if (node.type === "JSXAttribute") {
1224
+ const attr = node;
1225
+ if (attr.name?.type === "JSXIdentifier" && attr.name.name === "dangerouslySetInnerHTML" && attr.loc) {
1226
+ if (attr.value && subtreeContains(attr.value, (n) => {
1227
+ if (n.type !== "CallExpression") return false;
1228
+ const call = n;
1229
+ if (call.callee.type === "MemberExpression") {
1230
+ const mem = call.callee;
1231
+ return mem.object.type === "Identifier" && mem.object.name === "JSON" && mem.property.type === "Identifier" && mem.property.name === "stringify";
1232
+ }
1233
+ return false;
1234
+ })) {
1235
+ return;
1236
+ }
1237
+ const line = attr.loc.start.line;
1238
+ findings.push({
1239
+ ruleId: "unsafe-html",
1240
+ file: file.relativePath,
1241
+ line,
1242
+ column: file.lines[line - 1].indexOf("dangerouslySetInnerHTML") + 1,
1243
+ message: "dangerouslySetInnerHTML is an XSS risk \u2014 sanitize with DOMPurify or similar",
1244
+ severity: "critical",
1245
+ category: "security"
1246
+ });
1247
+ }
1248
+ }
1249
+ if (node.type === "ObjectProperty") {
1250
+ const prop = node;
1251
+ if (prop.key?.type === "Identifier" && prop.key.name === "dangerouslySetInnerHTML" && prop.loc) {
1252
+ if (prop.value && subtreeContains(prop.value, (n) => {
1253
+ if (n.type !== "CallExpression") return false;
1254
+ const call = n;
1255
+ if (call.callee.type === "MemberExpression") {
1256
+ const mem = call.callee;
1257
+ return mem.object.type === "Identifier" && mem.object.name === "JSON" && mem.property.type === "Identifier" && mem.property.name === "stringify";
1258
+ }
1259
+ return false;
1260
+ })) {
1261
+ return;
1262
+ }
1263
+ const line = prop.loc.start.line;
1264
+ findings.push({
1265
+ ruleId: "unsafe-html",
1266
+ file: file.relativePath,
1267
+ line,
1268
+ column: file.lines[line - 1].indexOf("dangerouslySetInnerHTML") + 1,
1269
+ message: "dangerouslySetInnerHTML is an XSS risk \u2014 sanitize with DOMPurify or similar",
1270
+ severity: "critical",
1271
+ category: "security"
1272
+ });
1273
+ }
1274
+ }
1275
+ if (node.type === "AssignmentExpression") {
1276
+ const assign = node;
1277
+ if (assign.left?.type === "MemberExpression" && assign.left.property?.type === "Identifier" && assign.left.property.name === "innerHTML" && assign.loc) {
1278
+ const line = assign.loc.start.line;
1279
+ findings.push({
1280
+ ruleId: "unsafe-html",
1281
+ file: file.relativePath,
1282
+ line,
1283
+ column: file.lines[line - 1].indexOf(".innerHTML") + 1,
1284
+ message: "Direct innerHTML assignment is an XSS risk",
1285
+ severity: "critical",
1286
+ category: "security"
1287
+ });
1288
+ }
1289
+ }
1290
+ });
1291
+ return findings;
1292
+ } catch {
1293
+ }
1294
+ }
1144
1295
  for (let i = 0; i < file.lines.length; i++) {
1145
1296
  if (isCommentLine(file.lines, i, file.commentMap)) continue;
1146
1297
  const line = file.lines[i];
@@ -1394,6 +1545,22 @@ var DIRECT_INPUT_PATTERNS = [
1394
1545
  var WARNING_PATTERNS = [
1395
1546
  /redirect\s*\(\s*(?:url|returnUrl|returnTo|redirectUrl|redirectTo|next|callbackUrl|destination|redirect|goto|to|target|uri|href)\s*[,)]/
1396
1547
  ];
1548
+ var SUSPICIOUS_VAR_NAMES = /* @__PURE__ */ new Set([
1549
+ "url",
1550
+ "returnUrl",
1551
+ "returnTo",
1552
+ "redirectUrl",
1553
+ "redirectTo",
1554
+ "next",
1555
+ "callbackUrl",
1556
+ "destination",
1557
+ "redirect",
1558
+ "goto",
1559
+ "to",
1560
+ "target",
1561
+ "uri",
1562
+ "href"
1563
+ ]);
1397
1564
  var openRedirectRule = {
1398
1565
  id: "open-redirect",
1399
1566
  name: "Open Redirect",
@@ -1403,6 +1570,62 @@ var openRedirectRule = {
1403
1570
  fileExtensions: ["ts", "tsx", "js", "jsx"],
1404
1571
  check(file, _project) {
1405
1572
  const findings = [];
1573
+ if (file.ast) {
1574
+ try {
1575
+ walkAST(file.ast.program, (node) => {
1576
+ if (node.type !== "CallExpression") return;
1577
+ const call = node;
1578
+ if (!call.loc) return;
1579
+ let isRedirect = false;
1580
+ if (call.callee.type === "Identifier" && call.callee.name === "redirect") {
1581
+ isRedirect = true;
1582
+ }
1583
+ if (call.callee.type === "MemberExpression") {
1584
+ const mem = call.callee;
1585
+ if (mem.object.type === "Identifier" && mem.object.name === "NextResponse" && mem.property.type === "Identifier" && mem.property.name === "redirect") {
1586
+ isRedirect = true;
1587
+ }
1588
+ }
1589
+ if (!isRedirect) return;
1590
+ const arg = call.arguments[0];
1591
+ if (!arg) return;
1592
+ if (isStaticString(arg)) return;
1593
+ let targetArg = arg;
1594
+ if (arg.type === "NewExpression" && arg.callee.type === "Identifier" && arg.callee.name === "URL") {
1595
+ targetArg = arg.arguments[0];
1596
+ if (!targetArg) return;
1597
+ if (isStaticString(targetArg)) return;
1598
+ }
1599
+ const lineNum = call.loc.start.line;
1600
+ const col = call.loc.start.column + 1;
1601
+ if (isUserInputNode(targetArg)) {
1602
+ findings.push({
1603
+ ruleId: "open-redirect",
1604
+ file: file.relativePath,
1605
+ line: lineNum,
1606
+ column: col,
1607
+ message: "User input in redirect \u2014 validate against an allowlist to prevent open redirect",
1608
+ severity: "warning",
1609
+ category: "security"
1610
+ });
1611
+ return;
1612
+ }
1613
+ if (targetArg.type === "Identifier" && SUSPICIOUS_VAR_NAMES.has(targetArg.name)) {
1614
+ findings.push({
1615
+ ruleId: "open-redirect",
1616
+ file: file.relativePath,
1617
+ line: lineNum,
1618
+ column: col,
1619
+ message: "Possible user input in redirect \u2014 verify the URL is validated before use",
1620
+ severity: "warning",
1621
+ category: "security"
1622
+ });
1623
+ }
1624
+ });
1625
+ return findings;
1626
+ } catch {
1627
+ }
1628
+ }
1406
1629
  for (let i = 0; i < file.lines.length; i++) {
1407
1630
  if (isCommentLine(file.lines, i, file.commentMap)) continue;
1408
1631
  const line = file.lines[i];
@@ -2050,6 +2273,34 @@ var shallowCatchRule = {
2050
2273
  if (isTestFile(file.relativePath)) return [];
2051
2274
  if (isScriptFile(file.relativePath)) return [];
2052
2275
  const findings = [];
2276
+ if (file.ast) {
2277
+ try {
2278
+ walkAST(file.ast.program, (node) => {
2279
+ if (node.type !== "CatchClause") return;
2280
+ if (!node.loc) return;
2281
+ const catchLine = node.loc.start.line - 1;
2282
+ const body = node.body;
2283
+ if (!body || !body.loc) return;
2284
+ const bodyStart = body.loc.start.line - 1;
2285
+ const bodyEnd = body.loc.end.line - 1;
2286
+ const bodyLines = file.lines.slice(bodyStart + 1, bodyEnd);
2287
+ const { score, label } = scoreCatchBody(bodyLines);
2288
+ if (score <= 1) {
2289
+ findings.push({
2290
+ ruleId: "shallow-catch",
2291
+ file: file.relativePath,
2292
+ line: catchLine + 1,
2293
+ column: file.lines[catchLine].indexOf("catch") + 1,
2294
+ message: score === 0 ? "Empty catch block \u2014 errors are silently swallowed" : `Decorative error handler: ${label}`,
2295
+ severity: score === 0 ? "warning" : "info",
2296
+ category: "reliability"
2297
+ });
2298
+ }
2299
+ });
2300
+ return findings;
2301
+ } catch {
2302
+ }
2303
+ }
2053
2304
  for (let i = 0; i < file.lines.length; i++) {
2054
2305
  if (isCommentLine(file.lines, i, file.commentMap)) continue;
2055
2306
  const trimmed = file.lines[i].trim();
@@ -2383,6 +2634,7 @@ var insecureCookieRule = {
2383
2634
 
2384
2635
  // src/rules/leaked-env-in-logs.ts
2385
2636
  var CONSOLE_WITH_ENV = /console\.(log|warn|error|info|debug)\s*\([^)]*process\.env\./;
2637
+ var CONSOLE_METHODS = /* @__PURE__ */ new Set(["log", "warn", "error", "info", "debug"]);
2386
2638
  var leakedEnvInLogsRule = {
2387
2639
  id: "leaked-env-in-logs",
2388
2640
  name: "Leaked Env in Logs",
@@ -2394,6 +2646,48 @@ var leakedEnvInLogsRule = {
2394
2646
  if (isTestFile(file.relativePath)) return [];
2395
2647
  if (isScriptFile(file.relativePath)) return [];
2396
2648
  const findings = [];
2649
+ if (file.ast) {
2650
+ try {
2651
+ walkAST(file.ast.program, (node) => {
2652
+ if (node.type !== "CallExpression") return;
2653
+ const call = node;
2654
+ if (!call.loc) return;
2655
+ if (call.callee.type !== "MemberExpression") return;
2656
+ const mem = call.callee;
2657
+ if (mem.object.type !== "Identifier" || mem.object.name !== "console") return;
2658
+ if (mem.property.type !== "Identifier" || !CONSOLE_METHODS.has(mem.property.name)) return;
2659
+ let hasEnvAccess = false;
2660
+ for (const arg of call.arguments) {
2661
+ if (subtreeContains(arg, (n) => {
2662
+ if (n.type !== "MemberExpression") return false;
2663
+ const m = n;
2664
+ if (m.object.type === "MemberExpression") {
2665
+ const inner = m.object;
2666
+ return inner.object.type === "Identifier" && inner.object.name === "process" && inner.property.type === "Identifier" && inner.property.name === "env";
2667
+ }
2668
+ return false;
2669
+ })) {
2670
+ hasEnvAccess = true;
2671
+ break;
2672
+ }
2673
+ }
2674
+ if (hasEnvAccess) {
2675
+ findings.push({
2676
+ ruleId: "leaked-env-in-logs",
2677
+ file: file.relativePath,
2678
+ line: call.loc.start.line,
2679
+ column: call.loc.start.column + 1,
2680
+ message: "process.env value in console output \u2014 may leak secrets in production logs",
2681
+ severity: "warning",
2682
+ category: "security",
2683
+ fix: "Remove process.env.* from console output \u2014 log a redacted summary instead"
2684
+ });
2685
+ }
2686
+ });
2687
+ return findings;
2688
+ } catch {
2689
+ }
2690
+ }
2397
2691
  for (let i = 0; i < file.lines.length; i++) {
2398
2692
  if (isCommentLine(file.lines, i, file.commentMap)) continue;
2399
2693
  const line = file.lines[i];
@@ -2498,6 +2792,15 @@ var nextServerActionValidationRule = {
2498
2792
  // src/rules/missing-transaction.ts
2499
2793
  var PRISMA_WRITE_OPS = /prisma\.\w+\.(?:create|update|delete|upsert|createMany|updateMany|deleteMany)\s*\(/;
2500
2794
  var PRISMA_TRANSACTION = /\$transaction\s*\(/;
2795
+ var PRISMA_WRITE_METHODS = /* @__PURE__ */ new Set([
2796
+ "create",
2797
+ "update",
2798
+ "delete",
2799
+ "upsert",
2800
+ "createMany",
2801
+ "updateMany",
2802
+ "deleteMany"
2803
+ ]);
2501
2804
  var missingTransactionRule = {
2502
2805
  id: "missing-transaction",
2503
2806
  name: "Missing Transaction",
@@ -2509,6 +2812,60 @@ var missingTransactionRule = {
2509
2812
  if (isTestFile(file.relativePath)) return [];
2510
2813
  if (isScriptFile(file.relativePath)) return [];
2511
2814
  if (!project.declaredDependencies.has("@prisma/client") && !project.detectedFrameworks.has("prisma")) return [];
2815
+ if (file.ast) {
2816
+ try {
2817
+ const parentMap = /* @__PURE__ */ new Map();
2818
+ walkAST(file.ast.program, (node, parent) => {
2819
+ if (parent) parentMap.set(node, parent);
2820
+ });
2821
+ const writesByScope = /* @__PURE__ */ new Map();
2822
+ const transactionScopes = /* @__PURE__ */ new Set();
2823
+ walkAST(file.ast.program, (node) => {
2824
+ if (node.type !== "CallExpression") return;
2825
+ const call = node;
2826
+ if (!call.loc) return;
2827
+ if (call.callee.type === "MemberExpression") {
2828
+ const mem = call.callee;
2829
+ if (mem.property.type === "Identifier" && mem.property.name === "$transaction") {
2830
+ const scope2 = findEnclosingFunction(node, parentMap);
2831
+ transactionScopes.add(scope2);
2832
+ return;
2833
+ }
2834
+ }
2835
+ if (call.callee.type !== "MemberExpression") return;
2836
+ const outerMem = call.callee;
2837
+ if (outerMem.property.type !== "Identifier") return;
2838
+ if (!PRISMA_WRITE_METHODS.has(outerMem.property.name)) return;
2839
+ if (outerMem.object.type !== "MemberExpression") return;
2840
+ const innerMem = outerMem.object;
2841
+ if (innerMem.object.type !== "Identifier" || innerMem.object.name !== "prisma") return;
2842
+ const scope = findEnclosingFunction(node, parentMap);
2843
+ const existing = writesByScope.get(scope);
2844
+ if (existing) {
2845
+ existing.count++;
2846
+ } else {
2847
+ writesByScope.set(scope, { count: 1, firstLine: call.loc.start.line });
2848
+ }
2849
+ });
2850
+ const findings = [];
2851
+ for (const [scope, { count, firstLine }] of writesByScope) {
2852
+ if (count < 2) continue;
2853
+ if (transactionScopes.has(scope)) continue;
2854
+ findings.push({
2855
+ ruleId: "missing-transaction",
2856
+ file: file.relativePath,
2857
+ line: firstLine,
2858
+ column: 1,
2859
+ message: `${count} Prisma write operations without $transaction \u2014 partial writes may leave inconsistent state`,
2860
+ severity: "warning",
2861
+ category: "reliability",
2862
+ fix: "Wrap sequential writes in prisma.$transaction([...]) for atomicity"
2863
+ });
2864
+ }
2865
+ return findings;
2866
+ } catch {
2867
+ }
2868
+ }
2512
2869
  let writeCount = 0;
2513
2870
  let firstWriteLine = -1;
2514
2871
  const hasTransaction = PRISMA_TRANSACTION.test(file.content);
@@ -2532,6 +2889,1276 @@ var missingTransactionRule = {
2532
2889
  }];
2533
2890
  }
2534
2891
  };
2892
+ function findEnclosingFunction(node, parentMap) {
2893
+ let current = parentMap.get(node);
2894
+ while (current) {
2895
+ if (current.type === "FunctionDeclaration" || current.type === "FunctionExpression" || current.type === "ArrowFunctionExpression") {
2896
+ return current;
2897
+ }
2898
+ current = parentMap.get(current);
2899
+ }
2900
+ return null;
2901
+ }
2902
+
2903
+ // src/rules/redirect-in-try-catch.ts
2904
+ var redirectInTryCatchRule = {
2905
+ id: "redirect-in-try-catch",
2906
+ name: "Redirect Inside Try/Catch",
2907
+ description: "Detects Next.js redirect() inside try/catch blocks \u2014 redirect throws internally and the catch swallows it",
2908
+ category: "reliability",
2909
+ severity: "critical",
2910
+ fileExtensions: ["ts", "tsx", "js", "jsx"],
2911
+ check(file, _project) {
2912
+ if (isTestFile(file.relativePath)) return [];
2913
+ if (!/redirect\s*\(/.test(file.content)) return [];
2914
+ const findings = [];
2915
+ let tryDepth = 0;
2916
+ for (let i = 0; i < file.lines.length; i++) {
2917
+ if (isCommentLine(file.lines, i, file.commentMap)) continue;
2918
+ const line = file.lines[i];
2919
+ const trimmed = line.trim();
2920
+ if (/\btry\s*\{/.test(trimmed) || trimmed === "try {") {
2921
+ tryDepth++;
2922
+ }
2923
+ if (/\}\s*catch\s*[\s(]/.test(trimmed)) {
2924
+ }
2925
+ if (tryDepth > 0) {
2926
+ const match = /\bredirect\s*\(/.exec(line);
2927
+ if (match && !/\/\//.test(line.slice(0, match.index))) {
2928
+ findings.push({
2929
+ ruleId: "redirect-in-try-catch",
2930
+ file: file.relativePath,
2931
+ line: i + 1,
2932
+ column: match.index + 1,
2933
+ message: "redirect() inside try/catch \u2014 Next.js redirect throws internally, the catch block will intercept it",
2934
+ severity: "critical",
2935
+ category: "reliability",
2936
+ fix: 'Move redirect() outside the try/catch block, or re-throw redirect errors in the catch: if (e instanceof Error && e.message === "NEXT_REDIRECT") throw e'
2937
+ });
2938
+ }
2939
+ }
2940
+ for (const ch of trimmed) {
2941
+ if (ch === "{" && tryDepth > 0) {
2942
+ }
2943
+ }
2944
+ if (tryDepth > 0 && /^\}\s*$/.test(trimmed)) {
2945
+ let nextLine = "";
2946
+ for (let j = i + 1; j < file.lines.length; j++) {
2947
+ nextLine = file.lines[j].trim();
2948
+ if (nextLine) break;
2949
+ }
2950
+ if (!/^catch\b/.test(nextLine) && !/^finally\b/.test(nextLine)) {
2951
+ tryDepth--;
2952
+ }
2953
+ }
2954
+ }
2955
+ return findings;
2956
+ }
2957
+ };
2958
+
2959
+ // src/rules/missing-revalidation.ts
2960
+ var USE_SERVER2 = /['"]use server['"]/;
2961
+ var DB_MUTATIONS = [
2962
+ /\.insert\s*\(/,
2963
+ /\.update\s*\(/,
2964
+ /\.delete\s*\(/,
2965
+ /\.upsert\s*\(/,
2966
+ /\.create\s*\(/,
2967
+ /\.createMany\s*\(/,
2968
+ /\.updateMany\s*\(/,
2969
+ /\.deleteMany\s*\(/,
2970
+ /\.remove\s*\(/,
2971
+ /\.save\s*\(/,
2972
+ /\.destroy\s*\(/
2973
+ ];
2974
+ var REVALIDATION = [
2975
+ /revalidatePath\s*\(/,
2976
+ /revalidateTag\s*\(/,
2977
+ /redirect\s*\(/
2978
+ ];
2979
+ var missingRevalidationRule = {
2980
+ id: "missing-revalidation",
2981
+ name: "Missing Revalidation After Mutation",
2982
+ description: "Detects server actions that mutate data without calling revalidatePath or revalidateTag \u2014 UI shows stale data",
2983
+ category: "reliability",
2984
+ severity: "warning",
2985
+ fileExtensions: ["ts", "tsx", "js", "jsx"],
2986
+ check(file, _project) {
2987
+ if (isTestFile(file.relativePath)) return [];
2988
+ if (!USE_SERVER2.test(file.content)) return [];
2989
+ const hasMutation = DB_MUTATIONS.some((p) => p.test(file.content));
2990
+ if (!hasMutation) return [];
2991
+ const hasRevalidation = REVALIDATION.some((p) => p.test(file.content));
2992
+ if (hasRevalidation) return [];
2993
+ let reportLine = 1;
2994
+ for (let i = 0; i < file.lines.length; i++) {
2995
+ if (DB_MUTATIONS.some((p) => p.test(file.lines[i]))) {
2996
+ reportLine = i + 1;
2997
+ break;
2998
+ }
2999
+ }
3000
+ return [{
3001
+ ruleId: "missing-revalidation",
3002
+ file: file.relativePath,
3003
+ line: reportLine,
3004
+ column: 1,
3005
+ message: "Server action mutates data without revalidatePath() or revalidateTag() \u2014 UI will show stale data",
3006
+ severity: "warning",
3007
+ category: "reliability",
3008
+ fix: 'Add revalidatePath("/affected-route") after the mutation'
3009
+ }];
3010
+ }
3011
+ };
3012
+
3013
+ // src/rules/use-client-overuse.ts
3014
+ var CLIENT_APIS = [
3015
+ /\buseState\b/,
3016
+ /\buseEffect\b/,
3017
+ /\buseRef\b/,
3018
+ /\buseReducer\b/,
3019
+ /\buseCallback\b/,
3020
+ /\buseMemo\b/,
3021
+ /\buseContext\b/,
3022
+ /\buseLayoutEffect\b/,
3023
+ /\buseInsertionEffect\b/,
3024
+ /\buseTransition\b/,
3025
+ /\buseDeferredValue\b/,
3026
+ /\buseSyncExternalStore\b/,
3027
+ /\buseFormStatus\b/,
3028
+ /\buseFormState\b/,
3029
+ /\buseOptimistic\b/,
3030
+ /\bonClick\b\s*[=:]/,
3031
+ /\bonChange\b\s*[=:]/,
3032
+ /\bonSubmit\b\s*[=:]/,
3033
+ /\bonBlur\b\s*[=:]/,
3034
+ /\bonFocus\b\s*[=:]/,
3035
+ /\bonKeyDown\b\s*[=:]/,
3036
+ /\bonKeyUp\b\s*[=:]/,
3037
+ /\bonMouseDown\b\s*[=:]/,
3038
+ /\bonMouseUp\b\s*[=:]/,
3039
+ /\bonScroll\b\s*[=:]/,
3040
+ /\bonInput\b\s*[=:]/,
3041
+ /\bonDrag\b/,
3042
+ /\bonDrop\b/,
3043
+ /\bonTouchStart\b/,
3044
+ /\bcreateContext\b/,
3045
+ /\bwindow\./,
3046
+ /\bdocument\./,
3047
+ /\blocalStorage\b/,
3048
+ /\bsessionStorage\b/,
3049
+ /\bnavigator\b/,
3050
+ /\bIntersectionObserver\b/,
3051
+ /\bResizeObserver\b/,
3052
+ /\bMutationObserver\b/
3053
+ ];
3054
+ var useClientOveruseRule = {
3055
+ id: "use-client-overuse",
3056
+ name: '"use client" Overuse',
3057
+ description: `Detects files with "use client" that don't use any client-side APIs \u2014 unnecessary client rendering`,
3058
+ category: "ai-quality",
3059
+ severity: "info",
3060
+ fileExtensions: ["tsx", "jsx"],
3061
+ check(file, _project) {
3062
+ if (isTestFile(file.relativePath)) return [];
3063
+ if (isConfigFile(file.relativePath)) return [];
3064
+ if (!isClientComponent(file.content)) return [];
3065
+ const usesClientApi = CLIENT_APIS.some((p) => p.test(file.content));
3066
+ if (usesClientApi) return [];
3067
+ return [{
3068
+ ruleId: "use-client-overuse",
3069
+ file: file.relativePath,
3070
+ line: 1,
3071
+ column: 1,
3072
+ message: '"use client" directive but no client-side APIs (hooks, event handlers, browser APIs) \u2014 this component could be a server component',
3073
+ severity: "info",
3074
+ category: "ai-quality",
3075
+ fix: 'Remove "use client" to let Next.js render this as a server component for better performance'
3076
+ }];
3077
+ }
3078
+ };
3079
+
3080
+ // src/rules/env-fallback-secret.ts
3081
+ var SENSITIVE_ENV = /process\.env\.(JWT_SECRET|SECRET_KEY|AUTH_SECRET|SESSION_SECRET|ENCRYPTION_KEY|API_SECRET|PRIVATE_KEY|SIGNING_KEY|NEXTAUTH_SECRET|TOKEN_SECRET|APP_SECRET|COOKIE_SECRET|HASH_SECRET)\s*(?:\|\||&&|\?\?)\s*['"`]/i;
3082
+ var ENV_FALLBACK = /process\.env\.\w*(SECRET|KEY|PASSWORD|TOKEN)\w*\s*(?:\|\||\?\?)\s*['"`]/i;
3083
+ var envFallbackSecretRule = {
3084
+ id: "env-fallback-secret",
3085
+ name: "Secret with Fallback Value",
3086
+ description: "Detects security-sensitive env vars with hardcoded fallback values \u2014 if the env var is missing, the fallback becomes the production secret",
3087
+ category: "security",
3088
+ severity: "critical",
3089
+ fileExtensions: ["ts", "tsx", "js", "jsx", "mjs", "cjs"],
3090
+ check(file, _project) {
3091
+ if (isTestFile(file.relativePath)) return [];
3092
+ const findings = [];
3093
+ for (let i = 0; i < file.lines.length; i++) {
3094
+ if (isCommentLine(file.lines, i, file.commentMap)) continue;
3095
+ const line = file.lines[i];
3096
+ const directMatch = SENSITIVE_ENV.exec(line);
3097
+ if (directMatch) {
3098
+ findings.push({
3099
+ ruleId: "env-fallback-secret",
3100
+ file: file.relativePath,
3101
+ line: i + 1,
3102
+ column: directMatch.index + 1,
3103
+ message: `Secret env var has a hardcoded fallback \u2014 if ${directMatch[1] || "the var"} is unset, this literal becomes the production secret`,
3104
+ severity: "critical",
3105
+ category: "security",
3106
+ fix: 'Throw an error if the env var is missing: const secret = process.env.SECRET ?? (() => { throw new Error("SECRET is required") })()'
3107
+ });
3108
+ continue;
3109
+ }
3110
+ const genericMatch = ENV_FALLBACK.exec(line);
3111
+ if (genericMatch && !isConfigFile(file.relativePath)) {
3112
+ findings.push({
3113
+ ruleId: "env-fallback-secret",
3114
+ file: file.relativePath,
3115
+ line: i + 1,
3116
+ column: genericMatch.index + 1,
3117
+ message: "Security-sensitive env var has a hardcoded fallback \u2014 defaults to a literal string when missing",
3118
+ severity: "warning",
3119
+ category: "security",
3120
+ fix: "Fail fast when required env vars are missing instead of falling back to a default value"
3121
+ });
3122
+ }
3123
+ }
3124
+ return findings;
3125
+ }
3126
+ };
3127
+
3128
+ // src/rules/verbose-error-response.ts
3129
+ var ERROR_LEAK_PATTERNS = [
3130
+ { pattern: /error\.stack/, msg: "error.stack exposed \u2014 leaks internal file paths and code structure" },
3131
+ { pattern: /error\.message/, msg: "error.message may leak internal details to clients" }
3132
+ ];
3133
+ var verboseErrorResponseRule = {
3134
+ id: "verbose-error-response",
3135
+ name: "Verbose Error Response",
3136
+ description: "Detects error details (stack traces, error messages) sent directly in API responses",
3137
+ category: "security",
3138
+ severity: "warning",
3139
+ fileExtensions: ["ts", "tsx", "js", "jsx"],
3140
+ check(file, _project) {
3141
+ if (isTestFile(file.relativePath)) return [];
3142
+ if (!isApiRoute(file.relativePath) && !/['"]use server['"]/.test(file.content)) return [];
3143
+ const findings = [];
3144
+ for (let i = 0; i < file.lines.length; i++) {
3145
+ if (isCommentLine(file.lines, i, file.commentMap)) continue;
3146
+ const line = file.lines[i];
3147
+ for (const { pattern, msg } of ERROR_LEAK_PATTERNS) {
3148
+ const match = pattern.exec(line);
3149
+ if (match) {
3150
+ const severity = pattern.source.includes("stack") ? "warning" : "info";
3151
+ findings.push({
3152
+ ruleId: "verbose-error-response",
3153
+ file: file.relativePath,
3154
+ line: i + 1,
3155
+ column: match.index + 1,
3156
+ message: msg,
3157
+ severity,
3158
+ category: "security",
3159
+ fix: 'Return a generic error message: { error: "Internal server error" }. Log the real error server-side.'
3160
+ });
3161
+ break;
3162
+ }
3163
+ }
3164
+ }
3165
+ return findings;
3166
+ }
3167
+ };
3168
+
3169
+ // src/rules/missing-webhook-verification.ts
3170
+ var WEBHOOK_PATH = /webhook/i;
3171
+ var VERIFICATION_PATTERNS = [
3172
+ /constructEvent\s*\(/,
3173
+ // Stripe
3174
+ /webhooks\.verify\s*\(/,
3175
+ // Clerk, GitHub
3176
+ /verify\s*\(/,
3177
+ // Generic
3178
+ /verifySignature\s*\(/,
3179
+ // Generic
3180
+ /validateWebhook\s*\(/,
3181
+ // Generic
3182
+ /svix.*verify/i,
3183
+ // Svix (used by Clerk, Resend)
3184
+ /crypto\.timingSafeEqual\s*\(/,
3185
+ // Manual HMAC comparison
3186
+ /hmac/i,
3187
+ // HMAC verification
3188
+ /x-hub-signature/i,
3189
+ // GitHub webhooks
3190
+ /stripe-signature/i,
3191
+ // Stripe signature header
3192
+ /svix-signature/i,
3193
+ // Svix signature header
3194
+ /webhook-secret/i
3195
+ ];
3196
+ var missingWebhookVerificationRule = {
3197
+ id: "missing-webhook-verification",
3198
+ name: "Missing Webhook Verification",
3199
+ description: "Detects webhook endpoints without signature verification \u2014 anyone can send fake events",
3200
+ category: "security",
3201
+ severity: "critical",
3202
+ fileExtensions: ["ts", "tsx", "js", "jsx"],
3203
+ check(file, _project) {
3204
+ if (isTestFile(file.relativePath)) return [];
3205
+ if (!isApiRoute(file.relativePath)) return [];
3206
+ if (!WEBHOOK_PATH.test(file.relativePath)) return [];
3207
+ const hasVerification = VERIFICATION_PATTERNS.some((p) => p.test(file.content));
3208
+ if (hasVerification) return [];
3209
+ let handlerLine = 1;
3210
+ for (let i = 0; i < file.lines.length; i++) {
3211
+ if (/export\s+(async\s+)?function\s+POST\b/.test(file.lines[i])) {
3212
+ handlerLine = i + 1;
3213
+ break;
3214
+ }
3215
+ }
3216
+ return [{
3217
+ ruleId: "missing-webhook-verification",
3218
+ file: file.relativePath,
3219
+ line: handlerLine,
3220
+ column: 1,
3221
+ message: "Webhook endpoint has no signature verification \u2014 anyone can forge events to this route",
3222
+ severity: "critical",
3223
+ category: "security",
3224
+ fix: "Verify the webhook signature before processing. For Stripe: stripe.webhooks.constructEvent(body, sig, secret)"
3225
+ }];
3226
+ }
3227
+ };
3228
+
3229
+ // src/rules/server-action-auth.ts
3230
+ var USE_SERVER3 = /['"]use server['"]/;
3231
+ var AUTH_PATTERNS2 = [
3232
+ /getServerSession\s*\(/,
3233
+ /getSession\s*\(/,
3234
+ /\.auth\.getUser\s*\(/,
3235
+ /auth\(\)/,
3236
+ /authenticate\s*\(/,
3237
+ /isAuthenticated/,
3238
+ /requireAuth/,
3239
+ /withAuth/,
3240
+ /getToken\s*\(/,
3241
+ /verifyToken\s*\(/,
3242
+ /jwt\.verify\s*\(/,
3243
+ /createServerComponentClient/,
3244
+ /currentUser\s*\(/,
3245
+ /getAuth\s*\(/,
3246
+ /cookies\(\).*auth/s,
3247
+ /session/i
3248
+ ];
3249
+ var PUBLIC_ACTION_NAMES = [
3250
+ /contact/i,
3251
+ /subscribe/i,
3252
+ /newsletter/i,
3253
+ /feedback/i,
3254
+ /signup/i,
3255
+ /login/i,
3256
+ /register/i
3257
+ ];
3258
+ var serverActionAuthRule = {
3259
+ id: "server-action-auth",
3260
+ name: "Server Action Without Auth",
3261
+ description: "Detects server actions that perform mutations without any authentication check",
3262
+ category: "security",
3263
+ severity: "warning",
3264
+ fileExtensions: ["ts", "tsx", "js", "jsx"],
3265
+ check(file, project) {
3266
+ if (isTestFile(file.relativePath)) return [];
3267
+ if (!USE_SERVER3.test(file.content)) return [];
3268
+ if (project.hasAuthMiddleware) return [];
3269
+ for (const p of PUBLIC_ACTION_NAMES) {
3270
+ if (p.test(file.relativePath)) return [];
3271
+ }
3272
+ const hasAuth = AUTH_PATTERNS2.some((p) => p.test(file.content));
3273
+ if (hasAuth) return [];
3274
+ const hasMutation = /\.(insert|update|delete|create|upsert|remove|destroy|save|push|set)\s*\(/i.test(file.content) || /\b(INSERT|UPDATE|DELETE)\b/.test(file.content);
3275
+ if (!hasMutation) return [];
3276
+ let reportLine = 1;
3277
+ for (let i = 0; i < file.lines.length; i++) {
3278
+ if (USE_SERVER3.test(file.lines[i])) {
3279
+ reportLine = i + 1;
3280
+ break;
3281
+ }
3282
+ }
3283
+ return [{
3284
+ ruleId: "server-action-auth",
3285
+ file: file.relativePath,
3286
+ line: reportLine,
3287
+ column: 1,
3288
+ message: "Server action performs mutations without any authentication check \u2014 anyone can call this action",
3289
+ severity: "warning",
3290
+ category: "security",
3291
+ fix: 'Add auth check: const session = await auth(); if (!session) throw new Error("Unauthorized")'
3292
+ }];
3293
+ }
3294
+ };
3295
+
3296
+ // src/rules/eval-injection.ts
3297
+ var EVAL_PATTERNS = [
3298
+ { pattern: /\beval\s*\(/, msg: "eval() executes arbitrary code \u2014 never use with dynamic input" },
3299
+ { pattern: /\bnew\s+Function\s*\(/, msg: "new Function() is equivalent to eval \u2014 avoid dynamic code execution" },
3300
+ { pattern: /\bsetTimeout\s*\(\s*['"`]/, msg: "setTimeout with a string argument is eval \u2014 pass a function instead" },
3301
+ { pattern: /\bsetInterval\s*\(\s*['"`]/, msg: "setInterval with a string argument is eval \u2014 pass a function instead" }
3302
+ ];
3303
+ var evalInjectionRule = {
3304
+ id: "eval-injection",
3305
+ name: "Eval / Code Injection",
3306
+ description: "Detects eval(), new Function(), and string arguments to setTimeout/setInterval",
3307
+ category: "security",
3308
+ severity: "critical",
3309
+ fileExtensions: ["ts", "tsx", "js", "jsx", "mjs", "cjs"],
3310
+ check(file, _project) {
3311
+ if (isTestFile(file.relativePath)) return [];
3312
+ const findings = [];
3313
+ for (let i = 0; i < file.lines.length; i++) {
3314
+ if (isCommentLine(file.lines, i, file.commentMap)) continue;
3315
+ const line = file.lines[i];
3316
+ for (const { pattern, msg } of EVAL_PATTERNS) {
3317
+ const match = pattern.exec(line);
3318
+ if (match) {
3319
+ findings.push({
3320
+ ruleId: "eval-injection",
3321
+ file: file.relativePath,
3322
+ line: i + 1,
3323
+ column: match.index + 1,
3324
+ message: msg,
3325
+ severity: "critical",
3326
+ category: "security"
3327
+ });
3328
+ break;
3329
+ }
3330
+ }
3331
+ }
3332
+ return findings;
3333
+ }
3334
+ };
3335
+
3336
+ // src/rules/missing-useeffect-cleanup.ts
3337
+ var NEEDS_CLEANUP = [
3338
+ /\bsetInterval\s*\(/,
3339
+ /\baddEventListener\s*\(/,
3340
+ /\.subscribe\s*\(/,
3341
+ /\.on\s*\(\s*['"`]/,
3342
+ /new\s+WebSocket\s*\(/,
3343
+ /new\s+EventSource\s*\(/,
3344
+ /new\s+IntersectionObserver\s*\(/,
3345
+ /new\s+ResizeObserver\s*\(/,
3346
+ /new\s+MutationObserver\s*\(/
3347
+ ];
3348
+ var missingUseEffectCleanupRule = {
3349
+ id: "missing-useeffect-cleanup",
3350
+ name: "Missing useEffect Cleanup",
3351
+ description: "Detects useEffect hooks with subscriptions or timers but no cleanup return function \u2014 causes memory leaks",
3352
+ category: "reliability",
3353
+ severity: "warning",
3354
+ fileExtensions: ["tsx", "jsx", "ts", "js"],
3355
+ check(file, _project) {
3356
+ if (isTestFile(file.relativePath)) return [];
3357
+ if (!isClientComponent(file.content)) return [];
3358
+ if (!/useEffect/.test(file.content)) return [];
3359
+ const findings = [];
3360
+ const lines = file.lines;
3361
+ for (let i = 0; i < lines.length; i++) {
3362
+ const line = lines[i];
3363
+ if (!/\buseEffect\s*\(/.test(line)) continue;
3364
+ let braceDepth = 0;
3365
+ let effectStart = -1;
3366
+ let effectEnd = -1;
3367
+ let started = false;
3368
+ for (let j = i; j < lines.length && j < i + 100; j++) {
3369
+ for (const ch of lines[j]) {
3370
+ if (ch === "(") {
3371
+ if (!started) {
3372
+ started = true;
3373
+ }
3374
+ braceDepth++;
3375
+ } else if (ch === ")") {
3376
+ braceDepth--;
3377
+ if (started && braceDepth === 0) {
3378
+ effectEnd = j;
3379
+ break;
3380
+ }
3381
+ } else if (ch === "{" && effectStart === -1 && started) {
3382
+ effectStart = j;
3383
+ }
3384
+ }
3385
+ if (effectEnd !== -1) break;
3386
+ }
3387
+ if (effectStart === -1 || effectEnd === -1) continue;
3388
+ const effectBody = lines.slice(effectStart, effectEnd + 1).join("\n");
3389
+ const needsCleanup = NEEDS_CLEANUP.some((p) => p.test(effectBody));
3390
+ if (!needsCleanup) continue;
3391
+ const hasReturn = /return\s*(?:\(\s*\)\s*=>|function|\(\))/.test(effectBody) || /return\s*\(\s*\)\s*\{/.test(effectBody) || /return\s+\w+\s*;?\s*$/.test(effectBody);
3392
+ if (!hasReturn) {
3393
+ const hasCleanupReturn = /return\s+(?:\(\)|(?:\(\s*\)\s*=>)|(?:function))/.test(effectBody);
3394
+ if (!hasCleanupReturn) {
3395
+ findings.push({
3396
+ ruleId: "missing-useeffect-cleanup",
3397
+ file: file.relativePath,
3398
+ line: i + 1,
3399
+ column: 1,
3400
+ message: "useEffect with subscription/timer but no cleanup return \u2014 will leak memory on unmount",
3401
+ severity: "warning",
3402
+ category: "reliability",
3403
+ fix: "Return a cleanup function: useEffect(() => { const id = setInterval(...); return () => clearInterval(id); }, [])"
3404
+ });
3405
+ }
3406
+ }
3407
+ }
3408
+ return findings;
3409
+ }
3410
+ };
3411
+
3412
+ // src/rules/next-public-sensitive.ts
3413
+ var SENSITIVE_PATTERN = /NEXT_PUBLIC_\w*(SECRET|PRIVATE|PASSWORD|DATABASE_URL|SERVICE_ROLE|SERVICE_KEY|ADMIN_KEY|sk_live|sk_test|SIGNING|ENCRYPTION)/i;
3414
+ var nextPublicSensitiveRule = {
3415
+ id: "next-public-sensitive",
3416
+ name: "Sensitive Env Var with NEXT_PUBLIC_ Prefix",
3417
+ description: "Detects NEXT_PUBLIC_ prefix on environment variables that should be server-only \u2014 exposes secrets to the browser",
3418
+ category: "security",
3419
+ severity: "critical",
3420
+ fileExtensions: ["ts", "tsx", "js", "jsx", "mjs", "env", "env.local", "env.production"],
3421
+ check(file, _project) {
3422
+ if (isTestFile(file.relativePath)) return [];
3423
+ const findings = [];
3424
+ for (let i = 0; i < file.lines.length; i++) {
3425
+ if (isCommentLine(file.lines, i, file.commentMap)) continue;
3426
+ const line = file.lines[i];
3427
+ const match = SENSITIVE_PATTERN.exec(line);
3428
+ if (match) {
3429
+ findings.push({
3430
+ ruleId: "next-public-sensitive",
3431
+ file: file.relativePath,
3432
+ line: i + 1,
3433
+ column: match.index + 1,
3434
+ message: `NEXT_PUBLIC_ prefix on a sensitive env var \u2014 this value will be embedded in the client-side JavaScript bundle`,
3435
+ severity: "critical",
3436
+ category: "security",
3437
+ fix: "Remove the NEXT_PUBLIC_ prefix. Access this value only in server components, API routes, or server actions."
3438
+ });
3439
+ }
3440
+ }
3441
+ return findings;
3442
+ }
3443
+ };
3444
+
3445
+ // src/rules/ssrf-risk.ts
3446
+ var USER_INPUT_IN_FETCH = [
3447
+ /fetch\s*\(\s*(?:req|request)\.(?:body|query|params|nextUrl)/,
3448
+ /fetch\s*\(\s*(?:url|href|endpoint|target|link|src)\s*[,)]/,
3449
+ /fetch\s*\(\s*searchParams\.get\s*\(/,
3450
+ /fetch\s*\(\s*formData\.get\s*\(/,
3451
+ /new\s+URL\s*\(\s*(?:req|request)\.(?:body|query)/,
3452
+ /axios\s*[.(]\s*(?:req|request)\.(?:body|query)/,
3453
+ /axios\.get\s*\(\s*(?:url|href|endpoint|target|link)\s*[,)]/
3454
+ ];
3455
+ var VALIDATION_PATTERNS3 = [
3456
+ /allowlist/i,
3457
+ /allowedUrls/i,
3458
+ /allowedHosts/i,
3459
+ /allowedDomains/i,
3460
+ /whitelist/i,
3461
+ /validUrl/i,
3462
+ /validateUrl/i,
3463
+ /URL\.canParse/,
3464
+ /new\s+URL\s*\(.*\)\.host/,
3465
+ /\.startsWith\s*\(\s*['"]https?:\/\//,
3466
+ /\.hostname\s*[!=]==?\s*['"`]/
3467
+ ];
3468
+ var SUSPICIOUS_URL_VARS = /* @__PURE__ */ new Set([
3469
+ "url",
3470
+ "href",
3471
+ "endpoint",
3472
+ "target",
3473
+ "link",
3474
+ "src"
3475
+ ]);
3476
+ var ssrfRiskRule = {
3477
+ id: "ssrf-risk",
3478
+ name: "SSRF Risk",
3479
+ description: "Detects fetch/HTTP calls with user-controlled URLs without validation \u2014 allows attackers to probe internal services",
3480
+ category: "security",
3481
+ severity: "warning",
3482
+ fileExtensions: ["ts", "tsx", "js", "jsx"],
3483
+ check(file, _project) {
3484
+ if (isTestFile(file.relativePath)) return [];
3485
+ if (!isApiRoute(file.relativePath) && !/['"]use server['"]/.test(file.content)) return [];
3486
+ const findings = [];
3487
+ if (file.ast) {
3488
+ try {
3489
+ const hasValidationInCode = VALIDATION_PATTERNS3.some((p) => p.test(file.content));
3490
+ walkAST(file.ast.program, (node) => {
3491
+ if (node.type !== "CallExpression") return;
3492
+ const call = node;
3493
+ if (!call.loc) return;
3494
+ let isFetchLike = false;
3495
+ if (call.callee.type === "Identifier" && call.callee.name === "fetch") {
3496
+ isFetchLike = true;
3497
+ }
3498
+ if (call.callee.type === "MemberExpression") {
3499
+ const mem = call.callee;
3500
+ if (mem.object.type === "Identifier" && mem.object.name === "axios") {
3501
+ isFetchLike = true;
3502
+ }
3503
+ }
3504
+ if (!isFetchLike) return;
3505
+ const arg = call.arguments[0];
3506
+ if (!arg) return;
3507
+ if (isStaticString(arg)) return;
3508
+ const lineNum = call.loc.start.line;
3509
+ const col = call.loc.start.column + 1;
3510
+ if (isUserInputNode(arg)) {
3511
+ findings.push({
3512
+ ruleId: "ssrf-risk",
3513
+ file: file.relativePath,
3514
+ line: lineNum,
3515
+ column: col,
3516
+ message: "User-controlled URL passed to fetch \u2014 validate against an allowlist to prevent SSRF",
3517
+ severity: "warning",
3518
+ category: "security",
3519
+ fix: "Validate the URL against an allowlist of permitted domains before making the request"
3520
+ });
3521
+ return;
3522
+ }
3523
+ if (arg.type === "Identifier" && SUSPICIOUS_URL_VARS.has(arg.name)) {
3524
+ if (hasValidationInCode) return;
3525
+ findings.push({
3526
+ ruleId: "ssrf-risk",
3527
+ file: file.relativePath,
3528
+ line: lineNum,
3529
+ column: col,
3530
+ message: "User-controlled URL passed to fetch \u2014 validate against an allowlist to prevent SSRF",
3531
+ severity: "warning",
3532
+ category: "security",
3533
+ fix: "Validate the URL against an allowlist of permitted domains before making the request"
3534
+ });
3535
+ }
3536
+ });
3537
+ return findings;
3538
+ } catch {
3539
+ }
3540
+ }
3541
+ const hasValidation = VALIDATION_PATTERNS3.some((p) => p.test(file.content));
3542
+ if (hasValidation) return [];
3543
+ for (let i = 0; i < file.lines.length; i++) {
3544
+ if (isCommentLine(file.lines, i, file.commentMap)) continue;
3545
+ const line = file.lines[i];
3546
+ for (const pattern of USER_INPUT_IN_FETCH) {
3547
+ const match = pattern.exec(line);
3548
+ if (match) {
3549
+ findings.push({
3550
+ ruleId: "ssrf-risk",
3551
+ file: file.relativePath,
3552
+ line: i + 1,
3553
+ column: match.index + 1,
3554
+ message: "User-controlled URL passed to fetch \u2014 validate against an allowlist to prevent SSRF",
3555
+ severity: "warning",
3556
+ category: "security",
3557
+ fix: "Validate the URL against an allowlist of permitted domains before making the request"
3558
+ });
3559
+ break;
3560
+ }
3561
+ }
3562
+ }
3563
+ return findings;
3564
+ }
3565
+ };
3566
+
3567
+ // src/rules/path-traversal.ts
3568
+ var FS_WITH_USER_INPUT = [
3569
+ { pattern: /(?:readFile|readFileSync|createReadStream)\s*\(\s*(?:req|request)\.(?:query|body|params)/, msg: "File read with user-controlled path \u2014 allows reading arbitrary files" },
3570
+ { pattern: /(?:readFile|readFileSync|createReadStream)\s*\(\s*(?:filePath|fileName|path|file|name)\s*[,)]/, msg: "File read with potentially user-controlled path \u2014 validate before use" },
3571
+ { pattern: /(?:writeFile|writeFileSync|createWriteStream)\s*\(\s*(?:req|request)\.(?:query|body|params)/, msg: "File write with user-controlled path \u2014 allows writing arbitrary files" },
3572
+ { pattern: /(?:unlink|unlinkSync|rm|rmSync)\s*\(\s*(?:req|request)\.(?:query|body|params)/, msg: "File delete with user-controlled path \u2014 allows deleting arbitrary files" },
3573
+ { pattern: /path\.join\s*\([^)]*(?:req|request)\.(?:query|body|params)/, msg: "path.join with user input \u2014 still vulnerable to traversal with ../" },
3574
+ { pattern: /\.sendFile\s*\(\s*(?:req|request)\.(?:query|body|params)/, msg: "express.sendFile with user-controlled path \u2014 validate against a base directory" }
3575
+ ];
3576
+ var SANITIZATION_PATTERNS = [
3577
+ /path\.resolve\s*\(.*\)\.startsWith/,
3578
+ /\.replace\s*\(\s*['"]\.\.['"],?\s*['"].*['"]\s*\)/,
3579
+ /\.includes\s*\(\s*['"]\.\.['"].*\)/,
3580
+ /normalize/,
3581
+ /sanitize/i,
3582
+ /realpath/
3583
+ ];
3584
+ var FS_FUNCTION_NAMES = /* @__PURE__ */ new Set([
3585
+ "readFile",
3586
+ "readFileSync",
3587
+ "createReadStream",
3588
+ "writeFile",
3589
+ "writeFileSync",
3590
+ "createWriteStream",
3591
+ "unlink",
3592
+ "unlinkSync",
3593
+ "rm",
3594
+ "rmSync"
3595
+ ]);
3596
+ var SUSPICIOUS_PATH_VARS = /* @__PURE__ */ new Set([
3597
+ "filePath",
3598
+ "fileName",
3599
+ "path",
3600
+ "file",
3601
+ "name"
3602
+ ]);
3603
+ var pathTraversalRule = {
3604
+ id: "path-traversal",
3605
+ name: "Path Traversal",
3606
+ description: "Detects filesystem operations with user-controlled paths \u2014 allows reading/writing arbitrary files via ../ sequences",
3607
+ category: "security",
3608
+ severity: "critical",
3609
+ fileExtensions: ["ts", "tsx", "js", "jsx"],
3610
+ check(file, _project) {
3611
+ if (isTestFile(file.relativePath)) return [];
3612
+ const findings = [];
3613
+ if (file.ast) {
3614
+ try {
3615
+ walkAST(file.ast.program, (node) => {
3616
+ if (node.type !== "CallExpression") return;
3617
+ const call = node;
3618
+ if (!call.loc) return;
3619
+ let fnName = null;
3620
+ if (call.callee.type === "Identifier" && FS_FUNCTION_NAMES.has(call.callee.name)) {
3621
+ fnName = call.callee.name;
3622
+ }
3623
+ if (call.callee.type === "MemberExpression") {
3624
+ const mem = call.callee;
3625
+ if (mem.property.type === "Identifier") {
3626
+ if (FS_FUNCTION_NAMES.has(mem.property.name)) {
3627
+ fnName = mem.property.name;
3628
+ }
3629
+ if (mem.property.name === "join" && mem.object.type === "Identifier" && mem.object.name === "path") {
3630
+ fnName = "path.join";
3631
+ }
3632
+ if (mem.property.name === "sendFile") {
3633
+ fnName = "sendFile";
3634
+ }
3635
+ }
3636
+ }
3637
+ if (!fnName) return;
3638
+ const argsToCheck = fnName === "path.join" ? call.arguments : [call.arguments[0]];
3639
+ for (const arg of argsToCheck) {
3640
+ if (!arg) continue;
3641
+ if (isStaticString(arg)) continue;
3642
+ const lineNum = call.loc.start.line;
3643
+ const col = call.loc.start.column + 1;
3644
+ if (isUserInputNode(arg)) {
3645
+ const action = fnName.includes("write") || fnName.includes("Write") ? "write" : fnName.includes("unlink") || fnName === "rm" || fnName === "rmSync" ? "delete" : fnName === "sendFile" ? "send" : "read";
3646
+ findings.push({
3647
+ ruleId: "path-traversal",
3648
+ file: file.relativePath,
3649
+ line: lineNum,
3650
+ column: col,
3651
+ message: fnName === "path.join" ? "path.join with user input \u2014 still vulnerable to traversal with ../" : `File ${action} with user-controlled path \u2014 allows ${action === "send" ? "sending" : action + "ing"} arbitrary files`,
3652
+ severity: "critical",
3653
+ category: "security",
3654
+ fix: "Validate the resolved path starts with an expected base directory: path.resolve(base, input).startsWith(path.resolve(base))"
3655
+ });
3656
+ return;
3657
+ }
3658
+ if (arg.type === "Identifier" && SUSPICIOUS_PATH_VARS.has(arg.name)) {
3659
+ findings.push({
3660
+ ruleId: "path-traversal",
3661
+ file: file.relativePath,
3662
+ line: lineNum,
3663
+ column: col,
3664
+ message: `File operation with potentially user-controlled path \u2014 validate before use`,
3665
+ severity: "warning",
3666
+ category: "security",
3667
+ fix: "Validate the resolved path starts with an expected base directory: path.resolve(base, input).startsWith(path.resolve(base))"
3668
+ });
3669
+ return;
3670
+ }
3671
+ }
3672
+ });
3673
+ return findings;
3674
+ } catch {
3675
+ }
3676
+ }
3677
+ const hasSanitization = SANITIZATION_PATTERNS.some((p) => p.test(file.content));
3678
+ if (hasSanitization) return [];
3679
+ for (let i = 0; i < file.lines.length; i++) {
3680
+ if (isCommentLine(file.lines, i, file.commentMap)) continue;
3681
+ const line = file.lines[i];
3682
+ for (const { pattern, msg } of FS_WITH_USER_INPUT) {
3683
+ const match = pattern.exec(line);
3684
+ if (match) {
3685
+ const severity = /req|request/.test(match[0]) ? "critical" : "warning";
3686
+ findings.push({
3687
+ ruleId: "path-traversal",
3688
+ file: file.relativePath,
3689
+ line: i + 1,
3690
+ column: match.index + 1,
3691
+ message: msg,
3692
+ severity,
3693
+ category: "security",
3694
+ fix: "Validate the resolved path starts with an expected base directory: path.resolve(base, input).startsWith(path.resolve(base))"
3695
+ });
3696
+ break;
3697
+ }
3698
+ }
3699
+ }
3700
+ return findings;
3701
+ }
3702
+ };
3703
+
3704
+ // src/rules/hydration-mismatch.ts
3705
+ var BROWSER_ONLY_PATTERNS = [
3706
+ { pattern: /\bwindow\./, msg: "window access in server-rendered code \u2014 will differ between server and client" },
3707
+ { pattern: /\bdocument\./, msg: "document access in server-rendered code \u2014 undefined on the server" },
3708
+ { pattern: /\blocalStorage\b/, msg: "localStorage in render path \u2014 undefined on server, causes hydration mismatch" },
3709
+ { pattern: /\bsessionStorage\b/, msg: "sessionStorage in render path \u2014 undefined on server, causes hydration mismatch" },
3710
+ { pattern: /\bnavigator\./, msg: "navigator access in render path \u2014 undefined on server" }
3711
+ ];
3712
+ var NONDETERMINISTIC_PATTERNS = [
3713
+ { pattern: /\bnew\s+Date\s*\(\s*\)/, msg: "new Date() in render path \u2014 server and client will have different timestamps, causing hydration mismatch" },
3714
+ { pattern: /\bDate\.now\s*\(\s*\)/, msg: "Date.now() in render path \u2014 different on server vs client" },
3715
+ { pattern: /\bMath\.random\s*\(\s*\)/, msg: "Math.random() in render path \u2014 produces different values on server vs client" }
3716
+ ];
3717
+ var hydrationMismatchRule = {
3718
+ id: "hydration-mismatch",
3719
+ name: "Hydration Mismatch Risk",
3720
+ description: "Detects browser-only APIs and non-deterministic calls in server component render paths",
3721
+ category: "reliability",
3722
+ severity: "warning",
3723
+ fileExtensions: ["tsx", "jsx", "ts", "js"],
3724
+ check(file, _project) {
3725
+ if (isTestFile(file.relativePath)) return [];
3726
+ if (isClientComponent(file.content)) return [];
3727
+ if (!/(?:^|\/)(?:src\/)?app\//.test(file.relativePath)) return [];
3728
+ if (/route\.[jt]sx?$/.test(file.relativePath)) return [];
3729
+ const findings = [];
3730
+ let useEffectRanges = [];
3731
+ if (file.ast) {
3732
+ try {
3733
+ useEffectRanges = findUseEffectRanges(file.ast);
3734
+ } catch {
3735
+ }
3736
+ }
3737
+ const hasAstRanges = useEffectRanges.length > 0 || file.ast != null;
3738
+ let insideUseEffect = false;
3739
+ for (let i = 0; i < file.lines.length; i++) {
3740
+ if (isCommentLine(file.lines, i, file.commentMap)) continue;
3741
+ const line = file.lines[i];
3742
+ if (hasAstRanges) {
3743
+ const inEffect = useEffectRanges.some((r) => i >= r.start && i <= r.end);
3744
+ if (inEffect) continue;
3745
+ } else {
3746
+ if (/\buseEffect\s*\(/.test(line)) {
3747
+ insideUseEffect = true;
3748
+ }
3749
+ if (insideUseEffect) {
3750
+ if (/^\s*\}\s*,\s*\[/.test(line) || /^\s*\}\s*\)\s*;?\s*$/.test(line)) {
3751
+ insideUseEffect = false;
3752
+ }
3753
+ continue;
3754
+ }
3755
+ }
3756
+ for (const { pattern, msg } of [...BROWSER_ONLY_PATTERNS, ...NONDETERMINISTIC_PATTERNS]) {
3757
+ const match = pattern.exec(line);
3758
+ if (match) {
3759
+ findings.push({
3760
+ ruleId: "hydration-mismatch",
3761
+ file: file.relativePath,
3762
+ line: i + 1,
3763
+ column: match.index + 1,
3764
+ message: msg,
3765
+ severity: "warning",
3766
+ category: "reliability",
3767
+ fix: 'Move this to a useEffect hook, or add "use client" if this component needs browser APIs'
3768
+ });
3769
+ break;
3770
+ }
3771
+ }
3772
+ }
3773
+ return findings;
3774
+ }
3775
+ };
3776
+
3777
+ // src/rules/server-component-fetch-self.ts
3778
+ var SELF_FETCH_PATTERNS = [
3779
+ /fetch\s*\(\s*['"`]\/api\//,
3780
+ /fetch\s*\(\s*['"`]http:\/\/localhost/,
3781
+ /fetch\s*\(\s*['"`]https?:\/\/localhost/,
3782
+ /fetch\s*\(\s*`\$\{.*\}\/api\//,
3783
+ /fetch\s*\(\s*(?:process\.env\.\w+\s*\+\s*)?['"`]\/api\//
3784
+ ];
3785
+ var serverComponentFetchSelfRule = {
3786
+ id: "server-component-fetch-self",
3787
+ name: "Server Component Fetching Own API",
3788
+ description: "Detects server components that fetch their own API routes instead of calling data logic directly \u2014 unnecessary network roundtrip",
3789
+ category: "performance",
3790
+ severity: "info",
3791
+ fileExtensions: ["tsx", "jsx", "ts", "js"],
3792
+ check(file, _project) {
3793
+ if (isTestFile(file.relativePath)) return [];
3794
+ if (isClientComponent(file.content)) return [];
3795
+ if (!/(?:^|\/)(?:src\/)?app\//.test(file.relativePath)) return [];
3796
+ if (/route\.[jt]sx?$/.test(file.relativePath)) return [];
3797
+ const findings = [];
3798
+ for (let i = 0; i < file.lines.length; i++) {
3799
+ if (isCommentLine(file.lines, i, file.commentMap)) continue;
3800
+ const line = file.lines[i];
3801
+ for (const pattern of SELF_FETCH_PATTERNS) {
3802
+ const match = pattern.exec(line);
3803
+ if (match) {
3804
+ findings.push({
3805
+ ruleId: "server-component-fetch-self",
3806
+ file: file.relativePath,
3807
+ line: i + 1,
3808
+ column: match.index + 1,
3809
+ message: "Server component fetches its own API route \u2014 call the data logic directly instead of making a network request to yourself",
3810
+ severity: "info",
3811
+ category: "performance",
3812
+ fix: 'Import and call the data function directly instead of fetch("/api/...")'
3813
+ });
3814
+ break;
3815
+ }
3816
+ }
3817
+ }
3818
+ return findings;
3819
+ }
3820
+ };
3821
+
3822
+ // src/rules/unsafe-file-upload.ts
3823
+ var UPLOAD_PATTERNS = [
3824
+ /\.get\s*\(\s*['"`]file['"`]\s*\)/,
3825
+ /\.get\s*\(\s*['"`]image['"`]\s*\)/,
3826
+ /\.get\s*\(\s*['"`]upload['"`]\s*\)/,
3827
+ /\.get\s*\(\s*['"`]attachment['"`]\s*\)/,
3828
+ /\.get\s*\(\s*['"`]document['"`]\s*\)/,
3829
+ /\.get\s*\(\s*['"`]avatar['"`]\s*\)/,
3830
+ /\.get\s*\(\s*['"`]photo['"`]\s*\)/,
3831
+ /\.type\s*===?\s*['"`]file['"`]/,
3832
+ /req\.file\b/,
3833
+ /multer/i,
3834
+ /busboy/i,
3835
+ /formidable/i
3836
+ ];
3837
+ var VALIDATION_PATTERNS4 = [
3838
+ /\.type\b.*(?:image|video|audio|pdf|text)\//,
3839
+ /content-type/i,
3840
+ /mime/i,
3841
+ /\.size\s*[><!]/,
3842
+ /maxFileSize/i,
3843
+ /maxSize/i,
3844
+ /fileSizeLimit/i,
3845
+ /allowedTypes/i,
3846
+ /acceptedTypes/i,
3847
+ /fileFilter/i,
3848
+ /\.endsWith\s*\(\s*['"`]\./,
3849
+ /\.extension/i
3850
+ ];
3851
+ var unsafeFileUploadRule = {
3852
+ id: "unsafe-file-upload",
3853
+ name: "Unsafe File Upload",
3854
+ description: "Detects file upload handlers without type or size validation",
3855
+ category: "security",
3856
+ severity: "warning",
3857
+ fileExtensions: ["ts", "tsx", "js", "jsx"],
3858
+ check(file, _project) {
3859
+ if (isTestFile(file.relativePath)) return [];
3860
+ if (!isApiRoute(file.relativePath) && !/['"]use server['"]/.test(file.content)) return [];
3861
+ const hasUpload = UPLOAD_PATTERNS.some((p) => p.test(file.content));
3862
+ if (!hasUpload) return [];
3863
+ const hasValidation = VALIDATION_PATTERNS4.some((p) => p.test(file.content));
3864
+ if (hasValidation) return [];
3865
+ let reportLine = 1;
3866
+ for (let i = 0; i < file.lines.length; i++) {
3867
+ if (UPLOAD_PATTERNS.some((p) => p.test(file.lines[i]))) {
3868
+ reportLine = i + 1;
3869
+ break;
3870
+ }
3871
+ }
3872
+ return [{
3873
+ ruleId: "unsafe-file-upload",
3874
+ file: file.relativePath,
3875
+ line: reportLine,
3876
+ column: 1,
3877
+ message: "File upload without type or size validation \u2014 accepts any file type and size",
3878
+ severity: "warning",
3879
+ category: "security",
3880
+ fix: "Validate file type (check MIME type, not just extension) and enforce a size limit before processing"
3881
+ }];
3882
+ }
3883
+ };
3884
+
3885
+ // src/rules/supabase-missing-rls.ts
3886
+ var CREATE_TABLE = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:public\.)?(\w+)/gi;
3887
+ var ENABLE_RLS = /ALTER\s+TABLE\s+(?:(?:public|"public")\.)?(\w+)\s+ENABLE\s+ROW\s+LEVEL\s+SECURITY/gi;
3888
+ var supabaseMissingRlsRule = {
3889
+ id: "supabase-missing-rls",
3890
+ name: "Missing Row-Level Security",
3891
+ description: "Detects SQL migrations that create tables without enabling Row-Level Security \u2014 all data is publicly accessible",
3892
+ category: "security",
3893
+ severity: "critical",
3894
+ fileExtensions: ["sql"],
3895
+ check(file, project) {
3896
+ if (isTestFile(file.relativePath)) return [];
3897
+ if (!/migration|supabase|schema/i.test(file.relativePath)) return [];
3898
+ const content = file.content;
3899
+ const findings = [];
3900
+ const tables = [];
3901
+ CREATE_TABLE.lastIndex = 0;
3902
+ let match;
3903
+ while ((match = CREATE_TABLE.exec(content)) !== null) {
3904
+ const name = match[1];
3905
+ if (name.startsWith("_") || name === "schema_migrations") continue;
3906
+ const beforeMatch = content.slice(0, match.index);
3907
+ const line = beforeMatch.split("\n").length;
3908
+ tables.push({ name, line });
3909
+ }
3910
+ if (tables.length === 0) return [];
3911
+ const rlsTables = /* @__PURE__ */ new Set();
3912
+ ENABLE_RLS.lastIndex = 0;
3913
+ while ((match = ENABLE_RLS.exec(content)) !== null) {
3914
+ rlsTables.add(match[1].toLowerCase());
3915
+ }
3916
+ for (const filePath of project.allFiles) {
3917
+ if (!filePath.endsWith(".sql")) continue;
3918
+ if (filePath === file.relativePath) continue;
3919
+ }
3920
+ for (const table of tables) {
3921
+ if (!rlsTables.has(table.name.toLowerCase())) {
3922
+ findings.push({
3923
+ ruleId: "supabase-missing-rls",
3924
+ file: file.relativePath,
3925
+ line: table.line,
3926
+ column: 1,
3927
+ message: `Table "${table.name}" created without ENABLE ROW LEVEL SECURITY \u2014 all rows are publicly accessible via the Supabase API`,
3928
+ severity: "critical",
3929
+ category: "security",
3930
+ fix: `Add: ALTER TABLE ${table.name} ENABLE ROW LEVEL SECURITY; and create appropriate policies`
3931
+ });
3932
+ }
3933
+ }
3934
+ return findings;
3935
+ }
3936
+ };
3937
+
3938
+ // src/rules/deprecated-oauth-flow.ts
3939
+ var IMPLICIT_GRANT = /response_type\s*[=:]\s*['"`]?token['"`]?/;
3940
+ var deprecatedOauthFlowRule = {
3941
+ id: "deprecated-oauth-flow",
3942
+ name: "Deprecated OAuth Flow",
3943
+ description: "Detects OAuth Implicit Grant flow (response_type=token) \u2014 deprecated in OAuth 2.1, vulnerable to token interception",
3944
+ category: "security",
3945
+ severity: "warning",
3946
+ fileExtensions: ["ts", "tsx", "js", "jsx", "mjs", "cjs"],
3947
+ check(file, _project) {
3948
+ if (isTestFile(file.relativePath)) return [];
3949
+ const findings = [];
3950
+ for (let i = 0; i < file.lines.length; i++) {
3951
+ if (isCommentLine(file.lines, i, file.commentMap)) continue;
3952
+ const line = file.lines[i];
3953
+ const match = IMPLICIT_GRANT.exec(line);
3954
+ if (match) {
3955
+ findings.push({
3956
+ ruleId: "deprecated-oauth-flow",
3957
+ file: file.relativePath,
3958
+ line: i + 1,
3959
+ column: match.index + 1,
3960
+ message: "OAuth Implicit Grant flow (response_type=token) is deprecated \u2014 tokens are exposed in the URL fragment",
3961
+ severity: "warning",
3962
+ category: "security",
3963
+ fix: "Use Authorization Code flow with PKCE: response_type=code with code_challenge and code_verifier"
3964
+ });
3965
+ }
3966
+ }
3967
+ return findings;
3968
+ }
3969
+ };
3970
+
3971
+ // src/rules/jwt-no-expiry.ts
3972
+ var JWT_SIGN = /jwt\.sign\s*\(/;
3973
+ var HAS_EXPIRY = [
3974
+ /expiresIn/,
3975
+ /exp\s*:/,
3976
+ /expirationTime/,
3977
+ /maxAge/
3978
+ ];
3979
+ var EXPIRY_KEYS = /* @__PURE__ */ new Set(["expiresIn", "exp", "expirationTime", "maxAge"]);
3980
+ var jwtNoExpiryRule = {
3981
+ id: "jwt-no-expiry",
3982
+ name: "JWT Without Expiration",
3983
+ description: "Detects jwt.sign() calls without an expiresIn option \u2014 tokens never expire, compromised tokens are valid forever",
3984
+ category: "security",
3985
+ severity: "warning",
3986
+ fileExtensions: ["ts", "tsx", "js", "jsx", "mjs", "cjs"],
3987
+ check(file, _project) {
3988
+ if (isTestFile(file.relativePath)) return [];
3989
+ if (!JWT_SIGN.test(file.content)) return [];
3990
+ const findings = [];
3991
+ if (file.ast) {
3992
+ try {
3993
+ walkAST(file.ast.program, (node) => {
3994
+ if (node.type !== "CallExpression") return;
3995
+ const call = node;
3996
+ if (!call.loc) return;
3997
+ if (call.callee.type !== "MemberExpression") return;
3998
+ const mem = call.callee;
3999
+ if (mem.object.type !== "Identifier" || mem.object.name !== "jwt") return;
4000
+ if (mem.property.type !== "Identifier" || mem.property.name !== "sign") return;
4001
+ let hasExpiry = false;
4002
+ for (const arg of call.arguments) {
4003
+ if (arg.type === "ObjectExpression") {
4004
+ const obj = arg;
4005
+ for (const prop of obj.properties) {
4006
+ if (prop.type === "ObjectProperty" && prop.key.type === "Identifier" && EXPIRY_KEYS.has(prop.key.name)) {
4007
+ hasExpiry = true;
4008
+ break;
4009
+ }
4010
+ }
4011
+ }
4012
+ if (hasExpiry) break;
4013
+ }
4014
+ if (!hasExpiry && call.arguments[0]?.type === "ObjectExpression") {
4015
+ const payload = call.arguments[0];
4016
+ for (const prop of payload.properties) {
4017
+ if (prop.type === "ObjectProperty" && prop.key.type === "Identifier" && prop.key.name === "exp") {
4018
+ hasExpiry = true;
4019
+ break;
4020
+ }
4021
+ }
4022
+ }
4023
+ if (!hasExpiry) {
4024
+ findings.push({
4025
+ ruleId: "jwt-no-expiry",
4026
+ file: file.relativePath,
4027
+ line: call.loc.start.line,
4028
+ column: call.loc.start.column + 1,
4029
+ message: "jwt.sign() without expiresIn \u2014 tokens never expire, a compromised token is valid forever",
4030
+ severity: "warning",
4031
+ category: "security",
4032
+ fix: 'Add expiration: jwt.sign(payload, secret, { expiresIn: "1h" })'
4033
+ });
4034
+ }
4035
+ });
4036
+ return findings;
4037
+ } catch {
4038
+ }
4039
+ }
4040
+ for (let i = 0; i < file.lines.length; i++) {
4041
+ if (isCommentLine(file.lines, i, file.commentMap)) continue;
4042
+ const line = file.lines[i];
4043
+ const match = JWT_SIGN.exec(line);
4044
+ if (!match) continue;
4045
+ const context = file.lines.slice(i, i + 6).join("\n");
4046
+ const hasExpiry = HAS_EXPIRY.some((p) => p.test(context));
4047
+ if (!hasExpiry) {
4048
+ findings.push({
4049
+ ruleId: "jwt-no-expiry",
4050
+ file: file.relativePath,
4051
+ line: i + 1,
4052
+ column: match.index + 1,
4053
+ message: "jwt.sign() without expiresIn \u2014 tokens never expire, a compromised token is valid forever",
4054
+ severity: "warning",
4055
+ category: "security",
4056
+ fix: 'Add expiration: jwt.sign(payload, secret, { expiresIn: "1h" })'
4057
+ });
4058
+ }
4059
+ }
4060
+ return findings;
4061
+ }
4062
+ };
4063
+
4064
+ // src/rules/client-side-auth-only.ts
4065
+ var CLIENT_AUTH_PATTERNS = [
4066
+ /localStorage\.(?:get|set)Item\s*\(\s*['"`](?:token|auth|session|jwt|access_token|user)['"`]/,
4067
+ /sessionStorage\.(?:get|set)Item\s*\(\s*['"`](?:token|auth|session|jwt|access_token|user)['"`]/
4068
+ ];
4069
+ var PASSWORD_CHECK = /(?:password|passwd)\s*[!=]==?\s*['"`]/;
4070
+ var clientSideAuthOnlyRule = {
4071
+ id: "client-side-auth-only",
4072
+ name: "Client-Side Auth Only",
4073
+ description: "Detects authentication logic implemented only in client-side code \u2014 easily bypassed via browser DevTools",
4074
+ category: "security",
4075
+ severity: "critical",
4076
+ fileExtensions: ["tsx", "jsx", "ts", "js"],
4077
+ check(file, _project) {
4078
+ if (isTestFile(file.relativePath)) return [];
4079
+ if (!isClientComponent(file.content)) return [];
4080
+ const findings = [];
4081
+ for (let i = 0; i < file.lines.length; i++) {
4082
+ const line = file.lines[i];
4083
+ const match = PASSWORD_CHECK.exec(line);
4084
+ if (match) {
4085
+ findings.push({
4086
+ ruleId: "client-side-auth-only",
4087
+ file: file.relativePath,
4088
+ line: i + 1,
4089
+ column: match.index + 1,
4090
+ message: "Password comparison in client-side code \u2014 the password is visible in the JavaScript bundle",
4091
+ severity: "critical",
4092
+ category: "security",
4093
+ fix: "Move authentication logic to a server action or API route"
4094
+ });
4095
+ }
4096
+ }
4097
+ for (let i = 0; i < file.lines.length; i++) {
4098
+ const line = file.lines[i];
4099
+ for (const pattern of CLIENT_AUTH_PATTERNS) {
4100
+ const match = pattern.exec(line);
4101
+ if (match) {
4102
+ findings.push({
4103
+ ruleId: "client-side-auth-only",
4104
+ file: file.relativePath,
4105
+ line: i + 1,
4106
+ column: match.index + 1,
4107
+ message: "Auth token in localStorage \u2014 accessible to any script on the page (XSS risk). Use httpOnly cookies instead.",
4108
+ severity: "warning",
4109
+ category: "security",
4110
+ fix: "Store auth tokens in httpOnly cookies set by the server, not in localStorage"
4111
+ });
4112
+ break;
4113
+ }
4114
+ }
4115
+ }
4116
+ return findings;
4117
+ }
4118
+ };
4119
+
4120
+ // src/rules/missing-abort-controller.ts
4121
+ var FETCH_CALL = /\bfetch\s*\(/;
4122
+ var HAS_TIMEOUT = [
4123
+ /AbortController/,
4124
+ /abort/i,
4125
+ /signal\s*:/,
4126
+ /timeout/i,
4127
+ /setTimeout.*abort/s
4128
+ ];
4129
+ var missingAbortControllerRule = {
4130
+ id: "missing-abort-controller",
4131
+ name: "Missing Abort Controller",
4132
+ description: "Detects fetch calls in API routes without timeout or AbortController \u2014 requests can hang indefinitely",
4133
+ category: "performance",
4134
+ severity: "info",
4135
+ fileExtensions: ["ts", "tsx", "js", "jsx"],
4136
+ check(file, _project) {
4137
+ if (isTestFile(file.relativePath)) return [];
4138
+ if (!isApiRoute(file.relativePath) && !/['"]use server['"]/.test(file.content)) return [];
4139
+ if (!FETCH_CALL.test(file.content)) return [];
4140
+ const hasTimeout = HAS_TIMEOUT.some((p) => p.test(file.content));
4141
+ if (hasTimeout) return [];
4142
+ let reportLine = 1;
4143
+ for (let i = 0; i < file.lines.length; i++) {
4144
+ if (isCommentLine(file.lines, i, file.commentMap)) continue;
4145
+ if (FETCH_CALL.test(file.lines[i])) {
4146
+ reportLine = i + 1;
4147
+ break;
4148
+ }
4149
+ }
4150
+ return [{
4151
+ ruleId: "missing-abort-controller",
4152
+ file: file.relativePath,
4153
+ line: reportLine,
4154
+ column: 1,
4155
+ message: "fetch() without timeout or AbortController \u2014 request will hang indefinitely if the upstream server doesn't respond",
4156
+ severity: "info",
4157
+ category: "performance",
4158
+ fix: "Add a timeout: const controller = new AbortController(); setTimeout(() => controller.abort(), 10000); fetch(url, { signal: controller.signal })"
4159
+ }];
4160
+ }
4161
+ };
2535
4162
 
2536
4163
  // src/rules/index.ts
2537
4164
  var rules = [
@@ -2550,6 +4177,19 @@ var rules = [
2550
4177
  leakedEnvInLogsRule,
2551
4178
  insecureRandomRule,
2552
4179
  nextServerActionValidationRule,
4180
+ envFallbackSecretRule,
4181
+ verboseErrorResponseRule,
4182
+ missingWebhookVerificationRule,
4183
+ serverActionAuthRule,
4184
+ evalInjectionRule,
4185
+ nextPublicSensitiveRule,
4186
+ ssrfRiskRule,
4187
+ pathTraversalRule,
4188
+ unsafeFileUploadRule,
4189
+ supabaseMissingRlsRule,
4190
+ deprecatedOauthFlowRule,
4191
+ jwtNoExpiryRule,
4192
+ clientSideAuthOnlyRule,
2553
4193
  // Reliability
2554
4194
  hallucinatedImportsRule,
2555
4195
  errorHandlingRule,
@@ -2558,11 +4198,17 @@ var rules = [
2558
4198
  missingLoadingStateRule,
2559
4199
  missingErrorBoundaryRule,
2560
4200
  missingTransactionRule,
4201
+ redirectInTryCatchRule,
4202
+ missingRevalidationRule,
4203
+ missingUseEffectCleanupRule,
4204
+ hydrationMismatchRule,
2561
4205
  // Performance
2562
4206
  noSyncFsRule,
2563
4207
  noNPlusOneRule,
2564
4208
  noUnboundedQueryRule,
2565
4209
  noDynamicImportLoopRule,
4210
+ serverComponentFetchSelfRule,
4211
+ missingAbortControllerRule,
2566
4212
  // AI Quality
2567
4213
  aiSmellsRule,
2568
4214
  placeholderContentRule,
@@ -2570,7 +4216,8 @@ var rules = [
2570
4216
  staleFallbackRule,
2571
4217
  comprehensionDebtRule,
2572
4218
  codebaseConsistencyRule,
2573
- deadExportsRule
4219
+ deadExportsRule,
4220
+ useClientOveruseRule
2574
4221
  ];
2575
4222
 
2576
4223
  // src/scanner.ts