loadwise 0.5.1 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/PERFORMANCE.md +31 -6
  2. package/README.md +580 -1024
  3. package/bin/loadwise.js +4 -0
  4. package/lib/accessibility/frontend-detect.js +2 -1
  5. package/lib/accessibility/rule-ids.js +12 -9
  6. package/{editor/accessibility-examples.cjs → lib/editor/accessibility-examples.js} +20 -21
  7. package/lib/editor/actions.js +117 -0
  8. package/{editor/apply-fix.cjs → lib/editor/apply-fix.js} +1 -6
  9. package/{editor/control-flow-comparison.cjs → lib/editor/control-flow-comparison.js} +1 -3
  10. package/lib/editor/diagnostics.js +365 -0
  11. package/lib/editor/dismissals.js +111 -0
  12. package/lib/editor/editor-document.js +99 -0
  13. package/{editor/finding-comparison.cjs → lib/editor/finding-comparison.js} +4 -7
  14. package/lib/editor/fix-edits.js +200 -0
  15. package/lib/editor/language-server.js +437 -0
  16. package/{editor/maintainability-examples.cjs → lib/editor/maintainability-examples.js} +1 -3
  17. package/{editor/perf-site-comparison.cjs → lib/editor/perf-site-comparison.js} +1 -3
  18. package/lib/editor/perf-watch.js +78 -0
  19. package/{editor/performance-examples.cjs → lib/editor/performance-examples.js} +129 -128
  20. package/{editor/reliability-examples.cjs → lib/editor/reliability-examples.js} +100 -41
  21. package/lib/editor/scan-session.js +334 -0
  22. package/{editor/security-examples.cjs → lib/editor/security-examples.js} +28 -32
  23. package/lib/editor/server-commands.js +232 -0
  24. package/{editor/source-example.cjs → lib/editor/source-example.js} +3 -5
  25. package/{editor/standalone-performance-examples.cjs → lib/editor/standalone-performance-examples.js} +349 -333
  26. package/lib/editor/types/dismissal.js +1 -0
  27. package/lib/editor/types/fix-example.js +1 -0
  28. package/lib/editor/types/source-document.js +1 -0
  29. package/lib/editor/workspace-files.js +78 -0
  30. package/lib/editor/workspace-paths.js +22 -0
  31. package/lib/maintainability/analyze-source.js +2 -0
  32. package/lib/maintainability/apply-fix.js +1 -1
  33. package/lib/maintainability/cli.js +1 -1
  34. package/lib/maintainability/examples.js +58 -41
  35. package/lib/maintainability/rule-ids.js +29 -14
  36. package/lib/maintainability/scan-changed.js +3 -0
  37. package/lib/maintainability/scan.js +13 -9
  38. package/lib/maintainability/tsconfig-strict.js +69 -0
  39. package/lib/maintainability/type-safety-hygiene.js +204 -0
  40. package/lib/performance/analyze.js +2 -0
  41. package/lib/performance/cli-arguments.js +0 -2
  42. package/lib/performance/cli-policy.js +17 -9
  43. package/lib/performance/cli-scan.js +10 -8
  44. package/lib/performance/cli.js +4 -23
  45. package/lib/performance/editor-signal.js +1 -1
  46. package/lib/performance/finding-text.js +3 -3
  47. package/lib/performance/fix-cli.js +1 -1
  48. package/lib/performance/frontend-perf.js +7 -0
  49. package/lib/performance/frontend-render-perf.js +200 -0
  50. package/lib/performance/llm-max-tokens.js +56 -0
  51. package/lib/performance/native.js +46 -26
  52. package/lib/performance/polyglot.js +22 -1
  53. package/lib/performance/pooling.js +38 -23
  54. package/lib/performance/projects.js +42 -21
  55. package/lib/performance/rule-ids.js +236 -222
  56. package/lib/performance/site-fixes/database.js +3 -1
  57. package/lib/performance/site-fixes/integrity.js +15 -1
  58. package/lib/performance/source-inputs.js +18 -6
  59. package/lib/performance/unscanned-javascript.js +66 -19
  60. package/lib/reliability/analyze.js +12 -0
  61. package/lib/reliability/child-process.js +106 -0
  62. package/lib/reliability/error-values.js +177 -0
  63. package/lib/reliability/pool-timeout.js +79 -0
  64. package/lib/reliability/react-bugs.js +602 -0
  65. package/lib/reliability/resource-leaks.js +3 -6
  66. package/lib/reliability/rule-ids.js +169 -127
  67. package/lib/reliability/switch-exhaustive.js +284 -0
  68. package/lib/reliability/uncaught-exception.js +223 -0
  69. package/lib/security/auth-crypto/rule-ids.js +3 -2
  70. package/lib/security/cli.js +6 -5
  71. package/lib/security/deps/rule-ids.js +1 -0
  72. package/lib/security/examples/auth-crypto.cjs +5 -4
  73. package/lib/security/examples/deps.cjs +1 -0
  74. package/lib/security/examples/exposure.cjs +55 -42
  75. package/lib/security/examples/files.cjs +1 -0
  76. package/lib/security/examples/injection.cjs +1 -0
  77. package/lib/security/examples/moved.cjs +5 -4
  78. package/lib/security/examples/request-forgery.cjs +1 -0
  79. package/lib/security/exposure/client-env.js +113 -0
  80. package/lib/security/exposure/frontend-security.js +12 -10
  81. package/lib/security/exposure/index.js +14 -3
  82. package/lib/security/exposure/jsx-url.js +267 -0
  83. package/lib/security/exposure/next-image-config.js +34 -0
  84. package/lib/security/exposure/package-manifest.js +45 -0
  85. package/lib/security/exposure/react-version.js +45 -0
  86. package/lib/security/exposure/rule-ids.js +16 -12
  87. package/lib/security/files/index.js +1 -1
  88. package/lib/security/files/rule-ids.js +1 -0
  89. package/lib/security/injection/code.js +24 -10
  90. package/lib/security/injection/command.js +81 -28
  91. package/lib/security/injection/nosql.js +109 -22
  92. package/lib/security/injection/redos.js +152 -308
  93. package/lib/security/injection/regex-pattern.js +290 -0
  94. package/lib/security/injection/regex.js +30 -11
  95. package/lib/security/injection/rule-ids.js +2 -1
  96. package/lib/security/injection/shared.js +19 -1
  97. package/lib/security/injection/sql.js +83 -2
  98. package/lib/security/request-forgery/rule-ids.js +1 -0
  99. package/lib/security/rule-descriptions.js +36 -32
  100. package/lib/security/rule-ids.js +74 -67
  101. package/lib/security/taint/filename-guard.js +3 -1
  102. package/lib/security/taint/guards.js +84 -10
  103. package/lib/security/taint/index.js +124 -13
  104. package/lib/security/taint/propagate.js +10 -7
  105. package/lib/security/taint/sanitizers.js +7 -3
  106. package/lib/security/taint/sources.js +6 -3
  107. package/lib/security/taint/summaries.js +13 -1
  108. package/lib/security/taint/url-parts.js +14 -5
  109. package/lib/shared/agent-session.js +2 -2
  110. package/lib/shared/check.js +9 -6
  111. package/lib/shared/explain.js +5 -5
  112. package/lib/shared/fix-convergence.js +1 -1
  113. package/lib/shared/formats/finding-location.js +6 -2
  114. package/lib/shared/formats/sarif.js +3 -3
  115. package/lib/shared/heap-limit.js +6 -0
  116. package/lib/shared/pillars.js +7 -7
  117. package/lib/shared/rule-docs.js +12 -0
  118. package/lib/shared/scan-cache.js +0 -1
  119. package/lib/shared/workspaces.js +31 -9
  120. package/package.json +25 -17
  121. package/plugin/.claude-plugin/plugin.json +1 -1
  122. package/schema/loadwise.config.schema.json +44 -0
  123. package/editor/README.md +0 -47
  124. package/examples/redis-keys.otlp.json +0 -22
  125. package/lib/maintainability/notify-editor.js +0 -1
  126. package/lib/performance/editor-report.js +0 -191
  127. package/lib/performance/editor-setup.js +0 -189
  128. package/lib/performance/editor-watch-supervisor.js +0 -104
  129. package/lib/performance/editor-watch.js +0 -193
  130. package/lib/performance/notify-editor.js +0 -1
  131. package/lib/performance/recursive-watch.js +0 -181
  132. /package/lib/{performance/types/editor-report.js → editor/types/comparison.js} +0 -0
@@ -0,0 +1,334 @@
1
+ // One workspace folder's scans. Performance, reliability and accessibility come from the
2
+ // incremental `perf -p <config> --watch --json` process when the folder has one config to follow;
3
+ // maintainability, security, templates and the polyglot rules rerun after each change, debounced.
4
+ // The folder's inputs are chosen the way `loadwise check` chooses them. Rapid changes coalesce into
5
+ // one scan of the newest state, and a change during a scan aborts the stale child.
6
+ import fs from 'node:fs/promises';
7
+ import path from 'node:path';
8
+ import { execFile } from 'node:child_process';
9
+ import { promisify } from 'node:util';
10
+ import { startPerfWatch } from './perf-watch.js';
11
+ import { hasFileWithSuffix, markupSuffixes, polyglotSuffixes, sourceSuffixes } from './workspace-files.js';
12
+ import { isMarkupFile } from '../accessibility/markup-files.js';
13
+ import { listenForEditorRefresh } from '../performance/editor-signal.js';
14
+ import { hasInfrastructureFiles } from '../security/files/index.js';
15
+ import { configlessSources, coveringConfig, hasWorkspaceSources } from '../shared/workspaces.js';
16
+ const run = promisify(execFile);
17
+ const debounceMs = 650;
18
+ const maxReportBytes = 64 * 1024 * 1024;
19
+ const perf = 'loadwise perf';
20
+ const maint = 'loadwise maint';
21
+ const sec = 'loadwise sec';
22
+ // The server's own scans must not ask the running editors to refresh again.
23
+ const scanEnv = { ...process.env, LOADWISE_EDITOR_SCAN: '1' };
24
+ function messageOf(error) {
25
+ return error instanceof Error ? error.message : String(error);
26
+ }
27
+ function execFailureOf(error) {
28
+ if (!(error instanceof Error))
29
+ throw error;
30
+ return {
31
+ message: error.message,
32
+ code: 'code' in error ? error.code : undefined,
33
+ stdout: 'stdout' in error && typeof error.stdout === 'string' ? error.stdout : undefined,
34
+ stderr: 'stderr' in error && typeof error.stderr === 'string' ? error.stderr : undefined,
35
+ };
36
+ }
37
+ function exists(file) {
38
+ return fs.access(file).then(() => true, () => false);
39
+ }
40
+ async function firstExisting(root, names) {
41
+ for (const name of names)
42
+ if (await exists(path.join(root, name)))
43
+ return name;
44
+ }
45
+ async function readFindings(script, args, cwd, signal) {
46
+ const options = {
47
+ cwd,
48
+ signal,
49
+ windowsHide: true,
50
+ maxBuffer: maxReportBytes,
51
+ encoding: 'utf8',
52
+ env: scanEnv,
53
+ };
54
+ let stdout;
55
+ try {
56
+ ({ stdout } = await run(process.execPath, [script, ...args, '--json'], options));
57
+ }
58
+ catch (error) {
59
+ const failure = execFailureOf(error);
60
+ // Exit code 1 means findings met the exit threshold; the report is still complete.
61
+ if (failure.code !== 1)
62
+ throw new Error(failure.stderr?.trim() || failure.message, { cause: error });
63
+ stdout = failure.stdout ?? '';
64
+ }
65
+ const report = JSON.parse(stdout);
66
+ if (!Array.isArray(report.findings))
67
+ throw new Error('Checker returned an invalid findings report.');
68
+ return report.findings;
69
+ }
70
+ // A project setting is used only when it stays inside the folder and cannot be read as a flag.
71
+ function explicitProject(root, setting) {
72
+ const trimmed = setting.trim();
73
+ if (!trimmed || trimmed.startsWith('-'))
74
+ return '';
75
+ const relative = path.relative(root, path.resolve(root, trimmed));
76
+ if (!relative || relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative))
77
+ return '';
78
+ return relative;
79
+ }
80
+ // Like `loadwise check`: a tsconfig.json beside a jsconfig.json is passed as the folder, so the
81
+ // JavaScript only the jsconfig covers is scanned too. The watcher follows one config, so that
82
+ // folder gets full scans instead.
83
+ async function configTarget(root, setting) {
84
+ const explicit = explicitProject(root, setting);
85
+ if (explicit)
86
+ return { project: explicit, watchable: true };
87
+ const own = await firstExisting(root, ['tsconfig.json', 'jsconfig.json']);
88
+ if (own === 'tsconfig.json' && (await exists(path.join(root, 'jsconfig.json')))) {
89
+ return { project: '.', watchable: false };
90
+ }
91
+ return own ? { project: own, watchable: true } : undefined;
92
+ }
93
+ // These walk the tree synchronously, so they run only for a folder without a config, once per
94
+ // change of its files.
95
+ function probeConfiglessInputs(root) {
96
+ const hasSources = Boolean(hasWorkspaceSources(root) || configlessSources(root) || coveringConfig(root));
97
+ return { hasSources, hasInfrastructure: !hasSources && hasInfrastructureFiles(root) };
98
+ }
99
+ function accessibilityArgs(project, inputs) {
100
+ if (project)
101
+ return ['a11y', '-p', project];
102
+ // Without a config the checker reads the markup files alone.
103
+ return inputs.hasMarkup ? ['a11y', '-p', '.'] : null;
104
+ }
105
+ function scanTasks(target, watching, inputs, configless) {
106
+ const project = target?.project;
107
+ const sourceArgs = (command) => (project ? [command, '-p', project] : null);
108
+ const hasMaintainabilityInput = Boolean(project) || inputs.hasSource;
109
+ const securityArgs = project ? sourceArgs('sec') : configless?.hasInfrastructure ? ['sec', '-p', '.'] : null;
110
+ return [
111
+ { id: perf, source: perf, args: sourceArgs('perf'), watchProject: watching ? project : undefined },
112
+ // The watcher reports reliability and accessibility with performance, under the perf label whose fix commands still apply them.
113
+ { id: perf + '-reliability', source: perf, args: watching ? null : sourceArgs('rel') },
114
+ // The watcher reads only the TypeScript program, so templates still need a scan of their own.
115
+ watching
116
+ ? {
117
+ id: perf + '-accessibility',
118
+ source: perf,
119
+ args: inputs.hasMarkup ? sourceArgs('a11y') : null,
120
+ markupOnly: true,
121
+ }
122
+ : { id: perf + '-accessibility', source: perf, args: accessibilityArgs(project, inputs) },
123
+ { id: maint, source: maint, args: hasMaintainabilityInput ? ['maint', '.'] : null },
124
+ { id: sec, source: sec, args: securityArgs },
125
+ { id: perf + '-polyglot', source: perf, args: inputs.hasPolyglot ? ['perf', 'polyglot', '.'] : null },
126
+ { id: perf + '-polyglot-reliability', source: perf, args: inputs.hasPolyglot ? ['rel', 'polyglot', '.'] : null },
127
+ { id: sec + '-polyglot', source: sec, args: inputs.hasPolyglot ? ['sec', 'polyglot', '.'] : null },
128
+ ];
129
+ }
130
+ function createScanSession(options) {
131
+ const { root, name } = options;
132
+ const disposed = new AbortController();
133
+ const reports = new Map();
134
+ let revision = 0;
135
+ let scannedRevision = -1;
136
+ let running;
137
+ let timer;
138
+ let activeScan;
139
+ let scanning = false;
140
+ let restartRequested = false;
141
+ let perfWatch;
142
+ // Set when the watcher dies; full rescans take over until a config change restarts it.
143
+ let watchUnavailable = false;
144
+ let inputs;
145
+ let configless;
146
+ // Scans finished in a terminal ask the editor to refresh through the shared signal folder.
147
+ const refreshListener = listenForEditorRefresh(root, () => schedule({ filesAddedOrRemoved: true }));
148
+ function log(id, text) {
149
+ options.log(name + ' / ' + id + ' — ' + text);
150
+ }
151
+ function logError(id, text) {
152
+ options.logError(name + ' / ' + id + ' — ' + text);
153
+ }
154
+ function show(id, source, findings) {
155
+ reports.set(id, { source, findings });
156
+ log(id, findings.length + ' finding(s)');
157
+ options.onReports();
158
+ options.onStatus();
159
+ }
160
+ function clear(id) {
161
+ if (reports.delete(id))
162
+ options.onReports();
163
+ }
164
+ function stopWatch() {
165
+ perfWatch?.handle?.stop();
166
+ perfWatch = undefined;
167
+ }
168
+ function ensureWatch(script, project, restart) {
169
+ const key = script + '\0' + project;
170
+ if (perfWatch?.key === key && !restart)
171
+ return;
172
+ stopWatch();
173
+ const current = { key, pending: true };
174
+ current.handle = startPerfWatch({
175
+ script,
176
+ project,
177
+ cwd: root,
178
+ env: scanEnv,
179
+ onFindings(findings) {
180
+ if (perfWatch !== current)
181
+ return;
182
+ current.pending = false;
183
+ show(perf, perf, findings);
184
+ },
185
+ onError(error) {
186
+ if (perfWatch !== current)
187
+ return;
188
+ // A config or project error produces no report; stop showing the scan as in progress.
189
+ current.pending = false;
190
+ logError(perf, error.message);
191
+ options.onStatus();
192
+ },
193
+ onExit(error) {
194
+ if (perfWatch !== current)
195
+ return;
196
+ perfWatch = undefined;
197
+ watchUnavailable = true;
198
+ logError(perf, error.message + ' Falling back to full rescans after each change.');
199
+ schedule();
200
+ },
201
+ });
202
+ perfWatch = current;
203
+ log(perf, 'watching ' + project + ' incrementally (process ' + current.handle.pid + ')');
204
+ options.onStatus();
205
+ }
206
+ async function probeInputs() {
207
+ const [hasSource, hasPolyglot, hasMarkup] = await Promise.all([
208
+ hasFileWithSuffix(root, sourceSuffixes),
209
+ hasFileWithSuffix(root, polyglotSuffixes),
210
+ hasFileWithSuffix(root, markupSuffixes),
211
+ ]);
212
+ return { hasSource, hasPolyglot, hasMarkup };
213
+ }
214
+ async function sourceTarget(setting) {
215
+ const target = await configTarget(root, setting);
216
+ if (target)
217
+ return target;
218
+ configless ??= probeConfiglessInputs(root);
219
+ return configless.hasSources ? { project: '.', watchable: false } : undefined;
220
+ }
221
+ async function runTask(task, script, restart, scanSignal) {
222
+ if (!task.args)
223
+ return clear(task.id);
224
+ if (!path.isAbsolute(script))
225
+ throw new Error('The loadwise.cli setting must be an absolute path.');
226
+ if (task.watchProject !== undefined)
227
+ return ensureWatch(script, task.watchProject, restart);
228
+ const findings = await readFindings(script, task.args, root, scanSignal);
229
+ if (scanSignal.aborted || disposed.signal.aborted)
230
+ return;
231
+ show(task.id, task.source, task.markupOnly ? findings.filter(({ file }) => file !== undefined && isMarkupFile(file)) : findings);
232
+ }
233
+ async function scan(version, scanSignal) {
234
+ const restart = restartRequested;
235
+ restartRequested = false;
236
+ if (restart)
237
+ watchUnavailable = false;
238
+ const settings = options.settings();
239
+ if (!settings.enabled) {
240
+ stopWatch();
241
+ for (const id of reports.keys())
242
+ clear(id);
243
+ return;
244
+ }
245
+ const target = await sourceTarget(settings.project);
246
+ const watching = Boolean(target?.watchable) && !watchUnavailable;
247
+ if (!watching)
248
+ stopWatch();
249
+ inputs ??= probeInputs();
250
+ const tasks = scanTasks(target, watching, await inputs, configless);
251
+ const script = settings.cli || options.defaultCli;
252
+ for (const task of tasks) {
253
+ if (disposed.signal.aborted || version !== revision)
254
+ return;
255
+ try {
256
+ await runTask(task, script, restart, scanSignal);
257
+ }
258
+ catch (error) {
259
+ if (disposed.signal.aborted || version !== revision)
260
+ return;
261
+ clear(task.id);
262
+ logError(task.id, messageOf(error));
263
+ }
264
+ }
265
+ }
266
+ async function runScan() {
267
+ const version = revision;
268
+ if (disposed.signal.aborted || version === scannedRevision)
269
+ return;
270
+ scannedRevision = version;
271
+ activeScan = new AbortController();
272
+ scanning = true;
273
+ options.onStatus();
274
+ try {
275
+ await scan(version, activeScan.signal);
276
+ }
277
+ catch (error) {
278
+ if (!disposed.signal.aborted && version === revision)
279
+ options.logError(name + ' — ' + messageOf(error));
280
+ }
281
+ finally {
282
+ activeScan = undefined;
283
+ scanning = false;
284
+ options.onStatus();
285
+ }
286
+ }
287
+ function start() {
288
+ clearTimeout(timer);
289
+ // A stale scan is aborted by schedule(); wait for it to wind down, then scan the newest state
290
+ // once.
291
+ const previous = running;
292
+ const current = (previous ?? Promise.resolve()).then(runScan).finally(() => {
293
+ if (running === current)
294
+ running = undefined;
295
+ });
296
+ running = current;
297
+ return current;
298
+ }
299
+ function schedule({ restart = false, filesAddedOrRemoved = false } = {}) {
300
+ if (disposed.signal.aborted)
301
+ return;
302
+ restartRequested ||= restart;
303
+ if (restart || filesAddedOrRemoved) {
304
+ inputs = undefined;
305
+ configless = undefined;
306
+ }
307
+ revision++;
308
+ clearTimeout(timer);
309
+ activeScan?.abort();
310
+ // A config change makes the running watcher stale too; the debounced follow-up starts a fresh
311
+ // one.
312
+ if (restart)
313
+ stopWatch();
314
+ timer = setTimeout(start, debounceMs);
315
+ }
316
+ return {
317
+ schedule,
318
+ scanNow() {
319
+ schedule({ restart: true });
320
+ return start();
321
+ },
322
+ reports: () => reports.values(),
323
+ isScanning: () => scanning || Boolean(perfWatch?.pending),
324
+ watcherPid: () => perfWatch?.handle?.pid,
325
+ dispose() {
326
+ clearTimeout(timer);
327
+ disposed.abort();
328
+ activeScan?.abort();
329
+ stopWatch();
330
+ refreshListener.close();
331
+ },
332
+ };
333
+ }
334
+ export { createScanSession };
@@ -1,19 +1,26 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.exampleFor = exampleFor;
7
1
  // Generic fix examples for security rules. Each group keeps its own [code, note] entries in
8
2
  // lib/security/examples.
9
- const moved_cjs_1 = __importDefault(require("../lib/security/examples/moved.cjs"));
10
- const injection_cjs_1 = __importDefault(require("../lib/security/examples/injection.cjs"));
11
- const request_forgery_cjs_1 = __importDefault(require("../lib/security/examples/request-forgery.cjs"));
12
- const auth_crypto_cjs_1 = __importDefault(require("../lib/security/examples/auth-crypto.cjs"));
13
- const exposure_cjs_1 = __importDefault(require("../lib/security/examples/exposure.cjs"));
14
- const deps_cjs_1 = __importDefault(require("../lib/security/examples/deps.cjs"));
15
- const files_cjs_1 = __importDefault(require("../lib/security/examples/files.cjs"));
3
+ import movedModule from '../security/examples/moved.cjs';
4
+ import injectionModule from '../security/examples/injection.cjs';
5
+ import requestForgeryModule from '../security/examples/request-forgery.cjs';
6
+ import authCryptoModule from '../security/examples/auth-crypto.cjs';
7
+ import exposureModule from '../security/examples/exposure.cjs';
8
+ import depsModule from '../security/examples/deps.cjs';
9
+ import filesModule from '../security/examples/files.cjs';
10
+ // Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
16
11
  const phase5Examples = {
12
+ 'express-cookie-auth-missing-csrf': [
13
+ "app.use(cookieParser());\napp.use(doubleCsrfProtection);\napp.post('/transfer', (req, res) => res.send('ok'));",
14
+ 'Enable CSRF middleware or `sameSite: "strict"` cookies for state-changing routes using cookie auth.',
15
+ ],
16
+ 'graphql-batching-unbounded': [
17
+ 'const server = new ApolloServer({\n typeDefs,\n resolvers,\n allowBatchedHttpRequests: true,\n validationRules: [depthLimit(5)],\n});',
18
+ 'Enforce a batch size, query depth, or complexity limit whenever GraphQL batching is enabled.',
19
+ ],
20
+ 'jwt-weak-secret-literal': [
21
+ "const secret = process.env.JWT_SECRET;\nif (!secret) throw new Error('Missing JWT_SECRET');\nconst token = jwt.sign({ sub: userId }, secret, { expiresIn: '15m' });",
22
+ 'Load a high-entropy >= 256-bit secret from environment or KMS instead of a weak literal.',
23
+ ],
17
24
  'server-action-missing-auth': [
18
25
  "'use server';\nexport async function deleteAccount(id: string) {\n const session = await auth();\n if (!session) throw new Error('Unauthorized');\n await db.user.delete({ where: { id } });\n}",
19
26
  'Verify the caller session before mutating state in a Server Action.',
@@ -26,27 +33,15 @@ const phase5Examples = {
26
33
  "import ivm from 'isolated-vm';\nconst isolate = new ivm.Isolate({ memoryLimit: 32 });\nconst result = await isolate.compileScript(code).then((s) => s.run(isolate.createContextSync()));",
27
34
  'Replace `node:vm` / `vm2` with `isolated-vm` or an OS-level sandbox for untrusted code.',
28
35
  ],
29
- 'jwt-weak-secret-literal': [
30
- "const secret = process.env.JWT_SECRET;\nif (!secret) throw new Error('Missing JWT_SECRET');\nconst token = jwt.sign({ sub: userId }, secret, { expiresIn: '15m' });",
31
- 'Load a high-entropy >= 256-bit secret from environment or KMS instead of a weak literal.',
32
- ],
33
- 'graphql-batching-unbounded': [
34
- 'const server = new ApolloServer({\n typeDefs,\n resolvers,\n allowBatchedHttpRequests: true,\n validationRules: [depthLimit(5)],\n});',
35
- 'Enforce a batch size, query depth, or complexity limit whenever GraphQL batching is enabled.',
36
- ],
37
- 'express-cookie-auth-missing-csrf': [
38
- "app.use(cookieParser());\napp.use(doubleCsrfProtection);\napp.post('/transfer', (req, res) => res.send('ok'));",
39
- 'Enable CSRF middleware or `sameSite: "strict"` cookies for state-changing routes using cookie auth.',
40
- ],
41
36
  };
42
37
  const examples = {
43
- ...moved_cjs_1.default,
44
- ...injection_cjs_1.default,
45
- ...request_forgery_cjs_1.default,
46
- ...auth_crypto_cjs_1.default,
47
- ...exposure_cjs_1.default,
48
- ...deps_cjs_1.default,
49
- ...files_cjs_1.default,
38
+ ...movedModule.default,
39
+ ...injectionModule.default,
40
+ ...requestForgeryModule.default,
41
+ ...authCryptoModule.default,
42
+ ...exposureModule.default,
43
+ ...depsModule.default,
44
+ ...filesModule.default,
50
45
  ...phase5Examples,
51
46
  };
52
47
  function exampleFor(ruleId, languageId) {
@@ -57,3 +52,4 @@ function exampleFor(ruleId, languageId) {
57
52
  const [code, note] = examples[ruleId];
58
53
  return { language: languageId.startsWith('typescript') ? 'typescript' : 'javascript', code, note };
59
54
  }
55
+ export { exampleFor };
@@ -0,0 +1,232 @@
1
+ // The workspace/executeCommand handlers. Arguments come back from the editor, so each one is checked
2
+ // again before it touches a file.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { commands } from './actions.js';
6
+ import { bulkFixesFor, fixAllEdit, fixEdit, missingFolders } from './fix-edits.js';
7
+ import { isRealPathInside } from './workspace-paths.js';
8
+ import { errorCode, errorMessage } from '../shared/error-code.js';
9
+ import { isRecord } from '../shared/is-record.js';
10
+ // A message request shows one button per entry, so long lists offer Restore all and the first few.
11
+ const maxRestoreButtons = 10;
12
+ function changeArgument(context, value) {
13
+ if (!isRecord(value))
14
+ return;
15
+ const { file, filename, line, before, after, create } = value;
16
+ if (typeof file !== 'string' || typeof filename !== 'string' || !path.isAbsolute(filename))
17
+ return;
18
+ if (typeof before !== 'string' || typeof after !== 'string')
19
+ return;
20
+ if (typeof line !== 'number' || !Number.isSafeInteger(line) || line < 1)
21
+ return;
22
+ const folder = context.folderFor(filename);
23
+ if (!folder || !isRealPathInside(folder.root, filename))
24
+ return;
25
+ return { file, filename, line, before, after, ...(create === true ? { create: true } : {}) };
26
+ }
27
+ function fixArgument(context, value) {
28
+ if (!isRecord(value) || !Array.isArray(value.changes) || !value.changes.length)
29
+ return;
30
+ const changes = [];
31
+ for (const item of value.changes) {
32
+ const change = changeArgument(context, item);
33
+ if (!change)
34
+ return;
35
+ changes.push(change);
36
+ }
37
+ return {
38
+ changes,
39
+ note: typeof value.note === 'string' ? value.note : undefined,
40
+ requiresReview: value.requiresReview === true,
41
+ };
42
+ }
43
+ function dismissalArgument(context, value) {
44
+ if (!isRecord(value) || typeof value.file !== 'string' || typeof value.ruleId !== 'string')
45
+ return;
46
+ if (!path.isAbsolute(value.file))
47
+ return;
48
+ const folder = context.folderFor(value.file);
49
+ if (!folder)
50
+ return;
51
+ const entry = { file: value.file, ruleId: value.ruleId };
52
+ if (typeof value.lineText === 'string')
53
+ entry.lineText = value.lineText;
54
+ return { folder, entry };
55
+ }
56
+ // Returns the folders it made, so a rejected edit leaves none behind.
57
+ function makeFolders(folders) {
58
+ const made = [];
59
+ try {
60
+ for (const folder of folders) {
61
+ try {
62
+ fs.mkdirSync(folder);
63
+ made.push(folder);
64
+ }
65
+ catch (error) {
66
+ if (errorCode(error) !== 'EEXIST')
67
+ throw error;
68
+ }
69
+ }
70
+ }
71
+ catch (error) {
72
+ removeEmptyFolders(made);
73
+ throw error;
74
+ }
75
+ return made;
76
+ }
77
+ function removeEmptyFolders(folders) {
78
+ for (const folder of folders.toReversed()) {
79
+ try {
80
+ fs.rmdirSync(folder);
81
+ }
82
+ catch {
83
+ // The editor wrote into it after all; the folder stays with its files.
84
+ }
85
+ }
86
+ }
87
+ // Only a transactional editor guarantees a rollback; `undo` is an attempt. A failure at the first
88
+ // operation ran nothing before it, while a missing index says nothing either way.
89
+ function mayBePartlyApplied(context, edit, failedChange) {
90
+ const operations = edit.documentChanges?.length ?? Object.keys(edit.changes ?? {}).length;
91
+ if (operations < 2 || failedChange === 0)
92
+ return false;
93
+ const createsFiles = edit.documentChanges?.some((change) => 'kind' in change) ?? false;
94
+ const { failureHandling } = context.fixWorkspace();
95
+ if (failureHandling === 'transactional')
96
+ return false;
97
+ return failureHandling !== 'textOnlyTransactional' || createsFiles;
98
+ }
99
+ async function applyEdit(context, { edit, createdFiles }, failure) {
100
+ const { window } = context.connection;
101
+ let made;
102
+ try {
103
+ made = makeFolders(missingFolders(createdFiles));
104
+ }
105
+ catch (error) {
106
+ window.showWarningMessage(failure + ' ' + errorMessage(error));
107
+ return false;
108
+ }
109
+ let result = { applied: false };
110
+ try {
111
+ result = await context.connection.workspace.applyEdit({ label: 'Loadwise', edit });
112
+ }
113
+ finally {
114
+ if (!result.applied)
115
+ removeEmptyFolders(made);
116
+ }
117
+ if (result.applied)
118
+ return true;
119
+ const partial = mayBePartlyApplied(context, edit, result.failedChange)
120
+ ? ' The editor may have kept changes made before the failure; undo them or check the files the fix names.'
121
+ : '';
122
+ window.showWarningMessage(failure + partial);
123
+ return false;
124
+ }
125
+ async function applyFix(context, value) {
126
+ const fix = fixArgument(context, value);
127
+ if (!fix)
128
+ return context.connection.window.showWarningMessage('Loadwise could not read this fix.');
129
+ const result = fixEdit(fix, context.fixWorkspace());
130
+ if (result.edit === undefined)
131
+ return context.connection.window.showWarningMessage(result.error);
132
+ await applyEdit(context, result, 'Loadwise could not apply the fix.');
133
+ }
134
+ async function applyAllFixes(context, value) {
135
+ const { window } = context.connection;
136
+ const { eligible, reviewCount } = bulkFixesFor(typeof value === 'string' ? context.entriesFor(value) : []);
137
+ if (!eligible.length && !reviewCount)
138
+ return window.showInformationMessage('Loadwise has no fixes for this file.');
139
+ const planned = fixAllEdit(eligible, context.fixWorkspace());
140
+ const { applied, skipped } = planned;
141
+ if (applied && !(await applyEdit(context, planned, 'Loadwise could not apply the selected fixes.')))
142
+ return;
143
+ const summary = 'Loadwise applied ' + applied + ' fix(es)';
144
+ const reviewNote = reviewCount ? ' ' + reviewCount + ' fix(es) require individual review.' : '';
145
+ if (!skipped)
146
+ window.showInformationMessage(summary + '.' + reviewNote);
147
+ else
148
+ window.showWarningMessage(summary + '; skipped ' + skipped + ' stale, overlapping or existing-file fix(es).' + reviewNote);
149
+ }
150
+ // A dismissal file that cannot be read or written is left alone, and the editor says why.
151
+ async function saveDismissals(context, save) {
152
+ try {
153
+ await save();
154
+ return true;
155
+ }
156
+ catch (error) {
157
+ context.connection.window.showErrorMessage('Loadwise could not update the dismissed findings: ' + errorMessage(error));
158
+ return false;
159
+ }
160
+ }
161
+ async function dismiss(context, value) {
162
+ const target = dismissalArgument(context, value);
163
+ if (!target)
164
+ return;
165
+ if (await saveDismissals(context, () => target.folder.dismissals.add(target.entry)))
166
+ context.republish(target.folder);
167
+ }
168
+ function allDismissed(context) {
169
+ return [...context.folders()].flatMap((folder) => folder.dismissals.entries().map((entry) => ({ folder, entry })));
170
+ }
171
+ async function restore(context, restored) {
172
+ const byFolder = new Map();
173
+ for (const { folder, entry } of restored)
174
+ byFolder.set(folder, [...(byFolder.get(folder) ?? []), entry]);
175
+ for (const [folder, entries] of byFolder) {
176
+ if (await saveDismissals(context, () => folder.dismissals.remove(entries)))
177
+ context.republish(folder);
178
+ }
179
+ }
180
+ function describe({ folder, entry }, index) {
181
+ const file = path.relative(folder.root, entry.file).split(path.sep).join('/');
182
+ const line = typeof entry.lineText === 'string' ? entry.lineText || '(blank line)' : 'Whole file';
183
+ return index + 1 + '. ' + entry.ruleId + ' — ' + file + ' — ' + line;
184
+ }
185
+ async function showDismissed(context) {
186
+ const { window } = context.connection;
187
+ const dismissed = allDismissed(context);
188
+ if (!dismissed.length)
189
+ return window.showInformationMessage('No Loadwise findings are dismissed.');
190
+ const restoreAll = { title: 'Restore all (' + dismissed.length + ')' };
191
+ const restoreOne = dismissed.slice(0, maxRestoreButtons).map((_item, index) => ({ title: 'Restore ' + (index + 1) }));
192
+ const message = ['Dismissed Loadwise findings:', ...dismissed.map(describe)].join('\n');
193
+ const picked = await window.showInformationMessage(message, restoreAll, ...restoreOne);
194
+ if (!picked)
195
+ return;
196
+ if (picked === restoreAll || picked.title === restoreAll.title)
197
+ return restore(context, dismissed);
198
+ const index = restoreOne.findIndex((action) => action.title === picked.title);
199
+ if (index !== -1)
200
+ await restore(context, [dismissed[index]]);
201
+ }
202
+ // With a dismissal entry it restores that one; without arguments it restores every dismissal.
203
+ async function restoreDismissed(context, value) {
204
+ if (value === undefined)
205
+ return restore(context, allDismissed(context));
206
+ const target = dismissalArgument(context, value);
207
+ if (target)
208
+ await restore(context, [target]);
209
+ }
210
+ async function scanAll(context) {
211
+ for (const folder of context.folders())
212
+ await folder.session.scanNow();
213
+ }
214
+ function runCommand(context, command, commandArguments) {
215
+ const [argument] = commandArguments;
216
+ switch (command) {
217
+ case commands.scan:
218
+ return scanAll(context);
219
+ case commands.applyFix:
220
+ return applyFix(context, argument);
221
+ case commands.applyAllFixes:
222
+ return applyAllFixes(context, argument);
223
+ case commands.dismiss:
224
+ return dismiss(context, argument);
225
+ case commands.showDismissed:
226
+ return showDismissed(context);
227
+ case commands.restoreDismissed:
228
+ return restoreDismissed(context, argument);
229
+ }
230
+ return Promise.reject(new Error('Unknown Loadwise command: ' + command));
231
+ }
232
+ export { runCommand };
@@ -1,7 +1,4 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.sourceExampleFor = sourceExampleFor;
4
- const perf_site_comparison_cjs_1 = require("./perf-site-comparison.cjs");
1
+ import { perfSiteComparison } from './perf-site-comparison.js';
5
2
  const scriptLanguages = new Set(['javascript', 'javascriptreact', 'typescript', 'typescriptreact']);
6
3
  // An omitted semicolon can continue the expression on the next line.
7
4
  const membershipExpression = /^\s*(return\s+)?(!?)\s*([$A-Z_a-z][$\w]*)\.(every|some)\(\s*(\()?([$A-Z_a-z][$\w]*)(\))?\s*=>\s*([$A-Z_a-z][$\w]*(?:\.[$A-Z_a-z][$\w]*)?)\.includes\(\s*([$A-Z_a-z][$\w]*)\s*\)\s*\);\s*$/;
@@ -13,7 +10,7 @@ function sourceExampleFor(document, diagnostic) {
13
10
  return;
14
11
  const line = document.lineAt(position.line).text;
15
12
  if (diagnostic.code !== 'array-repeated-membership') {
16
- const site = (0, perf_site_comparison_cjs_1.perfSiteComparison)(document, line, diagnostic);
13
+ const site = perfSiteComparison(document, line, diagnostic);
17
14
  return site && { ...site, language: document.languageId.startsWith('typescript') ? 'typescript' : 'javascript' };
18
15
  }
19
16
  if (diagnostic.message?.startsWith('This array was copied from a Set'))
@@ -64,3 +61,4 @@ function sourceExampleFor(document, diagnostic) {
64
61
  code: `let ${name} = ${alternative};\nif (!${name} && ${values}.length > 0) {\n ${build}\n ${name} = ${check}\n}`,
65
62
  };
66
63
  }
64
+ export { sourceExampleFor };