loadwise 0.9.0 → 0.10.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 (155) hide show
  1. package/README.md +88 -19
  2. package/agent/hooks/check-edited-file.mjs +146 -28
  3. package/dist/bin/github-action.js +3 -74
  4. package/dist/bin/loadwise.js +12 -12
  5. package/dist/lib/accessibility/aria-tables.js +10 -6
  6. package/dist/lib/accessibility/document-reference-rules.js +13 -3
  7. package/dist/lib/accessibility/jsx-elements.js +34 -16
  8. package/dist/lib/accessibility/native-interactive.js +51 -13
  9. package/dist/lib/accessibility/rules.js +4 -2
  10. package/dist/lib/accessibility/site-fixes/aria-typo.js +65 -0
  11. package/dist/lib/accessibility/site-fixes/html-language.js +45 -9
  12. package/dist/lib/accessibility/template-elements.js +5 -3
  13. package/dist/lib/editor/actions.js +15 -9
  14. package/dist/lib/editor/diagnostics.js +110 -107
  15. package/dist/lib/editor/finding-comparison.js +4 -25
  16. package/dist/lib/editor/hover-markdown.js +104 -0
  17. package/dist/lib/editor/inline-fix.js +50 -0
  18. package/dist/lib/editor/inline-recommendation.js +27 -0
  19. package/dist/lib/editor/language-server.js +94 -18
  20. package/dist/lib/editor/scan-session.js +2 -1
  21. package/dist/lib/editor/standalone-performance-examples.js +48 -0
  22. package/dist/lib/maintainability/analysis/analyze-source.js +2 -0
  23. package/dist/lib/maintainability/architecture/architecture.js +50 -2
  24. package/dist/lib/maintainability/cli/inputs.js +12 -5
  25. package/dist/lib/maintainability/cli/site-fix.js +3 -0
  26. package/dist/lib/maintainability/cli.js +6 -3
  27. package/dist/lib/maintainability/examples.js +48 -0
  28. package/dist/lib/maintainability/quality/modern-node-callbacks.js +188 -0
  29. package/dist/lib/maintainability/quality/modern-syntax.js +301 -0
  30. package/dist/lib/maintainability/quality/tsconfig-strict.js +307 -15
  31. package/dist/lib/maintainability/rule-ids.js +18 -0
  32. package/dist/lib/maintainability/scan-changed.js +33 -2
  33. package/dist/lib/maintainability/scan.js +10 -1
  34. package/dist/lib/maintainability/site-fixes/unused-bindings.js +15 -6
  35. package/dist/lib/maintainability/unused/module-usage-signatures.js +116 -0
  36. package/dist/lib/maintainability/unused/module-usage.js +67 -106
  37. package/dist/lib/maintainability/unused/unused-bindings.js +143 -8
  38. package/dist/lib/maintainability/unused/unused-dependencies.js +218 -0
  39. package/dist/lib/maintainability/unused/unused-modules.js +4 -0
  40. package/dist/lib/performance/analysis/missing-packages.js +3 -0
  41. package/dist/lib/performance/analysis/source-text.js +2 -2
  42. package/dist/lib/performance/analyze.js +4 -1
  43. package/dist/lib/performance/async/floating-promises.js +25 -4
  44. package/dist/lib/performance/cli/cli-output.js +9 -3
  45. package/dist/lib/performance/cli/cli-policy.js +25 -2
  46. package/dist/lib/performance/cli/cli-scan.js +25 -24
  47. package/dist/lib/performance/cli/scan-outcome.js +19 -1
  48. package/dist/lib/performance/cli/shared-security-inputs.js +27 -0
  49. package/dist/lib/performance/cli/watch.js +27 -8
  50. package/dist/lib/performance/collections/collection-lookups.js +27 -10
  51. package/dist/lib/performance/collections/collection-reduce.js +32 -2
  52. package/dist/lib/performance/collections/collections.js +28 -0
  53. package/dist/lib/performance/collections/repeated.js +25 -1
  54. package/dist/lib/performance/contracts/cli.js +22 -11
  55. package/dist/lib/performance/contracts/git-files.js +46 -1
  56. package/dist/lib/performance/datastores/pooling.js +1 -17
  57. package/dist/lib/performance/datastores/postgres.js +41 -33
  58. package/dist/lib/performance/engine/native.js +5 -1
  59. package/dist/lib/performance/frontend/angular-template-calls.js +187 -0
  60. package/dist/lib/performance/frontend/frontend-dom-perf.js +68 -8
  61. package/dist/lib/performance/frontend/frontend-perf.js +115 -171
  62. package/dist/lib/performance/frontend/frontend-render-perf.js +7 -3
  63. package/dist/lib/performance/frontend/jsx-element-perf.js +171 -0
  64. package/dist/lib/performance/frontend/next-fetch-waterfall.js +346 -29
  65. package/dist/lib/performance/frontend/rxjs-subscriptions.js +155 -0
  66. package/dist/lib/performance/frontend/seo/client-fetched-content.js +196 -0
  67. package/dist/lib/performance/frontend/seo/navigation-without-link.js +116 -0
  68. package/dist/lib/performance/frontend/seo/next-routes.js +114 -0
  69. package/dist/lib/performance/frontend/seo/route-metadata.js +158 -0
  70. package/dist/lib/performance/frontend/seo/seo-rules.js +9 -0
  71. package/dist/lib/performance/frontend/seo/sitewide-noindex.js +103 -0
  72. package/dist/lib/performance/frontend/template-tracking.js +86 -2
  73. package/dist/lib/performance/frontend/vue-options-hooks.js +108 -0
  74. package/dist/lib/performance/orm/prisma.js +1 -25
  75. package/dist/lib/performance/projects.js +3 -2
  76. package/dist/lib/performance/query-loops/service-loops.js +38 -8
  77. package/dist/lib/performance/request/json-stringify-output.js +82 -4
  78. package/dist/lib/performance/request/promise-schedulers.js +180 -0
  79. package/dist/lib/performance/request/request-handlers.js +43 -4
  80. package/dist/lib/performance/request/unbounded-promise-all.js +13 -52
  81. package/dist/lib/performance/rule-ids.js +26 -2
  82. package/dist/lib/performance/site-fix.js +1 -0
  83. package/dist/lib/reliability/react-bugs.js +9 -0
  84. package/dist/lib/reliability/react-state-aliases.js +94 -4
  85. package/dist/lib/reliability/react-state.js +24 -5
  86. package/dist/lib/security/auth-crypto/secrets.js +121 -16
  87. package/dist/lib/security/cli.js +1 -1
  88. package/dist/lib/security/credential-entropy.js +12 -0
  89. package/dist/lib/security/deps/lockfiles.js +3 -1
  90. package/dist/lib/security/examples/files.js +110 -0
  91. package/dist/lib/security/examples/request-forgery.js +1 -1
  92. package/dist/lib/security/exposure/frontend-security.js +11 -2
  93. package/dist/lib/security/exposure/prototype-pollution.js +73 -4
  94. package/dist/lib/security/files/azure-pipelines.js +69 -0
  95. package/dist/lib/security/files/bitbucket-pipelines.js +32 -0
  96. package/dist/lib/security/files/ci-platforms.js +16 -0
  97. package/dist/lib/security/files/ci-shared.js +260 -0
  98. package/dist/lib/security/files/circleci.js +81 -0
  99. package/dist/lib/security/files/dockerfile.js +188 -3
  100. package/dist/lib/security/files/github-actions.js +490 -0
  101. package/dist/lib/security/files/gitlab-ci.js +90 -0
  102. package/dist/lib/security/files/hcl.js +264 -0
  103. package/dist/lib/security/files/hosting-config.js +159 -0
  104. package/dist/lib/security/files/http-headers.js +65 -0
  105. package/dist/lib/security/files/index.js +62 -7
  106. package/dist/lib/security/files/jenkinsfile.js +482 -0
  107. package/dist/lib/security/files/json-nodes.js +67 -0
  108. package/dist/lib/security/files/nginx.js +501 -0
  109. package/dist/lib/security/files/package-scripts.js +175 -0
  110. package/dist/lib/security/files/rule-ids.js +29 -0
  111. package/dist/lib/security/files/secret-values.js +31 -5
  112. package/dist/lib/security/files/secrets.js +44 -13
  113. package/dist/lib/security/files/terraform.js +345 -0
  114. package/dist/lib/security/injection/nosql.js +2 -1
  115. package/dist/lib/security/injection/sql.js +2 -2
  116. package/dist/lib/security/lexical-declaration.js +28 -0
  117. package/dist/lib/security/pg-identifier-guards.js +90 -1
  118. package/dist/lib/security/request-forgery/member-chain.js +41 -0
  119. package/dist/lib/security/request-forgery/open-redirect.js +45 -8
  120. package/dist/lib/security/request-forgery/shared.js +18 -3
  121. package/dist/lib/security/rule-descriptions.js +29 -0
  122. package/dist/lib/security/rule-ids.js +29 -0
  123. package/dist/lib/security/taint/original-string-validation.js +229 -0
  124. package/dist/lib/security/taint/validators.js +1 -1
  125. package/dist/lib/shared/agent/review-delivery.js +3 -1
  126. package/dist/lib/shared/analysis/ast-semantics.js +17 -1
  127. package/dist/lib/shared/analysis/hot-path-graph.js +55 -19
  128. package/dist/lib/shared/analysis/next-env-config.js +232 -0
  129. package/dist/lib/shared/analysis/scan-cache-git.js +114 -0
  130. package/dist/lib/shared/analysis/scan-cache-loadwise-packages.js +54 -0
  131. package/dist/lib/shared/analysis/scan-cache-project-inputs.js +221 -0
  132. package/dist/lib/shared/analysis/scan-cache-sources.js +235 -0
  133. package/dist/lib/shared/analysis/scan-cache-storage.js +24 -0
  134. package/dist/lib/shared/analysis/scan-cache.js +158 -174
  135. package/dist/lib/shared/check-watch.js +3 -3
  136. package/dist/lib/shared/check.js +25 -4
  137. package/dist/lib/shared/config.js +1 -1
  138. package/dist/lib/shared/conventional-projects.js +40 -0
  139. package/dist/lib/shared/fix/fix-command.js +2 -0
  140. package/dist/lib/shared/fix/fix-usage.js +47 -0
  141. package/dist/lib/shared/fix/project-file-access.js +43 -20
  142. package/dist/lib/shared/fix.js +4 -35
  143. package/dist/lib/shared/formats/security-cwe.js +29 -0
  144. package/dist/lib/shared/project-root.js +1 -1
  145. package/dist/lib/shared/reporting/action-comparison.js +78 -0
  146. package/dist/lib/shared/reporting/automatic-fix-signal.js +7 -2
  147. package/dist/lib/shared/reporting/check-text.js +7 -5
  148. package/dist/lib/shared/reporting/pillars.js +28 -8
  149. package/dist/lib/shared/reporting/source-report.js +4 -4
  150. package/dist/lib/shared/system/git.js +31 -16
  151. package/dist/lib/shared/system/glob.js +146 -19
  152. package/dist/lib/shared/system/terminal-style.js +2 -2
  153. package/dist/lib/shared/workspaces.js +6 -1
  154. package/package.json +4 -1
  155. package/schema/loadwise.config.schema.json +86 -0
@@ -0,0 +1,40 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { listFiles } from '../maintainability/cli/inputs.js';
4
+ import { configFileName } from './config.js';
5
+ import { isBuildOutputFolder } from './system/build-output.js';
6
+ import { coveringConfig, hasWorkspaceDeclaration, implementationSource, projectConfig, subdirectories, } from './workspaces.js';
7
+ // Some multi-service repositories have no workspace manifest. Only search the immediate
8
+ // conventional app and service folders, and require a visible source in each candidate.
9
+ function conventionalProjectGroups(root) {
10
+ if (projectConfig(root) || fs.existsSync(path.join(root, configFileName)))
11
+ return [];
12
+ if (hasWorkspaceDeclaration(root) || coveringConfig(root))
13
+ return [];
14
+ return ['apps', 'services'].flatMap((group) => {
15
+ const parent = path.join(root, group);
16
+ if (!fs.lstatSync(parent, { throwIfNoEntry: false })?.isDirectory())
17
+ return [];
18
+ const projects = subdirectories(parent).flatMap((name) => {
19
+ if (isBuildOutputFolder(parent, name))
20
+ return [];
21
+ const directory = path.join(parent, name);
22
+ const config = projectConfig(directory);
23
+ return config && fs.lstatSync(config, { throwIfNoEntry: false })?.isFile()
24
+ ? [{ directory, config, name: group + '/' + name }]
25
+ : [];
26
+ });
27
+ return projects.length ? [{ parent, projects }] : [];
28
+ });
29
+ }
30
+ function conventionalProjects(root, inventory = listFiles) {
31
+ return conventionalProjectGroups(root).flatMap(({ parent, projects }) => {
32
+ const visible = new Set(inventory(parent)
33
+ .filter((file) => implementationSource.test(file))
34
+ .map((file) => file.split('/')[0]));
35
+ return projects
36
+ .filter(({ directory }) => visible.has(path.basename(directory)))
37
+ .sort((left, right) => left.name.localeCompare(right.name));
38
+ });
39
+ }
40
+ export { conventionalProjectGroups, conventionalProjects };
@@ -1,6 +1,8 @@
1
1
  import { quoteArgument } from '../system/shell-argument.js';
2
2
  // The same inputs make `--fix --only` rescan what was reported, so the ids it is given still match.
3
3
  function fixAllCommand(command, project, files, values) {
4
+ if (values.readOnly)
5
+ return;
4
6
  const inputs = [];
5
7
  if (project !== undefined)
6
8
  inputs.push('-p', project);
@@ -0,0 +1,47 @@
1
+ // The `loadwise fix --help` text.
2
+ const fixUsage = `Usage: loadwise fix [--apply | --all | --id <id> | --interactive | --handoff] [directory] [checkers...]
3
+
4
+ With no edit mode, preview automatic fixes. Nothing is written until you pass an edit mode.
5
+
6
+ Examples
7
+ loadwise fix Preview every automatic fix
8
+ loadwise fix --uncommitted Preview fixes for your local changes
9
+ loadwise fix --apply --only perf --id <id> Apply one previewed finding
10
+ loadwise fix --apply --only perf Apply the performance checker's automatic fixes
11
+ loadwise fix --all --only perf,sec Also apply review-marked edits eligible for bulk application
12
+ loadwise fix --handoff Print a brief of manual findings for a coding agent
13
+
14
+ Edit mode
15
+ --apply, --yes Apply automatic fixes
16
+ --interactive Review and approve fixes one finding at a time in a terminal
17
+ --all Apply generated fixes, including review-marked edits eligible for bulk application
18
+ --id <id> Apply exactly the named findings, including review-marked edits
19
+ (repeatable or comma-separated)
20
+ --dry-run Show generated edits before project formatting, without writing files
21
+ --reverse <run-id> Preview undoing an opted-in run. Add --apply to confirm
22
+ --polyglot-preview <sha256> Review a single saved Python debugger finding, without writes
23
+
24
+ Scope
25
+ [directory] Project folder (default: current folder). Use ./perf for a folder named like a checker
26
+ --only <checkers> Select checkers by name. Spaces or commas separate multiple names
27
+ --rule <id> Limit fixes to the named rule ID (repeatable)
28
+ --workspace <name|path> Restrict edits to selected packages (repeatable)
29
+ --uncommitted Limit edits to changes since HEAD, including untracked files
30
+ --staged | --changed-since <ref> Limit edits to changed lines
31
+ --config <file> Read project settings from this file
32
+ --recipe <name|file.cjs> With --all, use verified-private-types or a trusted local fix recipe
33
+
34
+ Output and safety
35
+ --json Print the preview or applied fix report as JSON
36
+ --handoff Print a read-only Markdown brief for manual findings
37
+ --review Save an applied fix report for a coding agent
38
+ --patch Write a read-only Git patch to redirected stdout. Compare to an apply with the
39
+ same options and --no-format
40
+ --record-reversal Save original text spanning the first and last edits for reversal
41
+ --no-verify-types Skip Layer-2 semantic type-check verification on modified TS files
42
+ --no-comments Do not add the "// Loadwise <rule-id>: <why>" comment above each fixed statement
43
+ --no-format Skip project formatting when applying edits
44
+
45
+ Checkers: performance (perf), reliability (rel), maintainability (maint), security (sec), accessibility (a11y).
46
+ Omit checker names to use the project's configured checkers.`;
47
+ export { fixUsage };
@@ -4,7 +4,7 @@
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import fs from 'node:fs';
6
6
  import path from 'node:path';
7
- import { renameWithRetry, unlinkWithRetry, writeResolvedFileAtomic } from '../system/atomic-write.js';
7
+ import { renameWithRetry, temporarySibling, unlinkWithRetry } from '../system/atomic-write.js';
8
8
  import { errorCode, errorMessage } from '../system/error-code.js';
9
9
  import { isPathInside, isPathInsideOrEqual } from '../system/path-inside.js';
10
10
  import { currentText, readBoundedFixText, readFixText } from './read-fix-text.js';
@@ -64,10 +64,48 @@ function projectFileAccess(roots, base = roots[0]) {
64
64
  currentText(real); // Recheck the target before replacing it, including files created since the plan.
65
65
  // A fix can create a file, such as a migration, in a folder that does not exist yet.
66
66
  fs.mkdirSync(path.dirname(real), { recursive: true });
67
- writeResolvedFileAtomic(real, (marked.has(absolute) ? byteOrderMark : '') + text);
67
+ const written = (marked.has(absolute) ? byteOrderMark : '') + text;
68
+ writeVerifiedFile(real, written, () => {
69
+ if (realTarget(real) !== real)
70
+ throw new Error('File changed while applying fixes: ' + file);
71
+ });
68
72
  },
69
73
  };
70
74
  }
75
+ // Replaces `real` through a temporary sibling. Each step takes the path again, so a folder swapped for a link after
76
+ // the checks would carry the write out of the project: the empty temporary file must resolve inside the checked
77
+ // folder before it receives any text, and `assertUnchanged` runs just before the rename.
78
+ function writeVerifiedFile(real, text, assertUnchanged) {
79
+ const existing = fs.lstatSync(real, { throwIfNoEntry: false });
80
+ if (existing?.isSymbolicLink())
81
+ throw new Error('Refusing to replace a symbolic link: ' + real);
82
+ if (existing && existing.nlink > 1)
83
+ throw new Error('Refusing to write a hard-linked file: ' + real);
84
+ const temporary = temporarySibling(real);
85
+ try {
86
+ writeStagedFile(temporary, text, existing ? 0o600 : 0o666, existing ? existing.mode & 0o7777 : undefined);
87
+ renameWithRetry(temporary, real, assertUnchanged);
88
+ }
89
+ finally {
90
+ fs.rmSync(temporary, { force: true });
91
+ }
92
+ }
93
+ // Creates the staged file empty and checks that it resolves where it was named before it receives any text: a folder
94
+ // swapped for a link would put it, and the fix text, outside the project. `finalMode` sets the exact bits the umask
95
+ // would narrow.
96
+ function writeStagedFile(temporary, text, creationMode, finalMode) {
97
+ const descriptor = fs.openSync(temporary, 'wx', creationMode);
98
+ try {
99
+ if (realTarget(temporary) !== temporary)
100
+ throw new Error('File changed while applying fixes: ' + temporary);
101
+ fs.writeFileSync(descriptor, text);
102
+ if (finalMode !== undefined)
103
+ fs.fchmodSync(descriptor, finalMode);
104
+ }
105
+ finally {
106
+ fs.closeSync(descriptor);
107
+ }
108
+ }
71
109
  // A hard link makes the complete staged file appear at once and never replaces an existing one. The exclusive copy
72
110
  // used where links are unavailable does not replace one either. Returns whether the file was linked.
73
111
  function publishNewFile(temporary, file) {
@@ -133,16 +171,9 @@ function writeFixUpdates(updates, onCommit, beforeWrite, onRestored) {
133
171
  fs.accessSync(file, fs.constants.W_OK);
134
172
  // Not temporarySibling: a fixed-length name still fits when the target's own name is near the filesystem limit.
135
173
  const temporary = path.join(path.dirname(file), '.loadwise-' + randomUUID() + '.tmp');
136
- const descriptor = fs.openSync(temporary, 'wx', before === undefined ? 0o666 : 0o600);
137
174
  staged.push({ ...update, temporary });
138
- try {
139
- fs.writeFileSync(descriptor, update.after ?? update.before);
140
- if (before !== undefined)
141
- fs.fchmodSync(descriptor, fs.statSync(file).mode);
142
- }
143
- finally {
144
- fs.closeSync(descriptor);
145
- }
175
+ const mode = before === undefined ? undefined : fs.statSync(file).mode;
176
+ writeStagedFile(temporary, update.after ?? update.before, before === undefined ? 0o666 : 0o600, mode);
146
177
  }
147
178
  beforeWrite?.();
148
179
  commitStagedUpdates(staged, written);
@@ -161,15 +192,7 @@ function writeFixUpdates(updates, onCommit, beforeWrite, onRestored) {
161
192
  }
162
193
  else {
163
194
  const mode = fs.statSync(file).mode;
164
- const descriptor = fs.openSync(temporary, 'wx', mode);
165
- try {
166
- fs.writeFileSync(descriptor, before);
167
- // The umask narrows the creation mode, so set the exact bits again before the rename.
168
- fs.fchmodSync(descriptor, mode);
169
- }
170
- finally {
171
- fs.closeSync(descriptor);
172
- }
195
+ writeStagedFile(temporary, before, mode, mode);
173
196
  renameWithRetry(temporary, file, assertStillApplied);
174
197
  }
175
198
  }
@@ -20,44 +20,13 @@ import { stylePatchLine } from './system/terminal-style.js';
20
20
  import { printTerminalLine, terminalSafe } from './system/terminal-safe.js';
21
21
  import { optionArguments, quoteArgument } from './system/shell-argument.js';
22
22
  import { relativePosix } from './system/posix-path.js';
23
+ import { fixUsage } from './fix/fix-usage.js';
23
24
  function hasFix(finding) {
24
25
  return Boolean(finding.fix);
25
26
  }
26
27
  function needsFixReview(fix) {
27
28
  return Boolean(fix.requiresReview || fix.requiresExplicitSelection);
28
29
  }
29
- const usage = `Usage: loadwise fix [--apply | --all | --id <id> | --interactive | --handoff] [directory] [checkers...]
30
- With no edit mode, preview automatic fixes.
31
- --apply, --yes Apply automatic fixes.
32
- --interactive Review and approve fixes one finding at a time in a terminal.
33
- --all Apply generated fixes, including review-marked edits eligible for bulk application.
34
- --dry-run Show generated edits before project formatting, without writing files.
35
- --id <id> Apply exactly the named findings, including review-marked edits (repeatable or comma-separated).
36
- [directory] Project folder (default: current folder). Use ./perf for a folder named like a checker.
37
- --config <file> Read project settings from this file.
38
- --workspace <name|path> Restrict edits to selected packages (repeatable).
39
- --uncommitted Limit edits to changes since HEAD, including untracked files.
40
- --staged | --changed-since <ref> Limit edits to changed lines.
41
- --rule <id> Limit fixes to the named rule ID (repeatable).
42
- --handoff Print a read-only Markdown brief for manual findings.
43
- --review Save an applied fix report for a coding agent.
44
- --json Print the preview or applied fix report as JSON.
45
- --patch Write a read-only Git patch to redirected stdout. Compare to an apply with the same options and --no-format.
46
- --record-reversal Save original text spanning the first and last edits for reversal.
47
- --reverse <run-id> Preview undoing an opted-in run. Add --apply to confirm.
48
- --polyglot-preview <sha256> Review a single saved Python debugger finding, without writes.
49
- --recipe <name|file.cjs> With --all, use verified-private-types or a trusted local fix recipe.
50
- --only Select checkers by name. Spaces or commas separate multiple names.
51
- --no-verify-types Skip Layer-2 semantic type-check verification on modified TS files.
52
- --no-comments Do not add the "// Loadwise <rule-id>: <why>" comment above each fixed statement.
53
- --no-format Skip project formatting when applying edits.
54
- Checkers: performance (perf), reliability (rel), maintainability (maint), security (sec), accessibility (a11y).
55
- Omit checker names to use the project's configured checkers.
56
-
57
- loadwise fix
58
- loadwise fix --only perf --id <finding-id>
59
- loadwise fix --apply --only perf
60
- loadwise fix --all --only perf,sec`;
61
30
  function parseFixArgs(args) {
62
31
  return parseArgs({
63
32
  args,
@@ -169,7 +138,7 @@ function pythonPreviewHash(values, ids, applyAutomatic) {
169
138
  throw new Error('--polyglot-preview is read-only. It cannot use an apply or review-recording mode.');
170
139
  return sourceHash;
171
140
  }
172
- function fixOptions(args, { values, positionals, tokens }) {
141
+ function fixOptions(args, { values, positionals, tokens } = parseFixArgs(args)) {
173
142
  const applyAutomatic = Boolean(values.apply || values.yes);
174
143
  validatePatchAndHandoff(values, applyAutomatic);
175
144
  const ids = values.id?.flatMap((entry) => entry.split(',').map((id) => id.trim()));
@@ -429,7 +398,7 @@ async function reverseFix(parsed, runId) {
429
398
  async function runFix(args) {
430
399
  const parsed = parseFixArgs(args);
431
400
  if (parsed.values.help) {
432
- console.log(usage);
401
+ console.log(fixUsage);
433
402
  return 0;
434
403
  }
435
404
  if (parsed.values.interactive)
@@ -528,4 +497,4 @@ async function outputFixResult(args, options, findings, result) {
528
497
  console.log(terminalSafe(`\nTo preview reversal, run:\nloadwise fix --reverse ${reversalId} ${quoteArgument(scope.directory)}`));
529
498
  return 0;
530
499
  }
531
- export { runFix, applyBulkFixes, realTarget };
500
+ export { runFix, applyBulkFixes, fixOptions, realTarget };
@@ -6,12 +6,20 @@
6
6
  const securityCwe = {
7
7
  'angular-bypass-security-trust': ['079'],
8
8
  'auth-route-without-rate-limit': ['307'],
9
+ 'azure-pipelines-script-injection': ['094', '078'],
9
10
  'bcrypt-low-cost': ['916'],
11
+ 'bitbucket-pipelines-script-injection': ['094', '078'],
12
+ 'bitbucket-pipelines-unpinned-image': ['1357'],
13
+ 'circleci-script-injection': ['094', '078'],
14
+ 'circleci-unpinned-image': ['1357'],
15
+ 'circleci-unpinned-orb': ['829'],
10
16
  'client-env-secret-exposed': ['540'],
11
17
  'code-injection': ['094', '095'],
12
18
  'command-injection': ['078'],
13
19
  'committed-secret': ['798'],
14
20
  'compose-hardcoded-secret': ['798'],
21
+ 'config-cors-credentials-any-origin': ['942'],
22
+ 'config-unsafe-security-header': ['693'],
15
23
  'cookie-missing-security-flags': ['1004', '614'],
16
24
  'cors-credentials-any-origin': ['942'],
17
25
  'cors-origin-regex-unanchored': ['942'],
@@ -22,6 +30,7 @@ const securityCwe = {
22
30
  'dependency-known-vulnerability': ['1395'],
23
31
  'discarded-signature-verification-result': ['347', '252'],
24
32
  'dockerfile-add-remote-url': ['494'],
33
+ 'dockerfile-npm-install': ['1357'],
25
34
  'dockerfile-runs-as-root': ['250'],
26
35
  'dockerfile-secret-in-build': ['798', '538'],
27
36
  'dockerfile-unpinned-base-image': ['1357'],
@@ -33,6 +42,12 @@ const securityCwe = {
33
42
  'express-cookie-auth-missing-csrf': ['352'],
34
43
  'express-missing-helmet': ['693'],
35
44
  'frontend-storage-secret-token': ['922'],
45
+ 'github-actions-pull-request-target-checkout': ['829'],
46
+ 'github-actions-script-injection': ['094', '078'],
47
+ 'github-actions-unpinned-action': ['829'],
48
+ 'gitlab-ci-script-injection': ['094', '078'],
49
+ 'gitlab-ci-unpinned-image': ['1357'],
50
+ 'gitlab-ci-unpinned-include': ['829'],
36
51
  'go-exec-command-shell': ['078'],
37
52
  'go-sql-sprintf-injection': ['089'],
38
53
  'go-tls-insecure-skip-verify': ['295'],
@@ -40,6 +55,7 @@ const securityCwe = {
40
55
  'graphql-introspection-enabled': ['200'],
41
56
  'graphql-query-depth-unbounded': ['770'],
42
57
  'hardcoded-secret': ['798'],
58
+ 'hosting-redirect-external-wildcard': ['601'],
43
59
  'insecure-cipher': ['327'],
44
60
  'insecure-deserialization': ['502'],
45
61
  'insecure-random-for-secret': ['338'],
@@ -47,6 +63,8 @@ const securityCwe = {
47
63
  'java-objectinputstream-request-deserialization': ['502'],
48
64
  'java-runtime-exec': ['078'],
49
65
  'java-sql-string-concat': ['089'],
66
+ 'jenkinsfile-credential-interpolation': ['214'],
67
+ 'jenkinsfile-script-injection': ['078'],
50
68
  'js-yaml-unsafe-schema': ['502'],
51
69
  'jsx-javascript-url': ['079'],
52
70
  'jwt-decode-for-auth': ['347'],
@@ -62,8 +80,11 @@ const securityCwe = {
62
80
  'mysql-dynamic-query-text': ['089'],
63
81
  'nest-validation-without-whitelist': ['915'],
64
82
  'next-image-any-remote-host': ['918'],
83
+ 'nginx-proxy-pass-request-host': ['918'],
65
84
  'nosql-operator-injection': ['943'],
66
85
  'open-redirect': ['601'],
86
+ 'package-script-remote-code': ['494'],
87
+ 'package-script-tls-verification-disabled': ['295'],
67
88
  'password-hash-in-response': ['201'],
68
89
  'path-traversal': ['022'],
69
90
  'pg-dynamic-query-text': ['089'],
@@ -97,6 +118,11 @@ const securityCwe = {
97
118
  'template-autoescape-disabled': ['079'],
98
119
  'template-injection': ['1336'],
99
120
  'template-raw-html-binding': ['079'],
121
+ 'terraform-admin-port-open-to-world': ['284'],
122
+ 'terraform-database-publicly-accessible': ['284'],
123
+ 'terraform-hardcoded-credential': ['798'],
124
+ 'terraform-storage-bucket-public': ['732'],
125
+ 'terraform-storage-encryption-disabled': ['311'],
100
126
  'tls-verification-disabled': ['295'],
101
127
  'trust-boundary-violation': ['501'],
102
128
  'typeorm-dynamic-query-text': ['089'],
@@ -105,6 +131,9 @@ const securityCwe = {
105
131
  'vue-v-html-unsanitized': ['079'],
106
132
  'weak-hash': ['328'],
107
133
  'weak-password-hash': ['916'],
134
+ 'web-server-directory-listing': ['548'],
135
+ 'web-server-legacy-tls': ['327'],
136
+ 'web-server-version-exposed': ['200'],
108
137
  'webhook-body-without-verification': ['347'],
109
138
  'xml-external-entities': ['611'],
110
139
  'xpath-injection': ['643'],
@@ -58,4 +58,4 @@ function relativeToBase(base, file) {
58
58
  }
59
59
  return toPosixPath(relativeFile);
60
60
  }
61
- export { isTempRoot, realDirectory, relativeToBase, safeExists };
61
+ export { isTempRoot, realDirectory, realExistingPrefix, relativeToBase, safeExists };
@@ -0,0 +1,78 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { loadSettings } from '../config.js';
4
+ import { selectPillars } from './pillars.js';
5
+ import { mergeBaseSince } from '../../performance/migrations/enforce.js';
6
+ import { isRecord } from '../system/is-record.js';
7
+ function eventBase(env, pullRequestEvent) {
8
+ const { GITHUB_EVENT_NAME, GITHUB_EVENT_PATH } = env;
9
+ if (!GITHUB_EVENT_PATH)
10
+ return;
11
+ let payload;
12
+ try {
13
+ payload = JSON.parse(fs.readFileSync(GITHUB_EVENT_PATH, 'utf8'));
14
+ }
15
+ catch {
16
+ return;
17
+ }
18
+ if (!isRecord(payload))
19
+ return;
20
+ if (GITHUB_EVENT_NAME === 'push')
21
+ return payload.before;
22
+ if (GITHUB_EVENT_NAME === 'merge_group' && isRecord(payload.merge_group))
23
+ return payload.merge_group.base_sha;
24
+ if (pullRequestEvent && isRecord(payload.pull_request) && isRecord(payload.pull_request.base))
25
+ return payload.pull_request.base.sha;
26
+ }
27
+ const unavailableBaseWarning = 'Warning: changed-only has no usable base commit; running a full scan. Fetch the base and full history with actions/checkout fetch-depth: 0.';
28
+ const nonFastForwardWarning = "Warning: the push's earlier commit is outside HEAD's history; running a full scan.";
29
+ function changedOnlyComparison(directory, env, resolveBase) {
30
+ const { GITHUB_EVENT_NAME, LOADWISE_BASE_SHA } = env;
31
+ const pullRequestEvent = GITHUB_EVENT_NAME === 'pull_request' || GITHUB_EVENT_NAME === 'pull_request_target';
32
+ // The comparison is required by the selected event or input even if its commit cannot be read.
33
+ const requiredBase = LOADWISE_BASE_SHA
34
+ ? 'base-sha override'
35
+ : pullRequestEvent
36
+ ? 'pull request base commit'
37
+ : undefined;
38
+ const unavailable = { warning: unavailableBaseWarning, requiredBase };
39
+ const base = LOADWISE_BASE_SHA || eventBase(env, pullRequestEvent);
40
+ if (typeof base !== 'string' || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(base) || /^0+$/.test(base))
41
+ return unavailable;
42
+ try {
43
+ const commonAncestor = resolveBase(base, directory);
44
+ // Changed-since compares against the common ancestor, which can omit reintroduced files on a force push.
45
+ if (commonAncestor && GITHUB_EVENT_NAME === 'push' && !LOADWISE_BASE_SHA && commonAncestor !== base.toLowerCase())
46
+ return { warning: nonFastForwardWarning };
47
+ if (commonAncestor)
48
+ return { base };
49
+ }
50
+ catch {
51
+ // Checkouts with incomplete history still run the check in full.
52
+ }
53
+ return unavailable;
54
+ }
55
+ function includesReliability(directory, env) {
56
+ const { LOADWISE_CHECKERS, LOADWISE_SKIP, LOADWISE_CONFIG } = env;
57
+ const explicit = LOADWISE_CONFIG ? path.resolve(directory, LOADWISE_CONFIG) : undefined;
58
+ const selection = LOADWISE_CHECKERS || LOADWISE_SKIP
59
+ ? { only: LOADWISE_CHECKERS || undefined, skip: LOADWISE_SKIP || undefined }
60
+ : { only: loadSettings({ directory, explicit }).checkers?.join(',') };
61
+ return selectPillars(selection).some(({ name }) => name === 'rel');
62
+ }
63
+ export function comparisonArgs(directory, env, logger = console, resolveBase = (base, cwd) => mergeBaseSince(base, cwd).base) {
64
+ if (env.LOADWISE_CHANGED_ONLY !== 'true')
65
+ return { flags: [], incomplete: false };
66
+ const comparison = changedOnlyComparison(directory, env, resolveBase);
67
+ if ('base' in comparison)
68
+ return { flags: ['--changed-since', comparison.base], incomplete: false };
69
+ logger.warn(comparison.warning);
70
+ const contractGate = env.LOADWISE_FAIL_ON === 'contract';
71
+ const incomplete = (contractGate || comparison.requiredBase !== undefined) && includesReliability(directory, env);
72
+ if (incomplete) {
73
+ logger.error(contractGate
74
+ ? 'Cannot compare API contracts without a usable base commit. The contract-gated scan is incomplete.'
75
+ : `Cannot compare API contracts without a usable ${comparison.requiredBase}. The changed-only scan is incomplete.`);
76
+ }
77
+ return { flags: [], incomplete };
78
+ }
@@ -1,10 +1,15 @@
1
1
  const automaticFixSignal = 'loadwise:automatic-fixes-available';
2
2
  const collectFixSignals = 'LOADWISE_INTERNAL_COLLECT_FIX_SIGNALS';
3
- function reportAutomaticFixes(findings) {
3
+ const findingCountSignal = 'loadwise:text-finding-count';
4
+ function isFindingCount(value) {
5
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
6
+ }
7
+ function reportTextFindings(findings) {
4
8
  if (!process.send || !process.connected || process.env[collectFixSignals] !== '1')
5
9
  return;
10
+ process.send({ kind: findingCountSignal, count: findings.length }, undefined, undefined, () => undefined);
6
11
  if (findings.some(({ fix }) => fix?.changes.length && !fix.requiresReview)) {
7
12
  process.send(automaticFixSignal, undefined, undefined, () => undefined);
8
13
  }
9
14
  }
10
- export { automaticFixSignal, collectFixSignals, reportAutomaticFixes };
15
+ export { automaticFixSignal, collectFixSignals, findingCountSignal, isFindingCount, reportTextFindings };
@@ -13,8 +13,9 @@ function explainLines(message, columns) {
13
13
  return wrapWords(message, width).map((line, index) => (index ? hangingIndent : explanationLabel) + line);
14
14
  }
15
15
  /** Lay out the combined report while passing through checker-specific details and commands. */
16
- function formatCheckText(text, columns = process.stdout.columns || maximumWidth) {
16
+ function formatCheckText(text, columns = process.stdout.columns || maximumWidth, title) {
17
17
  const lines = [];
18
+ const prefix = title ? title + ': ' : '';
18
19
  let reportedFindings = false;
19
20
  for (const line of text.split('\n')) {
20
21
  const finding = findingLine.exec(line);
@@ -33,12 +34,13 @@ function formatCheckText(text, columns = process.stdout.columns || maximumWidth)
33
34
  lines.push(line);
34
35
  reportedFindings = false;
35
36
  }
36
- else if (summaryLine.test(line)) {
37
+ else if (summaryLine.test(line) || /^No (?:new findings in changed lines|changed files to check)\.$/.test(line)) {
37
38
  if (reportedFindings && lines.at(-1))
38
39
  lines.push('');
39
- lines.push(line === singleWarning
40
- ? '1 finding is a warning and does not affect the exit code.'
41
- : line.replaceAll(countedWord, (_match, count, word) => `${count} ${word}${count === '1' ? '' : 's'}`));
40
+ lines.push(prefix +
41
+ (line === singleWarning
42
+ ? '1 finding is a warning and does not affect the exit code.'
43
+ : line.replaceAll(countedWord, (_match, count, word) => `${count} ${word}${count === '1' ? '' : 's'}`)));
42
44
  reportedFindings = false;
43
45
  }
44
46
  else {
@@ -3,11 +3,13 @@
3
3
  import { spawn } from 'node:child_process';
4
4
  import { cliEntryPath } from '../package-root.js';
5
5
  import { allowedHeapMegabytes, childHeapFlags, isHeapExhaustion } from '../system/heap-limit.js';
6
+ import { conventionalProjects } from '../conventional-projects.js';
6
7
  import { configlessSources, coveringConfig, hasWorkspaceSources, missingSourcesDetail, projectConfig, } from '../workspaces.js';
7
8
  import { cachedRun, withSharedInputFingerprint } from '../analysis/scan-cache.js';
8
9
  import { isRecord } from '../system/is-record.js';
9
- import { automaticFixSignal, collectFixSignals } from './automatic-fix-signal.js';
10
+ import { automaticFixSignal, collectFixSignals, findingCountSignal, isFindingCount } from './automatic-fix-signal.js';
10
11
  import { collectRulePackFingerprint, readRulePackFingerprint } from './rule-pack-fingerprint.js';
12
+ import { isOutsideSourceSignal, sourceWatchSpawn } from '../analysis/scan-cache-sources.js';
11
13
  import { rulesByPillar } from '../rule-registry.js';
12
14
  import { hasInfrastructureFiles } from '../../security/files/index.js';
13
15
  import { hasFrontendSourcesInWorkspaces, mayHaveVueTemplates } from '../../accessibility/frontend-detect.js';
@@ -20,7 +22,8 @@ function isChildRun(value) {
20
22
  return (isRecord(value) &&
21
23
  typeof value.code === 'number' &&
22
24
  typeof value.stdout === 'string' &&
23
- (value.stderr === undefined || typeof value.stderr === 'string'));
25
+ (value.stderr === undefined || typeof value.stderr === 'string') &&
26
+ (value.findingCount === undefined || isFindingCount(value.findingCount)));
24
27
  }
25
28
  function isSharedEnvelope(value, keys) {
26
29
  return isRecord(value) && keys.every((key) => isChildRun(value[key]));
@@ -33,7 +36,7 @@ function titleList(names) {
33
36
  const invalidInputCode = 2;
34
37
  // An unchanged project replays the stored report; see scan-cache.cjs for what invalidates it.
35
38
  function runChecker(args, cwd = process.cwd()) {
36
- return cachedRun(args, cwd, (receiveFingerprint) => spawnChecker(args, cwd, receiveFingerprint));
39
+ return cachedRun(args, cwd, (receiveFingerprint, sourceWatch) => spawnChecker(args, cwd, receiveFingerprint, sourceWatch));
37
40
  }
38
41
  // Names the checker a child ran, for messages about it.
39
42
  function checkerLabel(args) {
@@ -47,18 +50,20 @@ function heapExhaustionMessage(args, heapFlags) {
47
50
  return (`The ${checkerLabel(args)} ran out of memory (allowed ${allowedHeapMegabytes(heapFlags)} MB). ` +
48
51
  'Raise the limit with NODE_OPTIONS=--max-old-space-size=<megabytes> and run again.\n');
49
52
  }
50
- function spawnChecker(args, cwd, receiveFingerprint) {
53
+ function spawnChecker(args, cwd, receiveFingerprint, sourceWatch) {
51
54
  return new Promise((resolve) => {
52
55
  // The parent owns the review and its scope, including when several checkers run in child
53
56
  // processes.
54
57
  const heapFlags = childHeapFlags();
55
58
  const collect = pillarNames.includes(args[0]) && !args.includes('--json');
56
- const child = spawn(process.execPath, [...heapFlags, cliEntryPath, ...args], {
59
+ const watching = sourceWatch && sourceWatchSpawn(sourceWatch);
60
+ const child = spawn(process.execPath, [...heapFlags, ...(watching?.execArgv ?? []), cliEntryPath, ...args], {
57
61
  cwd,
58
62
  windowsHide: true,
59
- stdio: ['pipe', 'pipe', 'pipe', collect || receiveFingerprint ? 'ipc' : 'ignore'],
63
+ stdio: ['pipe', 'pipe', 'pipe', collect || receiveFingerprint || watching ? 'ipc' : 'ignore'],
60
64
  env: {
61
65
  ...process.env,
66
+ ...watching?.env,
62
67
  LOADWISE_AGENT: '0',
63
68
  NO_COLOR: '1',
64
69
  FORCE_COLOR: '0',
@@ -71,12 +76,17 @@ function spawnChecker(args, cwd, receiveFingerprint) {
71
76
  let stderr = '';
72
77
  let overflowed = false;
73
78
  let hasAutomaticFixes = false;
79
+ let findingCount;
74
80
  child.on('message', (message) => {
75
81
  if (message === automaticFixSignal)
76
82
  hasAutomaticFixes = true;
83
+ if (isRecord(message) && message.kind === findingCountSignal && isFindingCount(message.count))
84
+ findingCount = message.count;
77
85
  const fingerprint = readRulePackFingerprint(message);
78
86
  if (fingerprint !== undefined)
79
87
  receiveFingerprint?.(fingerprint);
88
+ if (isOutsideSourceSignal(message))
89
+ sourceWatch?.onOutsideSource();
80
90
  });
81
91
  child.stdout?.setEncoding('utf8').on('data', (text) => {
82
92
  if (stdout.length + text.length > maxOutputBytes) {
@@ -105,6 +115,7 @@ function spawnChecker(args, cwd, receiveFingerprint) {
105
115
  stdout,
106
116
  stderr,
107
117
  ...(hasAutomaticFixes && { hasAutomaticFixes: true }),
118
+ ...(findingCount !== undefined && { findingCount }),
108
119
  });
109
120
  });
110
121
  });
@@ -127,8 +138,10 @@ function mergeContractReport(source, contracts, contractFlags) {
127
138
  const stderr = source.stderr + contracts.stderr;
128
139
  if (contracts.code === invalidInputCode && !contracts.stdout.trim())
129
140
  return { ...source, code, stderr };
130
- if (!contractFlags?.includes('--json'))
131
- return { ...source, code, stdout: source.stdout + contracts.stdout, stderr };
141
+ if (!contractFlags?.includes('--json')) {
142
+ const findingCount = (source.findingCount ?? 0) + (contracts.findingCount ?? 0);
143
+ return { ...source, code, stdout: source.stdout + contracts.stdout, stderr, findingCount };
144
+ }
132
145
  let sourceReport;
133
146
  let contractReport;
134
147
  try {
@@ -158,6 +171,9 @@ function mergeContractReport(source, contracts, contractFlags) {
158
171
  stderr,
159
172
  };
160
173
  }
174
+ function hasConventionalSources(directory, flags) {
175
+ return (!flags.includes('--loadwise-config') && !flags.includes('--policy') && conventionalProjects(directory).length > 0);
176
+ }
161
177
  // `command` is perf, rel or a11y, which run the same source check.
162
178
  function runSourceChecker(command, { directory, flags, workspaces, relative }) {
163
179
  const workspaceFlags = workspaces.flatMap((selector) => ['--workspace', selector]);
@@ -165,6 +181,7 @@ function runSourceChecker(command, { directory, flags, workspaces, relative }) {
165
181
  if (workspaces.length ||
166
182
  projectConfig(directory) ||
167
183
  hasWorkspaceSources(directory) ||
184
+ hasConventionalSources(directory, flags) ||
168
185
  configlessSources(directory) ||
169
186
  coveringConfig(directory) ||
170
187
  (command === 'perf' && mayHaveVueTemplates(directory))) {
@@ -257,6 +274,7 @@ const pillars = [
257
274
  if (workspaces.length ||
258
275
  projectConfig(directory) ||
259
276
  hasWorkspaceSources(directory) ||
277
+ hasConventionalSources(directory, flags) ||
260
278
  configlessSources(directory) ||
261
279
  coveringConfig(directory)) {
262
280
  const workspaceFlags = workspaces.flatMap((selector) => ['--workspace', selector]);
@@ -362,6 +380,7 @@ async function runSharedSourceCheck(shared, options) {
362
380
  if (!workspaces.length &&
363
381
  !projectConfig(directory) &&
364
382
  !hasWorkspaceSources(directory) &&
383
+ !hasConventionalSources(directory, flags) &&
365
384
  !configlessSources(directory) &&
366
385
  !coveringConfig(directory)) {
367
386
  return runWithoutSourceConfig(shared, options, directory);
@@ -422,6 +441,7 @@ async function runSharedSourceCheck(shared, options) {
422
441
  stdout: report.stdout,
423
442
  stderr: index ? '' : run.stderr,
424
443
  ...(!index && run.hasAutomaticFixes && { hasAutomaticFixes: true }),
444
+ ...(report.findingCount !== undefined && { findingCount: report.findingCount }),
425
445
  };
426
446
  return pillar.name === 'rel' ? mergeContractReport(own, contracts, contractOptions?.contractFlags) : own;
427
447
  });