circle-ir 4.20.0 → 4.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/dist/analysis/config-loader.d.ts.map +1 -1
  2. package/dist/analysis/config-loader.js +17 -2
  3. package/dist/analysis/config-loader.js.map +1 -1
  4. package/dist/analysis/constant-propagation/patterns.d.ts.map +1 -1
  5. package/dist/analysis/constant-propagation/patterns.js +3 -0
  6. package/dist/analysis/constant-propagation/patterns.js.map +1 -1
  7. package/dist/analysis/constant-propagation/propagator.d.ts +46 -1
  8. package/dist/analysis/constant-propagation/propagator.d.ts.map +1 -1
  9. package/dist/analysis/constant-propagation/propagator.js +407 -56
  10. package/dist/analysis/constant-propagation/propagator.js.map +1 -1
  11. package/dist/analysis/findings.d.ts.map +1 -1
  12. package/dist/analysis/findings.js +7 -5
  13. package/dist/analysis/findings.js.map +1 -1
  14. package/dist/analysis/interprocedural.d.ts +16 -0
  15. package/dist/analysis/interprocedural.d.ts.map +1 -1
  16. package/dist/analysis/interprocedural.js +545 -197
  17. package/dist/analysis/interprocedural.js.map +1 -1
  18. package/dist/analysis/passes/csrf-samesite-none-session-pass.d.ts +58 -0
  19. package/dist/analysis/passes/csrf-samesite-none-session-pass.d.ts.map +1 -0
  20. package/dist/analysis/passes/csrf-samesite-none-session-pass.js +159 -0
  21. package/dist/analysis/passes/csrf-samesite-none-session-pass.js.map +1 -0
  22. package/dist/analysis/passes/interprocedural-pass.d.ts.map +1 -1
  23. package/dist/analysis/passes/interprocedural-pass.js +83 -10
  24. package/dist/analysis/passes/interprocedural-pass.js.map +1 -1
  25. package/dist/analysis/passes/language-sources-pass.d.ts +21 -19
  26. package/dist/analysis/passes/language-sources-pass.d.ts.map +1 -1
  27. package/dist/analysis/passes/language-sources-pass.js +703 -25
  28. package/dist/analysis/passes/language-sources-pass.js.map +1 -1
  29. package/dist/analysis/passes/param-source-flow-gate-pass.d.ts.map +1 -1
  30. package/dist/analysis/passes/param-source-flow-gate-pass.js +71 -1
  31. package/dist/analysis/passes/param-source-flow-gate-pass.js.map +1 -1
  32. package/dist/analysis/passes/prompt-injection-safety-gate-pass.js +1 -1
  33. package/dist/analysis/passes/prompt-injection-safety-gate-pass.js.map +1 -1
  34. package/dist/analysis/passes/scan-secrets-pass.js +2 -2
  35. package/dist/analysis/passes/scan-secrets-pass.js.map +1 -1
  36. package/dist/analysis/passes/sensitive-data-in-log-pass.d.ts +66 -0
  37. package/dist/analysis/passes/sensitive-data-in-log-pass.d.ts.map +1 -0
  38. package/dist/analysis/passes/sensitive-data-in-log-pass.js +462 -0
  39. package/dist/analysis/passes/sensitive-data-in-log-pass.js.map +1 -0
  40. package/dist/analysis/passes/sink-filter-pass.d.ts +7 -1
  41. package/dist/analysis/passes/sink-filter-pass.d.ts.map +1 -1
  42. package/dist/analysis/passes/sink-filter-pass.js +372 -14
  43. package/dist/analysis/passes/sink-filter-pass.js.map +1 -1
  44. package/dist/analysis/passes/taint-propagation-pass.d.ts.map +1 -1
  45. package/dist/analysis/passes/taint-propagation-pass.js +289 -13
  46. package/dist/analysis/passes/taint-propagation-pass.js.map +1 -1
  47. package/dist/analysis/project-callee-escape-gate.js +1 -1
  48. package/dist/analysis/project-callee-escape-gate.js.map +1 -1
  49. package/dist/analysis/rules.d.ts.map +1 -1
  50. package/dist/analysis/rules.js +9 -0
  51. package/dist/analysis/rules.js.map +1 -1
  52. package/dist/analysis/sbom.d.ts +49 -0
  53. package/dist/analysis/sbom.d.ts.map +1 -1
  54. package/dist/analysis/sbom.js +126 -1
  55. package/dist/analysis/sbom.js.map +1 -1
  56. package/dist/analysis/taint-matcher.d.ts.map +1 -1
  57. package/dist/analysis/taint-matcher.js +85 -16
  58. package/dist/analysis/taint-matcher.js.map +1 -1
  59. package/dist/analysis/taint-propagation.d.ts +1 -0
  60. package/dist/analysis/taint-propagation.d.ts.map +1 -1
  61. package/dist/analysis/taint-propagation.js +32 -0
  62. package/dist/analysis/taint-propagation.js.map +1 -1
  63. package/dist/analysis/test-to-production-taint-gate.d.ts +13 -0
  64. package/dist/analysis/test-to-production-taint-gate.d.ts.map +1 -0
  65. package/dist/analysis/test-to-production-taint-gate.js +30 -0
  66. package/dist/analysis/test-to-production-taint-gate.js.map +1 -0
  67. package/dist/analyzer.d.ts +15 -3
  68. package/dist/analyzer.d.ts.map +1 -1
  69. package/dist/analyzer.js +56 -2
  70. package/dist/analyzer.js.map +1 -1
  71. package/dist/browser/circle-ir.js +5149 -2477
  72. package/dist/core/circle-ir-core.cjs +2969 -2223
  73. package/dist/core/circle-ir-core.js +2969 -2219
  74. package/dist/core/extractors/calls.d.ts +10 -1
  75. package/dist/core/extractors/calls.d.ts.map +1 -1
  76. package/dist/core/extractors/calls.js +148 -6
  77. package/dist/core/extractors/calls.js.map +1 -1
  78. package/dist/core/extractors/cfg.d.ts.map +1 -1
  79. package/dist/core/extractors/cfg.js +12 -0
  80. package/dist/core/extractors/cfg.js.map +1 -1
  81. package/dist/core/extractors/dfg.d.ts.map +1 -1
  82. package/dist/core/extractors/dfg.js +151 -18
  83. package/dist/core/extractors/dfg.js.map +1 -1
  84. package/dist/core/extractors/types.d.ts +5 -0
  85. package/dist/core/extractors/types.d.ts.map +1 -1
  86. package/dist/core/extractors/types.js +149 -4
  87. package/dist/core/extractors/types.js.map +1 -1
  88. package/dist/core/parser.d.ts.map +1 -1
  89. package/dist/core/parser.js +3 -1
  90. package/dist/core/parser.js.map +1 -1
  91. package/dist/core/ts-grammar-workarounds.d.ts +18 -0
  92. package/dist/core/ts-grammar-workarounds.d.ts.map +1 -0
  93. package/dist/core/ts-grammar-workarounds.js +40 -0
  94. package/dist/core/ts-grammar-workarounds.js.map +1 -0
  95. package/dist/facts/facts2.d.ts +12 -3
  96. package/dist/facts/facts2.d.ts.map +1 -1
  97. package/dist/facts/facts2.js +24 -7
  98. package/dist/facts/facts2.js.map +1 -1
  99. package/dist/facts/index.d.ts +3 -1
  100. package/dist/facts/index.d.ts.map +1 -1
  101. package/dist/facts/index.js +2 -1
  102. package/dist/facts/index.js.map +1 -1
  103. package/dist/facts/schema2.d.ts +3 -3
  104. package/dist/facts/schema2.js +3 -3
  105. package/dist/facts/t6.d.ts +84 -0
  106. package/dist/facts/t6.d.ts.map +1 -0
  107. package/dist/facts/t6.js +226 -0
  108. package/dist/facts/t6.js.map +1 -0
  109. package/dist/graph-facts/dead-code.d.ts.map +1 -1
  110. package/dist/graph-facts/dead-code.js +3 -2
  111. package/dist/graph-facts/dead-code.js.map +1 -1
  112. package/dist/graph-facts/index.d.ts +1 -1
  113. package/dist/graph-facts/index.d.ts.map +1 -1
  114. package/dist/graph-facts/index.js +1 -1
  115. package/dist/graph-facts/index.js.map +1 -1
  116. package/dist/graph-facts/reach.d.ts +31 -4
  117. package/dist/graph-facts/reach.d.ts.map +1 -1
  118. package/dist/graph-facts/reach.js +120 -4
  119. package/dist/graph-facts/reach.js.map +1 -1
  120. package/dist/index.d.ts +8 -6
  121. package/dist/index.d.ts.map +1 -1
  122. package/dist/index.js +11 -7
  123. package/dist/index.js.map +1 -1
  124. package/dist/navigation/index.d.ts +1 -0
  125. package/dist/navigation/index.d.ts.map +1 -1
  126. package/dist/navigation/index.js +1 -0
  127. package/dist/navigation/index.js.map +1 -1
  128. package/dist/navigation/java-graph.d.ts +31 -9
  129. package/dist/navigation/java-graph.d.ts.map +1 -1
  130. package/dist/navigation/java-graph.js +174 -11
  131. package/dist/navigation/java-graph.js.map +1 -1
  132. package/dist/navigation/java-registrations.d.ts +93 -0
  133. package/dist/navigation/java-registrations.d.ts.map +1 -0
  134. package/dist/navigation/java-registrations.js +254 -0
  135. package/dist/navigation/java-registrations.js.map +1 -0
  136. package/dist/navigation/navigation-index.d.ts +65 -3
  137. package/dist/navigation/navigation-index.d.ts.map +1 -1
  138. package/dist/navigation/navigation-index.js +181 -11
  139. package/dist/navigation/navigation-index.js.map +1 -1
  140. package/dist/navigation/ts-call-edges.d.ts +6 -0
  141. package/dist/navigation/ts-call-edges.d.ts.map +1 -1
  142. package/dist/navigation/ts-call-edges.js.map +1 -1
  143. package/dist/navigation/ts-entry-tables.d.ts +1 -1
  144. package/dist/navigation/ts-entry-tables.d.ts.map +1 -1
  145. package/dist/navigation/ts-entry-tables.js.map +1 -1
  146. package/dist/navigation/xml-scan.d.ts +40 -0
  147. package/dist/navigation/xml-scan.d.ts.map +1 -0
  148. package/dist/navigation/xml-scan.js +269 -0
  149. package/dist/navigation/xml-scan.js.map +1 -0
  150. package/dist/stable-ids/index.d.ts +3 -3
  151. package/dist/stable-ids/index.d.ts.map +1 -1
  152. package/dist/stable-ids/index.js +16 -4
  153. package/dist/stable-ids/index.js.map +1 -1
  154. package/dist/stable-ids/nodes.d.ts +16 -6
  155. package/dist/stable-ids/nodes.d.ts.map +1 -1
  156. package/dist/stable-ids/nodes.js +17 -7
  157. package/dist/stable-ids/nodes.js.map +1 -1
  158. package/dist/stable-ids/ts-parse-errors.d.ts.map +1 -1
  159. package/dist/stable-ids/ts-parse-errors.js +21 -2
  160. package/dist/stable-ids/ts-parse-errors.js.map +1 -1
  161. package/dist/stable-ids/typescript.d.ts +5 -0
  162. package/dist/stable-ids/typescript.d.ts.map +1 -1
  163. package/dist/stable-ids/typescript.js +41 -8
  164. package/dist/stable-ids/typescript.js.map +1 -1
  165. package/dist/types/index.d.ts +21 -3
  166. package/dist/types/index.d.ts.map +1 -1
  167. package/dist/types/index.js +1 -0
  168. package/dist/types/index.js.map +1 -1
  169. package/docs/SPEC.md +9 -0
  170. package/package.json +3 -3
@@ -198,8 +198,14 @@ export class LanguageSourcesPass {
198
198
  additionalSources.push(...findOopFieldReadSources(types, code, language));
199
199
  // -- Java (#78 round 2): static field stores inside the same class -------
200
200
  additionalSources.push(...findStaticFieldSources(types, code, language));
201
+ // -- Java #1198: instance-field HTTP stores + reflection Field.get reads -
202
+ additionalSources.push(...findJavaInstanceFieldHttpSources(types, code, language));
203
+ additionalSources.push(...findJavaReflectionFieldGetSources(types, code, language));
204
+ additionalSources.push(...findJavaReflectionFieldSetSources(types, code, language));
201
205
  // -- Java (#78 round 2): non-bean setter/getter chains -------------------
202
206
  additionalSources.push(...findSetterChainSources(types, code, language));
207
+ // -- Java #1198: taint stored on locals' instance fields (Basic29-style) -
208
+ additionalSources.push(...findJavaHeapFieldDerivedSources(code, language));
203
209
  // -- JavaScript/TypeScript: assignment sources and DOM XSS sinks ---------
204
210
  additionalSources.push(...findJavaScriptAssignmentSources(code, language));
205
211
  // -- C#: explicit ASP.NET request sources --------------------------------
@@ -492,6 +498,8 @@ export class LanguageSourcesPass {
492
498
  additionalSanitizers.push(...findJsParameterizedSqlSanitizers(code));
493
499
  // #223 REG-144-20: JS path.resolve/join + startsWith(root) guard.
494
500
  additionalSanitizers.push(...findJsPathResolveStartsWithGuardSanitizers(code));
501
+ // JS/TS open_redirect: a same-site relative-path guard that rejects `//` AND `/\`.
502
+ additionalSanitizers.push(...findJsRelativeRedirectGuardSanitizers(code));
495
503
  // cognium-dev#1146: same-file helper returns path.resolve after allow-list guard.
496
504
  additionalSanitizers.push(...findJsPathAllowlistHelperSanitizers(code));
497
505
  // #223 REG-144-17/18/19: JS/TS command allowlist guard
@@ -1033,6 +1041,182 @@ function findStaticFieldSources(types, sourceCode, language) {
1033
1041
  }
1034
1042
  return sources;
1035
1043
  }
1044
+ const JAVA_HTTP_RHS_PATTERN = /\b(?:req|request|httpRequest|servletRequest|httpServletRequest)\.(?:getParameter|getParameterValues|getParameterMap|getHeader|getHeaders|getCookies|getQueryString|getPathInfo|getRequestURI|getRequestURL|getInputStream|getReader)\b/;
1045
+ /** Shared line matchers for reflection field get/set heuristics (#1198). */
1046
+ const JAVA_DECLARE_FIELD_LINE_RE = /^\s*(?:[\w.]+\s+)?Field\s+(\w+)\s*=\s*.+\.(?:getField|getDeclaredField)\s*\(\s*"([^"]+)"\s*\)/;
1047
+ const JAVA_FIELD_SET_LINE_RE = /^\s*(\w+)\.set\s*\(\s*(\w+)\s*,\s*(\w+)\s*\)\s*;?/;
1048
+ /** cognium-dev #1198 — heap field stores `base.field = rhs;` (shared for regex-lint budget). */
1049
+ const JAVA_LOCAL_FIELD_ASSIGN_LINE_RE = /^\s*([A-Za-z_]\w*)\.([A-Za-z_]\w*)\s*=\s*(.+?);\s*$/;
1050
+ const JAVA_BARE_ASSIGN_LINE_RE = /^\s*([A-Za-z_]\w*)\s*=\s*(.+?)(?:;\s*)?$/;
1051
+ /**
1052
+ * cognium-dev #1198 — Instance (non-static) field assigned from HTTP in any method.
1053
+ * Complements constructor-only #78 field sources (SecuriBench `Refl2` writes `name` in
1054
+ * `doGet`, not the ctor).
1055
+ */
1056
+ function findJavaInstanceFieldHttpSources(types, sourceCode, language) {
1057
+ if (language !== 'java')
1058
+ return [];
1059
+ const sources = [];
1060
+ const lines = sourceCode.split('\n');
1061
+ for (const type of types) {
1062
+ if (type.kind !== 'class' || type.name === '<module>')
1063
+ continue;
1064
+ const instanceFields = new Set(type.fields.filter(f => !f.modifiers.includes('static')).map(f => f.name));
1065
+ if (instanceFields.size === 0)
1066
+ continue;
1067
+ for (const m of type.methods) {
1068
+ const mStart = m.start_line;
1069
+ const mEnd = m.end_line;
1070
+ for (let i = mStart - 1; i < Math.min(mEnd, lines.length); i++) {
1071
+ const trimmed = (lines[i] ?? '').trim();
1072
+ if (!trimmed || trimmed.startsWith('//'))
1073
+ continue;
1074
+ const bm = trimmed.match(JAVA_BARE_ASSIGN_LINE_RE);
1075
+ if (!bm)
1076
+ continue;
1077
+ const fieldName = bm[1];
1078
+ const rhs = bm[2].trim().replace(/;\s*$/, '');
1079
+ if (!instanceFields.has(fieldName))
1080
+ continue;
1081
+ if (!JAVA_HTTP_RHS_PATTERN.test(rhs))
1082
+ continue;
1083
+ sources.push({
1084
+ type: 'http_param',
1085
+ location: `${type.name}.${fieldName} instance field (this.) set in ${m.name}() — #1198`,
1086
+ severity: 'high',
1087
+ line: i + 1,
1088
+ confidence: 0.85,
1089
+ variable: `this.${fieldName}`,
1090
+ });
1091
+ }
1092
+ }
1093
+ }
1094
+ return sources;
1095
+ }
1096
+ /**
1097
+ * cognium-dev #1198 — `Field.get` on a reflectively looked-up instance field that was
1098
+ * tainted earlier in the class (SecuriBench `Refl2`).
1099
+ */
1100
+ function findJavaReflectionFieldGetSources(types, sourceCode, language) {
1101
+ if (language !== 'java')
1102
+ return [];
1103
+ const lines = sourceCode.split('\n');
1104
+ const taintedFieldNames = new Set();
1105
+ for (const type of types) {
1106
+ if (type.kind !== 'class' || type.name === '<module>')
1107
+ continue;
1108
+ const instanceFields = new Set(type.fields.filter(f => !f.modifiers.includes('static')).map(f => f.name));
1109
+ for (const m of type.methods) {
1110
+ for (let i = m.start_line - 1; i < Math.min(m.end_line, lines.length); i++) {
1111
+ const trimmed = (lines[i] ?? '').trim();
1112
+ if (!trimmed || trimmed.startsWith('//'))
1113
+ continue;
1114
+ const bm = trimmed.match(JAVA_BARE_ASSIGN_LINE_RE);
1115
+ if (!bm)
1116
+ continue;
1117
+ const fieldName = bm[1];
1118
+ const rhs = bm[2].trim().replace(/;\s*$/, '');
1119
+ if (instanceFields.has(fieldName) && JAVA_HTTP_RHS_PATTERN.test(rhs)) {
1120
+ taintedFieldNames.add(fieldName);
1121
+ }
1122
+ }
1123
+ }
1124
+ }
1125
+ if (taintedFieldNames.size === 0)
1126
+ return [];
1127
+ const sources = [];
1128
+ const fieldVarToName = new Map();
1129
+ const fieldGetAssignRe = /^\s*(?:[\w.]+\s+)?(\w+)\s*=\s*\([^)]*\)\s*(\w+)\.get\s*\(/;
1130
+ for (let i = 0; i < lines.length; i++) {
1131
+ const trimmed = (lines[i] ?? '').trim();
1132
+ if (!trimmed || trimmed.startsWith('//'))
1133
+ continue;
1134
+ const decl = trimmed.match(JAVA_DECLARE_FIELD_LINE_RE);
1135
+ if (decl) {
1136
+ const [, varName, reflectedField] = decl;
1137
+ if (taintedFieldNames.has(reflectedField)) {
1138
+ fieldVarToName.set(varName, reflectedField);
1139
+ }
1140
+ continue;
1141
+ }
1142
+ const assign = trimmed.match(fieldGetAssignRe);
1143
+ if (!assign)
1144
+ continue;
1145
+ const [, lhs, fieldVar] = assign;
1146
+ const reflectedField = fieldVarToName.get(fieldVar);
1147
+ if (!reflectedField)
1148
+ continue;
1149
+ sources.push({
1150
+ type: 'http_param',
1151
+ location: `Field.get("${reflectedField}") assignment — #1198`,
1152
+ severity: 'high',
1153
+ line: i + 1,
1154
+ confidence: 0.85,
1155
+ variable: lhs,
1156
+ });
1157
+ }
1158
+ return sources;
1159
+ }
1160
+ /**
1161
+ * cognium-dev #1198 — `Field.set` stores HTTP-tainted data into a reflectively
1162
+ * looked-up instance field (`Refl3`: set on inner class field, read at sink).
1163
+ */
1164
+ function findJavaReflectionFieldSetSources(types, sourceCode, language) {
1165
+ if (language !== 'java')
1166
+ return [];
1167
+ const lines = sourceCode.split('\n');
1168
+ const taintedVars = new Set();
1169
+ for (const type of types) {
1170
+ if (type.kind !== 'class' || type.name === '<module>')
1171
+ continue;
1172
+ for (const m of type.methods) {
1173
+ for (let i = m.start_line - 1; i < Math.min(m.end_line, lines.length); i++) {
1174
+ const trimmed = (lines[i] ?? '').trim();
1175
+ if (!trimmed || trimmed.startsWith('//'))
1176
+ continue;
1177
+ const bm = trimmed.match(JAVA_BARE_ASSIGN_LINE_RE);
1178
+ if (!bm)
1179
+ continue;
1180
+ const rhs = bm[2].trim().replace(/;\s*$/, '');
1181
+ if (JAVA_HTTP_RHS_PATTERN.test(rhs)) {
1182
+ taintedVars.add(bm[1]);
1183
+ }
1184
+ }
1185
+ }
1186
+ }
1187
+ if (taintedVars.size === 0)
1188
+ return [];
1189
+ const fieldVarToName = new Map();
1190
+ const sources = [];
1191
+ for (let i = 0; i < lines.length; i++) {
1192
+ const trimmed = (lines[i] ?? '').trim();
1193
+ if (!trimmed || trimmed.startsWith('//'))
1194
+ continue;
1195
+ const decl = trimmed.match(JAVA_DECLARE_FIELD_LINE_RE);
1196
+ if (decl) {
1197
+ fieldVarToName.set(decl[1], decl[2]);
1198
+ continue;
1199
+ }
1200
+ const setM = trimmed.match(JAVA_FIELD_SET_LINE_RE);
1201
+ if (!setM)
1202
+ continue;
1203
+ const [, fieldVar, targetObj, valueArg] = setM;
1204
+ const reflectedField = fieldVarToName.get(fieldVar);
1205
+ if (!reflectedField)
1206
+ continue;
1207
+ if (!taintedVars.has(valueArg))
1208
+ continue;
1209
+ sources.push({
1210
+ type: 'http_param',
1211
+ location: `Field.set("${reflectedField}") on ${targetObj} — #1198`,
1212
+ severity: 'high',
1213
+ line: i + 1,
1214
+ confidence: 0.85,
1215
+ variable: `${targetObj}.${reflectedField}`,
1216
+ });
1217
+ }
1218
+ return sources;
1219
+ }
1036
1220
  /**
1037
1221
  * Issue #78 round 2 — Non-bean setter/getter chains (Java).
1038
1222
  *
@@ -1050,7 +1234,8 @@ function findStaticFieldSources(types, sourceCode, language) {
1050
1234
  * Strategy: for each class, build a `field -> { setter, getter }` map.
1051
1235
  * A setter is a 1-param method whose only body statement is
1052
1236
  * `this.<field> = <param>;`. A getter is a 0-param method whose only
1053
- * body statement is `return this.<field>;`. Then walk the whole source
1237
+ * body statement is `return this.<field>;` or `return <field>;` (common
1238
+ * in SecuriBench heap-widget cases). Then walk the whole source
1054
1239
  * for setter call sites whose argument matches a known HTTP source —
1055
1240
  * emit a synthetic source on the setter call line bound to the *getter*
1056
1241
  * method name, so the variable-name scan in `TaintPropagationPass`
@@ -1065,6 +1250,19 @@ function findSetterChainSources(types, sourceCode, language) {
1065
1250
  const sources = [];
1066
1251
  const lines = sourceCode.split('\n');
1067
1252
  const javaHttpPattern = /\b(?:req|request|httpRequest|servletRequest|httpServletRequest)\.(?:getParameter|getParameterValues|getParameterMap|getHeader|getHeaders|getCookies|getQueryString|getPathInfo|getRequestURI|getRequestURL|getInputStream|getReader)\b/;
1253
+ const setterArgFromHttp = (arg) => {
1254
+ const trimmed = arg.trim();
1255
+ if (javaHttpPattern.test(trimmed))
1256
+ return true;
1257
+ const id = /^\s*([A-Za-z_]\w*)\s*$/.exec(trimmed);
1258
+ if (!id)
1259
+ return false;
1260
+ const v = id[1].replace(/[$]/g, '\\$&');
1261
+ // cognium-dev#1198 — SecuriBench Basic16 passes taint as a local (`writePayload(s)`)
1262
+ // after `String s = req.getParameter(...)`; the setter-chain emitter only
1263
+ // matched literal HTTP call expressions in the argument position.
1264
+ return new RegExp(`\\b(?:[\\w.<>,\\s]+\\s+)?${v}\\s*=\\s*[^;\\n]*\\b(?:req|request|httpRequest|servletRequest|httpServletRequest)\\.(?:getParameter|getParameterValues|getHeader|getCookies|getQueryString|getInputStream|getReader)\\s*\\(`).test(sourceCode);
1265
+ };
1068
1266
  for (const type of types) {
1069
1267
  if (type.kind !== 'class')
1070
1268
  continue;
@@ -1073,7 +1271,7 @@ function findSetterChainSources(types, sourceCode, language) {
1073
1271
  // Build setter/getter pairs by inspecting per-method bodies.
1074
1272
  const pairs = new Map();
1075
1273
  const setterRe = /this\.([A-Za-z_]\w*)\s*=\s*([A-Za-z_]\w*)\s*;?/;
1076
- const getterRe = /return\s+this\.([A-Za-z_]\w*)\s*;?/;
1274
+ const getterRe = /return\s+(?:this\.)?([A-Za-z_]\w*)\s*;?/;
1077
1275
  for (const m of type.methods) {
1078
1276
  if (m.name === type.name)
1079
1277
  continue; // skip constructor
@@ -1132,7 +1330,7 @@ function findSetterChainSources(types, sourceCode, language) {
1132
1330
  if (!cm)
1133
1331
  continue;
1134
1332
  const arg = cm[2];
1135
- if (!javaHttpPattern.test(arg))
1333
+ if (!setterArgFromHttp(arg))
1136
1334
  continue;
1137
1335
  sources.push({
1138
1336
  type: 'http_param',
@@ -1147,6 +1345,60 @@ function findSetterChainSources(types, sourceCode, language) {
1147
1345
  }
1148
1346
  return sources;
1149
1347
  }
1348
+ /**
1349
+ * cognium-dev #1198 — `next.value = name` heap field stores and reference aliases
1350
+ * (`head.next = next`) for SecuriBench Basic29-style linked structures.
1351
+ */
1352
+ function findJavaHeapFieldDerivedSources(code, language) {
1353
+ if (language !== 'java')
1354
+ return [];
1355
+ const seeds = new Set();
1356
+ for (const line of code.split('\n')) {
1357
+ const trimmed = line.trim();
1358
+ if (!trimmed || trimmed.startsWith('//'))
1359
+ continue;
1360
+ if (!JAVA_HTTP_RHS_PATTERN.test(trimmed))
1361
+ continue;
1362
+ const eq = trimmed.indexOf('=');
1363
+ if (eq < 0)
1364
+ continue;
1365
+ const rhs = trimmed.slice(eq + 1).trim().replace(/;\s*$/, '');
1366
+ if (!JAVA_HTTP_RHS_PATTERN.test(rhs))
1367
+ continue;
1368
+ const lhs = trimmed.slice(0, eq).trim();
1369
+ const bare = JAVA_BARE_ASSIGN_LINE_RE.exec(`${lhs} = ${rhs};`);
1370
+ const local = bare
1371
+ ? bare[1]
1372
+ : lhs.split(/\s+/).pop() ?? '';
1373
+ if (isSimpleJavaLocalIdent(local))
1374
+ seeds.add(local);
1375
+ }
1376
+ if (seeds.size === 0)
1377
+ return [];
1378
+ const derived = buildJavaTaintedVars(code, seeds);
1379
+ const sources = [];
1380
+ for (const [varName, line] of derived) {
1381
+ if (!varName.includes('.'))
1382
+ continue;
1383
+ const lineText = code.split('\n')[line - 1]?.trim() ?? '';
1384
+ const m = JAVA_LOCAL_FIELD_ASSIGN_LINE_RE.exec(lineText);
1385
+ if (!m)
1386
+ continue;
1387
+ const written = `${m[1]}.${m[2]}`;
1388
+ // Direct write or same-line alias (e.g. head.next.value after next.value = name).
1389
+ if (varName !== written && !varName.endsWith(`.${m[2]}`))
1390
+ continue;
1391
+ sources.push({
1392
+ type: 'http_param',
1393
+ location: `heap field read ${varName} — #1198`,
1394
+ severity: 'high',
1395
+ line,
1396
+ confidence: 0.8,
1397
+ variable: varName,
1398
+ });
1399
+ }
1400
+ return sources;
1401
+ }
1150
1402
  /**
1151
1403
  * Explicit ASP.NET Core request sources (cognium-dev C#/.NET Phase-1).
1152
1404
  *
@@ -2254,6 +2506,7 @@ function findJavaScriptAssignmentSources(sourceCode, language) {
2254
2506
  // event-name allowlist to avoid firing on unrelated `.on('drain', cb)`
2255
2507
  // / `.on('close', cb)` etc. that carry non-user-input.
2256
2508
  sources.push(...findJavaScriptCallbackParamSources(sourceCode));
2509
+ sources.push(...findJavaScriptSubscribeCallbackParamSources(sourceCode));
2257
2510
  sources.push(...findExpressDestructuredRequestSources(sourceCode));
2258
2511
  if (language === 'javascript' || language === 'typescript') {
2259
2512
  sources.push(...findGraphqlResolverArgSources(sourceCode));
@@ -2660,6 +2913,41 @@ function findJavaScriptCallbackParamSources(sourceCode) {
2660
2913
  }
2661
2914
  return sources;
2662
2915
  }
2916
+ /**
2917
+ * cognium-dev #1224 — RxJS/Observable `.subscribe` callback first-parameter sources.
2918
+ *
2919
+ * Angular services return HTTP payloads through `service.method().subscribe((data) => …)`.
2920
+ * The first callback argument is user-influenced response body (stored-XSS shapes in Juice Shop).
2921
+ * Scoped to `.subscribe(` only — not every higher-order function — to avoid unrelated FPs.
2922
+ */
2923
+ function findJavaScriptSubscribeCallbackParamSources(sourceCode) {
2924
+ const sources = [];
2925
+ const SUBSCRIBE_CB_RE = /\.subscribe\s*\(\s*(?:async\s+)?(?:function\s*\*?\s*(?:\w+\s*)?\(\s*(\w+)|\(\s*(\w+)\s*(?:[,):]|$)|(\w+)\s*=>)/;
2926
+ const lines = sourceCode.split('\n');
2927
+ for (let i = 0; i < lines.length; i++) {
2928
+ const line = lines[i];
2929
+ const trimmed = line.trimStart();
2930
+ if (trimmed.startsWith('//') || trimmed.startsWith('*'))
2931
+ continue;
2932
+ const m = line.match(SUBSCRIBE_CB_RE);
2933
+ if (!m)
2934
+ continue;
2935
+ const paramName = m[1] ?? m[2] ?? m[3];
2936
+ if (!paramName)
2937
+ continue;
2938
+ if (paramName === 'err' || paramName === 'error')
2939
+ continue;
2940
+ sources.push({
2941
+ type: 'http_body',
2942
+ location: `Observable .subscribe(...) callback param '${paramName}' at line ${i + 1}`,
2943
+ severity: 'high',
2944
+ line: i + 1,
2945
+ confidence: 0.9,
2946
+ variable: paramName,
2947
+ });
2948
+ }
2949
+ return sources;
2950
+ }
2663
2951
  function findPythonAssignmentSources(sourceCode, language) {
2664
2952
  if (language !== 'python')
2665
2953
  return [];
@@ -4062,23 +4350,60 @@ export function buildJavaScriptTaintedVars(sourceCode, language) {
4062
4350
  continue;
4063
4351
  tainted.set(paramName, i + 1);
4064
4352
  }
4353
+ // cognium-dev#582 / #490: scan every assignment on the line; #1149: skip
4354
+ // matches inside string literals so `WHERE name = '…'` in SQL is not a bind.
4355
+ const assignmentRe = /(?:(?:var|let|const)\s+(\w+)\s*:\s*[^=;]+?\s*=(?![>=])|(?:(?:var|let|const)\s+)?(\w+)\s*=)\s*/g;
4356
+ function isInsideStringLiteral(line, index) {
4357
+ let inSingle = false;
4358
+ let inDouble = false;
4359
+ let inTemplate = false;
4360
+ let escape = false;
4361
+ for (let pos = 0; pos < index; pos++) {
4362
+ const c = line[pos];
4363
+ if (escape) {
4364
+ escape = false;
4365
+ continue;
4366
+ }
4367
+ if (c === '\\') {
4368
+ escape = true;
4369
+ continue;
4370
+ }
4371
+ if (!inDouble && !inTemplate && c === "'")
4372
+ inSingle = !inSingle;
4373
+ else if (!inSingle && !inTemplate && c === '"')
4374
+ inDouble = !inDouble;
4375
+ else if (!inSingle && !inDouble && c === '`')
4376
+ inTemplate = !inTemplate;
4377
+ }
4378
+ return inSingle || inDouble || inTemplate;
4379
+ }
4065
4380
  for (let i = 0; i < lines.length; i++) {
4066
4381
  const line = lines[i];
4067
4382
  const trimmed = line.trimStart();
4068
4383
  if (trimmed.startsWith('//') || trimmed.startsWith('*'))
4069
4384
  continue;
4070
- const assignMatch = line.match(/(?:(?:var|let|const)\s+)?(\w+)\s*=\s*(.+)/);
4071
- if (!assignMatch)
4072
- continue;
4073
- const [, lhs, rhs] = assignMatch;
4074
- if (['if', 'while', 'for', 'return', 'true', 'false', 'null', 'undefined', 'case'].includes(lhs))
4075
- continue;
4076
- if (isConstTableLookup(rhs, lookupTables))
4077
- continue; // #667
4078
- const isDirectSource = JS_TAINTED_PATTERNS.some(p => p.pattern.test(rhs));
4079
- const isTaintedPropagation = tainted.size > 0 && [...tainted.keys()].some(v => new RegExp(`\\b${v}\\b`).test(rhs));
4080
- if (isDirectSource || isTaintedPropagation)
4081
- tainted.set(lhs, i + 1);
4385
+ assignmentRe.lastIndex = 0;
4386
+ for (const assignmentMatch of line.matchAll(assignmentRe)) {
4387
+ const matchIndex = assignmentMatch.index ?? 0;
4388
+ if (isInsideStringLiteral(line, matchIndex))
4389
+ continue;
4390
+ const lhs = assignmentMatch[1] ?? assignmentMatch[2];
4391
+ if (!lhs)
4392
+ continue;
4393
+ if (['if', 'while', 'for', 'return', 'true', 'false', 'null', 'undefined', 'case'].includes(lhs)) {
4394
+ continue;
4395
+ }
4396
+ let rhs = line.slice(matchIndex + assignmentMatch[0].length).trim();
4397
+ const semi = rhs.indexOf(';');
4398
+ if (semi >= 0)
4399
+ rhs = rhs.slice(0, semi).trim();
4400
+ if (isConstTableLookup(rhs, lookupTables))
4401
+ continue; // #667
4402
+ const isDirectSource = JS_TAINTED_PATTERNS.some((p) => p.pattern.test(rhs));
4403
+ const isTaintedPropagation = tainted.size > 0 && [...tainted.keys()].some((v) => new RegExp(`\\b${v}\\b`).test(rhs));
4404
+ if (isDirectSource || isTaintedPropagation)
4405
+ tainted.set(lhs, i + 1);
4406
+ }
4082
4407
  }
4083
4408
  return tainted;
4084
4409
  }
@@ -4294,6 +4619,27 @@ function joinWrappedJavaStatement(lines, i) {
4294
4619
  * consumed by `detectExpressionScanFlows` in `taint-propagation-pass.ts`
4295
4620
  * to synthesize a virtual source for each derived var.
4296
4621
  */
4622
+ /** Reference-RHS alias in heap-field stores (no regex — regex-lint budget). */
4623
+ function isSimpleJavaLocalIdent(name) {
4624
+ if (!name)
4625
+ return false;
4626
+ const first = name.charCodeAt(0);
4627
+ if (!((first >= 65 && first <= 90) ||
4628
+ (first >= 97 && first <= 122) ||
4629
+ first === 95)) {
4630
+ return false;
4631
+ }
4632
+ for (let i = 1; i < name.length; i++) {
4633
+ const ch = name.charCodeAt(i);
4634
+ if (!((ch >= 48 && ch <= 57) ||
4635
+ (ch >= 65 && ch <= 90) ||
4636
+ (ch >= 97 && ch <= 122) ||
4637
+ ch === 95)) {
4638
+ return false;
4639
+ }
4640
+ }
4641
+ return true;
4642
+ }
4297
4643
  export function buildJavaTaintedVars(sourceCode, seedVars, deadBranchLines,
4298
4644
  /**
4299
4645
  * `trackSlots` (cognium-dev#913/#914/#916/#917): follow which element of a list
@@ -4353,6 +4699,29 @@ options) {
4353
4699
  complexTaintedRes.push(new RegExp(`(?<![\\p{L}\\p{N}_])${esc}(?![\\p{L}\\p{N}_])`, 'u'));
4354
4700
  }
4355
4701
  }
4702
+ /** cognium-dev#1198 — `head.next = next` reference alias for heap field reads. */
4703
+ const localRefAlias = new Map();
4704
+ const markQualifiedFieldTainted = (qualified, lineNo) => {
4705
+ if (knownTainted.has(qualified))
4706
+ return;
4707
+ derived.set(qualified, lineNo);
4708
+ knownTainted.add(qualified);
4709
+ if (!/^[\p{L}\p{N}_]+$/u.test(qualified)) {
4710
+ const esc = qualified.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
4711
+ complexTaintedRes.push(new RegExp(`(?<![\\p{L}\\p{N}_])${esc}(?![\\p{L}\\p{N}_])`, 'u'));
4712
+ }
4713
+ changed = true;
4714
+ const dot = qualified.lastIndexOf('.');
4715
+ if (dot <= 0)
4716
+ return;
4717
+ const recv = qualified.slice(0, dot);
4718
+ const field = qualified.slice(dot + 1);
4719
+ for (const [aliasPath, targetLocal] of localRefAlias) {
4720
+ if (targetLocal !== recv)
4721
+ continue;
4722
+ markQualifiedFieldTainted(`${aliasPath}.${field}`, lineNo);
4723
+ }
4724
+ };
4356
4725
  let changed = true;
4357
4726
  let guard = 0;
4358
4727
  while (changed && guard < lines.length + 2) {
@@ -4406,6 +4775,39 @@ options) {
4406
4775
  }
4407
4776
  continue;
4408
4777
  }
4778
+ const thisFieldListAddRe = /^\s*this\.([A-Za-z_]\w*)\.add\s*\(/;
4779
+ const thisListAdd = thisFieldListAddRe.exec(line);
4780
+ if (thisListAdd) {
4781
+ const field = thisListAdd[1];
4782
+ const argMatch = /this\.\w+\.add\s*\(\s*([^)]+)\)/.exec(line);
4783
+ if (argMatch) {
4784
+ const argCode = argMatch[1]
4785
+ .replace(/@?"(?:[^"\\]|\\.)*"/g, ' ')
4786
+ .replace(/'(?:[^'\\]|\\.)'/g, ' ');
4787
+ const idents = argCode.match(/[\p{L}\p{N}_]+/gu);
4788
+ const ref = (idents !== null && idents.some(t => knownTainted.has(t))) ||
4789
+ (complexTaintedRes.length > 0 && complexTaintedRes.some(re => re.test(argCode)));
4790
+ if (ref) {
4791
+ const aliases = [field, `this.${field}`];
4792
+ for (const name of aliases) {
4793
+ if (!knownTainted.has(name)) {
4794
+ derived.set(name, i + 1);
4795
+ knownTainted.add(name);
4796
+ changed = true;
4797
+ }
4798
+ }
4799
+ }
4800
+ }
4801
+ continue;
4802
+ }
4803
+ const addAllRe = /^\s*([A-Za-z_]\w*)\.addAll\s*\(\s*([A-Za-z_]\w*)\s*\)\s*;?\s*$/;
4804
+ const addAllMatch = addAllRe.exec(line.trimEnd());
4805
+ if (addAllMatch && knownTainted.has(addAllMatch[2]) && !knownTainted.has(addAllMatch[1])) {
4806
+ derived.set(addAllMatch[1], i + 1);
4807
+ knownTainted.add(addAllMatch[1]);
4808
+ changed = true;
4809
+ continue;
4810
+ }
4409
4811
  let statement = line;
4410
4812
  let declMatch = declRe.exec(statement);
4411
4813
  let assignMatch = !declMatch ? assignRe.exec(statement) : null;
@@ -4472,6 +4874,29 @@ options) {
4472
4874
  }
4473
4875
  continue;
4474
4876
  }
4877
+ const localFieldMatch = JAVA_LOCAL_FIELD_ASSIGN_LINE_RE.exec(statement.trim());
4878
+ if (localFieldMatch) {
4879
+ const recv = localFieldMatch[1];
4880
+ const field = localFieldMatch[2];
4881
+ const rhs = localFieldMatch[3];
4882
+ const qualified = `${recv}.${field}`;
4883
+ const rhsTrim = rhs.trim();
4884
+ if (isSimpleJavaLocalIdent(rhsTrim) &&
4885
+ !JAVA_KEYWORDS.has(rhsTrim)) {
4886
+ localRefAlias.set(qualified, rhsTrim);
4887
+ }
4888
+ const rhsCode = rhs
4889
+ .replace(/\$@?"(?:[^"\\]|\\.)*"/g, lit => ' ' + [...lit.matchAll(/\{([^}]*)\}/g)].map(x => x[1]).join(' ') + ' ')
4890
+ .replace(/@?"(?:[^"\\]|\\.)*"/g, ' ')
4891
+ .replace(/'(?:[^'\\]|\\.)'/g, ' ');
4892
+ const rhsIdents = rhsCode.match(/[\p{L}\p{N}_]+/gu);
4893
+ const ref = (rhsIdents !== null && rhsIdents.some(t => knownTainted.has(t))) ||
4894
+ (complexTaintedRes.length > 0 && complexTaintedRes.some(re => re.test(rhsCode)));
4895
+ if (ref) {
4896
+ markQualifiedFieldTainted(qualified, i + 1);
4897
+ }
4898
+ continue;
4899
+ }
4475
4900
  const m = declMatch ?? assignMatch;
4476
4901
  if (!m)
4477
4902
  continue;
@@ -5403,7 +5828,7 @@ function findGoMapAllowlistGuardSanitizers(code) {
5403
5828
  // (`if err != nil || !<mapName>[u.Host] {`, #293): the block runs when any
5404
5829
  // disjunct holds, so falling past it proves the key is in the map. The key
5405
5830
  // may be a selector (`u.Host`). Captures the map identifier in group 1.
5406
- const guardOpen = /^\s*if\s+(?:[^{&|]+\|\|\s*)*!\s*([A-Za-z_][A-Za-z0-9_]*)\s*\[\s*[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)?\s*\]\s*(?:\|\|[^{&]+)?\{/;
5831
+ const guardOpen = /^\s*if\s+(?:[^{&|]+\|\|)*\s*!\s*([A-Za-z_][A-Za-z0-9_]*)\s*\[\s*[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)?\s*\]\s*(?:\|\|[^{&]+)?\{/;
5407
5832
  // Allow-list naming heuristic.
5408
5833
  const allowlistName = /^(?:[A-Z][A-Z0-9_]+|.*?(allowed|accepted|whitelist|permitted|valid|approved).*)$/i;
5409
5834
  for (let i = 0; i < lines.length; i++) {
@@ -7581,7 +8006,8 @@ function findJsPathResolveStartsWithGuardSanitizers(code) {
7581
8006
  line: c.line,
7582
8007
  sanitizes: ['path_traversal', 'external_taint_escape'],
7583
8008
  });
7584
- for (let l = c.line; l < lines.length; l++) {
8009
+ // only inside the function the guard is in, and only until `full` is reassigned (#1257 review B1)
8010
+ for (const l of jsGuardCreditLines(lines, c.line, c.fullVar)) {
7585
8011
  if (!varRefRe.test(lines[l]))
7586
8012
  continue;
7587
8013
  sanitizers.push({
@@ -7594,6 +8020,126 @@ function findJsPathResolveStartsWithGuardSanitizers(code) {
7594
8020
  }
7595
8021
  return sanitizers;
7596
8022
  }
8023
+ /**
8024
+ * JS/TS open_redirect: the same-site relative-path guard (CWE-601).
8025
+ *
8026
+ * if (!next.startsWith('/') || next.startsWith('//') || next.startsWith('/\\')) return res.redirect('/');
8027
+ * res.redirect(next);
8028
+ *
8029
+ * if (next.startsWith('/') && !next.startsWith('//') && !next.startsWith('/\\')) { res.redirect(next); }
8030
+ * if (/^\/(?![\/\\])/.test(next)) { res.redirect(next); }
8031
+ * res.redirect(next.startsWith('/') && !next.startsWith('//') && !next.startsWith('/\\') ? next : '/');
8032
+ *
8033
+ * A path that starts with one `/` and is not `//…` (protocol-relative) or `/\…` (which browsers read as
8034
+ * `//…`) stays on the same site, so the redirect cannot leave it. BOTH `//` and `/\` must be rejected: a guard
8035
+ * that only rejects `//` is still bypassable with `/\evil.example`, and is not credited. The reject form
8036
+ * (conditions joined by `||`, then a terminator) credits every later line that uses the variable; the accept
8037
+ * form (joined by `&&`, or one of the strict regex spellings) credits the lines of its block. Only
8038
+ * `open_redirect` is sanitized. Matching is by substring on the whitespace-free condition (no new regex).
8039
+ */
8040
+ function findJsRelativeRedirectGuardSanitizers(code) {
8041
+ const sanitizers = [];
8042
+ if (!code.includes('startsWith') && !code.includes('.test('))
8043
+ return sanitizers;
8044
+ const lines = code.split('\n');
8045
+ const quotes = ["'", '"', '`'];
8046
+ const lit = (q, body) => `${q}${body}${q}`;
8047
+ const anyQ = (cond, f) => quotes.some((q) => cond.includes(f(q)));
8048
+ const strictRegexes = ['/^\\/(?![\\/\\\\])/.test(', '/^\\/(?!\\/|\\\\)/.test(', '/^\\/[^\\/\\\\]/.test('];
8049
+ const terminatorRe = /\b(?:throw|return|res\s*\.\s*status\s*\([^)]*\)\s*\.\s*(?:send|end|json))/;
8050
+ const varRefFor = (v) => new RegExp(`(?<![\\w$.])${v.replace(/[.$]/g, '\\$&')}(?![\\w$])`);
8051
+ for (let i = 0; i < lines.length; i++) {
8052
+ const raw = lines[i];
8053
+ const cond = raw.replace(/\s+/g, '');
8054
+ const isIf = /\bif\s*\(/.test(raw);
8055
+ // the ternary form on the redirect line itself: `res.redirect(<guard> ? next : '/')`
8056
+ if (!isIf && !(cond.includes('?') && cond.includes(':')))
8057
+ continue;
8058
+ // the guarded variable: the receiver of `.startsWith('//')`, or the argument of a strict regex's `.test(`
8059
+ let v;
8060
+ for (const q of quotes) {
8061
+ const at = cond.indexOf(`.startsWith(${lit(q, '//')})`);
8062
+ if (at > 0) {
8063
+ let k = at;
8064
+ while (k > 0 && /[\w$.]/.test(cond[k - 1]))
8065
+ k--;
8066
+ v = cond.slice(k, at).replace(/^!+/, '');
8067
+ break;
8068
+ }
8069
+ }
8070
+ const regexAccept = strictRegexes.find((r) => cond.includes(r));
8071
+ if (!v && regexAccept) {
8072
+ const after = cond.slice(cond.indexOf(regexAccept) + regexAccept.length);
8073
+ const m = /^([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\)/.exec(after);
8074
+ v = m?.[1];
8075
+ }
8076
+ if (!v || !/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(v))
8077
+ continue;
8078
+ const slash = (q) => `${v}.startsWith(${lit(q, '/')})`;
8079
+ const dbl = (q) => `${v}.startsWith(${lit(q, '//')})`;
8080
+ const back = (q) => `${v}.startsWith(${lit(q, '/\\\\')})`;
8081
+ const reject = cond.includes('||') && !cond.includes('&&') &&
8082
+ anyQ(cond, (q) => `!${slash(q)}`) && anyQ(cond, dbl) && anyQ(cond, back) &&
8083
+ !anyQ(cond, (q) => `!${dbl(q)}`) && !anyQ(cond, (q) => `!${back(q)}`);
8084
+ const accept = (cond.includes('&&') && !cond.includes('||') &&
8085
+ anyQ(cond, slash) && !anyQ(cond, (q) => `!${slash(q)}`) &&
8086
+ anyQ(cond, (q) => `!${dbl(q)}`) && anyQ(cond, (q) => `!${back(q)}`)) ||
8087
+ (!!regexAccept && !cond.includes(`!${regexAccept}`) && !cond.includes('||'));
8088
+ const ref = varRefFor(v);
8089
+ if (!isIf) {
8090
+ // ternary: credited only when the guarded value is the consequent (`<guard> ? next : <fallback>`)
8091
+ if (accept && cond.includes(`?${v}:`))
8092
+ sanitizers.push({ type: 'js_relative_redirect_guard', method: 'startsWith', line: i + 1, sanitizes: ['open_redirect'] });
8093
+ continue;
8094
+ }
8095
+ if (reject && guardRejects(lines, i, terminatorRe, 2)) {
8096
+ // from the guard line itself, so a block-form guard's own `{ … }` is counted, not read as the function's end
8097
+ for (const l of jsGuardCreditLines(lines, i, v)) {
8098
+ if (ref.test(lines[l]))
8099
+ sanitizers.push({ type: 'js_relative_redirect_guard', method: 'startsWith', line: l + 1, sanitizes: ['open_redirect'] });
8100
+ }
8101
+ }
8102
+ else if (accept) {
8103
+ const block = jsBracedBlockLines(lines, i);
8104
+ const body = block ?? [raw];
8105
+ for (let k = 0; k < body.length; k++) {
8106
+ if (ref.test(k === 0 ? raw.slice(raw.indexOf(')', raw.indexOf('if')) + 1) : body[k])) {
8107
+ sanitizers.push({ type: 'js_relative_redirect_guard', method: 'startsWith', line: i + k + 1, sanitizes: ['open_redirect'] });
8108
+ }
8109
+ }
8110
+ }
8111
+ }
8112
+ return sanitizers;
8113
+ }
8114
+ /**
8115
+ * The lines a guard on `v` at line index `from` may credit: from `from` to the end of the block that encloses it
8116
+ * (the handler or function the guard is in: the first `}` that closes a brace opened before `from`), stopping
8117
+ * before any reassignment of `v` (`v = …`, `let|const|var v = …`). Another handler in the same file, or the
8118
+ * variable after it is reassigned, is never credited by this guard. Braces inside string literals and comments
8119
+ * are not counted apart (a guard line with unbalanced quoted braces credits less, never more).
8120
+ */
8121
+ function jsGuardCreditLines(lines, from, v) {
8122
+ const esc = v.replace(/[.$]/g, '\\$&');
8123
+ const reassign = new RegExp(`(?:^|[^\\w$.])(?:(?:let|const|var)\\s+)?${esc}\\s*=(?!=)`);
8124
+ const out = [];
8125
+ let depth = 0;
8126
+ for (let l = from; l < lines.length; l++) {
8127
+ const line = lines[l];
8128
+ if (l > from && reassign.test(line))
8129
+ break;
8130
+ out.push(l);
8131
+ for (const c of line) {
8132
+ if (c === '{')
8133
+ depth++;
8134
+ else if (c === '}') {
8135
+ depth--;
8136
+ if (depth < 0)
8137
+ return out; // the enclosing block closed on this line
8138
+ }
8139
+ }
8140
+ }
8141
+ return out;
8142
+ }
7597
8143
  /** Lines of one `{ ... }` block starting at `startLineIdx` (inclusive). */
7598
8144
  function jsBracedBlockLines(lines, startLineIdx) {
7599
8145
  let depth = 0;
@@ -13388,9 +13934,126 @@ export function findPythonJinjaTemplateSstiFindings(code, file) {
13388
13934
  }
13389
13935
  return findings;
13390
13936
  }
13937
+ /**
13938
+ * The text of the first argument of a call whose `(` ends just before
13939
+ * `start` on `line`: up to the first top-level `,` or the closing `)`, or
13940
+ * to the end of the line when the call continues on the next one.
13941
+ */
13942
+ export function firstJsCallArg(line, start) {
13943
+ let depth = 0;
13944
+ for (let k = start; k < line.length; k++) {
13945
+ const ch = line[k];
13946
+ if (ch === "'" || ch === '"' || ch === '`') {
13947
+ const end = line.indexOf(ch, k + 1);
13948
+ if (end < 0)
13949
+ return line.slice(start);
13950
+ // Skip escaped quotes.
13951
+ let e = end;
13952
+ while (e > 0 && line[e - 1] === '\\') {
13953
+ const next = line.indexOf(ch, e + 1);
13954
+ if (next < 0)
13955
+ return line.slice(start);
13956
+ e = next;
13957
+ }
13958
+ k = e;
13959
+ continue;
13960
+ }
13961
+ if (ch === '(' || ch === '[' || ch === '{')
13962
+ depth++;
13963
+ else if (ch === ')' || ch === ']' || ch === '}') {
13964
+ if (depth === 0)
13965
+ return line.slice(start, k);
13966
+ depth--;
13967
+ }
13968
+ else if (ch === ',' && depth === 0)
13969
+ return line.slice(start, k);
13970
+ }
13971
+ return line.slice(start);
13972
+ }
13973
+ /**
13974
+ * For `const { a, b: c, d = 1 } = <rhs>` whose `<rhs>` reads the request
13975
+ * (`reqRe`), the bound names (`a`, `c`, `d`); otherwise null.
13976
+ */
13977
+ export function jsDestructuredFromRequest(stmt, reqRe) {
13978
+ const kw = ['const ', 'let ', 'var '].find(k => stmt.startsWith(k));
13979
+ if (!kw)
13980
+ return null;
13981
+ const t = stmt.slice(kw.length).trimStart();
13982
+ if (!t.startsWith('{'))
13983
+ return null;
13984
+ const close = t.indexOf('}');
13985
+ if (close < 0)
13986
+ return null;
13987
+ const rest = t.slice(close + 1).trimStart();
13988
+ if (!rest.startsWith('=') || !reqRe.test(blankJsStringText(rest.slice(1))))
13989
+ return null;
13990
+ const names = [];
13991
+ for (const raw of t.slice(1, close).split(',')) {
13992
+ let p = raw.trim();
13993
+ const eq = p.indexOf('=');
13994
+ if (eq >= 0)
13995
+ p = p.slice(0, eq).trim();
13996
+ const colon = p.indexOf(':');
13997
+ const bound = (colon >= 0 ? p.slice(colon + 1) : p).trim();
13998
+ if (/^[A-Za-z_$][\w$]*$/.test(bound))
13999
+ names.push(bound);
14000
+ }
14001
+ return names.length > 0 ? names : null;
14002
+ }
14003
+ /**
14004
+ * `expr` with the text of its string literals blanked: quoted strings become
14005
+ * `''`, a template literal keeps only its `${…}` substitutions. What remains
14006
+ * is the code that can read a variable.
14007
+ */
14008
+ export function blankJsStringText(expr) {
14009
+ let out = '';
14010
+ let k = 0;
14011
+ while (k < expr.length) {
14012
+ const ch = expr[k];
14013
+ if (ch === "'" || ch === '"') {
14014
+ let e = k + 1;
14015
+ while (e < expr.length && expr[e] !== ch)
14016
+ e += expr[e] === '\\' ? 2 : 1;
14017
+ out += "''";
14018
+ k = e + 1;
14019
+ continue;
14020
+ }
14021
+ if (ch === '`') {
14022
+ let e = k + 1;
14023
+ let subs = '';
14024
+ while (e < expr.length && expr[e] !== '`') {
14025
+ if (expr[e] === '\\') {
14026
+ e += 2;
14027
+ continue;
14028
+ }
14029
+ if (expr[e] === '$' && expr[e + 1] === '{') {
14030
+ const close = expr.indexOf('}', e + 2);
14031
+ if (close < 0) {
14032
+ subs += ` ${expr.slice(e + 2)}`;
14033
+ e = expr.length;
14034
+ break;
14035
+ }
14036
+ subs += ` ${expr.slice(e + 2, close)}`;
14037
+ e = close + 1;
14038
+ continue;
14039
+ }
14040
+ e++;
14041
+ }
14042
+ out += `''${subs}`;
14043
+ k = e + 1;
14044
+ continue;
14045
+ }
14046
+ out += ch;
14047
+ k++;
14048
+ }
14049
+ return out;
14050
+ }
13391
14051
  /**
13392
14052
  * Sprint 90 detector C (#189) — JS SSTI via `Handlebars.compile(<tainted>)`
13393
- * or `ejs.render(<tainted>, ...)` / `ejs.compile(<tainted>)`.
14053
+ * or `ejs.render(<tainted>, ...)` / `ejs.compile(<tainted>)`; also
14054
+ * `handlebars.compile`, `pug.render` / `pug.compile` and
14055
+ * `nunjucks.renderString`. Only the code of the first argument counts: a
14056
+ * fixed template literal that names a context variable is not tainted.
13394
14057
  *
13395
14058
  * Compiling an attacker-controlled template lets the attacker execute
13396
14059
  * arbitrary code through helper-shadowing / prototype gadgets
@@ -13400,8 +14063,9 @@ export function findJsTemplateInjectionSstiFindings(code, file) {
13400
14063
  const findings = [];
13401
14064
  if (typeof code !== 'string' || code.length === 0)
13402
14065
  return findings;
13403
- if (!/\bHandlebars\s*\.\s*compile\s*\(/.test(code) &&
13404
- !/\bejs\s*\.\s*(?:render|compile)\s*\(/.test(code)) {
14066
+ if (!/\b[Hh]andlebars\s*\.\s*compile\s*\(/.test(code) &&
14067
+ !/\b(?:ejs|pug)\s*\.\s*(?:render|compile)\s*\(/.test(code) &&
14068
+ !/\bnunjucks\s*\.\s*renderString\s*\(/.test(code)) {
13405
14069
  return findings;
13406
14070
  }
13407
14071
  if (!/\breq\s*\.\s*(?:query|body|params|headers|cookies)\b/.test(code)) {
@@ -13416,11 +14080,19 @@ export function findJsTemplateInjectionSstiFindings(code, file) {
13416
14080
  const t = lines[i].trim();
13417
14081
  if (t.startsWith('//'))
13418
14082
  continue;
14083
+ // `const { a, b: c } = req.body;` binds every destructured name.
14084
+ const destructured = jsDestructuredFromRequest(t, reqExtractRe);
14085
+ if (destructured) {
14086
+ for (const name of destructured)
14087
+ taintedVars.add(name);
14088
+ continue;
14089
+ }
13419
14090
  const m = t.match(/^(?:const|let|var)\s+(\w+)(?:\s*:\s*[^=]+)?\s*=\s*(.+?);?$/);
13420
14091
  if (!m)
13421
14092
  continue;
13422
14093
  const lhs = m[1];
13423
- const rhs = m[2];
14094
+ // A name inside a string literal is text, not a read (`'<p><%= name %></p>'`).
14095
+ const rhs = blankJsStringText(m[2]);
13424
14096
  if (taintedVars.has(lhs))
13425
14097
  continue;
13426
14098
  if (reqExtractRe.test(rhs)) {
@@ -13439,16 +14111,21 @@ export function findJsTemplateInjectionSstiFindings(code, file) {
13439
14111
  }
13440
14112
  if (taintedVars.size === 0)
13441
14113
  return findings;
13442
- const callRe = /\b(Handlebars\s*\.\s*compile|ejs\s*\.\s*(?:render|compile))\s*\(\s*([^,)]+)/;
14114
+ const callRe = /\b([Hh]andlebars\s*\.\s*compile|(?:ejs|pug)\s*\.\s*(?:render|compile)|nunjucks\s*\.\s*renderString)\s*\(/;
13443
14115
  const seen = new Set();
13444
14116
  for (let i = 0; i < lines.length; i++) {
13445
14117
  const line = lines[i];
13446
14118
  if (line.trim().startsWith('//'))
13447
14119
  continue;
13448
14120
  const m = line.match(callRe);
13449
- if (!m)
14121
+ if (!m || m.index === undefined)
14122
+ continue;
14123
+ // The template source is the first argument; only its code counts —
14124
+ // the text of a string literal (a fixed template that names a context
14125
+ // variable) and the context object after it do not.
14126
+ const arg = blankJsStringText(firstJsCallArg(line, m.index + m[0].length)).trim();
14127
+ if (arg === '')
13450
14128
  continue;
13451
- const arg = m[2].trim();
13452
14129
  let tainted = reqExtractRe.test(arg);
13453
14130
  if (!tainted) {
13454
14131
  for (const v of taintedVars) {
@@ -13473,7 +14150,8 @@ export function findJsTemplateInjectionSstiFindings(code, file) {
13473
14150
  level: 'error',
13474
14151
  message: 'Server-side template injection: compiling/rendering a template ' +
13475
14152
  'whose source is attacker-controlled (`Handlebars.compile(...)` / ' +
13476
- '`ejs.render(...)`) opens helper-shadowing and prototype-gadget RCE ' +
14153
+ '`ejs.render(...)` / `pug.render(...)` / `nunjucks.renderString(...)`) ' +
14154
+ 'opens helper-shadowing, prototype-gadget and template-code RCE ' +
13477
14155
  'paths. Use a fixed template and pass user data as context.',
13478
14156
  file,
13479
14157
  line: i + 1,