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,6 +1,15 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
// Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
|
|
3
4
|
const examples = {
|
|
5
|
+
'angular-bypass-security-trust': [
|
|
6
|
+
'this.sanitizer.bypassSecurityTrustHtml(DOMPurify.sanitize(html))',
|
|
7
|
+
"Sanitize before bypassing, or don't bypass.",
|
|
8
|
+
],
|
|
9
|
+
'client-env-secret-exposed': [
|
|
10
|
+
'// server-only code\nconst stripe = new Stripe(process.env.STRIPE_SECRET_KEY);',
|
|
11
|
+
'Read the secret on the server under an unprefixed name; ship only publishable keys to the browser.',
|
|
12
|
+
],
|
|
4
13
|
'cookie-missing-security-flags': [
|
|
5
14
|
"res.cookie('session', token, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'lax',\n});",
|
|
6
15
|
'httpOnly keeps scripts from reading the cookie, secure limits it to HTTPS and sameSite limits cross-site sends.',
|
|
@@ -13,14 +22,35 @@ const examples = {
|
|
|
13
22
|
'app.use(cors({\n origin: /^https:\\/\\/(?:[\\w-]+\\.)*example\\.com$/,\n credentials: true,\n}));',
|
|
14
23
|
'Start the host after `//` or a dot, escape its dots and end it with `$`, so look-alike hosts such as evilexample.com do not match.',
|
|
15
24
|
],
|
|
25
|
+
'database-error-in-response': [
|
|
26
|
+
"try {\n await prisma.user.create({ data });\n} catch (error) {\n logger.error(error);\n res.status(500).json({ error: 'Internal error' });\n}",
|
|
27
|
+
'Log the driver error on the server and return a generic message.',
|
|
28
|
+
],
|
|
29
|
+
'dom-xss-sink': ['el.textContent = location.hash;', 'Use textContent, or DOMPurify.sanitize() if markup is needed.'],
|
|
16
30
|
'error-stack-in-response': [
|
|
17
31
|
"logger.error(err);\nres.status(500).json({ message: 'Internal server error' });",
|
|
18
32
|
'Log the error on the server and return a generic message. Return err.message only when it is written for clients.',
|
|
19
33
|
],
|
|
34
|
+
'express-missing-helmet': [
|
|
35
|
+
'const app = express();\napp.use(helmet());\napp.listen(3000);',
|
|
36
|
+
'Set the headers in the app, or confirm your proxy or CDN sets them.',
|
|
37
|
+
],
|
|
38
|
+
'frontend-storage-secret-token': [
|
|
39
|
+
'// send the token in an HttpOnly, Secure, SameSite cookie from the server',
|
|
40
|
+
'Page scripts cannot read an HttpOnly cookie.',
|
|
41
|
+
],
|
|
20
42
|
'graphql-introspection-enabled': [
|
|
21
43
|
"new ApolloServer({\n typeDefs,\n introspection: process.env.NODE_ENV !== 'production',\n});",
|
|
22
44
|
'Turn introspection and the playground on only outside production.',
|
|
23
45
|
],
|
|
46
|
+
'graphql-query-depth-unbounded': [
|
|
47
|
+
'new ApolloServer({ typeDefs, resolvers, validationRules: [depthLimit(7)] });',
|
|
48
|
+
'A depth or cost limit rejects abusive nested queries before they run.',
|
|
49
|
+
],
|
|
50
|
+
'jsx-javascript-url': [
|
|
51
|
+
"const safeHref = /^https?:\\/\\//i.test(next) || /^\\/(?!\\/)/.test(next) ? next : '/';",
|
|
52
|
+
'Allow only http(s) or same-site relative URLs, then render the checked value in the href.',
|
|
53
|
+
],
|
|
24
54
|
'mass-assignment': [
|
|
25
55
|
'await prisma.user.create({\n data: { name: body.name, email: body.email },\n});',
|
|
26
56
|
'Copy the fields callers may set, or parse the body with a schema that strips unknown keys.',
|
|
@@ -29,10 +59,26 @@ const examples = {
|
|
|
29
59
|
'app.useGlobalPipes(new ValidationPipe({\n whitelist: true,\n forbidNonWhitelisted: true,\n}));',
|
|
30
60
|
'whitelist strips properties without a validation decorator; forbidNonWhitelisted rejects the request instead.',
|
|
31
61
|
],
|
|
62
|
+
'next-image-any-remote-host': [
|
|
63
|
+
"const nextConfig = {\n images: { remotePatterns: [{ protocol: 'https', hostname: 'images.example-cdn.com' }] },\n};",
|
|
64
|
+
'Name the hosts your images come from.',
|
|
65
|
+
],
|
|
66
|
+
'password-hash-in-response': [
|
|
67
|
+
'const user = await prisma.user.findUnique({ where: { id }, omit: { passwordHash: true } });\nres.json(user);',
|
|
68
|
+
'Leave the password hash out at the read so no response can include it.',
|
|
69
|
+
],
|
|
70
|
+
'postmessage-missing-origin-check': [
|
|
71
|
+
"window.addEventListener('message', (event) => {\n if (event.origin !== EXPECTED_ORIGIN) return;\n use(event.data);\n});",
|
|
72
|
+
"Check who sent the message, and name the target origin instead of '*' when sending.",
|
|
73
|
+
],
|
|
32
74
|
'prototype-pollution': [
|
|
33
75
|
"const blocked = new Set(['__proto__', 'constructor', 'prototype']);\nif (blocked.has(key)) throw new Error('Invalid key');\ntarget[key] = value;",
|
|
34
76
|
'Reject the keys that reach the prototype, or copy only fields you list.',
|
|
35
77
|
],
|
|
78
|
+
'react-dangerously-set-inner-html': [
|
|
79
|
+
"createElement('div', { dangerouslySetInnerHTML: { __html: DOMPurify.sanitize(html) } })",
|
|
80
|
+
'Sanitize first, or render JSX.',
|
|
81
|
+
],
|
|
36
82
|
'reflected-xss-response': [
|
|
37
83
|
'res.send(`<p>Hello ${escapeHtml(req.query.name)}</p>`);',
|
|
38
84
|
'Escape values placed in HTML (escape-html, he), or return JSON.',
|
|
@@ -41,58 +87,25 @@ const examples = {
|
|
|
41
87
|
'logger.info({ userId: user.id, tokenId: token.id });',
|
|
42
88
|
'Log an identifier or a redacted value, never the secret itself.',
|
|
43
89
|
],
|
|
44
|
-
'template-autoescape-disabled': [
|
|
45
|
-
"nunjucks.configure('views', { autoescape: true });\nswig.setDefaults({ autoescape: true });",
|
|
46
|
-
"Leave escaping on and mark a trusted value with the engine's safe filter or triple braces, one value at a time.",
|
|
47
|
-
],
|
|
48
|
-
'xml-external-entities': [
|
|
49
|
-
'const document = parseXml(xml);',
|
|
50
|
-
'Call the parser without noent and dtdload so external entities are not loaded.',
|
|
51
|
-
],
|
|
52
|
-
'password-hash-in-response': [
|
|
53
|
-
'const user = await prisma.user.findUnique({ where: { id }, omit: { passwordHash: true } });\nres.json(user);',
|
|
54
|
-
'Leave the password hash out at the read so no response can include it.',
|
|
55
|
-
],
|
|
56
|
-
'storage-object-public-acl': [
|
|
57
|
-
'await s3.send(new PutObjectCommand({ Bucket, Key, Body }));\nreturn getSignedUrl(s3, new GetObjectCommand({ Bucket, Key }), { expiresIn: 300 });',
|
|
58
|
-
'Keep objects private and hand out short-lived presigned URLs.',
|
|
59
|
-
],
|
|
60
90
|
'secret-in-url-query': [
|
|
61
91
|
'await fetch(`${base}/items`, { headers: { Authorization: `Bearer ${apiKey}` } });',
|
|
62
92
|
'Send credentials in a header or the body; URLs end up in logs and Referer headers.',
|
|
63
93
|
],
|
|
64
|
-
'
|
|
65
|
-
'new
|
|
66
|
-
'
|
|
67
|
-
],
|
|
68
|
-
'database-error-in-response': [
|
|
69
|
-
"try {\n await prisma.user.create({ data });\n} catch (error) {\n logger.error(error);\n res.status(500).json({ error: 'Internal error' });\n}",
|
|
70
|
-
'Log the driver error on the server and return a generic message.',
|
|
71
|
-
],
|
|
72
|
-
'dom-xss-sink': ['el.textContent = location.hash;', 'Use textContent, or DOMPurify.sanitize() if markup is needed.'],
|
|
73
|
-
'react-dangerously-set-inner-html': [
|
|
74
|
-
"createElement('div', { dangerouslySetInnerHTML: { __html: DOMPurify.sanitize(html) } })",
|
|
75
|
-
'Sanitize first, or render JSX.',
|
|
94
|
+
'storage-object-public-acl': [
|
|
95
|
+
'await s3.send(new PutObjectCommand({ Bucket, Key, Body }));\nreturn getSignedUrl(s3, new GetObjectCommand({ Bucket, Key }), { expiresIn: 300 });',
|
|
96
|
+
'Keep objects private and hand out short-lived presigned URLs.',
|
|
76
97
|
],
|
|
77
|
-
'
|
|
78
|
-
|
|
79
|
-
"
|
|
98
|
+
'template-autoescape-disabled': [
|
|
99
|
+
"nunjucks.configure('views', { autoescape: true });\nswig.setDefaults({ autoescape: true });",
|
|
100
|
+
"Leave escaping on and mark a trusted value with the engine's safe filter or triple braces, one value at a time.",
|
|
80
101
|
],
|
|
81
102
|
'vue-v-html-unsanitized': [
|
|
82
103
|
"h('div', { innerHTML: DOMPurify.sanitize(html) })",
|
|
83
104
|
'Sanitize first, or use text children.',
|
|
84
105
|
],
|
|
85
|
-
'
|
|
86
|
-
'
|
|
87
|
-
'
|
|
88
|
-
],
|
|
89
|
-
'postmessage-missing-origin-check': [
|
|
90
|
-
"window.addEventListener('message', (event) => {\n if (event.origin !== EXPECTED_ORIGIN) return;\n use(event.data);\n});",
|
|
91
|
-
"Check who sent the message, and name the target origin instead of '*' when sending.",
|
|
92
|
-
],
|
|
93
|
-
'express-missing-helmet': [
|
|
94
|
-
'const app = express();\napp.use(helmet());\napp.listen(3000);',
|
|
95
|
-
'Set the headers in the app, or confirm your proxy or CDN sets them.',
|
|
106
|
+
'xml-external-entities': [
|
|
107
|
+
'const document = parseXml(xml);',
|
|
108
|
+
'Call the parser without noent and dtdload so external entities are not loaded.',
|
|
96
109
|
],
|
|
97
110
|
};
|
|
98
111
|
exports.default = examples;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
// Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
|
|
3
4
|
const examples = {
|
|
4
5
|
'code-injection': [
|
|
5
6
|
"const operations = { sum: (a, b) => a + b, max: Math.max };\nconst operation = operations[req.body.operation];\nif (!operation) throw new BadRequestException('Unknown operation');",
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
// Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
|
|
3
4
|
const examples = {
|
|
5
|
+
'drizzle-scope-unverified': [
|
|
6
|
+
'const rows = await db.select().from(invoices).where(\n and(filter, eq(invoices.organizationId, currentOrganization()))\n);',
|
|
7
|
+
'Read example. Use the actual scoped property and trusted helper declared for your table. Preserve the predicate and ownership on writes.',
|
|
8
|
+
],
|
|
4
9
|
'pg-dynamic-query-text': [
|
|
5
10
|
"const { rows } = await client.query('SELECT id FROM users WHERE email = $1', [email]);",
|
|
6
11
|
'Bind values as parameters. For dynamic identifiers or sort directions, choose among fixed, allowlisted SQL fragments.',
|
|
@@ -9,9 +14,5 @@ const examples = {
|
|
|
9
14
|
'const rows = await prisma.invoice.findMany({\n where: { AND: [filter, { organizationId: currentOrganization() }] }\n});',
|
|
10
15
|
'Read example. Substitute the field and trusted scope helper declared by your policy. Protected writes must also preserve ownership in their input data.',
|
|
11
16
|
],
|
|
12
|
-
'drizzle-scope-unverified': [
|
|
13
|
-
'const rows = await db.select().from(invoices).where(\n and(filter, eq(invoices.organizationId, currentOrganization()))\n);',
|
|
14
|
-
'Read example. Use the actual scoped property and trusted helper declared for your table. Preserve the predicate and ownership on writes.',
|
|
15
|
-
],
|
|
16
17
|
};
|
|
17
18
|
exports.default = examples;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
// Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
|
|
3
4
|
const examples = {
|
|
4
5
|
'open-redirect': [
|
|
5
6
|
"const next = String(req.query.next ?? '/');\nconst target = next.startsWith('/') && !next.startsWith('//') ? next : '/';\nres.redirect(target);",
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// client-env-secret-exposed: a secret-named environment variable read under a prefix the build
|
|
2
|
+
// inlines into the browser bundle (`process.env.NEXT_PUBLIC_*`, `import.meta.env.VITE_*`,
|
|
3
|
+
// `$env/static/public`). The prefix, not the code that reads it, decides the exposure, so the
|
|
4
|
+
// variable is public wherever it is read; only its name is reported, never a value.
|
|
5
|
+
import { ts } from '../../performance/compiler.js';
|
|
6
|
+
import { unwrap } from './literals.js';
|
|
7
|
+
import { projectDeclares } from './package-manifest.js';
|
|
8
|
+
const ruleId = 'client-env-secret-exposed';
|
|
9
|
+
// Next.js, Create React App and Expo inline these from `process.env`. Nuxt's `NUXT_PUBLIC_` only
|
|
10
|
+
// overrides declared public runtime config, so the prefix alone exposes nothing.
|
|
11
|
+
const expoPrefix = 'EXPO_PUBLIC_';
|
|
12
|
+
const processEnvPrefixes = ['NEXT_PUBLIC_', 'REACT_APP_', expoPrefix];
|
|
13
|
+
// The framework that inlines each `process.env` prefix. Vite replaces `process.env` with an empty
|
|
14
|
+
// object, so in a Vite package without that framework the read exposes nothing.
|
|
15
|
+
const processEnvFrameworks = new Map([
|
|
16
|
+
['NEXT_PUBLIC_', 'next'],
|
|
17
|
+
['REACT_APP_', 'react-scripts'],
|
|
18
|
+
[expoPrefix, 'expo'],
|
|
19
|
+
]);
|
|
20
|
+
// Vite exposes `VITE_` on `import.meta.env`; Astro replaces it with `PUBLIC_`. SvelteKit keeps
|
|
21
|
+
// Vite's prefix there and uses `PUBLIC_` only for its `$env` modules.
|
|
22
|
+
const vitePrefix = 'VITE_';
|
|
23
|
+
const astroPrefix = 'PUBLIC_';
|
|
24
|
+
const importMetaEnvPrefixes = [vitePrefix, astroPrefix];
|
|
25
|
+
const svelteKitPublicModules = new Set(['$env/static/public', '$env/dynamic/public']);
|
|
26
|
+
const svelteKitPublicPrefix = 'PUBLIC_';
|
|
27
|
+
// The secret word must end the name: `..._DISABLE_PASSWORD_LOGIN` is a flag, `..._PASSWORD` a value.
|
|
28
|
+
// Publishable, anon, public, site keys, DSNs and client ids end in other words and stay clean.
|
|
29
|
+
const secretNameEnding = /(?:^|_)(?:SECRET(?:_KEY|_TOKEN|_ACCESS_KEY|_ACCESS_TOKEN)?|PASSWORD|PASSWD|PRIVATE_KEY|SERVICE_ROLE(?:_KEY)?|SERVICE_ACCOUNT_KEY|DATABASE_URL)$/;
|
|
30
|
+
function exposedPrefix(name, prefixes) {
|
|
31
|
+
return prefixes.find((prefix) => name.startsWith(prefix) && secretNameEnding.test(name.slice(prefix.length)));
|
|
32
|
+
}
|
|
33
|
+
function report(node, name, prefix, context) {
|
|
34
|
+
context.report(node, ruleId, `\`${name}\` is a secret-named variable with the browser-exposed \`${prefix}\` prefix, so the build inlines its value into the client bundle where anyone can read it. Keep the secret on the server under a name without the public prefix, and rotate it if it has shipped.`);
|
|
35
|
+
}
|
|
36
|
+
function isProcessEnv(receiver) {
|
|
37
|
+
if (!ts.isPropertyAccessExpression(receiver) || receiver.name.text !== 'env')
|
|
38
|
+
return false;
|
|
39
|
+
const root = unwrap(receiver.expression);
|
|
40
|
+
return ts.isIdentifier(root) && root.text === 'process';
|
|
41
|
+
}
|
|
42
|
+
function isImportMetaEnv(receiver) {
|
|
43
|
+
if (!ts.isPropertyAccessExpression(receiver) || receiver.name.text !== 'env')
|
|
44
|
+
return false;
|
|
45
|
+
const meta = unwrap(receiver.expression);
|
|
46
|
+
return ts.isMetaProperty(meta) && meta.keywordToken === ts.SyntaxKind.ImportKeyword && meta.name.text === 'meta';
|
|
47
|
+
}
|
|
48
|
+
// `env` in `import { env } from '$env/dynamic/public'`.
|
|
49
|
+
function isSvelteKitPublicEnv(receiver, context) {
|
|
50
|
+
if (!ts.isIdentifier(receiver))
|
|
51
|
+
return false;
|
|
52
|
+
const declaration = context.checker.getSymbolAtLocation(receiver)?.declarations?.[0];
|
|
53
|
+
return declaration !== undefined && ts.isImportSpecifier(declaration) && importedFromSvelteKitPublic(declaration);
|
|
54
|
+
}
|
|
55
|
+
function importedFromSvelteKitPublic(specifier) {
|
|
56
|
+
const moduleSpecifier = specifier.parent.parent.parent.moduleSpecifier;
|
|
57
|
+
return ts.isStringLiteral(moduleSpecifier) && svelteKitPublicModules.has(moduleSpecifier.text);
|
|
58
|
+
}
|
|
59
|
+
function prefixesFor(receiver, context) {
|
|
60
|
+
if (isProcessEnv(receiver))
|
|
61
|
+
return processEnvPrefixes;
|
|
62
|
+
if (isImportMetaEnv(receiver))
|
|
63
|
+
return importMetaEnvPrefixes;
|
|
64
|
+
return isSvelteKitPublicEnv(receiver, context) ? [svelteKitPublicPrefix] : undefined;
|
|
65
|
+
}
|
|
66
|
+
// `process.env[name]` with a variable key names nothing the build can inline.
|
|
67
|
+
function envKeyName(node) {
|
|
68
|
+
if (ts.isPropertyAccessExpression(node))
|
|
69
|
+
return ts.isIdentifier(node.name) ? node.name.text : undefined;
|
|
70
|
+
const key = unwrap(node.argumentExpression);
|
|
71
|
+
return ts.isStringLiteralLike(key) ? key.text : undefined;
|
|
72
|
+
}
|
|
73
|
+
function checkEnvRead(node, context) {
|
|
74
|
+
const name = envKeyName(node);
|
|
75
|
+
if (name === undefined)
|
|
76
|
+
return;
|
|
77
|
+
const receiver = unwrap(node.expression);
|
|
78
|
+
const prefixes = prefixesFor(receiver, context);
|
|
79
|
+
const prefix = prefixes && exposedPrefix(name, prefixes);
|
|
80
|
+
if (!prefix)
|
|
81
|
+
return;
|
|
82
|
+
// Expo inlines only the dot form; `process.env['EXPO_PUBLIC_X']` stays undefined in the app.
|
|
83
|
+
if (prefix === expoPrefix && ts.isElementAccessExpression(node))
|
|
84
|
+
return;
|
|
85
|
+
if (prefixes === importMetaEnvPrefixes && !exposedByBuildTool(prefix, context))
|
|
86
|
+
return;
|
|
87
|
+
if (prefixes === processEnvPrefixes && !inlinedOutsideVite(prefix, context))
|
|
88
|
+
return;
|
|
89
|
+
report(node, name, prefix, context);
|
|
90
|
+
}
|
|
91
|
+
function inlinedOutsideVite(prefix, context) {
|
|
92
|
+
const fileName = context.sourceFile.fileName;
|
|
93
|
+
const framework = processEnvFrameworks.get(prefix);
|
|
94
|
+
return !projectDeclares(fileName, 'vite') || (framework !== undefined && projectDeclares(fileName, framework));
|
|
95
|
+
}
|
|
96
|
+
// Read only after a secret-named match, so ordinary env reads never touch package.json.
|
|
97
|
+
function exposedByBuildTool(prefix, context) {
|
|
98
|
+
const isAstro = projectDeclares(context.sourceFile.fileName, 'astro');
|
|
99
|
+
return prefix === (isAstro ? astroPrefix : vitePrefix);
|
|
100
|
+
}
|
|
101
|
+
// `import { PUBLIC_STRIPE_SECRET_KEY } from '$env/static/public'`.
|
|
102
|
+
function checkImportSpecifier(specifier, context) {
|
|
103
|
+
// `import type` is erased, so no value reaches the browser through it.
|
|
104
|
+
if (specifier.isTypeOnly || specifier.parent.parent.isTypeOnly)
|
|
105
|
+
return;
|
|
106
|
+
if (!importedFromSvelteKitPublic(specifier))
|
|
107
|
+
return;
|
|
108
|
+
const name = (specifier.propertyName ?? specifier.name).text;
|
|
109
|
+
const prefix = exposedPrefix(name, [svelteKitPublicPrefix]);
|
|
110
|
+
if (prefix)
|
|
111
|
+
report(specifier, name, prefix, context);
|
|
112
|
+
}
|
|
113
|
+
export { checkEnvRead, checkImportSpecifier };
|
|
@@ -215,16 +215,17 @@ function isMessageEventData(node, context) {
|
|
|
215
215
|
return typeName === 'MessageEvent';
|
|
216
216
|
}
|
|
217
217
|
function assessMember(node, context, depth) {
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
218
|
+
const label = ts.isPropertyAccessExpression(node) ? untrustedMemberLabel(node, context) : undefined;
|
|
219
|
+
return label ? untrustedValue(label) : assess(node.expression, context, depth + 1);
|
|
220
|
+
}
|
|
221
|
+
function untrustedMemberLabel(node, context) {
|
|
222
|
+
const urlLabel = urlControlledLabel(node, context);
|
|
223
|
+
if (urlLabel)
|
|
224
|
+
return urlLabel;
|
|
225
|
+
if (isMessageEventData(node, context))
|
|
226
|
+
return 'The `postMessage` payload';
|
|
227
|
+
if (node.name.text === 'value' && declaredInDomInterface(node.name, context, FORM_FIELD_INTERFACES))
|
|
228
|
+
return 'A form field value';
|
|
228
229
|
}
|
|
229
230
|
function assessIdentifier(identifier, context, depth) {
|
|
230
231
|
const declarations = declarationsOf(identifier, context);
|
|
@@ -545,3 +546,4 @@ function checkProperty(property, context) {
|
|
|
545
546
|
});
|
|
546
547
|
}
|
|
547
548
|
export { checkAssignment, checkCall, checkJsxAttribute, checkProperty };
|
|
549
|
+
export { MAX_DEPTH, declarationsOf, declaredInDefaultLibrary, declaredInitializer, memberChain, moduleOfDeclaration, originModule, untrustedMemberLabel, unwrap, };
|
|
@@ -13,6 +13,9 @@ import * as passwordResponse from './password-response.js';
|
|
|
13
13
|
import * as storageAcl from './storage-acl.js';
|
|
14
14
|
import * as urlSecrets from './url-secrets.js';
|
|
15
15
|
import * as frontend from './frontend-security.js';
|
|
16
|
+
import * as jsxUrl from './jsx-url.js';
|
|
17
|
+
import * as clientEnv from './client-env.js';
|
|
18
|
+
import * as nextImageConfig from './next-image-config.js';
|
|
16
19
|
import * as backend from './backend-security-mastery.js';
|
|
17
20
|
// Keyed by ts.SyntaxKind name; each check is (node, context) => void and reports through
|
|
18
21
|
// context.report.
|
|
@@ -46,7 +49,15 @@ export const checks = {
|
|
|
46
49
|
validationPipe.check,
|
|
47
50
|
graphql.checkServer,
|
|
48
51
|
],
|
|
49
|
-
PropertyAccessExpression: [urlSecrets.checkPropertyAccess],
|
|
50
|
-
|
|
51
|
-
|
|
52
|
+
PropertyAccessExpression: [urlSecrets.checkPropertyAccess, clientEnv.checkEnvRead],
|
|
53
|
+
ElementAccessExpression: [clientEnv.checkEnvRead],
|
|
54
|
+
ImportSpecifier: [clientEnv.checkImportSpecifier],
|
|
55
|
+
JsxAttribute: [frontend.checkJsxAttribute, jsxUrl.checkJsxUrlAttribute],
|
|
56
|
+
PropertyAssignment: [
|
|
57
|
+
cors.checkCorsProperty,
|
|
58
|
+
graphql.checkProperty,
|
|
59
|
+
storageAcl.checkProperty,
|
|
60
|
+
frontend.checkProperty,
|
|
61
|
+
nextImageConfig.checkProperty,
|
|
62
|
+
],
|
|
52
63
|
};
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
// jsx-javascript-url: an untrusted value at the start of a JSX link, form action or frame source
|
|
2
|
+
// decides its scheme, so a `javascript:` URL runs script. Only React 18 and older and Preact render
|
|
3
|
+
// these URLs as written; react-version.ts reads which one the project uses.
|
|
4
|
+
import { ts } from '../../performance/compiler.js';
|
|
5
|
+
import { rendersJavaScriptUrls } from './react-version.js';
|
|
6
|
+
import { MAX_DEPTH, declarationsOf, declaredInDefaultLibrary, declaredInitializer, memberChain, moduleOfDeclaration, originModule, untrustedMemberLabel, unwrap, } from './frontend-security.js';
|
|
7
|
+
const LOCATION_BASES = ['location', 'window.location', 'self.location', 'document.location'];
|
|
8
|
+
const SCHEME_SAFE_PATHS = new Set([
|
|
9
|
+
...LOCATION_BASES.flatMap((base) => ['href', 'pathname', 'origin', 'host', 'hostname'].map((member) => `${base}.${member}`)),
|
|
10
|
+
'document.URL',
|
|
11
|
+
'document.documentURI',
|
|
12
|
+
'document.referrer',
|
|
13
|
+
]);
|
|
14
|
+
// A host name cannot hold a scheme, so even a slice of it stays safe; a slice of the full address or
|
|
15
|
+
// path can (`/javascript:alert(1)`.slice(1)).
|
|
16
|
+
const HOST_MEMBERS = new Set(['origin', 'host', 'hostname']);
|
|
17
|
+
// `?q=1` and `#x` are relative URLs; only a slice or parse of them can start with a scheme.
|
|
18
|
+
const RELATIVE_PART_MEMBERS = new Set(['search', 'hash']);
|
|
19
|
+
// These keep what their input starts with: a decoded, case-converted or `String`-converted `#x`
|
|
20
|
+
// still starts with `#`, and `new URL(x)` keeps the scheme of `x`.
|
|
21
|
+
const PREFIX_PRESERVING_CALLS = new Set([
|
|
22
|
+
'decodeURI',
|
|
23
|
+
'decodeURIComponent',
|
|
24
|
+
'unescape',
|
|
25
|
+
'encodeURI',
|
|
26
|
+
'String',
|
|
27
|
+
'URL',
|
|
28
|
+
'toLowerCase',
|
|
29
|
+
'toUpperCase',
|
|
30
|
+
'toLocaleLowerCase',
|
|
31
|
+
'toLocaleUpperCase',
|
|
32
|
+
]);
|
|
33
|
+
// These escape `:`, so their output can never be read as a scheme unless a decoder around them
|
|
34
|
+
// restores it.
|
|
35
|
+
const SCHEME_ESCAPING_CALLS = new Set(['encodeURIComponent', 'escape']);
|
|
36
|
+
const COLON_DECODING_CALLS = new Set(['decodeURIComponent', 'unescape']);
|
|
37
|
+
// These can drop a constant start: `('/' + value).slice(1)` starts with `value`.
|
|
38
|
+
const PREFIX_CUTTING_METHODS = new Set(['slice', 'substring', 'substr', 'split']);
|
|
39
|
+
const SUBSTRING_METHODS = new Set(['slice', 'substring', 'substr']);
|
|
40
|
+
// The elements on which each attribute loads or navigates to its URL.
|
|
41
|
+
const URL_ATTRIBUTE_TAGS = new Map([
|
|
42
|
+
['href', new Set(['a', 'area'])],
|
|
43
|
+
['xlinkHref', new Set(['a'])],
|
|
44
|
+
['action', new Set(['form'])],
|
|
45
|
+
['formAction', new Set(['button', 'input'])],
|
|
46
|
+
['src', new Set(['iframe', 'frame', 'embed'])],
|
|
47
|
+
]);
|
|
48
|
+
const SEARCH_PARAM_READERS = new Set(['get', 'getAll']);
|
|
49
|
+
const SEARCH_PARAMS_MODULES = new Set(['next/navigation', 'react-router', 'react-router-dom']);
|
|
50
|
+
const NEXT_ROUTER_MODULE = 'next/router';
|
|
51
|
+
const NEXT_LINK_MODULE = 'next/link';
|
|
52
|
+
const URL_STRIPPED_CODE_POINT_LIMIT = 0x20;
|
|
53
|
+
const JAVASCRIPT_SCHEME = 'javascript:';
|
|
54
|
+
// URL parsing removes tabs and newlines anywhere in the input.
|
|
55
|
+
const URL_REMOVED_CHARACTERS = /[\t\n\r]/g;
|
|
56
|
+
const isIntrinsicTag = (tagName) => /^[a-z]/.test(tagName);
|
|
57
|
+
// Whether a constant start leaves the scheme open to what follows: `' '` is dropped by URL parsing,
|
|
58
|
+
// and `'java'` can still become `javascript:`. `/`, `#`, `?` or `https://` settle it.
|
|
59
|
+
function leavesSchemeOpen(text) {
|
|
60
|
+
const firstKept = [...text].findIndex((character) => (character.codePointAt(0) ?? 0) > URL_STRIPPED_CODE_POINT_LIMIT);
|
|
61
|
+
if (firstKept === -1)
|
|
62
|
+
return true;
|
|
63
|
+
const start = [...text].slice(firstKept).join('').replaceAll(URL_REMOVED_CHARACTERS, '').toLowerCase();
|
|
64
|
+
return JAVASCRIPT_SCHEME.startsWith(start);
|
|
65
|
+
}
|
|
66
|
+
const untouched = { transformed: false, prefixCut: false, decoded: false };
|
|
67
|
+
function isOwnAddress(node, context, transformed) {
|
|
68
|
+
const chain = memberChain(node);
|
|
69
|
+
if (!chain || !declaredInDefaultLibrary(chain.root, context))
|
|
70
|
+
return false;
|
|
71
|
+
const member = ts.isPropertyAccessExpression(node) ? node.name.text : '';
|
|
72
|
+
if (SCHEME_SAFE_PATHS.has(chain.path))
|
|
73
|
+
return !transformed || HOST_MEMBERS.has(member);
|
|
74
|
+
return !transformed && RELATIVE_PART_MEMBERS.has(member);
|
|
75
|
+
}
|
|
76
|
+
// `searchParams.get('next')` with `useSearchParams` from next/navigation or react-router, or
|
|
77
|
+
// `useRouter().query` from next/router.
|
|
78
|
+
function routerQueryLabel(node, context) {
|
|
79
|
+
if (ts.isCallExpression(node)) {
|
|
80
|
+
const callee = unwrap(node.expression);
|
|
81
|
+
const readsParam = ts.isPropertyAccessExpression(callee) && SEARCH_PARAM_READERS.has(callee.name.text);
|
|
82
|
+
const module = readsParam ? originModule(callee.expression, context) : undefined;
|
|
83
|
+
return module !== undefined && SEARCH_PARAMS_MODULES.has(module) ? 'A URL search parameter' : undefined;
|
|
84
|
+
}
|
|
85
|
+
if (!ts.isPropertyAccessExpression(node) || node.name.text !== 'query')
|
|
86
|
+
return;
|
|
87
|
+
return originModule(node.expression, context) === NEXT_ROUTER_MODULE ? 'The router query' : undefined;
|
|
88
|
+
}
|
|
89
|
+
// `' '`, `' ' + '\t'`: the text of a string built only from literals.
|
|
90
|
+
function literalText(node) {
|
|
91
|
+
const value = unwrap(node);
|
|
92
|
+
if (ts.isStringLiteralLike(value))
|
|
93
|
+
return value.text;
|
|
94
|
+
if (!ts.isBinaryExpression(value) || value.operatorToken.kind !== ts.SyntaxKind.PlusToken)
|
|
95
|
+
return;
|
|
96
|
+
const left = literalText(value.left);
|
|
97
|
+
const right = left === undefined ? undefined : literalText(value.right);
|
|
98
|
+
return left === undefined || right === undefined ? undefined : left + right;
|
|
99
|
+
}
|
|
100
|
+
// The bindings whose URL protocol a condition reads: `target` in
|
|
101
|
+
// `new URL(target, location.origin).protocol === 'https:'`.
|
|
102
|
+
function protocolCheckedBindings(condition, context) {
|
|
103
|
+
const bindings = new Set();
|
|
104
|
+
const visit = (node) => {
|
|
105
|
+
if (ts.isPropertyAccessExpression(node) && node.name.text === 'protocol') {
|
|
106
|
+
const parsed = unwrap(node.expression);
|
|
107
|
+
const input = ts.isNewExpression(parsed) && isGlobalUrl(parsed.expression, context) ? parsed.arguments?.[0] : undefined;
|
|
108
|
+
const binding = input && ts.isIdentifier(unwrap(input)) ? declarationsOf(unwrap(input), context)[0] : undefined;
|
|
109
|
+
if (binding)
|
|
110
|
+
bindings.add(binding);
|
|
111
|
+
}
|
|
112
|
+
ts.forEachChild(node, visit);
|
|
113
|
+
};
|
|
114
|
+
visit(condition);
|
|
115
|
+
return bindings;
|
|
116
|
+
}
|
|
117
|
+
function isGlobalUrl(callee, context) {
|
|
118
|
+
const name = unwrap(callee);
|
|
119
|
+
return ts.isIdentifier(name) && name.text === 'URL' && declaredInDefaultLibrary(name, context);
|
|
120
|
+
}
|
|
121
|
+
// A branch that renders the very binding the condition checked the protocol of is guarded.
|
|
122
|
+
function conditionalLeadSource(node, context, next) {
|
|
123
|
+
const checked = protocolCheckedBindings(node.condition, context);
|
|
124
|
+
const unguarded = (branch) => {
|
|
125
|
+
const value = unwrap(branch);
|
|
126
|
+
return !(ts.isIdentifier(value) && checked.has(declarationsOf(value, context)[0]));
|
|
127
|
+
};
|
|
128
|
+
const whenTrue = unguarded(node.whenTrue) ? next(node.whenTrue) : undefined;
|
|
129
|
+
return whenTrue ?? (unguarded(node.whenFalse) ? next(node.whenFalse) : undefined);
|
|
130
|
+
}
|
|
131
|
+
function templateLeadSource(node, state, next) {
|
|
132
|
+
if (!state.prefixCut)
|
|
133
|
+
return leavesSchemeOpen(node.head.text) ? next(node.templateSpans[0].expression) : undefined;
|
|
134
|
+
for (const span of node.templateSpans) {
|
|
135
|
+
const source = next(span.expression);
|
|
136
|
+
if (source)
|
|
137
|
+
return source;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
// The part of a template, conditional or operator expression that starts the value.
|
|
141
|
+
function compoundLeadSource(node, context, state, next) {
|
|
142
|
+
if (ts.isTemplateExpression(node))
|
|
143
|
+
return templateLeadSource(node, state, next);
|
|
144
|
+
if (ts.isConditionalExpression(node))
|
|
145
|
+
return conditionalLeadSource(node, context, next);
|
|
146
|
+
const operator = node.operatorToken.kind;
|
|
147
|
+
if (operator === ts.SyntaxKind.PlusToken) {
|
|
148
|
+
const left = unwrap(node.left);
|
|
149
|
+
if (state.prefixCut)
|
|
150
|
+
return next(left) ?? next(node.right);
|
|
151
|
+
const prefix = literalText(left);
|
|
152
|
+
if (prefix === undefined)
|
|
153
|
+
return next(left);
|
|
154
|
+
return leavesSchemeOpen(prefix) ? next(node.right) : undefined;
|
|
155
|
+
}
|
|
156
|
+
// `a && b` yields `b` whenever `a` is truthy; a falsy `a` cannot hold a scheme.
|
|
157
|
+
if (operator === ts.SyntaxKind.AmpersandAmpersandToken)
|
|
158
|
+
return next(node.right);
|
|
159
|
+
const fallback = operator === ts.SyntaxKind.QuestionQuestionToken || operator === ts.SyntaxKind.BarBarToken;
|
|
160
|
+
return fallback ? (next(node.left) ?? next(node.right)) : undefined;
|
|
161
|
+
}
|
|
162
|
+
// The untrusted source that decides a URL's scheme, or undefined when the value starts with a
|
|
163
|
+
// constant, is opaque or comes from the app itself. Only untrusted sources are reported: a prop or
|
|
164
|
+
// fetched link is how most apps render links.
|
|
165
|
+
function urlLeadSource(expression, context, depth = 0, state = untouched) {
|
|
166
|
+
const node = unwrap(expression);
|
|
167
|
+
if (!node || depth > MAX_DEPTH || isOwnAddress(node, context, state.transformed))
|
|
168
|
+
return;
|
|
169
|
+
const next = (part) => urlLeadSource(part, context, depth + 1, state);
|
|
170
|
+
if (ts.isTemplateExpression(node) || ts.isConditionalExpression(node) || ts.isBinaryExpression(node))
|
|
171
|
+
return compoundLeadSource(node, context, state, next);
|
|
172
|
+
const routerLabel = routerQueryLabel(node, context);
|
|
173
|
+
if (routerLabel)
|
|
174
|
+
return routerLabel;
|
|
175
|
+
if (ts.isCallExpression(node) || ts.isNewExpression(node))
|
|
176
|
+
return leadOfLibraryCall(node, context, depth, state);
|
|
177
|
+
if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) {
|
|
178
|
+
if (isParsedUrlHost(node, context))
|
|
179
|
+
return;
|
|
180
|
+
const label = ts.isPropertyAccessExpression(node) ? untrustedMemberLabel(node, context) : undefined;
|
|
181
|
+
return label ?? next(node.expression);
|
|
182
|
+
}
|
|
183
|
+
if (!ts.isIdentifier(node) || declaredInDefaultLibrary(node, context))
|
|
184
|
+
return;
|
|
185
|
+
const initializer = declaredInitializer(node, context);
|
|
186
|
+
return initializer && next(initializer);
|
|
187
|
+
}
|
|
188
|
+
// `new URL(x).origin` is `"null"` for a `javascript:` URL, and no host holds a scheme.
|
|
189
|
+
function isParsedUrlHost(node, context) {
|
|
190
|
+
if (!ts.isPropertyAccessExpression(node) || !HOST_MEMBERS.has(node.name.text))
|
|
191
|
+
return false;
|
|
192
|
+
return context.checker.getTypeAtLocation(node.expression).getSymbol()?.name === 'URL';
|
|
193
|
+
}
|
|
194
|
+
// A method such as `x.slice(1)` reads its receiver; a global function, even reached through
|
|
195
|
+
// `window.String(x)`, reads its first argument.
|
|
196
|
+
function callInput(call, nameNode, context) {
|
|
197
|
+
const callee = unwrap(call.expression);
|
|
198
|
+
const isMethod = ts.isPropertyAccessExpression(callee) &&
|
|
199
|
+
declarationsOf(nameNode, context).some((declaration) => ts.isMethodSignature(declaration) || ts.isMethodDeclaration(declaration));
|
|
200
|
+
return isMethod ? callee.expression : call.arguments?.[0];
|
|
201
|
+
}
|
|
202
|
+
// `decodeURIComponent(x)`, `x.slice(1)`, `new URL(x)`: standard library calls pass their first
|
|
203
|
+
// input through; project functions (a `safeUrl` helper) are opaque.
|
|
204
|
+
function leadOfLibraryCall(call, context, depth, state) {
|
|
205
|
+
const callee = unwrap(call.expression);
|
|
206
|
+
const nameNode = ts.isPropertyAccessExpression(callee) ? callee.name : callee;
|
|
207
|
+
if (!ts.isIdentifier(nameNode) || !declaredInDefaultLibrary(nameNode, context))
|
|
208
|
+
return;
|
|
209
|
+
const name = nameNode.text;
|
|
210
|
+
const escapesColon = SCHEME_ESCAPING_CALLS.has(name);
|
|
211
|
+
// `encodeURI` keeps `:` but escapes `%`, so an outer decoder only undoes this layer.
|
|
212
|
+
const escapesPercent = name === 'encodeURI';
|
|
213
|
+
if (escapesColon && !state.decoded)
|
|
214
|
+
return;
|
|
215
|
+
const input = callInput(call, nameNode, context);
|
|
216
|
+
if (!input)
|
|
217
|
+
return;
|
|
218
|
+
const cutsStart = cutsPrefix(call, name);
|
|
219
|
+
// `location.hash.slice(0, 80)` still starts with `#`.
|
|
220
|
+
const keepsStart = SUBSTRING_METHODS.has(name) && !cutsStart;
|
|
221
|
+
const keepsPrefix = escapesColon || keepsStart || PREFIX_PRESERVING_CALLS.has(name);
|
|
222
|
+
return urlLeadSource(input, context, depth + 1, {
|
|
223
|
+
transformed: state.transformed || !keepsPrefix,
|
|
224
|
+
prefixCut: state.prefixCut || cutsStart,
|
|
225
|
+
decoded: escapesColon || escapesPercent ? false : state.decoded || COLON_DECODING_CALLS.has(name),
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
// `slice(1)` cuts; `slice(0, n)` keeps the start.
|
|
229
|
+
function cutsPrefix(call, name) {
|
|
230
|
+
if (!PREFIX_CUTTING_METHODS.has(name) || !ts.isPropertyAccessExpression(unwrap(call.expression)))
|
|
231
|
+
return false;
|
|
232
|
+
const start = call.arguments?.[0];
|
|
233
|
+
return !(start && ts.isNumericLiteral(start) && Number(start.text) === 0);
|
|
234
|
+
}
|
|
235
|
+
function urlAttributeOf(attribute) {
|
|
236
|
+
if (!ts.isIdentifier(attribute.name))
|
|
237
|
+
return;
|
|
238
|
+
const tagName = attribute.parent.parent.tagName;
|
|
239
|
+
if (!ts.isIdentifier(tagName))
|
|
240
|
+
return;
|
|
241
|
+
const name = attribute.name.text;
|
|
242
|
+
if (!isIntrinsicTag(tagName.text))
|
|
243
|
+
return name === 'href' ? name : undefined;
|
|
244
|
+
return URL_ATTRIBUTE_TAGS.get(name)?.has(tagName.text) ? name : undefined;
|
|
245
|
+
}
|
|
246
|
+
// Component links count only when they render a plain anchor: `<Link>` from next/link.
|
|
247
|
+
function isUrlSink(attribute, context) {
|
|
248
|
+
const tagName = attribute.parent.parent.tagName;
|
|
249
|
+
if (ts.isIdentifier(tagName) && isIntrinsicTag(tagName.text))
|
|
250
|
+
return true;
|
|
251
|
+
return moduleOfDeclaration(declarationsOf(tagName, context)[0]) === NEXT_LINK_MODULE;
|
|
252
|
+
}
|
|
253
|
+
function checkJsxUrlAttribute(attribute, context) {
|
|
254
|
+
const name = urlAttributeOf(attribute);
|
|
255
|
+
const initializer = attribute.initializer;
|
|
256
|
+
if (context.fileContext.isTestSource || !name || !initializer)
|
|
257
|
+
return;
|
|
258
|
+
if (!ts.isJsxExpression(initializer) || !initializer.expression)
|
|
259
|
+
return;
|
|
260
|
+
if (!isUrlSink(attribute, context))
|
|
261
|
+
return;
|
|
262
|
+
const source = urlLeadSource(initializer.expression, context);
|
|
263
|
+
if (!source || !rendersJavaScriptUrls(context.sourceFile.fileName))
|
|
264
|
+
return;
|
|
265
|
+
context.report(attribute, 'jsx-javascript-url', `${source} decides the scheme of \`${name}\`, so a \`javascript:\` URL runs script when the link or form is used (XSS). Allow only http(s) or relative URLs, for example \`new URL(value, location.origin).protocol === 'https:'\`, before rendering it.`);
|
|
266
|
+
}
|
|
267
|
+
export { checkJsxUrlAttribute };
|