loadwise 0.5.0 → 0.6.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.
- package/README.md +543 -628
- package/bin/loadwise.js +5 -1
- package/lib/accessibility/frontend-detect.js +2 -1
- package/lib/accessibility/rule-ids.js +12 -9
- package/lib/accessibility/template-attributes.js +4 -2
- package/{editor/accessibility-examples.cjs → lib/editor/accessibility-examples.js} +20 -21
- package/lib/editor/actions.js +117 -0
- package/{editor/apply-fix.cjs → lib/editor/apply-fix.js} +1 -6
- package/{editor/control-flow-comparison.cjs → lib/editor/control-flow-comparison.js} +1 -3
- package/lib/editor/diagnostics.js +365 -0
- package/lib/editor/dismissals.js +111 -0
- package/lib/editor/editor-document.js +99 -0
- package/{editor/finding-comparison.cjs → lib/editor/finding-comparison.js} +4 -7
- package/lib/editor/fix-edits.js +200 -0
- package/lib/editor/language-server.js +437 -0
- package/{editor/maintainability-examples.cjs → lib/editor/maintainability-examples.js} +1 -3
- package/{editor/perf-site-comparison.cjs → lib/editor/perf-site-comparison.js} +1 -3
- package/lib/editor/perf-watch.js +78 -0
- package/{editor/performance-examples.cjs → lib/editor/performance-examples.js} +129 -128
- package/{editor/reliability-examples.cjs → lib/editor/reliability-examples.js} +100 -41
- package/lib/editor/scan-session.js +334 -0
- package/{editor/security-examples.cjs → lib/editor/security-examples.js} +28 -32
- package/lib/editor/server-commands.js +232 -0
- package/{editor/source-example.cjs → lib/editor/source-example.js} +3 -5
- package/{editor/standalone-performance-examples.cjs → lib/editor/standalone-performance-examples.js} +349 -333
- package/lib/editor/types/dismissal.js +1 -0
- package/lib/editor/types/fix-example.js +1 -0
- package/lib/editor/types/source-document.js +1 -0
- package/lib/editor/workspace-files.js +78 -0
- package/lib/editor/workspace-paths.js +22 -0
- package/lib/maintainability/analyze-source.js +2 -0
- package/lib/maintainability/apply-fix.js +1 -1
- package/lib/maintainability/cli.js +1 -1
- package/lib/maintainability/examples.js +58 -41
- package/lib/maintainability/rule-ids.js +29 -14
- package/lib/maintainability/scan-changed.js +3 -0
- package/lib/maintainability/scan.js +13 -9
- package/lib/maintainability/tsconfig-strict.js +69 -0
- package/lib/maintainability/type-safety-hygiene.js +204 -0
- package/lib/performance/analyze.js +2 -0
- package/lib/performance/cli-arguments.js +0 -2
- package/lib/performance/cli-policy.js +17 -9
- package/lib/performance/cli-scan.js +10 -8
- package/lib/performance/cli.js +4 -23
- package/lib/performance/editor-signal.js +1 -1
- package/lib/performance/finding-text.js +3 -3
- package/lib/performance/fix-cli.js +1 -1
- package/lib/performance/frontend-perf.js +7 -0
- package/lib/performance/frontend-render-perf.js +200 -0
- package/lib/performance/llm-max-tokens.js +56 -0
- package/lib/performance/native.js +46 -26
- package/lib/performance/polyglot.js +22 -1
- package/lib/performance/pooling.js +38 -23
- package/lib/performance/projects.js +42 -21
- package/lib/performance/rule-ids.js +236 -222
- package/lib/performance/site-fixes/database.js +3 -1
- package/lib/performance/site-fixes/integrity.js +15 -1
- package/lib/performance/source-inputs.js +18 -6
- package/lib/performance/unscanned-javascript.js +66 -19
- package/lib/reliability/analyze.js +12 -0
- package/lib/reliability/child-process.js +106 -0
- package/lib/reliability/error-values.js +177 -0
- package/lib/reliability/pool-timeout.js +79 -0
- package/lib/reliability/react-bugs.js +602 -0
- package/lib/reliability/resource-leaks.js +3 -6
- package/lib/reliability/rule-ids.js +169 -127
- package/lib/reliability/switch-exhaustive.js +284 -0
- package/lib/reliability/uncaught-exception.js +223 -0
- package/lib/security/auth-crypto/rule-ids.js +3 -2
- package/lib/security/cli.js +6 -5
- package/lib/security/deps/rule-ids.js +1 -0
- package/lib/security/examples/auth-crypto.cjs +5 -4
- package/lib/security/examples/deps.cjs +1 -0
- package/lib/security/examples/exposure.cjs +55 -42
- package/lib/security/examples/files.cjs +1 -0
- package/lib/security/examples/injection.cjs +1 -0
- package/lib/security/examples/moved.cjs +5 -4
- package/lib/security/examples/request-forgery.cjs +1 -0
- package/lib/security/exposure/client-env.js +113 -0
- package/lib/security/exposure/frontend-security.js +12 -10
- package/lib/security/exposure/index.js +14 -3
- package/lib/security/exposure/jsx-url.js +267 -0
- package/lib/security/exposure/next-image-config.js +34 -0
- package/lib/security/exposure/package-manifest.js +45 -0
- package/lib/security/exposure/react-version.js +45 -0
- package/lib/security/exposure/rule-ids.js +16 -12
- package/lib/security/files/index.js +1 -1
- package/lib/security/files/rule-ids.js +1 -0
- package/lib/security/injection/code.js +24 -10
- package/lib/security/injection/command.js +81 -28
- package/lib/security/injection/nosql.js +109 -22
- package/lib/security/injection/redos.js +152 -308
- package/lib/security/injection/regex-pattern.js +290 -0
- package/lib/security/injection/regex.js +30 -11
- package/lib/security/injection/rule-ids.js +2 -1
- package/lib/security/injection/shared.js +19 -1
- package/lib/security/injection/sql.js +83 -2
- package/lib/security/request-forgery/rule-ids.js +1 -0
- package/lib/security/rule-descriptions.js +36 -32
- package/lib/security/rule-ids.js +74 -67
- package/lib/security/taint/filename-guard.js +3 -1
- package/lib/security/taint/guards.js +84 -10
- package/lib/security/taint/index.js +124 -13
- package/lib/security/taint/propagate.js +10 -7
- package/lib/security/taint/sanitizers.js +7 -3
- package/lib/security/taint/sources.js +6 -3
- package/lib/security/taint/summaries.js +13 -1
- package/lib/security/taint/url-parts.js +14 -5
- package/lib/shared/agent-session.js +2 -2
- package/lib/shared/check.js +16 -6
- package/lib/shared/explain.js +5 -5
- package/lib/shared/fix-convergence.js +1 -1
- package/lib/shared/formats/finding-location.js +6 -2
- package/lib/shared/formats/sarif.js +3 -3
- package/lib/shared/heap-limit.js +20 -3
- package/lib/shared/pillars.js +7 -7
- package/lib/shared/rule-docs.js +12 -0
- package/lib/shared/scan-cache.js +0 -1
- package/lib/shared/workspaces.js +31 -9
- package/package.json +12 -19
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/schema/loadwise.config.schema.json +44 -0
- package/editor/README.md +0 -47
- package/examples/redis-keys.otlp.json +0 -22
- package/lib/maintainability/notify-editor.js +0 -1
- package/lib/performance/editor-report.js +0 -191
- package/lib/performance/editor-setup.js +0 -189
- package/lib/performance/editor-watch-supervisor.js +0 -104
- package/lib/performance/editor-watch.js +0 -193
- package/lib/performance/notify-editor.js +0 -1
- package/lib/performance/recursive-watch.js +0 -181
- /package/lib/{performance/types/editor-report.js → editor/types/comparison.js} +0 -0
|
@@ -1,77 +1,136 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.exampleFor = exampleFor;
|
|
4
1
|
// Generic fix examples for the reliability rules the shared source pass reports outside the performance examples.
|
|
5
2
|
// The moved performance rules keep their examples in performance-examples.cts, which exampleFor consults first.
|
|
6
|
-
|
|
3
|
+
import { exampleFor as performanceExample } from './performance-examples.js';
|
|
4
|
+
// Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
|
|
7
5
|
const examples = {
|
|
8
|
-
'swallowed-error': {
|
|
9
|
-
before: 'try {\n await saveOrder(order);\n} catch {}\nnotifyCustomer(order);',
|
|
10
|
-
code: 'try {\n await saveOrder(order);\n} catch (error) {\n throw new OrderNotSavedError(order.id, { cause: error });\n}',
|
|
11
|
-
note: 'Handle, rethrow or report the error so the code after the try does not run as if it succeeded.',
|
|
12
|
-
},
|
|
13
|
-
'sql-insert-truncated-at-semicolon': {
|
|
14
|
-
before: 'const inserts = /INSERT INTO orders VALUES ([\\s\\S]*?);/gi;\nwhile ((match = inserts.exec(dump)) !== null) {\n const values = match[1]; // stops inside a quoted semicolon\n}',
|
|
15
|
-
code: '// Use your SQL dialect parser to read complete statements and literal values.\nfor (const insert of readInsertStatements(dump)) {\n importRows(insert.rows);\n}',
|
|
16
|
-
note: 'A semicolon inside a quoted value ends the regular expression match early and drops the rest of the row.',
|
|
17
|
-
},
|
|
18
|
-
'unguarded-boundary-access': {
|
|
19
|
-
before: 'const email = req.body.user.email;',
|
|
20
|
-
code: 'const email = req.body.user?.email;',
|
|
21
|
-
note: 'The read now yields undefined instead of throwing when user is missing. Add `?? default` or answer with a 400 when the input is required.',
|
|
22
|
-
},
|
|
23
6
|
'assignment-in-condition': {
|
|
24
7
|
before: 'if (user.role = "admin") {\n grantAccess(user);\n}',
|
|
25
8
|
code: 'if (user.role === "admin") {\n grantAccess(user);\n}',
|
|
26
9
|
note: 'Assigns instead of comparing; review that no later code needs the assigned value.',
|
|
27
10
|
},
|
|
28
|
-
'
|
|
29
|
-
before: '
|
|
30
|
-
code: '
|
|
31
|
-
note: '
|
|
11
|
+
'browser-not-closed': {
|
|
12
|
+
before: 'const browser = await chromium.launch();\nawait run(browser);\nawait browser.close();',
|
|
13
|
+
code: 'const browser = await chromium.launch();\ntry {\n await run(browser);\n} finally {\n await browser.close();\n}',
|
|
14
|
+
note: 'A failed run leaves the browser process running.',
|
|
15
|
+
},
|
|
16
|
+
'child-process-without-error-listener': {
|
|
17
|
+
before: "const child = spawn('convert', [input, output]);",
|
|
18
|
+
code: "const child = spawn('convert', [input, output]);\nchild.on('error', (error) => {\n logger.error({ err: error }, 'convert failed to start');\n});",
|
|
19
|
+
note: "Without an 'error' listener a failed spawn throws an uncaught exception and crashes the process.",
|
|
20
|
+
},
|
|
21
|
+
'error-logged-without-stack': {
|
|
22
|
+
before: 'try {\n await sync();\n} catch (error) {\n logger.error(error.message);\n}',
|
|
23
|
+
code: "try {\n await sync();\n} catch (error) {\n logger.error({ err: error }, 'sync failed');\n}",
|
|
24
|
+
note: 'Pass the error itself so the logger records the stack.',
|
|
25
|
+
},
|
|
26
|
+
'error-rethrown-without-cause': {
|
|
27
|
+
before: "try {\n await saveOrder(order);\n} catch (error) {\n throw new Error('Order not saved');\n}",
|
|
28
|
+
code: "try {\n await saveOrder(order);\n} catch (error) {\n throw new Error('Order not saved', { cause: error });\n}",
|
|
29
|
+
note: 'The cause keeps the original message and stack reachable.',
|
|
30
|
+
},
|
|
31
|
+
'file-handle-not-closed': {
|
|
32
|
+
before: 'const handle = await open(path);\nawait handle.stat();\nawait handle.close();',
|
|
33
|
+
code: 'const handle = await open(path);\ntry {\n await handle.stat();\n} finally {\n await handle.close();\n}',
|
|
34
|
+
note: 'An error before close() leaks the file descriptor.',
|
|
35
|
+
},
|
|
36
|
+
'interval-not-cleared': {
|
|
37
|
+
before: 'function start() {\n setInterval(poll, 1000);\n}',
|
|
38
|
+
code: 'function start() {\n const timer = setInterval(poll, 1000);\n return () => clearInterval(timer);\n}',
|
|
39
|
+
note: 'Keep the handle so the owner can stop the timer.',
|
|
32
40
|
},
|
|
33
41
|
'invalid-typeof-comparison': {
|
|
34
42
|
before: 'if (typeof value === "strnig") {\n value = value.trim();\n}',
|
|
35
43
|
code: 'if (typeof value === "string") {\n value = value.trim();\n}',
|
|
36
44
|
note: "'strnig' looks like a misspelling of 'string', so the branch never ran.",
|
|
37
45
|
},
|
|
38
|
-
'unreachable-code': {
|
|
39
|
-
before: 'function total(items) {\n return sum(items);\n cleanup();\n}',
|
|
40
|
-
code: 'function total(items) {\n return sum(items);\n}',
|
|
41
|
-
note: 'The statements after the exit are deleted; review that nothing there was needed.',
|
|
42
|
-
},
|
|
43
46
|
'loop-index-past-length': {
|
|
44
47
|
before: 'for (let i = 0; i <= items.length; i++) {\n use(items[i]);\n}',
|
|
45
48
|
code: 'for (let i = 0; i < items.length; i++) {\n use(items[i]);\n}',
|
|
46
49
|
note: 'Valid indexes stop at length - 1.',
|
|
47
50
|
},
|
|
48
|
-
'
|
|
49
|
-
before: '
|
|
50
|
-
code: '
|
|
51
|
-
note: '
|
|
51
|
+
'nan-comparison': {
|
|
52
|
+
before: 'if (value === NaN) {\n value = 0;\n}',
|
|
53
|
+
code: 'if (Number.isNaN(value)) {\n value = 0;\n}',
|
|
54
|
+
note: 'NaN is never equal to anything, itself included.',
|
|
55
|
+
},
|
|
56
|
+
'next-server-env-in-client': {
|
|
57
|
+
before: "'use client';\nconst url = process.env.API_URL;",
|
|
58
|
+
code: "'use client';\nconst url = process.env.NEXT_PUBLIC_API_URL;",
|
|
59
|
+
note: 'Next.js only inlines NEXT_PUBLIC_ variables into the browser bundle.',
|
|
60
|
+
},
|
|
61
|
+
'pool-without-connection-timeout': {
|
|
62
|
+
before: 'const pool = new Pool({ connectionString });',
|
|
63
|
+
code: 'const pool = new Pool({ connectionString, connectionTimeoutMillis: 5000 });',
|
|
64
|
+
note: 'The default of 0 waits forever for a connection; pick a timeout that suits your slowest healthy checkout.',
|
|
52
65
|
},
|
|
53
66
|
'query-runner-not-released': {
|
|
54
67
|
before: 'const runner = dataSource.createQueryRunner();\nawait runner.connect();',
|
|
55
68
|
code: 'const runner = dataSource.createQueryRunner();\ntry {\n await runner.connect();\n} finally {\n await runner.release();\n}',
|
|
56
69
|
note: 'An unreleased runner holds a pooled connection.',
|
|
57
70
|
},
|
|
58
|
-
'
|
|
59
|
-
before: '
|
|
60
|
-
code: '
|
|
61
|
-
note: '
|
|
71
|
+
'react-async-effect-callback': {
|
|
72
|
+
before: 'useEffect(async () => {\n await load();\n}, []);',
|
|
73
|
+
code: 'useEffect(() => {\n load().catch(reportError);\n}, []);',
|
|
74
|
+
note: 'The effect callback must return nothing or a cleanup function, not a promise.',
|
|
62
75
|
},
|
|
63
|
-
'
|
|
64
|
-
before: '
|
|
65
|
-
code: '
|
|
66
|
-
note: '
|
|
76
|
+
'react-effect-sets-state-every-render': {
|
|
77
|
+
before: 'useEffect(() => {\n setItems([...items, next]);\n});',
|
|
78
|
+
code: 'useEffect(() => {\n setItems((previous) => [...previous, next]);\n}, [next]);',
|
|
79
|
+
note: 'Without a dependency array the effect runs after every render, and each run renders again. Keep `next` stable (a primitive or memoised value) or the loop continues.',
|
|
80
|
+
},
|
|
81
|
+
'react-list-missing-key': {
|
|
82
|
+
before: 'rows.map((row) => <li>{row.name}</li>)',
|
|
83
|
+
code: 'rows.map((row) => <li key={row.id}>{row.name}</li>)',
|
|
84
|
+
note: 'A stable key lets React match items between renders.',
|
|
85
|
+
},
|
|
86
|
+
'react-state-mutated-in-place': {
|
|
87
|
+
before: 'items.push(item);\nsetItems(items);',
|
|
88
|
+
code: 'setItems([...items, item]);',
|
|
89
|
+
note: 'React skips the render when the setter receives the same reference.',
|
|
90
|
+
},
|
|
91
|
+
'sql-insert-truncated-at-semicolon': {
|
|
92
|
+
before: 'const inserts = /INSERT INTO orders VALUES ([\\s\\S]*?);/gi;\nwhile ((match = inserts.exec(dump)) !== null) {\n const values = match[1]; // stops inside a quoted semicolon\n}',
|
|
93
|
+
code: '// Use your SQL dialect parser to read complete statements and literal values.\nfor (const insert of readInsertStatements(dump)) {\n importRows(insert.rows);\n}',
|
|
94
|
+
note: 'A semicolon inside a quoted value ends the regular expression match early and drops the rest of the row.',
|
|
95
|
+
},
|
|
96
|
+
'swallowed-error': {
|
|
97
|
+
before: 'try {\n await saveOrder(order);\n} catch {}\nnotifyCustomer(order);',
|
|
98
|
+
code: 'try {\n await saveOrder(order);\n} catch (error) {\n throw new OrderNotSavedError(order.id, { cause: error });\n}',
|
|
99
|
+
note: 'Handle, rethrow or report the error so the code after the try does not run as if it succeeded.',
|
|
100
|
+
},
|
|
101
|
+
'switch-not-exhaustive': {
|
|
102
|
+
before: 'switch (status) {\n case "paid": return 1;\n case "open": return 2;\n}',
|
|
103
|
+
code: 'switch (status) {\n case "paid": return 1;\n case "open": return 2;\n default: throw new Error(status);\n}',
|
|
104
|
+
note: 'Add the missing cases, or a default that throws so a new member cannot fall through unnoticed.',
|
|
105
|
+
},
|
|
106
|
+
'throw-non-error': {
|
|
107
|
+
before: "throw 'order not found';",
|
|
108
|
+
code: "throw new Error('order not found');",
|
|
109
|
+
note: 'An Error carries a stack trace; a thrown string or object does not.',
|
|
110
|
+
},
|
|
111
|
+
'uncaught-exception-continues': {
|
|
112
|
+
before: "process.on('uncaughtException', (error) => {\n logger.error(error);\n});",
|
|
113
|
+
code: "process.on('uncaughtException', (error) => {\n logger.error(error);\n logger.flush(() => process.exit(1));\n});",
|
|
114
|
+
note: 'The process is in an unknown state after an uncaught exception; flush logs, then exit non-zero.',
|
|
115
|
+
},
|
|
116
|
+
'unguarded-boundary-access': {
|
|
117
|
+
before: 'const email = req.body.user.email;',
|
|
118
|
+
code: 'const email = req.body.user?.email;',
|
|
119
|
+
note: 'The read now yields undefined instead of throwing when user is missing. Add `?? default` or answer with a 400 when the input is required.',
|
|
120
|
+
},
|
|
121
|
+
'unreachable-code': {
|
|
122
|
+
before: 'function total(items) {\n return sum(items);\n cleanup();\n}',
|
|
123
|
+
code: 'function total(items) {\n return sum(items);\n}',
|
|
124
|
+
note: 'The statements after the exit are deleted; review that nothing there was needed.',
|
|
67
125
|
},
|
|
68
126
|
};
|
|
69
127
|
const scriptLanguages = ['javascript', 'javascriptreact', 'typescript', 'typescriptreact'];
|
|
70
128
|
function exampleFor(ruleId, languageId, message = '') {
|
|
71
129
|
if (!Object.hasOwn(examples, ruleId))
|
|
72
|
-
return (
|
|
130
|
+
return performanceExample(ruleId, languageId, message);
|
|
73
131
|
if (!scriptLanguages.includes(languageId))
|
|
74
132
|
return;
|
|
75
133
|
const { before, code, note } = examples[ruleId];
|
|
76
134
|
return { language: languageId.startsWith('typescript') ? 'typescript' : 'javascript', before, code, note };
|
|
77
135
|
}
|
|
136
|
+
export { exampleFor };
|
|
@@ -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
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
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
|
-
...
|
|
44
|
-
...
|
|
45
|
-
...
|
|
46
|
-
...
|
|
47
|
-
...
|
|
48
|
-
...
|
|
49
|
-
...
|
|
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 };
|