loadwise 0.6.2 → 0.8.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.
Files changed (278) hide show
  1. package/README.md +175 -115
  2. package/dist/bin/loadwise.js +132 -67
  3. package/dist/lib/accessibility/analyze.js +5 -3
  4. package/dist/lib/accessibility/angular-inline.js +9 -11
  5. package/dist/lib/accessibility/angular-literal.js +39 -0
  6. package/dist/lib/accessibility/form-context.js +36 -0
  7. package/dist/lib/accessibility/frame-head.js +92 -0
  8. package/dist/lib/accessibility/frame-viewport.js +149 -0
  9. package/dist/lib/accessibility/frontend-detect.js +6 -5
  10. package/dist/lib/accessibility/jsx-elements.js +13 -3
  11. package/dist/lib/accessibility/markup-files.js +7 -2
  12. package/dist/lib/accessibility/rule-ids.js +3 -0
  13. package/dist/lib/accessibility/rules.js +128 -41
  14. package/dist/lib/accessibility/site-fixes/buttons.js +5 -1
  15. package/dist/lib/accessibility/template-attributes.js +5 -3
  16. package/dist/lib/accessibility/template-elements.js +25 -6
  17. package/dist/lib/accessibility/template-file.js +40 -25
  18. package/dist/lib/accessibility/usage.js +10 -2
  19. package/dist/lib/editor/accessibility-examples.js +6 -1
  20. package/dist/lib/editor/actions.js +46 -7
  21. package/dist/lib/editor/apply-fix.js +69 -4
  22. package/dist/lib/editor/configured-setup.js +63 -0
  23. package/dist/lib/editor/diagnostics.js +206 -17
  24. package/dist/lib/editor/dismissals.js +85 -26
  25. package/dist/lib/editor/editor-document.js +5 -2
  26. package/dist/lib/editor/editor-launcher.js +170 -0
  27. package/dist/lib/editor/fix-edits.js +19 -0
  28. package/dist/lib/editor/jetbrains-setup.js +53 -0
  29. package/dist/lib/editor/language-server.js +80 -24
  30. package/dist/lib/editor/managed-config.js +37 -0
  31. package/dist/lib/editor/native-setup.js +86 -0
  32. package/dist/lib/editor/perf-watch.js +8 -6
  33. package/dist/lib/editor/release-vsix.js +61 -0
  34. package/dist/lib/editor/reliability-examples.js +15 -0
  35. package/dist/lib/editor/scan-session.js +29 -8
  36. package/dist/lib/editor/server-commands.js +38 -9
  37. package/dist/lib/editor/setup-server.js +87 -0
  38. package/dist/lib/editor/setup-vim.js +63 -0
  39. package/dist/lib/editor/setup.js +131 -0
  40. package/dist/lib/editor/stdio-setup.js +6 -0
  41. package/dist/lib/editor/workspace-files.js +61 -7
  42. package/dist/lib/editor/workspace-paths.js +41 -1
  43. package/dist/lib/maintainability/analysis/analyze-source.js +1 -1
  44. package/dist/lib/maintainability/architecture/architecture.js +4 -4
  45. package/dist/lib/maintainability/cli/changed-lines.js +20 -2
  46. package/dist/lib/maintainability/cli/inputs.js +12 -3
  47. package/dist/lib/maintainability/cli.js +18 -5
  48. package/dist/lib/maintainability/entry-points/entry-points.js +44 -15
  49. package/dist/lib/maintainability/entry-points/html-entry-points.js +5 -1
  50. package/dist/lib/maintainability/examples.js +4 -0
  51. package/dist/lib/maintainability/quality/functions.js +9 -6
  52. package/dist/lib/maintainability/quality/limits.js +19 -0
  53. package/dist/lib/maintainability/quality/size-limits.js +8 -2
  54. package/dist/lib/maintainability/quality/stray-console.js +62 -1
  55. package/dist/lib/maintainability/quality/tsconfig-strict.js +2 -0
  56. package/dist/lib/maintainability/rule-ids.js +3 -0
  57. package/dist/lib/maintainability/scan-changed.js +4 -1
  58. package/dist/lib/maintainability/scan-worker.js +6 -2
  59. package/dist/lib/maintainability/scan.js +21 -8
  60. package/dist/lib/maintainability/site-fixes/unused-bindings.js +138 -3
  61. package/dist/lib/maintainability/unused/module-usage.js +43 -21
  62. package/dist/lib/maintainability/unused/unused-bindings.js +39 -4
  63. package/dist/lib/maintainability/unused/unused-modules.js +5 -10
  64. package/dist/lib/performance/analysis/source-inputs.js +7 -2
  65. package/dist/lib/performance/analysis/source-options.js +7 -6
  66. package/dist/lib/performance/analyze.js +16 -3
  67. package/dist/lib/performance/cli/changed-lines.js +8 -1
  68. package/dist/lib/performance/cli/cli-arguments.js +19 -8
  69. package/dist/lib/performance/cli/cli-output.js +4 -0
  70. package/dist/lib/performance/cli/cli-scan.js +21 -2
  71. package/dist/lib/performance/cli.js +16 -7
  72. package/dist/lib/performance/collections/memory-growth.js +55 -12
  73. package/dist/lib/performance/contracts/openapi.js +13 -4
  74. package/dist/lib/performance/datastores/pg-integrity.js +68 -22
  75. package/dist/lib/performance/datastores/pg-session-release.js +114 -0
  76. package/dist/lib/performance/datastores/pg-session-sql.js +144 -0
  77. package/dist/lib/performance/datastores/pooling.js +62 -3
  78. package/dist/lib/performance/datastores/redis.js +94 -18
  79. package/dist/lib/performance/datastores/session-store.js +2 -1
  80. package/dist/lib/performance/db/checks.js +19 -8
  81. package/dist/lib/performance/db/gateway.js +3 -1
  82. package/dist/lib/performance/db/plan-estimates.js +4 -4
  83. package/dist/lib/performance/engine/native-syntax.js +3 -0
  84. package/dist/lib/performance/engine/native.js +11 -7
  85. package/dist/lib/performance/evidence/plans.js +7 -5
  86. package/dist/lib/performance/evidence/traces.js +21 -1
  87. package/dist/lib/performance/frontend/angular-teardown.js +96 -0
  88. package/dist/lib/performance/frontend/effect-cleanup.js +148 -0
  89. package/dist/lib/performance/frontend/frontend-dom-perf.js +14 -2
  90. package/dist/lib/performance/frontend/frontend-helpers.js +1 -9
  91. package/dist/lib/performance/frontend/frontend-perf.js +149 -74
  92. package/dist/lib/performance/migrations/extract-code-sql.js +16 -4
  93. package/dist/lib/performance/migrations/extract-code.js +13 -5
  94. package/dist/lib/performance/migrations/extract-sql.js +82 -38
  95. package/dist/lib/performance/migrations/operations.js +56 -13
  96. package/dist/lib/performance/migrations/postgres-lock-timeout.js +52 -0
  97. package/dist/lib/performance/migrations/postgres-registry.js +127 -26
  98. package/dist/lib/performance/migrations/postgres-settings.js +78 -0
  99. package/dist/lib/performance/migrations/rules-postgres-add-column.js +3 -3
  100. package/dist/lib/performance/migrations/rules-postgres-shared.js +9 -0
  101. package/dist/lib/performance/migrations/rules-postgres.js +88 -39
  102. package/dist/lib/performance/orm/offset-pagination.js +6 -4
  103. package/dist/lib/performance/orm/prisma-aggregates.js +69 -18
  104. package/dist/lib/performance/orm/unbounded-list-chain.js +29 -0
  105. package/dist/lib/performance/orm/unbounded-list-queries.js +18 -13
  106. package/dist/lib/performance/polyglot.js +111 -14
  107. package/dist/lib/performance/projects.js +3 -3
  108. package/dist/lib/performance/query-loops/sequential-loops.js +1 -0
  109. package/dist/lib/performance/request/backend-mastery.js +151 -42
  110. package/dist/lib/performance/request/bulk-listener-registration.js +111 -0
  111. package/dist/lib/performance/request/fastify-receivers.js +93 -0
  112. package/dist/lib/performance/request/fresh-loop-socket.js +103 -0
  113. package/dist/lib/performance/request/mongoose-lean.js +298 -46
  114. package/dist/lib/performance/request/node-event-listener-leak.js +99 -5
  115. package/dist/lib/performance/request/phase5-ast.js +6 -7
  116. package/dist/lib/performance/request/phase5-rules.js +204 -23
  117. package/dist/lib/performance/request/request-handlers.js +120 -23
  118. package/dist/lib/performance/request/sql-select-star.js +150 -0
  119. package/dist/lib/performance/request/unbounded-promise-all.js +54 -29
  120. package/dist/lib/performance/request/upload-limits.js +5 -1
  121. package/dist/lib/performance/site-fix.js +4 -4
  122. package/dist/lib/performance/site-fixes/backend-mastery-fixes.js +298 -16
  123. package/dist/lib/performance/site-fixes/collection-existence.js +2 -1
  124. package/dist/lib/performance/site-fixes/collections.js +1 -2
  125. package/dist/lib/performance/site-fixes/frontend-fixes.js +358 -14
  126. package/dist/lib/performance/site-fixes/helpers.js +3 -4
  127. package/dist/lib/performance/site-fixes/integrity.js +2 -4
  128. package/dist/lib/performance/site-fixes/migration-context.js +8 -1
  129. package/dist/lib/performance/site-fixes/migration-lock-rules.js +66 -30
  130. package/dist/lib/performance/site-fixes/prisma-aggregates.js +29 -9
  131. package/dist/lib/performance/site-fixes/small-rewrites.js +168 -10
  132. package/dist/lib/performance/site-fixes/sync-calls.js +14 -12
  133. package/dist/lib/performance/site-fixes/upload-limits.js +13 -7
  134. package/dist/lib/performance/sql/mysql-tokens.js +38 -12
  135. package/dist/lib/reliability/boundary-access.js +114 -57
  136. package/dist/lib/reliability/react-bugs.js +29 -7
  137. package/dist/lib/reliability/resource-leak-intervals.js +258 -0
  138. package/dist/lib/reliability/resource-leaks.js +209 -195
  139. package/dist/lib/reliability/rule-ids.js +10 -1
  140. package/dist/lib/reliability/site-fixes/resource-leaks.js +16 -1
  141. package/dist/lib/reliability/swallowed-errors.js +107 -21
  142. package/dist/lib/reliability/test-cleanup-after-await.js +92 -18
  143. package/dist/lib/reliability/usage.js +16 -5
  144. package/dist/lib/reliability/walk.js +3 -2
  145. package/dist/lib/security/auth-crypto/hashing.js +24 -8
  146. package/dist/lib/security/auth-crypto/jwt.js +21 -6
  147. package/dist/lib/security/auth-crypto/secrets.js +44 -1
  148. package/dist/lib/security/auth-crypto/shared.js +3 -1
  149. package/dist/lib/security/auth-crypto/signing-algorithm.js +79 -0
  150. package/dist/lib/security/auth-crypto/transport-and-ciphers.js +85 -1
  151. package/dist/lib/security/cli.js +21 -6
  152. package/dist/lib/security/cookie-credentials.js +115 -0
  153. package/dist/lib/security/cookie-csrf.js +241 -0
  154. package/dist/lib/security/deps/advisory.js +50 -109
  155. package/dist/lib/security/deps/cli.js +1 -1
  156. package/dist/lib/security/deps/cvss-score.js +14 -0
  157. package/dist/lib/security/deps/fixed-version.js +97 -0
  158. package/dist/lib/security/deps/lockfiles.js +135 -74
  159. package/dist/lib/security/deps/osv.js +11 -3
  160. package/dist/lib/security/deps/scan.js +47 -20
  161. package/dist/lib/security/deps/yarn-lock.js +158 -0
  162. package/dist/lib/security/examples/injection.cjs +4 -0
  163. package/dist/lib/security/exposure/cookies.js +17 -2
  164. package/dist/lib/security/exposure/cors-origin-regex.js +2 -3
  165. package/dist/lib/security/exposure/frontend-security.js +21 -14
  166. package/dist/lib/security/exposure/jsx-url.js +18 -33
  167. package/dist/lib/security/exposure/logging.js +49 -10
  168. package/dist/lib/security/exposure/prototype-pollution.js +126 -56
  169. package/dist/lib/security/exposure/react-html.js +26 -0
  170. package/dist/lib/security/exposure/reflected-xss.js +34 -5
  171. package/dist/lib/security/files/compose.js +126 -1
  172. package/dist/lib/security/files/dockerfile.js +62 -4
  173. package/dist/lib/security/files/index.js +1 -1
  174. package/dist/lib/security/injection/command.js +46 -18
  175. package/dist/lib/security/injection/index.js +2 -0
  176. package/dist/lib/security/injection/ldap.js +86 -0
  177. package/dist/lib/security/injection/nosql.js +28 -4
  178. package/dist/lib/security/injection/redos.js +1 -1
  179. package/dist/lib/security/injection/rule-ids.js +1 -0
  180. package/dist/lib/security/injection/shared.js +5 -1
  181. package/dist/lib/security/injection/sql.js +28 -13
  182. package/dist/lib/security/lexical-declaration.js +113 -0
  183. package/dist/lib/security/pg-dynamic-query.js +28 -1
  184. package/dist/lib/security/pg-identifier-guards.js +107 -3
  185. package/dist/lib/security/phase5-rules.js +26 -135
  186. package/dist/lib/security/polyglot.js +2 -2
  187. package/dist/lib/security/redirect-settings.js +98 -0
  188. package/dist/lib/security/request-forgery/open-redirect.js +18 -5
  189. package/dist/lib/security/request-forgery/path-traversal.js +84 -6
  190. package/dist/lib/security/request-forgery/shared.js +1 -7
  191. package/dist/lib/security/request-forgery/ssrf.js +176 -14
  192. package/dist/lib/security/rule-descriptions.js +5 -1
  193. package/dist/lib/security/rule-ids.js +7 -0
  194. package/dist/lib/security/site-fixes/auth-crypto.js +5 -78
  195. package/dist/lib/security/site-fixes/exposure.js +21 -3
  196. package/dist/lib/security/site-fixes/files.js +11 -13
  197. package/dist/lib/security/site-fixes/frontend-security-fixes.js +2 -2
  198. package/dist/lib/security/site-fixes/injection.js +17 -4
  199. package/dist/lib/security/site-fixes/jwt.js +1 -20
  200. package/dist/lib/security/site-fixes/request-forgery.js +37 -29
  201. package/dist/lib/security/taint/binding-inputs.js +236 -0
  202. package/dist/lib/security/taint/filename-guard.js +45 -45
  203. package/dist/lib/security/taint/guards.js +14 -8
  204. package/dist/lib/security/taint/index.js +126 -154
  205. package/dist/lib/security/taint/propagate.js +43 -9
  206. package/dist/lib/security/taint/record-writes.js +161 -0
  207. package/dist/lib/security/taint/resolution-cache.js +13 -7
  208. package/dist/lib/security/taint/sanitizers.js +89 -5
  209. package/dist/lib/security/taint/trace-nodes.js +61 -0
  210. package/dist/lib/security/taint/validators.js +89 -9
  211. package/dist/lib/shared/agent/agent-init.js +28 -5
  212. package/dist/lib/shared/agent/agent-prompt.js +74 -0
  213. package/dist/lib/shared/agent/agent-session.js +6 -1
  214. package/dist/lib/shared/agent/agent-verify.js +58 -11
  215. package/dist/lib/shared/agent/git-hook.js +17 -6
  216. package/dist/lib/shared/agent/review-delivery.js +1 -1
  217. package/dist/lib/shared/agent/review-mcp.js +8 -2
  218. package/dist/lib/shared/analysis/ast-semantics.js +2 -2
  219. package/dist/lib/shared/analysis/scan-cache.js +99 -14
  220. package/dist/lib/shared/check.js +172 -20
  221. package/dist/lib/shared/cli-dispatch.js +17 -0
  222. package/dist/lib/shared/config.js +27 -10
  223. package/dist/lib/shared/explain.js +1 -1
  224. package/dist/lib/shared/fix/fix-convergence.js +19 -31
  225. package/dist/lib/shared/fix/fix-handoff.js +16 -11
  226. package/dist/lib/shared/fix/fix-imports.js +4 -162
  227. package/dist/lib/shared/fix/fix-presentation-comments.js +23 -9
  228. package/dist/lib/shared/fix/fix-presentation-prettier.js +1 -46
  229. package/dist/lib/shared/fix/fix-presentation-rows.js +45 -1
  230. package/dist/lib/shared/fix/fix-presentation.js +9 -6
  231. package/dist/lib/shared/fix/fix-safety.js +32 -1
  232. package/dist/lib/shared/fix/fix-scope.js +82 -0
  233. package/dist/lib/shared/fix/fix-terminal.js +28 -1
  234. package/dist/lib/shared/fix/fix-typecheck.js +8 -4
  235. package/dist/lib/shared/fix/import-text-edits.js +148 -0
  236. package/dist/lib/shared/fix/project-file-access.js +17 -26
  237. package/dist/lib/shared/fix/read-fix-text.js +20 -0
  238. package/dist/lib/shared/fix.js +241 -104
  239. package/dist/lib/shared/formats/finding-location.js +4 -1
  240. package/dist/lib/shared/formats/github.js +3 -3
  241. package/dist/lib/shared/formats/sarif.js +9 -3
  242. package/dist/lib/shared/report-fp.js +97 -0
  243. package/dist/lib/shared/reporting/automatic-fix-signal.js +10 -0
  244. package/dist/lib/shared/reporting/baseline.js +7 -5
  245. package/dist/lib/shared/reporting/check-text.js +50 -0
  246. package/dist/lib/shared/reporting/pillars.js +54 -19
  247. package/dist/lib/shared/reporting/source-report.js +3 -0
  248. package/dist/lib/shared/system/atomic-write.js +5 -2
  249. package/dist/lib/shared/system/glob.js +34 -8
  250. package/dist/lib/shared/system/sentry.js +222 -0
  251. package/dist/lib/shared/system/shell-argument.js +5 -1
  252. package/dist/lib/shared/system/terminal-safe.js +3 -2
  253. package/dist/lib/shared/system/terminal-style.js +131 -0
  254. package/dist/lib/shared/workspaces.js +15 -3
  255. package/docs/assets/cli-workflow.gif +0 -0
  256. package/integrations/sublime/plugin.py +22 -0
  257. package/integrations/zed/Cargo.lock +845 -0
  258. package/integrations/zed/Cargo.toml +11 -0
  259. package/integrations/zed/extension.toml +11 -0
  260. package/integrations/zed/src/lib.rs +25 -0
  261. package/package.json +15 -3
  262. package/plugin/.claude-plugin/plugin.json +1 -1
  263. package/plugin/commands/loadwise.md +11 -6
  264. package/plugin/hooks/check-edited-file.mjs +27 -5
  265. package/polyglot/performance/rules/csharp.yml +34 -5
  266. package/polyglot/performance/rules/java.yml +24 -1
  267. package/polyglot/performance/rules/python.yml +74 -2
  268. package/polyglot/performance/sgconfig.yml +1 -0
  269. package/polyglot/reliability/rules/csharp.yml +12 -6
  270. package/polyglot/reliability/rules/go.yml +86 -6
  271. package/polyglot/reliability/rules/java.yml +22 -1
  272. package/polyglot/reliability/sgconfig.yml +1 -0
  273. package/polyglot/security/rules/go.yml +100 -22
  274. package/polyglot/security/rules/python.yml +74 -6
  275. package/polyglot/security/rules/rust.yml +65 -0
  276. package/polyglot/security/sgconfig.yml +1 -0
  277. package/schema/loadwise.config.schema.json +556 -76
  278. /package/polyglot/{performance/rules → shared-rules}/input.yml +0 -0
@@ -1,5 +1,6 @@
1
1
  // prototype-pollution: request-controlled keys written into an object without filtering.
2
2
  import { ts } from '../../performance/engine/compiler.js';
3
+ import { isGuardedByCondition, isReassigned } from '../taint/guards.js';
3
4
  import { unwrap } from './literals.js';
4
5
  import { reportTraced } from './report.js';
5
6
  const ruleId = 'prototype-pollution';
@@ -10,7 +11,7 @@ const pathWriteFunctions = new Set(['set', 'setWith', 'update', 'updateWith', 's
10
11
  const libraryMethods = new Set([...deepMergeFunctions, ...pathWriteFunctions]);
11
12
  const pathLibraries = /^(?:lodash(?:-es)?(?:\/.*)?|object-path|dot-prop)$/;
12
13
  const parameterPathReason = 'Contextual: the key path is a function parameter; confirm callers never pass request-controlled keys.';
13
- const prototypeWords = /__proto__|prototype|constructor/;
14
+ const prototypeKeys = ['__proto__', 'constructor', 'prototype'];
14
15
  function reportMessage(traced) {
15
16
  return message.replace('<source>', traced.label);
16
17
  }
@@ -27,27 +28,48 @@ function isNullPrototypeRoot(expression, checker) {
27
28
  initializer.arguments.length >= 1 &&
28
29
  unwrap(initializer.arguments[0]).kind === ts.SyntaxKind.NullKeyword);
29
30
  }
30
- // An `if`, ternary or `&&` before the write whose condition names the key and a prototype word:
31
- // `key === '__proto__'`,
32
- // `['__proto__', 'constructor'].includes(key)`. Either branch may be the safe one, so the write is
33
- // not reported.
34
- function hasPrototypeKeyGuard(key, write) {
35
- const keyText = unwrap(key).getText();
36
- const scope = ts.findAncestor(write, ts.isFunctionLike) ?? write.getSourceFile();
37
- let guarded = false;
38
- (function visit(node) {
39
- const condition = ts.isIfStatement(node)
40
- ? node.expression
41
- : ts.isConditionalExpression(node)
42
- ? node.condition
43
- : undefined;
44
- if (condition && condition.end <= write.getStart()) {
45
- const text = condition.getText();
46
- guarded ||= prototypeWords.test(text) && text.includes(keyText);
31
+ // Every sensitive name must be excluded on the control-flow path that reaches this use.
32
+ function hasPrototypeKeyGuard(key, use, checker) {
33
+ const binding = unwrap(key);
34
+ if (!ts.isIdentifier(binding))
35
+ return false;
36
+ const symbol = checker.getSymbolAtLocation(binding);
37
+ const declaration = symbol?.valueDeclaration;
38
+ if (!declaration || !ts.isVariableDeclaration(declaration))
39
+ return false;
40
+ const scope = ts.findAncestor(use, ts.isFunctionLike) ?? use.getSourceFile();
41
+ if (!(declaration.parent.flags & ts.NodeFlags.Const) && isReassigned(scope, symbol, checker))
42
+ return false;
43
+ return prototypeKeys.every((excluded) => isGuardedByCondition(use, (condition, truth) => {
44
+ if (ts.isCallExpression(condition) && ts.isPropertyAccessExpression(condition.expression)) {
45
+ const method = condition.expression;
46
+ if (method.name.text !== 'includes' ||
47
+ condition.arguments.length !== 1 ||
48
+ checker.getSymbolAtLocation(unwrap(condition.arguments[0])) !== symbol)
49
+ return false;
50
+ const options = unwrap(method.expression);
51
+ if (!ts.isArrayLiteralExpression(options) || !options.elements.every(ts.isStringLiteralLike))
52
+ return false;
53
+ const contains = options.elements.some((option) => ts.isStringLiteralLike(option) && option.text === excluded);
54
+ return truth ? !contains : contains;
47
55
  }
48
- ts.forEachChild(node, visit);
49
- })(scope);
50
- return guarded;
56
+ if (!ts.isBinaryExpression(condition))
57
+ return false;
58
+ const operator = condition.operatorToken.kind;
59
+ if (operator !== ts.SyntaxKind.EqualsEqualsEqualsToken && operator !== ts.SyntaxKind.ExclamationEqualsEqualsToken)
60
+ return false;
61
+ const equal = truth === (operator === ts.SyntaxKind.EqualsEqualsEqualsToken);
62
+ for (const [subject, literal] of [
63
+ [condition.left, condition.right],
64
+ [condition.right, condition.left],
65
+ ]) {
66
+ const value = unwrap(literal);
67
+ if (!ts.isStringLiteralLike(value) || checker.getSymbolAtLocation(unwrap(subject)) !== symbol)
68
+ continue;
69
+ return equal ? value.text !== excluded : value.text === excluded;
70
+ }
71
+ return false;
72
+ }));
51
73
  }
52
74
  const primitiveTypes = ts.TypeFlags.StringLike |
53
75
  ts.TypeFlags.NumberLike |
@@ -83,8 +105,8 @@ function checkAssignment(node, context) {
83
105
  if (!ts.isElementAccessExpression(access) || ts.isStringLiteralLike(access.argumentExpression))
84
106
  continue;
85
107
  const traced = context.taint.trace(access.argumentExpression, 'proto-key');
86
- if (traced && hasPrototypeKeyGuard(access.argumentExpression, node))
87
- return;
108
+ if (traced && hasPrototypeKeyGuard(access.argumentExpression, node, context.checker))
109
+ continue;
88
110
  if (traced)
89
111
  return reportTraced(context, node, ruleId, reportMessage(traced), traced);
90
112
  }
@@ -95,7 +117,7 @@ function checkAssignment(node, context) {
95
117
  const traced = context.taint.trace(target.argumentExpression, 'proto-key');
96
118
  if (!traced)
97
119
  return checkParameterPathWrite(node, context);
98
- if (!hasPrototypeKeyGuard(target.argumentExpression, node))
120
+ if (!hasPrototypeKeyGuard(target.argumentExpression, node, context.checker))
99
121
  context.report(node, ruleId, reportMessage(traced), singleKeyReason, { taint: traced });
100
122
  }
101
123
  function isParameterIdentifier(node, checker) {
@@ -135,6 +157,57 @@ function isWalkedPathVariable(expression, scope) {
135
157
  })(scope);
136
158
  return walked;
137
159
  }
160
+ // A guarded path array must be the one used at every step of the walk. Decline aliases,
161
+ // mutations and uses outside element reads, length checks and the membership tests themselves.
162
+ function protectedPathArray(index, scope, checker) {
163
+ const entry = unwrap(index);
164
+ if (!ts.isElementAccessExpression(entry) || !ts.isIdentifier(entry.expression))
165
+ return false;
166
+ const symbol = checker.getSymbolAtLocation(entry.expression);
167
+ const parameter = symbol?.valueDeclaration;
168
+ if (!parameter ||
169
+ !ts.isParameter(parameter) ||
170
+ !parameter.type ||
171
+ !ts.isArrayTypeNode(parameter.type) ||
172
+ isReassigned(scope, symbol, checker, true))
173
+ return false;
174
+ const declaredName = parameter.name;
175
+ function unchecked(node) {
176
+ if (ts.isIdentifier(node) && node !== declaredName && checker.getSymbolAtLocation(node) === symbol) {
177
+ const access = node.parent;
178
+ if (ts.isPropertyAccessExpression(access) &&
179
+ access.expression === node &&
180
+ (access.name.text === 'length' ||
181
+ (access.name.text === 'includes' &&
182
+ ts.isCallExpression(access.parent) &&
183
+ access.parent.expression === access)))
184
+ return false;
185
+ if (ts.isPropertyAccessExpression(access) &&
186
+ access.expression === node &&
187
+ access.name.text === 'push' &&
188
+ ts.isCallExpression(access.parent) &&
189
+ access.parent.expression === access &&
190
+ access.parent.arguments.every((argument) => ts.isStringLiteralLike(argument) && !prototypeKeys.includes(argument.text)))
191
+ return false;
192
+ if (!ts.isElementAccessExpression(access) || access.expression !== node)
193
+ return true;
194
+ return !prototypeKeys.every((key) => isGuardedByCondition(access, (test, truth) => {
195
+ if (truth ||
196
+ !ts.isCallExpression(test) ||
197
+ test.arguments.length !== 1 ||
198
+ !ts.isPropertyAccessExpression(test.expression))
199
+ return false;
200
+ const arg = test.arguments[0];
201
+ return (test.expression.name.text === 'includes' &&
202
+ checker.getSymbolAtLocation(test.expression.expression) === symbol &&
203
+ ts.isStringLiteralLike(arg) &&
204
+ arg.text === key);
205
+ }));
206
+ }
207
+ return ts.forEachChild(node, (child) => unchecked(child) || undefined);
208
+ }
209
+ return !unchecked(scope);
210
+ }
138
211
  // minimist's setKey: a key path handed in by the caller is walked and written with no `__proto__`
139
212
  // check. Whether the path is attacker-controlled depends on the callers, so this stays contextual.
140
213
  function checkParameterPathWrite(node, context) {
@@ -142,11 +215,12 @@ function checkParameterPathWrite(node, context) {
142
215
  if (!ts.isElementAccessExpression(target) || ts.isStringLiteralLike(target.argumentExpression))
143
216
  return;
144
217
  const scope = ts.findAncestor(node, ts.isFunctionLike);
145
- if (!scope || prototypeWords.test(scope.getText()))
218
+ if (!scope)
146
219
  return;
147
220
  if (!derivesFromParameter(target.argumentExpression, context.checker))
148
221
  return;
149
- if (!isWalkedPathVariable(target.expression, scope))
222
+ if (!isWalkedPathVariable(target.expression, scope) ||
223
+ protectedPathArray(target.argumentExpression, scope, context.checker))
150
224
  return;
151
225
  context.report(node, ruleId, reportMessage({ label: 'the key path argument' }), parameterPathReason);
152
226
  }
@@ -189,7 +263,7 @@ function checkLibraryCall(call, context) {
189
263
  if (isNullPrototypeRoot(call.arguments[0], context.checker))
190
264
  return;
191
265
  const traced = context.taint.trace(call.arguments[1], 'proto-key');
192
- if (traced && !hasPrototypeKeyGuard(call.arguments[1], call))
266
+ if (traced)
193
267
  reportTraced(context, call.arguments[1], ruleId, reportMessage(traced), traced);
194
268
  }
195
269
  }
@@ -209,55 +283,51 @@ function localFunctionOf(call, checker) {
209
283
  if (initializer && (ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer)))
210
284
  return { name: callee.text, body: initializer };
211
285
  }
212
- function assignsLoopKey(loop, keyName) {
213
- let found = false;
286
+ function hasUnguardedMergeStep(loop, key, name, checker) {
287
+ const symbol = checker.getSymbolAtLocation(key);
288
+ if (!symbol)
289
+ return false;
290
+ let writesKey = false;
291
+ let callsMerge = false;
292
+ let unguarded = false;
214
293
  (function visit(node) {
215
- if (found)
294
+ if (ts.isFunctionLike(node))
216
295
  return;
217
- if (ts.isBinaryExpression(node) &&
296
+ const writes = ts.isBinaryExpression(node) &&
218
297
  node.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
219
298
  ts.isElementAccessExpression(node.left) &&
220
- node.left.argumentExpression.getText() === keyName)
221
- found = true;
299
+ checker.getSymbolAtLocation(node.left.argumentExpression) === symbol;
300
+ const recurses = ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === name;
301
+ writesKey ||= writes;
302
+ callsMerge ||= recurses;
303
+ if (writes || recurses)
304
+ unguarded ||= !hasPrototypeKeyGuard(key, node, checker);
222
305
  ts.forEachChild(node, visit);
223
306
  })(loop);
224
- return found;
307
+ return writesKey && callsMerge && unguarded;
225
308
  }
226
- function loopKeyName(loop) {
309
+ function loopKey(loop) {
227
310
  const declaration = loop.initializer;
228
311
  if (!ts.isVariableDeclarationList(declaration) || declaration.declarations.length !== 1)
229
312
  return;
230
313
  const [variable] = declaration.declarations;
231
- return ts.isIdentifier(variable.name) ? variable.name.text : undefined;
232
- }
233
- function callsItself(body, name) {
234
- let found = false;
235
- (function visit(node) {
236
- if (found)
237
- return;
238
- if (ts.isCallExpression(node) && node.expression.getText() === name)
239
- found = true;
240
- ts.forEachChild(node, visit);
241
- })(body);
242
- return found;
314
+ return ts.isIdentifier(variable.name) ? variable.name : undefined;
243
315
  }
244
316
  // A project-local recursive merge: a key loop that assigns `target[key]` and calls the function
245
317
  // again.
246
- function isUnguardedRecursiveMerge({ name, body }) {
247
- if (prototypeWords.test(body.getText()))
248
- return false;
318
+ function isUnguardedRecursiveMerge({ name, body }, checker) {
249
319
  let merges = false;
250
320
  (function visit(node) {
251
321
  if ((ts.isForInStatement(node) || ts.isForOfStatement(node)) && !merges) {
252
- const key = loopKeyName(node);
253
- merges = key !== undefined && assignsLoopKey(node, key);
322
+ const key = loopKey(node);
323
+ merges = key !== undefined && hasUnguardedMergeStep(node, key, name, checker);
254
324
  }
255
325
  ts.forEachChild(node, visit);
256
326
  })(body);
257
- return merges && callsItself(body, name);
327
+ return merges;
258
328
  }
259
329
  const localMergeCache = new WeakMap();
260
- function isCachedUnguardedRecursiveMerge(local) {
330
+ function isCachedUnguardedRecursiveMerge(local, checker) {
261
331
  let byName = localMergeCache.get(local.body);
262
332
  if (byName) {
263
333
  const cached = byName.get(local.name);
@@ -268,7 +338,7 @@ function isCachedUnguardedRecursiveMerge(local) {
268
338
  byName = new Map();
269
339
  localMergeCache.set(local.body, byName);
270
340
  }
271
- const result = isUnguardedRecursiveMerge(local);
341
+ const result = isUnguardedRecursiveMerge(local, checker);
272
342
  byName.set(local.name, result);
273
343
  return result;
274
344
  }
@@ -276,7 +346,7 @@ function checkLocalMerge(call, context) {
276
346
  if (call.arguments.length < 2)
277
347
  return;
278
348
  const local = localFunctionOf(call, context.checker);
279
- if (!local || !isCachedUnguardedRecursiveMerge(local))
349
+ if (!local || !isCachedUnguardedRecursiveMerge(local, context.checker))
280
350
  return;
281
351
  for (const argument of call.arguments.slice(1)) {
282
352
  const traced = wholeRequest(argument, context);
@@ -0,0 +1,26 @@
1
+ import { ts } from '../../performance/engine/compiler.js';
2
+ // `<script type="application/ld+json" dangerouslySetInnerHTML=... />` carries data, not markup.
3
+ function isJsonScript(attribute) {
4
+ const element = attribute.parent.parent;
5
+ if (!ts.isIdentifier(element.tagName) || element.tagName.text !== 'script')
6
+ return false;
7
+ return element.attributes.properties.some((property) => ts.isJsxAttribute(property) &&
8
+ ts.isIdentifier(property.name) &&
9
+ property.name.text === 'type' &&
10
+ !!property.initializer &&
11
+ ts.isStringLiteral(property.initializer) &&
12
+ property.initializer.text.includes('json'));
13
+ }
14
+ // Only generate the DOMPurify edit when this exact runtime import is visible at the sink.
15
+ function hasDomPurifyAt(attribute, checker) {
16
+ const binding = checker.resolveName('DOMPurify', attribute, ts.SymbolFlags.Value, true);
17
+ const declaration = binding?.declarations?.[0];
18
+ if (!declaration ||
19
+ !ts.isImportClause(declaration) ||
20
+ declaration.isTypeOnly ||
21
+ declaration.name?.text !== 'DOMPurify')
22
+ return false;
23
+ const specifier = declaration.parent.moduleSpecifier;
24
+ return ts.isStringLiteral(specifier) && specifier.text === 'dompurify';
25
+ }
26
+ export { hasDomPurifyAt, isJsonScript };
@@ -1,6 +1,7 @@
1
1
  // reflected-xss-response: request data interpolated into an HTML string that is sent back
2
2
  // unescaped.
3
3
  import { ts } from '../../performance/engine/compiler.js';
4
+ import { constInitializer } from '../../shared/analysis/ast-semantics.js';
4
5
  import { unwrap, chainRootName, methodName } from './literals.js';
5
6
  import { reportTraced } from './report.js';
6
7
  const ruleId = 'reflected-xss-response';
@@ -8,20 +9,48 @@ const message = '`<source>` is placed into an HTML response without escaping. Es
8
9
  const contextualReason = 'Contextual in v1; confirm the response is served as HTML.';
9
10
  const responseNames = new Set(['res', 'response', 'reply']);
10
11
  const jsonContentTypePattern = /application\/json|\.type\(\s*['"]json['"]\s*\)/;
12
+ function constStringInitializer(expression, checker) {
13
+ const seen = new Set();
14
+ let current = unwrap(expression);
15
+ while (ts.isIdentifier(current) && !seen.has(current)) {
16
+ seen.add(current);
17
+ const next = constInitializer(current, checker);
18
+ if (!next)
19
+ return;
20
+ current = unwrap(next);
21
+ }
22
+ return ts.isStringLiteralLike(current) ||
23
+ ts.isTemplateExpression(current) ||
24
+ (ts.isBinaryExpression(current) && current.operatorToken.kind === ts.SyntaxKind.PlusToken)
25
+ ? current
26
+ : undefined;
27
+ }
11
28
  // The parts of a string built by a template or `+`, and whether any literal part opens a tag.
12
- function stringParts(expression, parts = { values: [], hasMarkup: false }) {
29
+ function stringParts(expression, checker, parts = { values: [], hasMarkup: false }, seen = new Set()) {
13
30
  const node = unwrap(expression);
31
+ if (seen.has(node)) {
32
+ parts.values.push(node);
33
+ return parts;
34
+ }
35
+ seen.add(node);
14
36
  if (ts.isTemplateExpression(node)) {
15
37
  parts.hasMarkup ||=
16
38
  node.head.text.includes('<') || node.templateSpans.some((span) => span.literal.text.includes('<'));
17
- node.templateSpans.forEach((span) => parts.values.push(span.expression));
39
+ node.templateSpans.forEach((span) => stringParts(span.expression, checker, parts, seen));
18
40
  }
19
41
  else if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.PlusToken) {
20
- stringParts(node.left, parts);
21
- stringParts(node.right, parts);
42
+ stringParts(node.left, checker, parts, seen);
43
+ stringParts(node.right, checker, parts, seen);
22
44
  }
23
45
  else if (ts.isStringLiteralLike(node))
24
46
  parts.hasMarkup ||= node.text.includes('<');
47
+ else if (ts.isIdentifier(node)) {
48
+ const resolved = constStringInitializer(node, checker);
49
+ if (resolved)
50
+ stringParts(resolved, checker, parts, seen);
51
+ else
52
+ parts.values.push(node);
53
+ }
25
54
  else
26
55
  parts.values.push(node);
27
56
  return parts;
@@ -30,7 +59,7 @@ function checkBody(body, context) {
30
59
  const scope = ts.findAncestor(body, ts.isFunctionLike);
31
60
  if (scope && jsonContentTypePattern.test(scope.getText()))
32
61
  return;
33
- const parts = stringParts(body);
62
+ const parts = stringParts(body, context.checker);
34
63
  if (!parts.hasMarkup)
35
64
  return;
36
65
  for (const value of parts.values) {
@@ -7,14 +7,103 @@ const composeName = /^(?:docker-)?compose(?:[.-].+)?\.ya?ml$|\.compose\.ya?ml$/i
7
7
  // that uses them.
8
8
  const datastoreImage = /^\s*image:\s*["']?(?:[\w.-]+\/)*[\w.-]*(?:postgres|mysql|mariadb|mongo|redis|oracle|mssql|sqlserver|cockroach|minio|rustfs|localstack|rabbitmq|clickhouse|elasticsearch|opensearch)/i;
9
9
  const environmentHeader = /^(\s*)environment:\s*(?:#.*)?$/;
10
+ const flowEnvironment = /^(\s*)environment:\s*\{(.*)$/;
11
+ // A list item or mapping value that opens a literal or folded block scalar; its deeper lines are text, not entries.
12
+ const blockScalarStart = /[:-]\s+[|>][+-]?\d?[+-]?\s*(?:#.*)?$/;
13
+ const sequenceLine = /^\s*-(?:\s|$)/;
10
14
  const listEntry = /^\s*-\s*["']?([A-Za-z_][\w.]*)=(.*?)["']?\s*$/;
11
15
  const mapEntry = /^\s*["']?([A-Za-z_][\w.]*)["']?\s*:\s*(.+?)\s*$/;
16
+ // A list item or mapping value that opens a quoted scalar; the scalar may continue on later lines.
17
+ const quotedScalarStart = /^\s*(?:-\s+)?(?:["']?[A-Za-z_][\w.]*["']?\s*:\s+)?(["'])/;
18
+ // Splits the text after an inline `{` at top-level commas and stops at the closing brace outside
19
+ // quotes. A quote only opens at a scalar boundary, so an apostrophe inside a plain scalar
20
+ // (O'Reilly) is literal. Returns undefined when the brace never closes on the line (a comment
21
+ // starts first) or more than a comment follows.
22
+ function splitFlowEntries(rest) {
23
+ const parts = [];
24
+ let start = 0;
25
+ let quote;
26
+ let atBoundary = true;
27
+ for (let index = 0; index < rest.length; index++) {
28
+ const ch = rest[index];
29
+ if (quote) {
30
+ if (quote === '"' && ch === '\\')
31
+ index++;
32
+ else if (quote === "'" && ch === "'" && rest[index + 1] === "'")
33
+ index++;
34
+ else if (ch === quote)
35
+ quote = undefined;
36
+ continue;
37
+ }
38
+ if (ch === '#' && (index === 0 || /\s/.test(rest[index - 1])))
39
+ return undefined;
40
+ if (atBoundary && (ch === '"' || ch === "'"))
41
+ quote = ch;
42
+ else if (ch === '}') {
43
+ parts.push(rest.slice(start, index));
44
+ return /^\s*(?:#.*)?$/.test(rest.slice(index + 1)) ? parts : undefined;
45
+ }
46
+ else if (ch === ',') {
47
+ parts.push(rest.slice(start, index));
48
+ start = index + 1;
49
+ }
50
+ if (ch === ',' || ch === ':')
51
+ atBoundary = true;
52
+ else if (!/\s/.test(ch))
53
+ atBoundary = false;
54
+ }
55
+ return undefined;
56
+ }
57
+ const doubleQuoteEscapes = {
58
+ n: '\n',
59
+ t: '\t',
60
+ r: '\r',
61
+ '0': '\0',
62
+ '"': '"',
63
+ '\\': '\\',
64
+ '/': '/',
65
+ };
66
+ // Decodes the quoted YAML scalar so classification sees the value the container receives.
67
+ function unquoteScalar(value) {
68
+ const match = /^(["'])(.*)\1$/.exec(value);
69
+ if (!match)
70
+ return value;
71
+ if (match[1] === "'")
72
+ return match[2].replaceAll("''", "'");
73
+ return match[2].replaceAll(/\\(?:x([0-9a-fA-F]{2})|u([0-9a-fA-F]{4})|(.))/g, (whole, hex2, hex4, simple) => hex2 || hex4 ? String.fromCodePoint(Number.parseInt(hex2 || hex4, 16)) : (doubleQuoteEscapes[simple] ?? whole));
74
+ }
75
+ function flowEntriesOf(rest) {
76
+ const entries = [];
77
+ for (const raw of splitFlowEntries(rest) ?? []) {
78
+ const match = mapEntry.exec(raw.trim());
79
+ if (!match)
80
+ continue;
81
+ entries.push({ key: match[1], value: unquoteScalar(match[2].replace(/^&\S+\s+/, '')) });
82
+ }
83
+ return entries;
84
+ }
12
85
  function isComposeFile(file) {
13
86
  return composeName.test(file.split('/').at(-1) ?? '');
14
87
  }
15
88
  function indentOf(line) {
16
89
  return line.length - line.trimStart().length;
17
90
  }
91
+ // The quote still open after scanning text, honouring backslash escapes in double quotes and '' in single.
92
+ function openQuoteAfter(text, openQuote) {
93
+ let open = openQuote;
94
+ for (let index = 0; index < text.length; index++) {
95
+ const char = text[index];
96
+ if (!open)
97
+ continue;
98
+ if (open === '"' && char === '\\')
99
+ index++;
100
+ else if (char === open && open === "'" && text[index + 1] === "'")
101
+ index++;
102
+ else if (char === open)
103
+ open = undefined;
104
+ }
105
+ return open;
106
+ }
18
107
  function entryOf(line) {
19
108
  const match = listEntry.exec(line) ?? mapEntry.exec(line);
20
109
  if (!match)
@@ -49,12 +138,48 @@ function checkCompose(text, file) {
49
138
  const lines = text.split(/\r?\n/);
50
139
  let environmentIndent;
51
140
  let datastoreService = false;
141
+ let blockScalarIndent;
142
+ let openQuote;
52
143
  lines.forEach((line, index) => {
144
+ if (openQuote) {
145
+ openQuote = openQuoteAfter(line, openQuote);
146
+ return;
147
+ }
53
148
  if (!line.trim() || line.trim().startsWith('#'))
54
149
  return;
55
150
  const indent = indentOf(line);
56
- if (environmentIndent !== undefined && indent <= environmentIndent)
151
+ if (environmentIndent !== undefined &&
152
+ (indent < environmentIndent || (indent === environmentIndent && !sequenceLine.test(line)))) {
57
153
  environmentIndent = undefined;
154
+ }
155
+ if (blockScalarIndent !== undefined) {
156
+ if (indent > blockScalarIndent)
157
+ return;
158
+ blockScalarIndent = undefined;
159
+ }
160
+ if (blockScalarStart.test(line))
161
+ blockScalarIndent = indent;
162
+ const flow = flowEnvironment.exec(line);
163
+ if (flow) {
164
+ const flowIndent = flow[1].length;
165
+ const isDatastore = runsDatastoreImage(lines, index, flowIndent);
166
+ for (const entry of flowEntriesOf(flow[2])) {
167
+ if (!isSecretKey(entry.key) || isPlaceholderValue(entry.value, entry.key))
168
+ continue;
169
+ const contextualReason = contextualReasonFor(entry.value, isDatastore, file);
170
+ findings.push({
171
+ ruleId: 'compose-hardcoded-secret',
172
+ line: index + 1,
173
+ column: indent + 1,
174
+ ...(contextualReason && { contextualReason }),
175
+ message: `Compose environment sets "${entry.key}" to a literal value (starts "${redactedPrefix(entry.value)}"). Read it from an env file or a secret instead.`,
176
+ });
177
+ }
178
+ return;
179
+ }
180
+ const quotedStart = quotedScalarStart.exec(line);
181
+ if (quotedStart)
182
+ openQuote = openQuoteAfter(line.slice(quotedStart[0].length), quotedStart[1]);
58
183
  const header = environmentHeader.exec(line);
59
184
  if (header) {
60
185
  environmentIndent = header[1].length;
@@ -35,14 +35,51 @@ function isInDevelopmentFolder(file) {
35
35
  function isDockerfile(file) {
36
36
  return dockerfileName.test(baseNameOf(file));
37
37
  }
38
+ function heredocDelimiters(instruction) {
39
+ if (!instruction.args.includes('<<'))
40
+ return [];
41
+ const command = instruction.name === 'ONBUILD' ? instruction.args : instruction.name + ' ' + instruction.args;
42
+ if (!/^(?:COPY|ADD|RUN)\s/i.test(command))
43
+ return [];
44
+ const delimiters = [];
45
+ // Inspect whole shell words: a quoted or escaped "<<EOF" argument is literal text.
46
+ const words = command.matchAll(/(?:[^\s"'\\]|\\.|"(?:[^"\\]|\\.)*"|'[^']*')+/g);
47
+ for (const [word] of words) {
48
+ // BuildKit also joins a bare << operator with the following delimiter word.
49
+ const token = /^\d*<<$/.test(word) ? word + (words.next().value?.[0] ?? '') : word;
50
+ const marker = /^\d*<<(-?)([^<]+)$/.exec(token);
51
+ if (!marker)
52
+ continue;
53
+ const name = marker[2].replaceAll(/'([^']*)'|"((?:[^"\\]|\\.)*)"|\\(.)/g, (_match, single, double, escaped) => single ?? double?.replaceAll(/\\(["\\$])/g, '$1') ?? escaped ?? '');
54
+ delimiters.push({ name, stripTabs: marker[1] === '-' });
55
+ }
56
+ return delimiters;
57
+ }
38
58
  function logicalInstructions(text) {
39
59
  const instructions = [];
40
60
  let pending;
61
+ let delimiters = [];
62
+ let nextDelimiter = 0;
63
+ let escape = '\\';
64
+ let readingDirectives = true;
41
65
  text.split(/\r?\n/).forEach((rawLine, index) => {
66
+ const delimiter = delimiters[nextDelimiter];
67
+ if (delimiter) {
68
+ if ((delimiter.stripTabs ? rawLine.replace(/^\t+/, '') : rawLine) === delimiter.name)
69
+ nextDelimiter++;
70
+ return;
71
+ }
42
72
  const trimmed = rawLine.trim();
73
+ if (readingDirectives) {
74
+ const directive = /^#\s*(syntax|escape|check)\s*=\s*(.+)$/i.exec(trimmed);
75
+ readingDirectives = Boolean(directive);
76
+ if (directive?.[1].toLowerCase() === 'escape' && ['\\', '`'].includes(directive[2])) {
77
+ escape = directive[2];
78
+ }
79
+ }
43
80
  if (trimmed.startsWith('#') || (!trimmed && !pending))
44
81
  return;
45
- const continued = trimmed.endsWith('\\');
82
+ const continued = trimmed.endsWith(escape) && trimmed.at(-2) !== escape;
46
83
  const content = continued ? trimmed.slice(0, -1) : trimmed;
47
84
  if (pending)
48
85
  pending.text += ' ' + content;
@@ -51,8 +88,12 @@ function logicalInstructions(text) {
51
88
  if (continued)
52
89
  return;
53
90
  const match = /^(\w+)\s*(.*)$/.exec(pending.text);
54
- if (match)
55
- instructions.push({ line: pending.line, name: match[1].toUpperCase(), args: match[2] });
91
+ if (match) {
92
+ const instruction = { line: pending.line, name: match[1].toUpperCase(), args: match[2] };
93
+ instructions.push(instruction);
94
+ delimiters = heredocDelimiters(instruction);
95
+ nextDelimiter = 0;
96
+ }
56
97
  pending = undefined;
57
98
  });
58
99
  return instructions;
@@ -203,4 +244,21 @@ function checkDockerfile(file, text) {
203
244
  .filter((finding) => finding !== undefined)
204
245
  .map((finding) => ({ column: 1, ...finding, ...(contextualReason && { contextualReason }) }));
205
246
  }
206
- export { checkDockerfile, isDockerfile };
247
+ // Reuse only a numeric identity explicitly selected in this stage, without changing subsequent build steps.
248
+ function previousNumericUser(text, rootLine) {
249
+ const final = parseStages(logicalInstructions(text)).at(-1);
250
+ if (!final)
251
+ return;
252
+ const index = final.instructions.findIndex((instruction) => instruction.line === rootLine && instruction.name === 'USER');
253
+ if (index < 0 ||
254
+ final.instructions
255
+ .slice(index + 1)
256
+ .some(({ name }) => !['CMD', 'ENTRYPOINT', 'LABEL', 'EXPOSE', 'HEALTHCHECK', 'STOPSIGNAL'].includes(name)))
257
+ return;
258
+ const user = final.instructions.slice(0, index).findLast(({ name }) => name === 'USER')?.args;
259
+ if (!user || !/^[1-9]\d*(?::(?:0|[1-9]\d*))?$/.test(user))
260
+ return;
261
+ const maxId = 2 ** 32 - 2;
262
+ return user.split(':').every((id) => Number(id) <= maxId) ? user : undefined;
263
+ }
264
+ export { checkDockerfile, isDockerfile, previousNumericUser };
@@ -14,7 +14,7 @@ const maxFileBytes = 1 << 20;
14
14
  const binarySniffBytes = 8000;
15
15
  const skippedExtensions = new Set('.png .jpg .jpeg .gif .webp .ico .pdf .zip .gz .tgz .woff .woff2 .ttf .eot .mp3 .mp4 .wasm .map .lock .svg'.split(' '));
16
16
  const skippedNamePattern = /\.min\./i;
17
- const skippedNames = new Set(['package-lock.json', 'pnpm-lock.yaml', 'yarn.lock']);
17
+ const skippedNames = new Set(['npm-shrinkwrap.json', 'package-lock.json', 'pnpm-lock.yaml', 'yarn.lock']);
18
18
  const exampleLanguages = { 'committed-secret': 'dotenv', 'compose-hardcoded-secret': 'yaml' };
19
19
  function readText(absolute) {
20
20
  const stat = fs.lstatSync(absolute, { throwIfNoEntry: false });