loadwise 0.7.0 → 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 (228) hide show
  1. package/README.md +23 -15
  2. package/dist/bin/loadwise.js +12 -24
  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/jsx-elements.js +13 -3
  10. package/dist/lib/accessibility/markup-files.js +7 -2
  11. package/dist/lib/accessibility/rule-ids.js +3 -0
  12. package/dist/lib/accessibility/rules.js +128 -41
  13. package/dist/lib/accessibility/site-fixes/buttons.js +5 -1
  14. package/dist/lib/accessibility/template-attributes.js +5 -3
  15. package/dist/lib/accessibility/template-elements.js +25 -6
  16. package/dist/lib/accessibility/template-file.js +40 -25
  17. package/dist/lib/editor/accessibility-examples.js +6 -1
  18. package/dist/lib/editor/actions.js +46 -7
  19. package/dist/lib/editor/apply-fix.js +69 -4
  20. package/dist/lib/editor/configured-setup.js +5 -3
  21. package/dist/lib/editor/diagnostics.js +206 -17
  22. package/dist/lib/editor/dismissals.js +85 -26
  23. package/dist/lib/editor/editor-document.js +5 -2
  24. package/dist/lib/editor/editor-launcher.js +7 -2
  25. package/dist/lib/editor/language-server.js +64 -25
  26. package/dist/lib/editor/native-setup.js +3 -2
  27. package/dist/lib/editor/perf-watch.js +8 -6
  28. package/dist/lib/editor/reliability-examples.js +15 -0
  29. package/dist/lib/editor/scan-session.js +29 -8
  30. package/dist/lib/editor/server-commands.js +36 -9
  31. package/dist/lib/editor/setup-server.js +1 -1
  32. package/dist/lib/editor/setup-vim.js +6 -4
  33. package/dist/lib/editor/workspace-files.js +61 -7
  34. package/dist/lib/editor/workspace-paths.js +41 -1
  35. package/dist/lib/maintainability/analysis/analyze-source.js +1 -1
  36. package/dist/lib/maintainability/architecture/architecture.js +4 -4
  37. package/dist/lib/maintainability/cli/changed-lines.js +20 -2
  38. package/dist/lib/maintainability/cli/inputs.js +9 -1
  39. package/dist/lib/maintainability/cli.js +4 -0
  40. package/dist/lib/maintainability/entry-points/entry-points.js +44 -15
  41. package/dist/lib/maintainability/entry-points/html-entry-points.js +5 -1
  42. package/dist/lib/maintainability/quality/functions.js +9 -6
  43. package/dist/lib/maintainability/quality/limits.js +19 -0
  44. package/dist/lib/maintainability/quality/size-limits.js +8 -2
  45. package/dist/lib/maintainability/quality/stray-console.js +62 -1
  46. package/dist/lib/maintainability/quality/tsconfig-strict.js +2 -0
  47. package/dist/lib/maintainability/scan-changed.js +4 -1
  48. package/dist/lib/maintainability/scan-worker.js +6 -2
  49. package/dist/lib/maintainability/scan.js +21 -8
  50. package/dist/lib/maintainability/unused/module-usage.js +43 -21
  51. package/dist/lib/maintainability/unused/unused-modules.js +5 -10
  52. package/dist/lib/performance/analysis/source-inputs.js +7 -2
  53. package/dist/lib/performance/analysis/source-options.js +7 -6
  54. package/dist/lib/performance/analyze.js +16 -3
  55. package/dist/lib/performance/cli/cli-output.js +1 -0
  56. package/dist/lib/performance/cli/cli-scan.js +21 -2
  57. package/dist/lib/performance/cli.js +8 -3
  58. package/dist/lib/performance/collections/memory-growth.js +55 -12
  59. package/dist/lib/performance/contracts/openapi.js +13 -4
  60. package/dist/lib/performance/datastores/pg-integrity.js +61 -22
  61. package/dist/lib/performance/datastores/pg-session-release.js +114 -0
  62. package/dist/lib/performance/datastores/pg-session-sql.js +144 -0
  63. package/dist/lib/performance/datastores/pooling.js +56 -2
  64. package/dist/lib/performance/datastores/redis.js +94 -18
  65. package/dist/lib/performance/datastores/session-store.js +2 -1
  66. package/dist/lib/performance/db/checks.js +19 -8
  67. package/dist/lib/performance/db/gateway.js +3 -1
  68. package/dist/lib/performance/db/plan-estimates.js +4 -4
  69. package/dist/lib/performance/engine/native.js +11 -7
  70. package/dist/lib/performance/evidence/plans.js +7 -5
  71. package/dist/lib/performance/evidence/traces.js +21 -1
  72. package/dist/lib/performance/frontend/angular-teardown.js +96 -0
  73. package/dist/lib/performance/frontend/effect-cleanup.js +148 -0
  74. package/dist/lib/performance/frontend/frontend-dom-perf.js +14 -2
  75. package/dist/lib/performance/frontend/frontend-helpers.js +1 -9
  76. package/dist/lib/performance/frontend/frontend-perf.js +72 -57
  77. package/dist/lib/performance/migrations/extract-code-sql.js +16 -4
  78. package/dist/lib/performance/migrations/extract-code.js +13 -5
  79. package/dist/lib/performance/migrations/extract-sql.js +82 -38
  80. package/dist/lib/performance/migrations/operations.js +56 -13
  81. package/dist/lib/performance/migrations/postgres-lock-timeout.js +52 -0
  82. package/dist/lib/performance/migrations/postgres-registry.js +127 -26
  83. package/dist/lib/performance/migrations/postgres-settings.js +78 -0
  84. package/dist/lib/performance/migrations/rules-postgres-add-column.js +3 -3
  85. package/dist/lib/performance/migrations/rules-postgres-shared.js +9 -0
  86. package/dist/lib/performance/migrations/rules-postgres.js +88 -39
  87. package/dist/lib/performance/orm/offset-pagination.js +6 -4
  88. package/dist/lib/performance/orm/prisma-aggregates.js +69 -18
  89. package/dist/lib/performance/orm/unbounded-list-chain.js +29 -0
  90. package/dist/lib/performance/orm/unbounded-list-queries.js +18 -13
  91. package/dist/lib/performance/polyglot.js +111 -14
  92. package/dist/lib/performance/projects.js +3 -3
  93. package/dist/lib/performance/query-loops/sequential-loops.js +1 -0
  94. package/dist/lib/performance/request/backend-mastery.js +151 -42
  95. package/dist/lib/performance/request/mongoose-lean.js +175 -10
  96. package/dist/lib/performance/request/phase5-rules.js +74 -13
  97. package/dist/lib/performance/request/sql-select-star.js +150 -0
  98. package/dist/lib/performance/request/unbounded-promise-all.js +54 -29
  99. package/dist/lib/performance/request/upload-limits.js +5 -1
  100. package/dist/lib/performance/site-fix.js +4 -4
  101. package/dist/lib/performance/site-fixes/backend-mastery-fixes.js +298 -16
  102. package/dist/lib/performance/site-fixes/frontend-fixes.js +350 -10
  103. package/dist/lib/performance/site-fixes/migration-context.js +8 -1
  104. package/dist/lib/performance/site-fixes/migration-lock-rules.js +66 -30
  105. package/dist/lib/performance/site-fixes/prisma-aggregates.js +29 -9
  106. package/dist/lib/performance/site-fixes/small-rewrites.js +168 -10
  107. package/dist/lib/performance/site-fixes/sync-calls.js +14 -12
  108. package/dist/lib/performance/site-fixes/upload-limits.js +13 -7
  109. package/dist/lib/performance/sql/mysql-tokens.js +38 -12
  110. package/dist/lib/reliability/boundary-access.js +114 -57
  111. package/dist/lib/reliability/react-bugs.js +18 -4
  112. package/dist/lib/reliability/resource-leak-intervals.js +258 -0
  113. package/dist/lib/reliability/resource-leaks.js +209 -195
  114. package/dist/lib/reliability/rule-ids.js +10 -1
  115. package/dist/lib/reliability/site-fixes/resource-leaks.js +16 -1
  116. package/dist/lib/reliability/swallowed-errors.js +107 -21
  117. package/dist/lib/reliability/test-cleanup-after-await.js +92 -18
  118. package/dist/lib/reliability/walk.js +3 -2
  119. package/dist/lib/security/auth-crypto/hashing.js +24 -8
  120. package/dist/lib/security/auth-crypto/jwt.js +21 -6
  121. package/dist/lib/security/auth-crypto/secrets.js +44 -1
  122. package/dist/lib/security/auth-crypto/shared.js +3 -1
  123. package/dist/lib/security/auth-crypto/signing-algorithm.js +79 -0
  124. package/dist/lib/security/auth-crypto/transport-and-ciphers.js +85 -1
  125. package/dist/lib/security/cli.js +6 -2
  126. package/dist/lib/security/cookie-credentials.js +115 -0
  127. package/dist/lib/security/cookie-csrf.js +241 -0
  128. package/dist/lib/security/deps/advisory.js +50 -109
  129. package/dist/lib/security/deps/cli.js +1 -1
  130. package/dist/lib/security/deps/cvss-score.js +14 -0
  131. package/dist/lib/security/deps/fixed-version.js +97 -0
  132. package/dist/lib/security/deps/lockfiles.js +135 -74
  133. package/dist/lib/security/deps/osv.js +11 -3
  134. package/dist/lib/security/deps/scan.js +47 -20
  135. package/dist/lib/security/deps/yarn-lock.js +158 -0
  136. package/dist/lib/security/examples/injection.cjs +4 -0
  137. package/dist/lib/security/exposure/cookies.js +17 -2
  138. package/dist/lib/security/exposure/cors-origin-regex.js +2 -3
  139. package/dist/lib/security/exposure/frontend-security.js +21 -14
  140. package/dist/lib/security/exposure/jsx-url.js +18 -33
  141. package/dist/lib/security/exposure/logging.js +49 -10
  142. package/dist/lib/security/exposure/prototype-pollution.js +126 -56
  143. package/dist/lib/security/exposure/react-html.js +26 -0
  144. package/dist/lib/security/exposure/reflected-xss.js +34 -5
  145. package/dist/lib/security/files/compose.js +126 -1
  146. package/dist/lib/security/files/dockerfile.js +62 -4
  147. package/dist/lib/security/files/index.js +1 -1
  148. package/dist/lib/security/injection/command.js +46 -18
  149. package/dist/lib/security/injection/index.js +2 -0
  150. package/dist/lib/security/injection/ldap.js +86 -0
  151. package/dist/lib/security/injection/nosql.js +28 -4
  152. package/dist/lib/security/injection/redos.js +1 -1
  153. package/dist/lib/security/injection/rule-ids.js +1 -0
  154. package/dist/lib/security/injection/shared.js +5 -1
  155. package/dist/lib/security/injection/sql.js +28 -13
  156. package/dist/lib/security/lexical-declaration.js +113 -0
  157. package/dist/lib/security/pg-dynamic-query.js +28 -1
  158. package/dist/lib/security/pg-identifier-guards.js +107 -3
  159. package/dist/lib/security/phase5-rules.js +26 -135
  160. package/dist/lib/security/polyglot.js +2 -2
  161. package/dist/lib/security/redirect-settings.js +98 -0
  162. package/dist/lib/security/request-forgery/open-redirect.js +18 -5
  163. package/dist/lib/security/request-forgery/path-traversal.js +84 -6
  164. package/dist/lib/security/request-forgery/shared.js +1 -7
  165. package/dist/lib/security/request-forgery/ssrf.js +176 -14
  166. package/dist/lib/security/rule-descriptions.js +5 -1
  167. package/dist/lib/security/rule-ids.js +7 -0
  168. package/dist/lib/security/site-fixes/auth-crypto.js +5 -78
  169. package/dist/lib/security/site-fixes/exposure.js +21 -3
  170. package/dist/lib/security/site-fixes/files.js +11 -13
  171. package/dist/lib/security/site-fixes/frontend-security-fixes.js +2 -2
  172. package/dist/lib/security/site-fixes/injection.js +17 -4
  173. package/dist/lib/security/site-fixes/jwt.js +1 -20
  174. package/dist/lib/security/site-fixes/request-forgery.js +37 -29
  175. package/dist/lib/security/taint/binding-inputs.js +236 -0
  176. package/dist/lib/security/taint/filename-guard.js +45 -45
  177. package/dist/lib/security/taint/guards.js +14 -8
  178. package/dist/lib/security/taint/index.js +126 -154
  179. package/dist/lib/security/taint/propagate.js +43 -9
  180. package/dist/lib/security/taint/record-writes.js +161 -0
  181. package/dist/lib/security/taint/resolution-cache.js +13 -7
  182. package/dist/lib/security/taint/sanitizers.js +89 -5
  183. package/dist/lib/security/taint/trace-nodes.js +61 -0
  184. package/dist/lib/security/taint/validators.js +89 -9
  185. package/dist/lib/shared/agent/agent-init.js +2 -1
  186. package/dist/lib/shared/agent/agent-verify.js +4 -1
  187. package/dist/lib/shared/agent/git-hook.js +17 -6
  188. package/dist/lib/shared/agent/review-mcp.js +8 -2
  189. package/dist/lib/shared/analysis/ast-semantics.js +2 -2
  190. package/dist/lib/shared/analysis/scan-cache.js +96 -12
  191. package/dist/lib/shared/cli-dispatch.js +17 -0
  192. package/dist/lib/shared/config.js +27 -10
  193. package/dist/lib/shared/explain.js +1 -1
  194. package/dist/lib/shared/fix/fix-convergence.js +5 -3
  195. package/dist/lib/shared/fix/fix-imports.js +4 -171
  196. package/dist/lib/shared/fix/fix-presentation-comments.js +23 -9
  197. package/dist/lib/shared/fix/fix-presentation.js +5 -3
  198. package/dist/lib/shared/fix/fix-safety.js +7 -1
  199. package/dist/lib/shared/fix/fix-typecheck.js +8 -4
  200. package/dist/lib/shared/fix/import-text-edits.js +148 -0
  201. package/dist/lib/shared/fix.js +31 -7
  202. package/dist/lib/shared/formats/finding-location.js +4 -1
  203. package/dist/lib/shared/formats/github.js +3 -3
  204. package/dist/lib/shared/formats/sarif.js +9 -3
  205. package/dist/lib/shared/report-fp.js +6 -2
  206. package/dist/lib/shared/reporting/baseline.js +7 -5
  207. package/dist/lib/shared/reporting/pillars.js +9 -3
  208. package/dist/lib/shared/reporting/source-report.js +1 -0
  209. package/dist/lib/shared/system/glob.js +34 -8
  210. package/dist/lib/shared/system/sentry.js +26 -7
  211. package/dist/lib/shared/workspaces.js +15 -3
  212. package/package.json +5 -1
  213. package/plugin/.claude-plugin/plugin.json +1 -1
  214. package/plugin/hooks/check-edited-file.mjs +27 -5
  215. package/polyglot/performance/rules/csharp.yml +34 -5
  216. package/polyglot/performance/rules/java.yml +24 -1
  217. package/polyglot/performance/rules/python.yml +74 -2
  218. package/polyglot/performance/sgconfig.yml +1 -0
  219. package/polyglot/reliability/rules/csharp.yml +12 -6
  220. package/polyglot/reliability/rules/go.yml +86 -6
  221. package/polyglot/reliability/rules/java.yml +22 -1
  222. package/polyglot/reliability/sgconfig.yml +1 -0
  223. package/polyglot/security/rules/go.yml +100 -22
  224. package/polyglot/security/rules/python.yml +74 -6
  225. package/polyglot/security/rules/rust.yml +65 -0
  226. package/polyglot/security/sgconfig.yml +1 -0
  227. package/schema/loadwise.config.schema.json +554 -76
  228. /package/polyglot/{performance/rules → shared-rules}/input.yml +0 -0
@@ -12,6 +12,7 @@ const tlsEnvironmentVariable = 'NODE_TLS_REJECT_UNAUTHORIZED';
12
12
  const brokenCipher = /^(?:des|des-ede|rc4|rc2|bf)|-ecb$/i;
13
13
  const cipherFunctions = new Set(['createCipher', 'createDecipher', 'createCipheriv', 'createDecipheriv']);
14
14
  const tlsMessage = 'TLS certificate verification is turned off. Enable verification, connect using a host name covered by the server certificate, and configure the trusted CA if it is private.';
15
+ const tlsServerMessage = 'TLS client certificate verification is turned off on a server requesting client certificates. Enable verification unless unauthenticated or self-signed client certificates are intentionally accepted.';
15
16
  // An operator opt-in such as `process.env.PG_SSL_ALLOW_SELF_SIGNED === 'true'` or
16
17
  // `config.get('ALLOW_SELF_SIGNED')`.
17
18
  const selfSignedOptIn = /ALLOW_SELF_SIGNED|ALLOW_INSECURE|ALLOW_UNAUTHORIZED|SKIP_TLS_VERIFY|INSECURE_SKIP_VERIFY|IGNORE_SSL|IGNORE_TLS|ACCEPT_INVALID_CERTS|accept_invalid_certs|ignoreSSLIssues|allowUnauthorized/i;
@@ -306,6 +307,49 @@ function isOverriddenAtEveryUse(property, key, context) {
306
307
  const references = referencesOf(declaration.name, context.sourceFile, context.checker);
307
308
  return references.length > 0 && references.every((reference) => overridesSpread(reference, key));
308
309
  }
310
+ function isTlsServerCall(call, context) {
311
+ if (libraryFunction(call, context, ['node:tls', 'tls', 'node:https', 'https']) === 'createServer')
312
+ return true;
313
+ return libraryFunction(call, context, ['node:http2', 'http2']) === 'createSecureServer';
314
+ }
315
+ function isServerOptionsArgument(node, context) {
316
+ let current = node;
317
+ while (ts.isOuterExpression(current.parent))
318
+ current = current.parent;
319
+ const parent = current.parent;
320
+ return Boolean(ts.isCallExpression(parent) && parent.arguments[0] === current && isTlsServerCall(parent, context));
321
+ }
322
+ function tlsServerRole(object, context) {
323
+ let isServer = isServerOptionsArgument(object, context);
324
+ if (!isServer) {
325
+ let value = object;
326
+ while (ts.isOuterExpression(value.parent))
327
+ value = value.parent;
328
+ const declaration = value.parent;
329
+ if (ts.isVariableDeclaration(declaration) &&
330
+ declaration.initializer === value &&
331
+ ts.isIdentifier(declaration.name) &&
332
+ Boolean(declaration.parent.flags & ts.NodeFlags.Const) &&
333
+ !isExported(declaration)) {
334
+ const references = referencesOf(declaration.name, context.sourceFile, context.checker);
335
+ isServer = references.length > 0 && references.every((reference) => isServerOptionsArgument(reference, context));
336
+ }
337
+ }
338
+ if (!isServer)
339
+ return;
340
+ const requestCert = effectiveProperty(object, 'requestCert');
341
+ if (requestCert === 'unknown')
342
+ return;
343
+ if (requestCert === undefined)
344
+ return 'no-client-cert';
345
+ if (!ts.isPropertyAssignment(requestCert) && !ts.isShorthandPropertyAssignment(requestCert))
346
+ return;
347
+ const value = settingValue(requestCert, context.checker);
348
+ if (value === false)
349
+ return 'no-client-cert';
350
+ if (value === true)
351
+ return 'client-cert';
352
+ }
309
353
  function checkTlsProperty(property, context) {
310
354
  const key = propertyKeyName(property.name);
311
355
  if (key === undefined || !verificationOptions.has(key))
@@ -314,6 +358,13 @@ function checkTlsProperty(property, context) {
314
358
  return;
315
359
  if (isReplacedByEnclosingObject(property, key, context.checker) || isOverriddenAtEveryUse(property, key, context))
316
360
  return;
361
+ if (key === 'rejectUnauthorized') {
362
+ const role = tlsServerRole(property.parent, context);
363
+ if (role === 'no-client-cert')
364
+ return;
365
+ if (role === 'client-cert')
366
+ return reportTlsOverride(property, context, tlsServerMessage);
367
+ }
317
368
  reportTlsOverride(property, context);
318
369
  }
319
370
  function environmentVariableName(target) {
@@ -361,6 +412,36 @@ function isStaticInitializationVector(node, context) {
361
412
  (ts.isStringLiteralLike(source) ||
362
413
  (ts.isArrayLiteralExpression(source) && source.elements.every((element) => ts.isNumericLiteral(element)))));
363
414
  }
415
+ const aesKeyWrapAlgorithm = /^(?:id-)?aes(?:128|192|256)-wrap$/i;
416
+ function isRfc3394DefaultIv(node, context) {
417
+ const value = resolveConstant(node, context.checker);
418
+ if (!ts.isCallExpression(value) || !ts.isPropertyAccessExpression(value.expression))
419
+ return false;
420
+ const { expression: receiver, name } = value.expression;
421
+ if (!ts.isIdentifier(receiver) || receiver.text !== 'Buffer')
422
+ return false;
423
+ if (name.text === 'alloc') {
424
+ const size = value.arguments[0] && ts.skipOuterExpressions(value.arguments[0]);
425
+ const fill = value.arguments[1] && ts.skipOuterExpressions(value.arguments[1]);
426
+ return (Boolean(size && ts.isNumericLiteral(size) && Number(size.text) === 8) &&
427
+ Boolean(fill && ts.isNumericLiteral(fill) && Number(fill.text) === 0xa6));
428
+ }
429
+ if (name.text !== 'from')
430
+ return false;
431
+ const source = value.arguments[0] && ts.skipOuterExpressions(value.arguments[0]);
432
+ const encoding = value.arguments[1] && ts.skipOuterExpressions(value.arguments[1]);
433
+ if (source &&
434
+ ts.isStringLiteralLike(source) &&
435
+ encoding &&
436
+ ts.isStringLiteralLike(encoding) &&
437
+ encoding.text.toLowerCase() === 'hex') {
438
+ return source.text.toLowerCase() === 'a6a6a6a6a6a6a6a6';
439
+ }
440
+ if (!source || !ts.isArrayLiteralExpression(source))
441
+ return false;
442
+ return (source.elements.length === 8 &&
443
+ source.elements.every((element) => ts.isNumericLiteral(element) && Number(element.text) === 0xa6));
444
+ }
364
445
  function weaknessOf(name, call, context) {
365
446
  if (name === 'createCipher' || name === 'createDecipher')
366
447
  return 'the deprecated `' + name + '` derives its key without a salt and uses no IV';
@@ -370,8 +451,11 @@ function weaknessOf(name, call, context) {
370
451
  return /-ecb$/i.test(algorithm)
371
452
  ? 'ECB mode encrypts equal blocks to equal output'
372
453
  : `${algorithm} is a broken or outdated cipher`;
373
- if (call.arguments[2] && isStaticInitializationVector(call.arguments[2], context))
454
+ if (call.arguments[2] && isStaticInitializationVector(call.arguments[2], context)) {
455
+ if (algorithm && aesKeyWrapAlgorithm.test(algorithm) && isRfc3394DefaultIv(call.arguments[2], context))
456
+ return undefined;
374
457
  return 'a fixed IV makes equal messages encrypt identically';
458
+ }
375
459
  }
376
460
  function checkCipher(call, context) {
377
461
  if (!fileMentions(context.sourceFile, ['crypto']))
@@ -277,9 +277,13 @@ async function runPolyglot(args) {
277
277
  parseMinImpact(values['min-impact']);
278
278
  if (!positionals.length)
279
279
  throw new Error('Pass at least one file or directory to polyglot.');
280
- const result = await (await import('./polyglot.js')).checkSecurityPolyglot(positionals);
281
280
  const settings = loadSettings({ directory: process.cwd(), explicit: values['loadwise-config'] });
282
- const printable = { scannedFiles: result.scannedFiles, findings: result.findings };
281
+ const result = await (await import('./polyglot.js')).checkSecurityPolyglot(positionals, settings.isIgnored);
282
+ const printable = {
283
+ scannedFiles: result.scannedFiles,
284
+ findings: result.findings,
285
+ ...(result.skippedFiles === 0 ? {} : { skippedFiles: result.skippedFiles }),
286
+ };
283
287
  const code = await report.printResult(printable, { ...values, ignore: [], settings, projectDirectory: process.cwd() }, pillar);
284
288
  return exitCodeWithSkips(printable, code);
285
289
  }
@@ -0,0 +1,115 @@
1
+ import { ts } from '../performance/engine/compiler.js';
2
+ import { isUnshadowedGlobal, unwrapExpression } from '../shared/analysis/ast-semantics.js';
3
+ function inlineHandler(expression) {
4
+ const value = unwrapExpression(expression);
5
+ return ts.isArrowFunction(value) || ts.isFunctionExpression(value) ? value : undefined;
6
+ }
7
+ // Inline handlers and transparent local wrappers whose returned middleware directly forwards its
8
+ // request to the callback, including Promise.resolve(callback(req, res, next)).catch(next).
9
+ function forwardedHandler(argument, checker) {
10
+ const direct = inlineHandler(argument);
11
+ if (direct)
12
+ return direct;
13
+ if (!ts.isCallExpression(argument) || argument.arguments.length !== 1)
14
+ return;
15
+ const callback = inlineHandler(argument.arguments[0]);
16
+ const factory = checker.getResolvedSignature(argument)?.declaration;
17
+ if (!callback || !factory || !ts.isArrowFunction(factory) || !ts.isArrowFunction(factory.body))
18
+ return;
19
+ const middleware = factory.body;
20
+ const request = middleware.parameters[0];
21
+ if (!request || ts.isBlock(middleware.body))
22
+ return;
23
+ let value = unwrapExpression(middleware.body);
24
+ if (ts.isCallExpression(value) &&
25
+ ts.isPropertyAccessExpression(value.expression) &&
26
+ value.expression.name.text === 'catch') {
27
+ value = unwrapExpression(value.expression.expression);
28
+ }
29
+ if (ts.isCallExpression(value) &&
30
+ ts.isPropertyAccessExpression(value.expression) &&
31
+ value.expression.name.text === 'resolve' &&
32
+ isUnshadowedGlobal(value.expression.expression, 'Promise', checker) &&
33
+ value.arguments.length === 1) {
34
+ value = unwrapExpression(value.arguments[0]);
35
+ }
36
+ if (!ts.isCallExpression(value) || !ts.isIdentifier(value.expression) || !value.arguments.length)
37
+ return;
38
+ if (checker.getSymbolAtLocation(value.expression)?.valueDeclaration !== factory.parameters[0] ||
39
+ checker.getSymbolAtLocation(value.arguments[0])?.valueDeclaration !== request)
40
+ return;
41
+ return callback;
42
+ }
43
+ function requestCookie(value, request, checker) {
44
+ const access = unwrapExpression(value);
45
+ if (!(ts.isElementAccessExpression(access) || ts.isPropertyAccessExpression(access)))
46
+ return false;
47
+ const store = unwrapExpression(access.expression);
48
+ return (ts.isPropertyAccessExpression(store) &&
49
+ ['cookies', 'signedCookies'].includes(store.name.text) &&
50
+ ts.isIdentifier(store.expression) &&
51
+ checker.getSymbolAtLocation(store.expression)?.valueDeclaration === request);
52
+ }
53
+ // Follow a directly returned request cookie through one local helper and an optional immutable
54
+ // token binding. A helper that only reads a cookie while returning a body credential is unrelated.
55
+ function credentialSource(expression, request, checker) {
56
+ let value = unwrapExpression(expression);
57
+ if (ts.isIdentifier(value)) {
58
+ const initial = checker.getSymbolAtLocation(value)?.valueDeclaration;
59
+ if (!initial ||
60
+ !ts.isVariableDeclaration(initial) ||
61
+ !(initial.parent.flags & ts.NodeFlags.Const) ||
62
+ !initial.initializer)
63
+ return false;
64
+ value = unwrapExpression(initial.initializer);
65
+ }
66
+ if (requestCookie(value, request, checker))
67
+ return true;
68
+ if (!ts.isCallExpression(value) ||
69
+ !value.arguments[0] ||
70
+ checker.getSymbolAtLocation(value.arguments[0])?.valueDeclaration !== request)
71
+ return false;
72
+ const helper = checker.getResolvedSignature(value)?.declaration;
73
+ if (!helper || !ts.isFunctionDeclaration(helper) || !helper.body || !helper.parameters[0])
74
+ return false;
75
+ const parameter = helper.parameters[0];
76
+ function returnsCookie(node) {
77
+ if (ts.isFunctionLike(node))
78
+ return;
79
+ if (ts.isReturnStatement(node))
80
+ return node.expression && requestCookie(node.expression, parameter, checker) ? true : undefined;
81
+ return ts.forEachChild(node, returnsCookie);
82
+ }
83
+ return !!returnsCookie(helper.body);
84
+ }
85
+ export function consumesCookieCredential(argument, checker) {
86
+ const handler = forwardedHandler(argument, checker);
87
+ const request = handler?.parameters[0];
88
+ if (!handler || !request)
89
+ return false;
90
+ function consumes(call, request) {
91
+ const callee = call.expression;
92
+ if (!ts.isPropertyAccessExpression(callee) ||
93
+ !['logout', 'refresh', 'authenticate'].includes(callee.name.text) ||
94
+ !ts.isIdentifier(callee.expression) ||
95
+ !call.arguments[0] ||
96
+ !credentialSource(call.arguments[0], request, checker))
97
+ return false;
98
+ const receiver = checker.getSymbolAtLocation(callee.expression)?.valueDeclaration;
99
+ if (!receiver || !ts.isVariableDeclaration(receiver) || !(receiver.parent.flags & ts.NodeFlags.Const))
100
+ return false;
101
+ const service = receiver.initializer;
102
+ return (!!service &&
103
+ ts.isNewExpression(service) &&
104
+ ts.isIdentifier(service.expression) &&
105
+ /^(?:Auth|Authentication|Session)Service$/.test(service.expression.text));
106
+ }
107
+ function visit(node) {
108
+ if (ts.isFunctionLike(node))
109
+ return;
110
+ if (ts.isCallExpression(node) && request && consumes(node, request))
111
+ return true;
112
+ return ts.forEachChild(node, visit);
113
+ }
114
+ return !!visit(handler.body);
115
+ }
@@ -0,0 +1,241 @@
1
+ import { consumesCookieCredential } from './cookie-credentials.js';
2
+ import { importedFrom } from './bindings.js';
3
+ import { ts } from '../performance/engine/compiler.js';
4
+ import { effectiveProperty, staticMemberName, unwrapExpression } from '../shared/analysis/ast-semantics.js';
5
+ import { constantDeclaration } from './request-forgery/shared.js';
6
+ const routes = new Set(['post', 'put', 'patch', 'delete']);
7
+ const cookies = new Set(['cookie-parser', 'express-session', 'cookie-session', '@fastify/session', '@fastify/cookie']);
8
+ function routerBinding(call, context) {
9
+ const callee = unwrapExpression(call.expression);
10
+ if (!ts.isPropertyAccessExpression(callee) || !ts.isIdentifier(callee.expression))
11
+ return;
12
+ const declaration = constantDeclaration(callee.expression, context.checker);
13
+ const factory = declaration?.initializer && unwrapExpression(declaration.initializer);
14
+ if (!factory || !ts.isCallExpression(factory))
15
+ return;
16
+ const binding = context.libraryCall(factory);
17
+ if (!binding?.module || !['express', 'fastify'].includes(binding.module))
18
+ return;
19
+ if (!['*', 'default', 'Router', 'fastify'].includes(binding.method ?? binding.exported ?? ''))
20
+ return;
21
+ return declaration;
22
+ }
23
+ function ownValue(object, key) {
24
+ const property = effectiveProperty(object, key, { guardSpreadGetters: true });
25
+ return property && property !== 'unknown' && ts.isPropertyAssignment(property)
26
+ ? unwrapExpression(property.initializer)
27
+ : undefined;
28
+ }
29
+ function strictCookie(options, sessionModule) {
30
+ if (!options || !ts.isObjectLiteralExpression(options))
31
+ return false;
32
+ const cookie = sessionModule === 'cookie-session' ? options : ownValue(options, 'cookie');
33
+ const value = cookie && ts.isObjectLiteralExpression(cookie) && ownValue(cookie, 'sameSite');
34
+ return !!value && ts.isStringLiteralLike(value) && value.text.toLowerCase() === 'strict';
35
+ }
36
+ // csrf-csrf and csrf-sync return their protection middleware inside a destructured result.
37
+ function destructuredProtection(identifier, context) {
38
+ const element = context.checker.getSymbolAtLocation(identifier)?.valueDeclaration;
39
+ if (!element || !ts.isBindingElement(element))
40
+ return;
41
+ const declaration = element.parent.parent;
42
+ const factory = ts.isVariableDeclaration(declaration) && declaration.initializer;
43
+ if (!factory)
44
+ return;
45
+ const call = unwrapExpression(factory);
46
+ if (!ts.isCallExpression(call))
47
+ return;
48
+ const module = context.libraryCall(call)?.module;
49
+ return module === 'csrf-csrf' || module === 'csrf-sync' ? 'csrf' : undefined;
50
+ }
51
+ // Middleware may be passed directly or inside array literals.
52
+ function middlewareKinds(argument, context) {
53
+ const value = unwrapExpression(argument);
54
+ if (ts.isArrayLiteralExpression(value)) {
55
+ const kinds = [];
56
+ for (const element of value.elements) {
57
+ kinds.push(...middlewareKinds(element, context));
58
+ if (endsChain(element))
59
+ break;
60
+ }
61
+ return kinds;
62
+ }
63
+ const kind = middlewareFactory(value, context);
64
+ return kind ? [kind] : [];
65
+ }
66
+ // Recognize middleware factories by import and follow a local immutable middleware alias once.
67
+ function middlewareFactory(argument, context) {
68
+ let value = unwrapExpression(argument);
69
+ if (ts.isIdentifier(value)) {
70
+ const initializer = constantDeclaration(value, context.checker)?.initializer;
71
+ if (initializer)
72
+ value = unwrapExpression(initializer);
73
+ }
74
+ if (ts.isIdentifier(value))
75
+ return destructuredProtection(value, context);
76
+ if (!ts.isCallExpression(value))
77
+ return;
78
+ const binding = context.libraryCall(value);
79
+ const method = binding?.method ?? binding?.exported;
80
+ if (!binding?.module)
81
+ return;
82
+ if ((binding.module === 'csurf' && ['default', '*'].includes(method ?? '')) ||
83
+ (binding.module === 'lusca' && method === 'csrf'))
84
+ return 'csrf';
85
+ if (!cookies.has(binding.module) || !['*', 'default'].includes(method ?? ''))
86
+ return;
87
+ if (binding.module !== 'cookie-parser' && strictCookie(value.arguments[0], binding.module))
88
+ return 'strict';
89
+ return 'cookie';
90
+ }
91
+ function isRouterCsrfProtection(value, router, context) {
92
+ const hook = unwrapExpression(value);
93
+ return (ts.isPropertyAccessExpression(hook) &&
94
+ hook.name.text === 'csrfProtection' &&
95
+ ts.isIdentifier(hook.expression) &&
96
+ constantDeclaration(hook.expression, context.checker) === router);
97
+ }
98
+ function mountedMiddleware(call, method, router, context) {
99
+ const first = call.arguments[0];
100
+ if (!first)
101
+ return [];
102
+ if (method === 'addHook') {
103
+ const hook = call.arguments[1];
104
+ const hookName = ts.isStringLiteralLike(first) ? first.text : '';
105
+ return hook && ['onRequest', 'preHandler'].includes(hookName) && isRouterCsrfProtection(hook, router, context)
106
+ ? [{ prefix: '/', kind: 'csrf' }]
107
+ : [];
108
+ }
109
+ if (method === 'register') {
110
+ const module = importedFrom(first, context.checker)?.module;
111
+ if (module === '@fastify/csrf-protection' || module === 'fastify-csrf')
112
+ return [{ prefix: '/', kind: 'csrf-plugin' }];
113
+ if (module !== '@fastify/session' && module !== '@fastify/cookie')
114
+ return [];
115
+ if (module === '@fastify/session' && strictCookie(call.arguments[1], module))
116
+ return [{ prefix: '/', kind: 'strict' }];
117
+ return [{ prefix: '/', kind: 'cookie' }];
118
+ }
119
+ const scoped = ts.isStringLiteralLike(first);
120
+ const prefix = scoped ? first.text.replace(/\/$/, '') || '/' : '/';
121
+ // A mount path that is not a string literal cannot be matched, so it adds no cookie scope.
122
+ const pathUnknown = !scoped && middlewareKinds(first, context).length === 0;
123
+ return call.arguments.slice(scoped ? 1 : 0).flatMap((argument) => middlewareKinds(argument, context)
124
+ .filter((kind) => kind === 'csrf' || !pathUnknown)
125
+ .map((kind) => ({ kind, prefix })));
126
+ }
127
+ function fastifyHook(call, router, context) {
128
+ const options = call.arguments[1];
129
+ if (!options || !ts.isObjectLiteralExpression(options))
130
+ return false;
131
+ return ['onRequest', 'preHandler'].some((key) => {
132
+ const hook = ownValue(options, key);
133
+ const hooks = hook && ts.isArrayLiteralExpression(hook) ? hook.elements : hook ? [hook] : [];
134
+ return hooks.some((candidate) => isRouterCsrfProtection(candidate, router, context));
135
+ });
136
+ }
137
+ // A leading rejection based on the handler's request parameter distinguishes a credential read
138
+ // from merely issuing a response cookie. Other handler shapes keep contextual guidance.
139
+ function guardsOnCookieIdentity(handler, context) {
140
+ if (!handler || !(ts.isArrowFunction(handler) || ts.isFunctionExpression(handler)) || !ts.isBlock(handler.body))
141
+ return false;
142
+ const request = handler.parameters[0];
143
+ const guard = handler.body.statements[0];
144
+ if (!request || !ts.isIdentifier(request.name) || !guard || !ts.isIfStatement(guard))
145
+ return false;
146
+ const rejection = ts.isBlock(guard.thenStatement) ? guard.thenStatement.statements[0] : guard.thenStatement;
147
+ if (!rejection || !(ts.isReturnStatement(rejection) || ts.isThrowStatement(rejection)))
148
+ return false;
149
+ const condition = unwrapExpression(guard.expression);
150
+ if (!ts.isPrefixUnaryExpression(condition) || condition.operator !== ts.SyntaxKind.ExclamationToken)
151
+ return false;
152
+ const field = unwrapExpression(condition.operand);
153
+ if (!(ts.isPropertyAccessExpression(field) || ts.isElementAccessExpression(field)))
154
+ return false;
155
+ const store = unwrapExpression(field.expression);
156
+ if (!ts.isPropertyAccessExpression(store) || !ts.isIdentifier(store.expression))
157
+ return false;
158
+ if (context.checker.getSymbolAtLocation(store.expression)?.valueDeclaration !== request)
159
+ return false;
160
+ const name = staticMemberName(field) ?? '';
161
+ if (store.name.text === 'session')
162
+ return /^(?:user|userId|account|accountId|passport)$/i.test(name);
163
+ return (['cookies', 'signedCookies'].includes(store.name.text) &&
164
+ /^(?:session(?:id)?|sid|auth(?:token)?|(?:access|refresh)[_-]?token|jwt)$/i.test(name));
165
+ }
166
+ // An inline handler without a `next` parameter cannot pass control to later middleware.
167
+ // A rest parameter may forward `next`, so it is not treated as terminating.
168
+ function cannotContinueChain(argument) {
169
+ const handler = unwrapExpression(argument);
170
+ return ((ts.isArrowFunction(handler) || ts.isFunctionExpression(handler)) &&
171
+ handler.parameters.length < 3 &&
172
+ !handler.parameters.some((parameter) => parameter.dotDotDotToken));
173
+ }
174
+ // An array argument ends the chain when any of its handlers cannot pass control onward.
175
+ function endsChain(argument) {
176
+ const value = unwrapExpression(argument);
177
+ return ts.isArrayLiteralExpression(value) ? value.elements.some(endsChain) : cannotContinueChain(value);
178
+ }
179
+ function checkRegistration(call, apps, context) {
180
+ if (!ts.isPropertyAccessExpression(call.expression))
181
+ return;
182
+ const method = call.expression.name.text;
183
+ const mount = method === 'use' || method === 'register' || method === 'addHook';
184
+ if (!mount && !routes.has(method))
185
+ return;
186
+ const app = routerBinding(call, context);
187
+ if (!app)
188
+ return;
189
+ const existing = apps.get(app) ?? [];
190
+ if (mount) {
191
+ existing.push(...mountedMiddleware(call, method, app, context));
192
+ apps.set(app, existing);
193
+ return;
194
+ }
195
+ const path = call.arguments[0];
196
+ if (!path || !ts.isStringLiteralLike(path))
197
+ return;
198
+ const kinds = new Set(existing
199
+ .filter(({ prefix }) => prefix === '/' || path.text === prefix || path.text.startsWith(prefix + '/'))
200
+ .map(({ kind }) => kind));
201
+ for (const argument of call.arguments.slice(1)) {
202
+ for (const kind of middlewareKinds(argument, context))
203
+ kinds.add(kind);
204
+ if (endsChain(argument))
205
+ break;
206
+ }
207
+ if (kinds.has('csrf') ||
208
+ (kinds.has('strict') && !kinds.has('cookie')) ||
209
+ (kinds.has('csrf-plugin') && fastifyHook(call, app, context)))
210
+ return;
211
+ if (call.arguments.slice(1).some((argument) => consumesCookieCredential(argument, context.checker)) ||
212
+ (kinds.has('cookie') && guardsOnCookieIdentity(call.arguments.at(-1), context))) {
213
+ context.report(call, 'express-cookie-auth-missing-csrf', 'This state-changing route can use an incoming cookie credential or session identity. Check for CSRF protection before the handler changes state.',
214
+ // A router with no recognized mount may be protected by the app that mounts it.
215
+ kinds.size === 0
216
+ ? 'A parent app, gateway or custom middleware may verify requests before this route.'
217
+ : undefined);
218
+ return;
219
+ }
220
+ if (!kinds.has('cookie'))
221
+ return;
222
+ context.report(call, 'express-cookie-auth-missing-csrf', 'This state-changing route has cookie middleware with no recognized CSRF check. Confirm that authentication uses these cookies and that requests are verified.', 'A gateway, custom middleware or another module may verify requests before this route.');
223
+ }
224
+ export function checkExpressCookieAuthCsrf(sourceFile, context) {
225
+ // Only a previous registration in the same block establishes a known middleware chain.
226
+ function visit(scope) {
227
+ if (ts.isSourceFile(scope) || ts.isBlock(scope)) {
228
+ const apps = new Map();
229
+ for (const statement of scope.statements) {
230
+ if (!ts.isExpressionStatement(statement))
231
+ continue;
232
+ const expression = unwrapExpression(statement.expression);
233
+ const call = ts.isAwaitExpression(expression) ? unwrapExpression(expression.expression) : expression;
234
+ if (ts.isCallExpression(call))
235
+ checkRegistration(call, apps, context);
236
+ }
237
+ }
238
+ ts.forEachChild(scope, visit);
239
+ }
240
+ visit(sourceFile);
241
+ }