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,501 @@
1
+ // Web server configuration checks for Nginx (nginx.conf, *.conf under nginx/ or conf.d/) and Apache
2
+ // (httpd.conf, apache2.conf, .htaccess). Directive names of the two servers do not overlap, so
3
+ // every candidate file is read with both grammars.
4
+ import { checkConfiguredHeaders } from './http-headers.js';
5
+ import { normalizeSlashes } from '../../shared/system/posix-path.js';
6
+ const directoryListingRule = 'web-server-directory-listing';
7
+ const versionRule = 'web-server-version-exposed';
8
+ const legacyTlsRule = 'web-server-legacy-tls';
9
+ const proxyHostRule = 'nginx-proxy-pass-request-host';
10
+ const configName = /(?:^|\/)(?:(?:nginx|httpd|apache2?)(?:\.[\w-]+)*\.conf(?:\.template)?|\.htaccess)$/i;
11
+ const configFolderFile = /(?:^|\/)(?:nginx|conf\.d|sites-(?:available|enabled)|apache2?|httpd)\/(?:[^/]+\/)*[^/]+\.conf(?:\.template)?$/i;
12
+ const legacyProtocols = new Set(['sslv2', 'sslv3', 'tlsv1', 'tlsv1.1']);
13
+ // Nginx variables that hold request text: headers, query arguments, cookies, and the Host value
14
+ // ($hostname, the machine's own name, is not one of them).
15
+ const requestVariable = /^\$\{?(host|http_\w+|arg_\w+|cookie_\w+)(?!\w)\}?/i;
16
+ const proxyTarget = /^(?:(?:[a-z]+|\$\{?scheme\}?):\/\/)?/i;
17
+ const regexCapture = /^\$\{?([1-9])\}?(?=$|[/:$?])/;
18
+ const literalServerName = /^[a-z0-9-]+(?:\.[a-z0-9-]+)+$/i;
19
+ const exposingServerTokens = new Set(['full', 'os', 'min', 'minor', 'minimal']);
20
+ // Real configurations nest a few levels; deeper braces are not tracked as blocks.
21
+ const maxBlockDepth = 64;
22
+ // Nginx separates words with ASCII whitespace only; the line break is handled on its own.
23
+ const asciiSpace = new Set([' ', '\t', '\r', '\f', '\v']);
24
+ const apacheDirectives = new Set(['options', 'servertokens', 'sslprotocol', 'header']);
25
+ const apacheHeaderActions = new Set(['set', 'add', 'append', 'merge']);
26
+ const originVariable = /^\$\{?http_origin\}?$/i;
27
+ // Origin regex checks: an alternative starting at the scheme cannot match inside another origin,
28
+ // and a `.*` or `.+` not followed by `\.` lets any text complete the host (`evilexample.com`,
29
+ // or every origin for `^https://.*$`). A leading inline option such as `(?i)` is skipped.
30
+ const inlineOptions = /^\(\?[a-z]+\)/i;
31
+ const startsWithScheme = /^\(?https?/i;
32
+ const endAnchor = /(?<!\\)\$$/;
33
+ const hostWildcard = /(?<!\\)\.[*+](?!\\\.)/;
34
+ // Map entries that configure the map instead of matching a value.
35
+ const mapParameters = new Set(['hostnames', 'volatile', 'include']);
36
+ function isWebServerConfig(file) {
37
+ const normalized = normalizeSlashes(file);
38
+ return configName.test(normalized) || configFolderFile.test(normalized);
39
+ }
40
+ function childOf(block, name, args, line, column) {
41
+ return {
42
+ name,
43
+ args,
44
+ line,
45
+ column,
46
+ parent: block,
47
+ children: [],
48
+ server: block.name === 'server' ? block : block.server,
49
+ location: block.name === 'location' ? block : block.location,
50
+ };
51
+ }
52
+ // Reads Nginx words, directives and blocks in one pass; quotes, `#` comments and `${var}` are
53
+ // honoured, and an unbalanced `}` is ignored.
54
+ class NginxReader {
55
+ text;
56
+ root = { name: '', args: [], line: 0, column: 0, children: [] };
57
+ block = this.root;
58
+ depth = 0;
59
+ // Braces past maxBlockDepth, read as plain statement ends so they cost no block objects.
60
+ flattenedBlocks = 0;
61
+ words = [];
62
+ start;
63
+ word = '';
64
+ inWord = false;
65
+ line = 1;
66
+ lineStart = 0;
67
+ constructor(text) {
68
+ this.text = text;
69
+ }
70
+ read() {
71
+ for (let index = 0; index < this.text.length; index++)
72
+ index = this.readAt(index);
73
+ return this.root;
74
+ }
75
+ // Handles the character at index and returns the index of the last character it consumed.
76
+ readAt(index) {
77
+ const char = this.text[index];
78
+ if (char === '\n') {
79
+ this.endWord();
80
+ this.newLine(index);
81
+ }
82
+ else if (char === '"' || char === "'")
83
+ return this.readQuoted(index, char);
84
+ else if (char === '#' && !this.inWord)
85
+ return this.lineEnd(index);
86
+ else if (char === ';')
87
+ this.endStatement(false);
88
+ else if (char === '{' && !(this.inWord && this.word.endsWith('$')))
89
+ this.endStatement(true);
90
+ else if (char === '}')
91
+ this.closeBlock();
92
+ else if (asciiSpace.has(char))
93
+ this.endWord();
94
+ else
95
+ return this.readWordCharacter(index, char);
96
+ return index;
97
+ }
98
+ newLine(index) {
99
+ this.line++;
100
+ this.lineStart = index + 1;
101
+ }
102
+ lineEnd(index) {
103
+ const end = this.text.indexOf('\n', index);
104
+ return end === -1 ? this.text.length - 1 : end - 1;
105
+ }
106
+ readQuoted(index, quote) {
107
+ this.beginWord(index);
108
+ let cursor = index + 1;
109
+ for (; cursor < this.text.length && this.text[cursor] !== quote; cursor++) {
110
+ // Nginx drops the backslash only before a quote or a backslash; regexes keep `\.` as written.
111
+ if (this.text[cursor] === '\\' && (this.text[cursor + 1] === quote || this.text[cursor + 1] === '\\'))
112
+ cursor++;
113
+ if (this.text[cursor] === '\n')
114
+ this.newLine(cursor);
115
+ this.word += this.text[cursor];
116
+ }
117
+ return cursor;
118
+ }
119
+ readWordCharacter(index, char) {
120
+ this.beginWord(index);
121
+ this.word += char;
122
+ if (char !== '{')
123
+ return index;
124
+ // `${name}` stays one word.
125
+ let cursor = index + 1;
126
+ while (cursor < this.text.length && this.text[cursor] !== '}' && this.text[cursor] !== '\n')
127
+ cursor++;
128
+ this.word += this.text.slice(index + 1, cursor);
129
+ if (this.text[cursor] === '}')
130
+ this.word += '}';
131
+ return cursor;
132
+ }
133
+ endWord() {
134
+ if (this.inWord)
135
+ this.words.push(this.word);
136
+ this.word = '';
137
+ this.inWord = false;
138
+ }
139
+ beginWord(index) {
140
+ if (!this.words.length && !this.inWord)
141
+ this.start = { line: this.line, column: index - this.lineStart + 1 };
142
+ this.inWord = true;
143
+ }
144
+ endStatement(requestsBlock) {
145
+ this.endWord();
146
+ const opensBlock = requestsBlock && this.depth < maxBlockDepth;
147
+ if (requestsBlock && !opensBlock)
148
+ this.flattenedBlocks++;
149
+ if (opensBlock)
150
+ this.depth++;
151
+ const [name, ...args] = this.words;
152
+ if (name !== undefined && this.start) {
153
+ const directive = childOf(this.block, name, args, this.start.line, this.start.column);
154
+ this.block.children.push(directive);
155
+ if (opensBlock)
156
+ this.block = directive;
157
+ }
158
+ else if (opensBlock) {
159
+ const anonymous = childOf(this.block, '', [], this.line, 1);
160
+ this.block.children.push(anonymous);
161
+ this.block = anonymous;
162
+ }
163
+ this.words = [];
164
+ this.start = undefined;
165
+ }
166
+ closeBlock() {
167
+ this.endStatement(false);
168
+ if (this.flattenedBlocks) {
169
+ this.flattenedBlocks--;
170
+ return;
171
+ }
172
+ if (this.block === this.root)
173
+ return;
174
+ this.depth--;
175
+ this.block = this.block.parent ?? this.root;
176
+ }
177
+ }
178
+ function parseNginx(text) {
179
+ return new NginxReader(text).read();
180
+ }
181
+ function directivesOf(root) {
182
+ const all = [];
183
+ const pending = [...root.children].reverse();
184
+ for (let directive = pending.pop(); directive; directive = pending.pop()) {
185
+ all.push(directive);
186
+ for (let index = directive.children.length - 1; index >= 0; index--)
187
+ pending.push(directive.children[index]);
188
+ }
189
+ return all;
190
+ }
191
+ // Only a server block that can receive arbitrary Host values (the default server, or one with a
192
+ // wildcard, regex or catch-all name) lets the client choose $host.
193
+ function hostReason(directive) {
194
+ const { server } = directive;
195
+ if (!server)
196
+ return undefined;
197
+ const names = server.children.filter(({ name }) => name === 'server_name').flatMap(({ args }) => args);
198
+ const isDefault = server.children.some(({ name, args }) => name === 'listen' && args.some((arg) => arg === 'default_server' || arg === 'default'));
199
+ if (isDefault || !names.length || !names.every((name) => literalServerName.test(name)))
200
+ return undefined;
201
+ return 'The server block matches only its listed server_name values unless it is the default server for its port.';
202
+ }
203
+ // A numbered capture of a regex location holds part of the request path, which the client chooses.
204
+ function pathCapture(directive, host) {
205
+ const capture = regexCapture.exec(host)?.[1];
206
+ const { location } = directive;
207
+ return capture && /^~\*?$/.test(location?.args[0] ?? '') ? capture : undefined;
208
+ }
209
+ function checkProxyPass(directive) {
210
+ const target = directive.args[0] ?? '';
211
+ const host = target.slice(proxyTarget.exec(target)?.[0].length ?? 0);
212
+ const variable = requestVariable.exec(host)?.[1] ?? pathCapture(directive, host);
213
+ if (!variable)
214
+ return undefined;
215
+ const fromHost = /^(?:host|http_host)$/i.test(variable);
216
+ const contextualReason = fromHost ? hostReason(directive) : undefined;
217
+ return {
218
+ ruleId: proxyHostRule,
219
+ line: directive.line,
220
+ column: directive.column,
221
+ ...(contextualReason && { contextualReason }),
222
+ message: `proxy_pass takes its upstream host from $${variable}, which the client sends, so Nginx can be made to forward requests to any host, including internal services. Proxy to a fixed upstream or a map of allowed hosts.`,
223
+ };
224
+ }
225
+ function variableName(word) {
226
+ return /^\$\{?(\w+)\}?$/.exec(word)?.[1].toLowerCase();
227
+ }
228
+ // The words of an `if` condition without the parentheses the reader keeps on the first and last.
229
+ function conditionWords(args) {
230
+ const words = args.map((arg, index) => {
231
+ const opened = index === 0 ? arg.replace(/^\(/, '') : arg;
232
+ return index === args.length - 1 ? opened.replace(/\)$/, '') : opened;
233
+ });
234
+ return words.filter(Boolean);
235
+ }
236
+ // The top-level alternatives of a regex, after removing one group around the whole pattern.
237
+ function regexBranches(regex, unwrap = true) {
238
+ const branches = [];
239
+ let depth = 0;
240
+ let inClass = false;
241
+ let start = 0;
242
+ let outerGroupEnd = -1;
243
+ for (let index = 0; index < regex.length; index++) {
244
+ const char = regex[index];
245
+ if (char === '\\')
246
+ index++;
247
+ else if (inClass)
248
+ inClass = char !== ']';
249
+ else if (char === '[')
250
+ inClass = true;
251
+ else if (char === '(')
252
+ depth++;
253
+ else if (char === ')' && --depth === 0 && regex[0] === '(' && outerGroupEnd < 0)
254
+ outerGroupEnd = index;
255
+ else if (char === '|' && depth === 0) {
256
+ branches.push(regex.slice(start, index));
257
+ start = index + 1;
258
+ }
259
+ }
260
+ if (unwrap && !branches.length && outerGroupEnd === regex.length - 1)
261
+ return regexBranches(regex.slice(1, -1), false);
262
+ branches.push(regex.slice(start));
263
+ return branches;
264
+ }
265
+ // True when every alternative ends with `$` and starts with `^` or a scheme, with no `.*` running
266
+ // into a host name, so `evil-example.com` and `example.com.evil.net` cannot match.
267
+ function isAnchoredOriginRegex(regex) {
268
+ return regexBranches(regex.replace(inlineOptions, '')).every((branch) => (branch.startsWith('^') || startsWithScheme.test(branch)) && endAnchor.test(branch) && !hostWildcard.test(branch));
269
+ }
270
+ // True for a test that passes only listed origins: $http_origin compared (or, negated, rejected)
271
+ // with `=` or an anchored regex.
272
+ function testsListedOrigins(words, negated) {
273
+ const [subject = '', operator = '', pattern = ''] = words;
274
+ if (!originVariable.test(subject) || !pattern || operator.startsWith('!') !== negated)
275
+ return false;
276
+ const comparison = operator.replace(/^!/, '');
277
+ return comparison === '=' || (/^~\*?$/.test(comparison) && isAnchoredOriginRegex(pattern));
278
+ }
279
+ // A map from $http_origin reflects any origin when a default or unanchored entry copies
280
+ // $http_origin, and is a trusted check when every such entry yields an empty value or 0.
281
+ function classifyOriginMap(map, variables) {
282
+ const target = variableName(map.args[1] ?? '');
283
+ if (!target)
284
+ return;
285
+ const unlisted = map.children.filter(({ name }) => {
286
+ if (mapParameters.has(name))
287
+ return false;
288
+ const regex = /^~\*?(.*)$/s.exec(name)?.[1];
289
+ return name === 'default' || (regex !== undefined && !isAnchoredOriginRegex(regex));
290
+ });
291
+ const values = unlisted.flatMap(({ args }) => args);
292
+ if (values.some((value) => originVariable.test(value)))
293
+ variables.reflecting.add(target);
294
+ else if (values.every((value) => value === '' || value === '0'))
295
+ variables.trusted.add(target);
296
+ }
297
+ // True when a value the flag gets for any origin passes the `if` test: `= value` matches it, and a
298
+ // plain test passes anything but empty and 0. Other comparisons are not modelled.
299
+ function passesElsewhere([flag = '', operator, pattern], elsewhere) {
300
+ const name = variableName(flag) ?? '';
301
+ if (operator === '=')
302
+ return elsewhere.values.get(name)?.has(pattern ?? '') ?? false;
303
+ return operator === undefined && elsewhere.truthy.has(name);
304
+ }
305
+ // Blocks where only listed origins arrive: inside an `if` that matches them, or one that tests a
306
+ // trusted variable, and blocks holding an `if` that returns for every other origin. A variable
307
+ // set inside such a block becomes trusted. A value it is also set to elsewhere reaches every origin,
308
+ // so a test that this value (or, for a plain test, any value but empty and 0) passes is not
309
+ // trusted. A `set` in an outer block runs before a nested `if` wherever it is written, so the
310
+ // values a first pass finds are applied again in a second one.
311
+ function listedOriginBlocks(directives, variables) {
312
+ const guarded = new Set();
313
+ for (const directive of directives) {
314
+ const words = directive.name === 'if' ? conditionWords(directive.args) : [];
315
+ const returns = directive.children.some(({ name }) => name === 'return');
316
+ if (returns && testsListedOrigins(words, true))
317
+ guarded.add(directive.parent);
318
+ }
319
+ const first = flagPass(directives, variables, guarded, { values: new Map(), truthy: new Set() });
320
+ return flagPass(directives, variables, guarded, first.elsewhere).blocks;
321
+ }
322
+ // One pass in document order, which reaches each block before its children.
323
+ function flagPass(directives, variables, guarded, known) {
324
+ const blocks = new Set(guarded);
325
+ const elsewhere = { values: new Map(), truthy: new Set() };
326
+ for (const directive of directives) {
327
+ const inListed = blocks.has(directive.parent);
328
+ const words = directive.name === 'if' ? conditionWords(directive.args) : [];
329
+ const tested = variableName(words[0] ?? '') ?? '';
330
+ const testsTrusted = variables.trusted.has(tested) && !passesElsewhere(words, known) && !passesElsewhere(words, elsewhere);
331
+ if (inListed || testsListedOrigins(words, false) || testsTrusted)
332
+ blocks.add(directive);
333
+ const flag = directive.name === 'set' ? variableName(directive.args[0] ?? '') : undefined;
334
+ const value = directive.args[1] ?? '';
335
+ if (flag && inListed)
336
+ variables.trusted.add(flag);
337
+ else if (flag) {
338
+ elsewhere.values.set(flag, (elsewhere.values.get(flag) ?? new Set()).add(value));
339
+ if (value !== '' && value !== '0')
340
+ elsewhere.truthy.add(flag);
341
+ }
342
+ }
343
+ return { blocks, elsewhere };
344
+ }
345
+ function nginxHeaderFindings(directives) {
346
+ const variables = { reflecting: new Set(), trusted: new Set() };
347
+ for (const directive of directives)
348
+ if (directive.name === 'map' && originVariable.test(directive.args[0] ?? ''))
349
+ classifyOriginMap(directive, variables);
350
+ const listedOrigins = listedOriginBlocks(directives, variables);
351
+ const byBlock = new Map();
352
+ for (const directive of directives) {
353
+ if (directive.name !== 'add_header' || directive.args.length < 2)
354
+ continue;
355
+ const headers = byBlock.get(directive.parent) ?? [];
356
+ headers.push({ name: directive.args[0], value: directive.args[1], line: directive.line, column: directive.column });
357
+ byBlock.set(directive.parent, headers);
358
+ }
359
+ const reflects = (value) => originVariable.test(value) || variables.reflecting.has(variableName(value) ?? '');
360
+ return [...byBlock].flatMap(([block, headers]) => checkConfiguredHeaders(headers, (value) => !listedOrigins.has(block) && reflects(value)));
361
+ }
362
+ function checkNginx(text) {
363
+ const directives = directivesOf(parseNginx(text));
364
+ const findings = [];
365
+ for (const directive of directives) {
366
+ const { name, args, line, column } = directive;
367
+ const value = args[0]?.toLowerCase();
368
+ if (name === 'autoindex' && value === 'on') {
369
+ findings.push({
370
+ ruleId: directoryListingRule,
371
+ line,
372
+ column,
373
+ message: 'autoindex on lists every file in the served folder, including backups and files nobody linked to. Turn it off unless the folder is meant to be browsed.',
374
+ });
375
+ }
376
+ else if (name === 'server_tokens' && value === 'on') {
377
+ findings.push({
378
+ ruleId: versionRule,
379
+ line,
380
+ column,
381
+ message: 'server_tokens on adds the Nginx version to the Server header and error pages, which helps match the server to known vulnerabilities. Use server_tokens off.',
382
+ });
383
+ }
384
+ else if (name === 'ssl_protocols') {
385
+ const legacy = args.filter((protocol) => legacyProtocols.has(protocol.toLowerCase()));
386
+ if (legacy.length)
387
+ findings.push(legacyTlsFinding(legacy, line, column));
388
+ }
389
+ else if (name === 'proxy_pass') {
390
+ const finding = checkProxyPass(directive);
391
+ if (finding)
392
+ findings.push(finding);
393
+ }
394
+ }
395
+ findings.push(...nginxHeaderFindings(directives));
396
+ return findings;
397
+ }
398
+ function legacyTlsFinding(protocols, line, column) {
399
+ return {
400
+ ruleId: legacyTlsRule,
401
+ line,
402
+ column,
403
+ message: `The TLS configuration enables ${protocols.join(', ')}, which are deprecated (RFC 8996) and open to downgrade attacks. Allow only TLSv1.2 and TLSv1.3.`,
404
+ };
405
+ }
406
+ // Apache's `all` always includes TLSv1 and TLSv1.1 (SSLv3 depends on the OpenSSL build), so those
407
+ // two count unless a later `-TLSv1` or `-TLSv1.1` removes them.
408
+ function apacheLegacyProtocols(args) {
409
+ const enabled = new Map();
410
+ for (const arg of args) {
411
+ const protocol = arg.replace(/^[+-]/, '').toLowerCase();
412
+ if (arg.startsWith('-')) {
413
+ if (protocol === 'all')
414
+ enabled.clear();
415
+ else
416
+ enabled.delete(protocol);
417
+ }
418
+ else if (protocol === 'all') {
419
+ enabled.set('tlsv1', 'TLSv1').set('tlsv1.1', 'TLSv1.1');
420
+ }
421
+ else if (legacyProtocols.has(protocol)) {
422
+ enabled.set(protocol, arg.replace(/^\+/, ''));
423
+ }
424
+ }
425
+ return [...enabled.values()];
426
+ }
427
+ // Splits one Apache directive line into words, keeping quoted text together.
428
+ function apacheWords(line) {
429
+ const words = [];
430
+ const word = /"((?:[^"\\]|\\.)*)"|'([^']*)'|(\S+)/g;
431
+ for (const match of line.matchAll(word))
432
+ words.push(match[1] ?? match[2] ?? match[3]);
433
+ return words;
434
+ }
435
+ function checkApacheDirective(words, line, column, headers) {
436
+ const [name = '', ...args] = words;
437
+ const directive = name.toLowerCase();
438
+ if (directive === 'options' &&
439
+ args.some((arg) => /^\+?(?:indexes|all)$/i.test(arg)) &&
440
+ !args.some((arg) => /^-indexes$/i.test(arg))) {
441
+ return {
442
+ ruleId: directoryListingRule,
443
+ line,
444
+ column,
445
+ message: 'Options enables Indexes, so Apache lists every file in a folder without an index page. Use Options -Indexes unless the folder is meant to be browsed.',
446
+ };
447
+ }
448
+ if (directive === 'servertokens' && exposingServerTokens.has(args[0]?.toLowerCase() ?? '')) {
449
+ return {
450
+ ruleId: versionRule,
451
+ line,
452
+ column,
453
+ message: `ServerTokens ${args[0]} adds the Apache version to the Server header, which helps match the server to known vulnerabilities. Use ServerTokens Prod.`,
454
+ };
455
+ }
456
+ if (directive === 'sslprotocol') {
457
+ const legacy = apacheLegacyProtocols(args);
458
+ return legacy.length ? legacyTlsFinding(legacy, line, column) : undefined;
459
+ }
460
+ if (directive === 'header') {
461
+ const rest = /^(?:always|onsuccess)$/i.test(args[0] ?? '') ? args.slice(1) : args;
462
+ if (apacheHeaderActions.has(rest[0]?.toLowerCase() ?? '') && rest.length >= 3)
463
+ headers.push({ name: rest[1], value: rest[2], line, column });
464
+ }
465
+ return undefined;
466
+ }
467
+ function checkApache(text) {
468
+ const findings = [];
469
+ const sections = [[]];
470
+ const finished = [];
471
+ const lines = text.split(/\r?\n/);
472
+ for (let index = 0; index < lines.length; index++) {
473
+ const line = lines[index];
474
+ const trimmed = line.trim();
475
+ if (!trimmed || trimmed.startsWith('#'))
476
+ continue;
477
+ const column = line.length - line.trimStart().length + 1;
478
+ if (trimmed.startsWith('</')) {
479
+ if (sections.length > 1)
480
+ finished.push(sections.pop() ?? []);
481
+ continue;
482
+ }
483
+ if (trimmed.startsWith('<')) {
484
+ sections.push([]);
485
+ continue;
486
+ }
487
+ // Only the directives this check reads are split into words.
488
+ if (!apacheDirectives.has(/^\S+/.exec(trimmed)?.[0].toLowerCase() ?? ''))
489
+ continue;
490
+ const finding = checkApacheDirective(apacheWords(trimmed), index + 1, column, sections[sections.length - 1]);
491
+ if (finding)
492
+ findings.push(finding);
493
+ }
494
+ for (const headers of [...finished, ...sections])
495
+ findings.push(...checkConfiguredHeaders(headers));
496
+ return findings;
497
+ }
498
+ function checkWebServerConfig(text) {
499
+ return [...checkNginx(text), ...checkApache(text)].sort((first, second) => first.line - second.line);
500
+ }
501
+ export { checkWebServerConfig, isWebServerConfig };
@@ -0,0 +1,175 @@
1
+ // package.json script checks: install lifecycle scripts that download code and run it, and scripts
2
+ // that turn off TLS certificate verification.
3
+ import { isUnquoted, printsArguments, quoteStates } from './ci-shared.js';
4
+ import { member, parseJsonValue } from './json-nodes.js';
5
+ const remoteCodeRule = 'package-script-remote-code';
6
+ const tlsRule = 'package-script-tls-verification-disabled';
7
+ // Scripts npm, pnpm, Yarn and Bun run on `install` in the project or on a git dependency install.
8
+ const lifecycleScripts = ['preinstall', 'install', 'postinstall', 'preprepare', 'prepare', 'postprepare'];
9
+ const downloader = /\b(?:curl|wget|iwr|irm|Invoke-WebRequest|Invoke-RestMethod)\b/i;
10
+ const interpreter = /^(?:(?:ba|z|da|k|fi)?sh|node|python[23]?|perl|ruby|pwsh|powershell|iex|Invoke-Expression)(?:\.exe)?$/i;
11
+ // `sh -c "$(curl …)"`, `node -e "$(wget …)"`, `eval "$(curl …)"` and `bash <(curl …)`.
12
+ const evaluatedDownload = /(?:(?:^|\s)-[ce]\s+|\beval\s+)["']?(?:\$\(|`)\s*(?:curl|wget)\b|\b(?:(?:ba|z)?sh|source|\.)\s+<\(\s*(?:curl|wget)\b/i;
13
+ const tlsDisabled = new RegExp([
14
+ String.raw `\bNODE_TLS_REJECT_UNAUTHORIZED\s*=\s*["']?0(?!\d)`,
15
+ String.raw `\bstrict-?ssl(?:\s*=\s*|\s+)["']?false\b`,
16
+ String.raw `--no-strict-ssl\b`,
17
+ String.raw `\bhttp\.sslVerify(?:\s*=\s*|\s+)["']?false\b`,
18
+ String.raw `\bGIT_SSL_NO_VERIFY\s*=\s*["']?(?:1|true)\b`,
19
+ String.raw `--no-check-certificate\b`,
20
+ String.raw `--insecure(?![\w-])`,
21
+ ].join('|'), 'i');
22
+ // curl's short -k, alone or in a flag group such as -fsSLk; case-sensitive because -K reads a config file.
23
+ const curlInsecureFlag = /^-[a-zA-Z]*k[a-zA-Z]*$/;
24
+ // A > redirect of standard output; 2> and &> are other streams.
25
+ const stdoutRedirect = /(?:^|[^\d&])>/;
26
+ const teeStage = /^\s*(?:sudo\s+)?tee\b/;
27
+ const scriptReference = /\b(?:(?:npm|pnpm|bun)\s+run(?:-script)?|yarn(?:\s+run)?|pnpm)\s+([\w:.-]+)/g;
28
+ const commandSeparators = new Set([';', '&', '|', '\n']);
29
+ function isPackageManifest(file) {
30
+ return (file.split(/[\\/]/).at(-1) ?? '') === 'package.json';
31
+ }
32
+ // True when the pipeline stage is an interpreter that reads its program from standard input: no
33
+ // script file argument (`sh`, `sudo -E bash`), or an explicit `-s`, `-` or `--`.
34
+ function readsProgramFromInput(stage) {
35
+ const words = stage.trim().split(/\s+/);
36
+ let index = 0;
37
+ if (words[index] === 'sudo')
38
+ for (index++; words[index]?.startsWith('-'); index++)
39
+ ;
40
+ if (!interpreter.test(words[index] ?? ''))
41
+ return false;
42
+ for (const word of words.slice(index + 1)) {
43
+ if (word === '-s' || word === '-' || word === '--')
44
+ return true;
45
+ if (!word.startsWith('-'))
46
+ return false;
47
+ }
48
+ return true;
49
+ }
50
+ // True when a download stage writes the response to standard output. wget saves to a file unless
51
+ // given -O-, and curl saves with -o, -O or a > redirect.
52
+ function streamsDownload(stage) {
53
+ if (stdoutRedirect.test(stage))
54
+ return false;
55
+ const words = stage.trim().split(/\s+/);
56
+ const tool = words.find((word) => /^(?:curl|wget)(?:\.exe)?$/i.test(word))?.toLowerCase();
57
+ const toStdout = (index) => words[index + 1] === '-' || words[index + 1] === '/dev/stdout';
58
+ if (tool?.startsWith('wget'))
59
+ return words.some((word, index) => /^-[a-zA-Z]*O-$/.test(word) ||
60
+ word === '--output-document=-' ||
61
+ ((/^-[a-zA-Z]*O$/.test(word) || word === '--output-document') && toStdout(index)));
62
+ if (tool?.startsWith('curl'))
63
+ return !words.some((word, index) => (/^-[a-zA-Z]*[oO]$/.test(word) || /^--(?:output|remote-name)/.test(word)) && !toStdout(index));
64
+ return true;
65
+ }
66
+ // Pipes a download into an interpreter within one command: `curl … | sh`, `wget -O- … | sudo bash`,
67
+ // also through `|&` and `tee`, which pass the downloaded bytes on.
68
+ function runsDownloadedCode(script) {
69
+ if (evaluatedDownload.test(script))
70
+ return true;
71
+ for (const command of script.replaceAll('|&', '|').split(/&&|\|\||[;&\n]/)) {
72
+ let carriesDownload = false;
73
+ for (const stage of command.split('|')) {
74
+ if (carriesDownload && readsProgramFromInput(stage))
75
+ return true;
76
+ carriesDownload = downloader.test(stage) ? streamsDownload(stage) : carriesDownload && teeStage.test(stage);
77
+ }
78
+ }
79
+ return false;
80
+ }
81
+ // Word by word, so a script repeating `curl` many times is still scanned in linear time.
82
+ function runsInsecureCurl(script) {
83
+ for (const command of script.split(/[|;&\n]/)) {
84
+ const words = command.trim().split(/\s+/);
85
+ const curl = words.indexOf('curl');
86
+ if (curl >= 0 && words.slice(curl + 1).some((word) => curlInsecureFlag.test(word)))
87
+ return true;
88
+ }
89
+ return false;
90
+ }
91
+ function redirectsOutput(script, states, start, end) {
92
+ for (let index = start; index < end; index++)
93
+ if (script[index] === '>' && isUnquoted(states, index))
94
+ return true;
95
+ return false;
96
+ }
97
+ // The script without its echo and printf commands: `echo "then run curl … | sh"` only prints the
98
+ // words. A command whose output is piped or redirected, such as `echo strict-ssl=false >> .npmrc`,
99
+ // or that holds a command substitution still acts, so it stays.
100
+ function withoutPrintedText(script) {
101
+ const substitutions = [];
102
+ const states = quoteStates(script, substitutions);
103
+ let kept = '';
104
+ let commandStart = 0;
105
+ let nextSubstitution = 0;
106
+ for (let index = 0; index <= script.length; index++) {
107
+ const atEnd = index === script.length;
108
+ if (!atEnd && !(commandSeparators.has(script[index]) && isUnquoted(states, index)))
109
+ continue;
110
+ let substitutes = false;
111
+ for (; nextSubstitution < substitutions.length && substitutions[nextSubstitution].start < index; nextSubstitution++)
112
+ substitutes = true;
113
+ const command = script.slice(commandStart, index);
114
+ const piped = script[index] === '|' && script[index + 1] !== '|';
115
+ const printed = printsArguments.test(command) && !piped && !substitutes && !redirectsOutput(script, states, commandStart, index);
116
+ kept += (printed ? '' : command) + (atEnd ? '' : script[index]);
117
+ commandStart = index + 1;
118
+ }
119
+ return kept;
120
+ }
121
+ // Lifecycle script names, plus the scripts they start with `npm run <name>` and similar, mapped to
122
+ // the lifecycle script that reaches them.
123
+ function installScripts(scripts) {
124
+ const reached = new Map();
125
+ const pending = [];
126
+ for (const name of lifecycleScripts) {
127
+ if (!scripts.has(name))
128
+ continue;
129
+ reached.set(name, name);
130
+ pending.push(name);
131
+ }
132
+ for (let name = pending.pop(); name !== undefined; name = pending.pop()) {
133
+ for (const match of (scripts.get(name)?.value ?? '').matchAll(scriptReference)) {
134
+ const target = match[1];
135
+ if (!scripts.has(target) || reached.has(target))
136
+ continue;
137
+ reached.set(target, reached.get(name) ?? name);
138
+ pending.push(target);
139
+ }
140
+ }
141
+ return reached;
142
+ }
143
+ function checkPackageScripts(file, text) {
144
+ const scriptsValue = member(parseJsonValue(file, text), 'scripts');
145
+ if (scriptsValue?.kind !== 'object')
146
+ return [];
147
+ const scripts = new Map();
148
+ for (const [name, value] of scriptsValue.entries)
149
+ if (value.kind === 'string')
150
+ scripts.set(name, { ...value, value: withoutPrintedText(value.value) });
151
+ const install = installScripts(scripts);
152
+ const findings = [];
153
+ for (const [name, { value, line, column }] of scripts) {
154
+ const lifecycle = install.get(name);
155
+ if (lifecycle && runsDownloadedCode(value)) {
156
+ const via = lifecycle === name ? '' : ` through "${lifecycle}"`;
157
+ findings.push({
158
+ ruleId: remoteCodeRule,
159
+ line,
160
+ column,
161
+ message: `The "${name}" script runs during install${via} and executes code downloaded at that moment, with no checksum or pinned version. Whoever controls the URL or the network path runs code on every machine that installs the package. Vendor the file or verify a checksum before running it.`,
162
+ });
163
+ }
164
+ if (tlsDisabled.test(value) || runsInsecureCurl(value)) {
165
+ findings.push({
166
+ ruleId: tlsRule,
167
+ line,
168
+ column,
169
+ message: `The "${name}" script turns off TLS certificate verification, so anyone on the network path can impersonate the registry or server it contacts. Trust the needed CA with NODE_EXTRA_CA_CERTS or the cafile setting instead.`,
170
+ });
171
+ }
172
+ }
173
+ return findings;
174
+ }
175
+ export { checkPackageScripts, isPackageManifest };