eslint-plugin-node-security 6.0.6 → 6.1.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/AGENTS.md +121 -0
- package/package.json +3 -2
- package/src/index.js +1 -1
- package/src/rules/no-math-random-crypto/index.js +1 -1
package/AGENTS.md
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
<!-- Generated by scripts/generate-plugin-agents-md.ts from package.json and the plugin exports. Do not edit by hand; run `npm run agents-md`. -->
|
|
2
|
+
|
|
3
|
+
# eslint-plugin-node-security
|
|
4
|
+
|
|
5
|
+
Guide for AI coding assistants using this plugin in a project. To change the plugin's own source, read https://github.com/ofri-peretz/eslint/blob/main/AGENTS.md instead.
|
|
6
|
+
|
|
7
|
+
> ESLint Node security rules for Node.js — detects command injection, path traversal, SSRF, zip slip, and weak crypto (MD5/SHA-1, ECB, static IV) in fs, child_process, vm, and crypto.
|
|
8
|
+
|
|
9
|
+
## Enable it
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install --save-dev eslint-plugin-node-security
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Requires ESLint ^8.40.0 || ^9.0.0 || ^10.0.0 and Node >=22.13.0.
|
|
16
|
+
|
|
17
|
+
Flat config files (`eslint.config.*`) are found by ESLint 8.57 and newer; on ESLint 9 and 10 they are the default.
|
|
18
|
+
|
|
19
|
+
```js
|
|
20
|
+
// eslint.config.mjs
|
|
21
|
+
import nodeSecurity from 'eslint-plugin-node-security';
|
|
22
|
+
|
|
23
|
+
export default [nodeSecurity.configs.recommended];
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Each preset is one flat config object: put it in the array as an element, do not spread it. Rule ids are prefixed `node-security/`. Add it to the config you already have; do not remove other plugins. TypeScript files need a TypeScript parser in the config (`typescript-eslint`).
|
|
27
|
+
|
|
28
|
+
Use it alongside `eslint-plugin-security`, not instead of it: keep that plugin if the project has it. Measured overlap and the limits of both: https://eslint.interlace.tools/docs/getting-started/with-eslint-plugin-security
|
|
29
|
+
|
|
30
|
+
## Presets
|
|
31
|
+
|
|
32
|
+
| Preset | Rules | Errors | Warnings |
|
|
33
|
+
| ------------- | ----- | ------ | -------- |
|
|
34
|
+
| `recommended` | 31 | 25 | 6 |
|
|
35
|
+
| `strict` | 43 | 43 | 0 |
|
|
36
|
+
|
|
37
|
+
### `recommended`
|
|
38
|
+
|
|
39
|
+
31 rules:
|
|
40
|
+
|
|
41
|
+
- `detect-child-process` (error): Detects child_process usage that may allow command injection.
|
|
42
|
+
- `detect-eval-with-expression` (error): Detects strings turned into running code — eval(variable), the Function constructor, and the vm / vm2 sinks that are mistaken for sandboxes.
|
|
43
|
+
- `detect-non-literal-fs-filename` (warn): Detects variable in filename argument of fs calls, which might allow an attacker to access anything on your system.
|
|
44
|
+
- `no-unsafe-dynamic-require` (error): Prevent unsafe dynamic require() calls that could enable code injection.
|
|
45
|
+
- `no-buffer-overread` (warn): Detects buffer access beyond bounds.
|
|
46
|
+
- `no-deprecated-buffer` (error): Disallow the deprecated `new Buffer()` constructor and `Buffer()` factory call.
|
|
47
|
+
- `no-unsafe-buffer-alloc` (warn): Disallow `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()`, which return uninitialized memory.
|
|
48
|
+
- `no-toctou-vulnerability` (error): Detects Time-of-Check-Time-of-Use vulnerabilities.
|
|
49
|
+
- `no-zip-slip` (error): Detects zip slip/archive extraction vulnerabilities.
|
|
50
|
+
- `no-arbitrary-file-access` (error): Prevent file access from user input.
|
|
51
|
+
- `no-data-in-temp-storage` (error): Prevent sensitive data in temp directories.
|
|
52
|
+
- `no-ssrf` (warn): Flags HTTP calls whose URL argument is a user-input-named identifier or reads off a request object — a heuristic prompt for code review, not a proof of SSRF.
|
|
53
|
+
- `no-shell-injection` (error): Disallow string concatenation or template expressions in shell command arguments (CWE-78).
|
|
54
|
+
- `no-dynamic-command-string` (error): Disallow dynamically assembled command strings passed to a shell flag or to a command-runner that does not escape (CWE-77).
|
|
55
|
+
- `no-env-injection` (error): Disallow writing process.env under a key the caller controls, which can overwrite PATH, NODE_OPTIONS or LD_PRELOAD (CWE-99).
|
|
56
|
+
- `no-dynamic-algorithm-selection` (error): Disallow dynamic algorithm names in Node.js crypto functions (CWE-327).
|
|
57
|
+
- `no-timing-unsafe-compare` (warn): Disallow timing-unsafe comparison of secrets.
|
|
58
|
+
- `detect-suspicious-dependencies` (warn): Detect typosquatting in package names.
|
|
59
|
+
- `require-dependency-integrity` (error): Require SRI (Subresource Integrity) for CDN resources.
|
|
60
|
+
- `no-weak-hash-algorithm` (error): Disallow weak hash algorithms (MD5, SHA1, MD4).
|
|
61
|
+
- `no-weak-cipher-algorithm` (error): Disallow weak cipher algorithms (DES, 3DES, RC4, Blowfish).
|
|
62
|
+
- `no-weak-dh-parameters` (error): Disallow Diffie-Hellman and ECDH parameters below a safe strength.
|
|
63
|
+
- `no-static-iv` (error): Disallow static or hardcoded initialization vectors (IVs).
|
|
64
|
+
- `no-ecb-mode` (error): Disallow ECB encryption mode (use GCM or CBC instead).
|
|
65
|
+
- `no-math-random-crypto` (error): Disallow Math.random() for cryptographic purposes.
|
|
66
|
+
- `no-cryptojs` (error): Disallow deprecated crypto-js library (use native crypto instead).
|
|
67
|
+
- `no-self-signed-certs` (error): Disallow rejectUnauthorized: false in TLS options.
|
|
68
|
+
- `require-aead-tag-verification` (error): Require AEAD decryption to verify the authentication tag (setAuthTag + final).
|
|
69
|
+
- `no-unbounded-decompression` (error): Require a maxOutputLength ceiling on zlib one-shot decompression.
|
|
70
|
+
- `no-insecure-http-parser` (error): Disallow insecureHTTPParser: true on Node HTTP servers and clients.
|
|
71
|
+
- `require-stream-error-handler` (error): Require an 'error' listener on streams passed to .pipe(), which does not forward errors.
|
|
72
|
+
|
|
73
|
+
### `strict`
|
|
74
|
+
|
|
75
|
+
Everything in `recommended` plus 12 more (some shared rules run at a different severity here):
|
|
76
|
+
|
|
77
|
+
- `lock-file` (error): Ensure package lock file exists for the configured package manager.
|
|
78
|
+
- `no-dynamic-dependency-loading` (error): Prevent runtime dependency injection with dynamic paths.
|
|
79
|
+
- `require-secure-credential-storage` (error): Enforce secure storage patterns for credentials.
|
|
80
|
+
- `require-secure-deletion` (error): Require secure data deletion patterns.
|
|
81
|
+
- `require-storage-encryption` (error): Require encryption for persistent storage.
|
|
82
|
+
- `no-dynamic-require` (error): Forbid `require()` calls with expressions.
|
|
83
|
+
- `no-cryptojs-weak-random` (error): Disallow crypto-js WordArray.random() (CVE-2020-36732).
|
|
84
|
+
- `no-deprecated-cipher-method` (error): Disallow deprecated crypto.createCipher/createDecipher methods (use createCipheriv/createDecipheriv instead).
|
|
85
|
+
- `no-insecure-key-derivation` (error): Disallow PBKDF2 with insufficient iterations (< 100,000).
|
|
86
|
+
- `no-insecure-rsa-padding` (error): Disallow RSA PKCS#1 v1.5 padding (CVE-2023-46809 Marvin Attack).
|
|
87
|
+
- `no-sha1-hash` (error): Disallow sha1() from crypto-hash package (use sha256 or sha512).
|
|
88
|
+
- `prefer-native-crypto` (error): Prefer native crypto over third-party libraries.
|
|
89
|
+
|
|
90
|
+
## Other Interlace plugins by dependency
|
|
91
|
+
|
|
92
|
+
If the project also depends on one of these, add the matching plugin the same way:
|
|
93
|
+
|
|
94
|
+
- `express`: `eslint-plugin-express-security`
|
|
95
|
+
- `@nestjs/common`, `@nestjs/core`: `eslint-plugin-nestjs-security`
|
|
96
|
+
- `react`, `react-dom`, `preact`, `vue`, `svelte`, `@angular/core`, `solid-js`, `lit`, `next`, `nuxt`: `eslint-plugin-browser-security`
|
|
97
|
+
- `jsonwebtoken`, `jose`, `express-jwt`, `@nestjs/jwt`, `jwks-rsa`, `jwt-decode`: `eslint-plugin-jwt-security`
|
|
98
|
+
- `pg`, `pg-pool`, `pg-promise`, `postgres`, `slonik`: `eslint-plugin-postgresql-security`
|
|
99
|
+
- `mysql2`, `mysql`: `eslint-plugin-mysql-security`
|
|
100
|
+
- `mongodb`, `mongoose`: `eslint-plugin-mongodb-security`
|
|
101
|
+
- `better-sqlite3`, `sqlite3`: `eslint-plugin-sqlite-security`
|
|
102
|
+
- `knex`: `eslint-plugin-knex-security`
|
|
103
|
+
- `@prisma/client`, `prisma`: `eslint-plugin-prisma-security`
|
|
104
|
+
- `drizzle-orm`: `eslint-plugin-drizzle-security`
|
|
105
|
+
- `sequelize`: `eslint-plugin-sequelize-security`
|
|
106
|
+
- `typeorm`: `eslint-plugin-typeorm-security`
|
|
107
|
+
- `@supabase/supabase-js`: `eslint-plugin-supabase-security`
|
|
108
|
+
- `@modelcontextprotocol/*`: `eslint-plugin-mcp-sdk-security`
|
|
109
|
+
- `openai`, `@openai/agents`: `eslint-plugin-openai-security`
|
|
110
|
+
- `@anthropic-ai/sdk`, `@anthropic-ai/claude-agent-sdk`: `eslint-plugin-anthropic-security`
|
|
111
|
+
- `@google/genai`: `eslint-plugin-gemini-security`
|
|
112
|
+
- `ai`: `eslint-plugin-vercel-ai-security`
|
|
113
|
+
- `aws-lambda`, `@types/aws-lambda`, `@middy/core`: `eslint-plugin-lambda-security`
|
|
114
|
+
|
|
115
|
+
The full stack-to-plugin playbook (with config rendering and a proof step) is the `security-linting` skill: https://github.com/ofri-peretz/eslint/tree/main/skills/security-linting
|
|
116
|
+
|
|
117
|
+
## More
|
|
118
|
+
|
|
119
|
+
- Docs: https://eslint.interlace.tools/docs/security/plugin-node-security
|
|
120
|
+
- README.md in this package: every rule with examples.
|
|
121
|
+
- `eslint-plugin-node-security/oxlint` is an entry point for oxlint's JS plugin support; see the README.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "eslint-plugin-node-security",
|
|
3
|
-
"version": "6.0
|
|
3
|
+
"version": "6.1.0",
|
|
4
4
|
"description": "ESLint Node security rules for Node.js — detects command injection, path traversal, SSRF, zip slip, and weak crypto (MD5/SHA-1, ECB, static IV) in fs, child_process, vm, and crypto.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -38,7 +38,8 @@
|
|
|
38
38
|
"files": [
|
|
39
39
|
"src/",
|
|
40
40
|
"README.md",
|
|
41
|
-
"LICENSE"
|
|
41
|
+
"LICENSE",
|
|
42
|
+
"AGENTS.md"
|
|
42
43
|
],
|
|
43
44
|
"keywords": [
|
|
44
45
|
"eslint",
|
package/src/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.rules={get"detect-child-process"(){return require("./rules/detect-child-process").detectChildProcess},get"detect-eval-with-expression"(){return require("./rules/detect-eval-with-expression").detectEvalWithExpression},get"detect-non-literal-fs-filename"(){return require("./rules/detect-non-literal-fs-filename").detectNonLiteralFsFilename},get"no-unsafe-dynamic-require"(){return require("./rules/no-unsafe-dynamic-require").noUnsafeDynamicRequire},get"no-buffer-overread"(){return require("./rules/no-buffer-overread").noBufferOverread},get"no-deprecated-buffer"(){return require("./rules/no-deprecated-buffer").noDeprecatedBuffer},get"no-unsafe-buffer-alloc"(){return require("./rules/no-unsafe-buffer-alloc").noUnsafeBufferAlloc},get"no-toctou-vulnerability"(){return require("./rules/no-toctou-vulnerability").noToctouVulnerability},get"no-zip-slip"(){return require("./rules/no-zip-slip").noZipSlip},get"no-arbitrary-file-access"(){return require("./rules/no-arbitrary-file-access").noArbitraryFileAccess},get"no-data-in-temp-storage"(){return require("./rules/no-data-in-temp-storage").noDataInTempStorage},get"no-ssrf"(){return require("./rules/no-ssrf").noSsrf},get"no-shell-injection"(){return require("./rules/no-shell-injection").noShellInjection},get"no-dynamic-command-string"(){return require("./rules/no-dynamic-command-string").noDynamicCommandString},get"no-env-injection"(){return require("./rules/no-env-injection").noEnvInjection},get"no-dynamic-algorithm-selection"(){return require("./rules/no-dynamic-algorithm-selection").noDynamicAlgorithmSelection},get"detect-suspicious-dependencies"(){return require("./rules/detect-suspicious-dependencies").detectSuspiciousDependencies},get"lock-file"(){return require("./rules/lock-file").lockFile},get"no-dynamic-dependency-loading"(){return require("./rules/no-dynamic-dependency-loading").noDynamicDependencyLoading},get"require-dependency-integrity"(){return require("./rules/require-dependency-integrity").requireDependencyIntegrity},get"require-secure-credential-storage"(){return require("./rules/require-secure-credential-storage").requireSecureCredentialStorage},get"require-secure-deletion"(){return require("./rules/require-secure-deletion").requireSecureDeletion},get"require-storage-encryption"(){return require("./rules/require-storage-encryption").requireStorageEncryption},get"no-dynamic-require"(){return require("./rules/no-dynamic-require").noDynamicRequire},get"no-cryptojs"(){return require("./rules/no-cryptojs").noCryptojs},get"no-cryptojs-weak-random"(){return require("./rules/no-cryptojs-weak-random").noCryptojsWeakRandom},get"no-deprecated-cipher-method"(){return require("./rules/no-deprecated-cipher-method").noDeprecatedCipherMethod},get"no-ecb-mode"(){return require("./rules/no-ecb-mode").noEcbMode},get"no-insecure-key-derivation"(){return require("./rules/no-insecure-key-derivation").noInsecureKeyDerivation},get"no-insecure-rsa-padding"(){return require("./rules/no-insecure-rsa-padding").noInsecureRsaPadding},get"no-math-random-crypto"(){return require("./rules/no-math-random-crypto").noMathRandomCrypto},get"no-self-signed-certs"(){return require("./rules/no-self-signed-certs").noSelfSignedCerts},get"no-sha1-hash"(){return require("./rules/no-sha1-hash").noSha1Hash},get"no-static-iv"(){return require("./rules/no-static-iv").noStaticIv},get"no-timing-unsafe-compare"(){return require("./rules/no-timing-unsafe-compare").noTimingUnsafeCompare},get"no-weak-cipher-algorithm"(){return require("./rules/no-weak-cipher-algorithm").noWeakCipherAlgorithm},get"no-weak-dh-parameters"(){return require("./rules/no-weak-dh-parameters").noWeakDhParameters},get"no-weak-hash-algorithm"(){return require("./rules/no-weak-hash-algorithm").noWeakHashAlgorithm},get"prefer-native-crypto"(){return require("./rules/prefer-native-crypto").preferNativeCrypto},get"require-aead-tag-verification"(){return require("./rules/require-aead-tag-verification").requireAeadTagVerification},get"no-unbounded-decompression"(){return require("./rules/no-unbounded-decompression").noUnboundedDecompression},get"no-insecure-http-parser"(){return require("./rules/no-insecure-http-parser").noInsecureHttpParser},get"require-stream-error-handler"(){return require("./rules/require-stream-error-handler").requireStreamErrorHandler}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-node-security",exports.rules);exports.plugin={meta:{name:"eslint-plugin-node-security",version:"6.0
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.rules={get"detect-child-process"(){return require("./rules/detect-child-process").detectChildProcess},get"detect-eval-with-expression"(){return require("./rules/detect-eval-with-expression").detectEvalWithExpression},get"detect-non-literal-fs-filename"(){return require("./rules/detect-non-literal-fs-filename").detectNonLiteralFsFilename},get"no-unsafe-dynamic-require"(){return require("./rules/no-unsafe-dynamic-require").noUnsafeDynamicRequire},get"no-buffer-overread"(){return require("./rules/no-buffer-overread").noBufferOverread},get"no-deprecated-buffer"(){return require("./rules/no-deprecated-buffer").noDeprecatedBuffer},get"no-unsafe-buffer-alloc"(){return require("./rules/no-unsafe-buffer-alloc").noUnsafeBufferAlloc},get"no-toctou-vulnerability"(){return require("./rules/no-toctou-vulnerability").noToctouVulnerability},get"no-zip-slip"(){return require("./rules/no-zip-slip").noZipSlip},get"no-arbitrary-file-access"(){return require("./rules/no-arbitrary-file-access").noArbitraryFileAccess},get"no-data-in-temp-storage"(){return require("./rules/no-data-in-temp-storage").noDataInTempStorage},get"no-ssrf"(){return require("./rules/no-ssrf").noSsrf},get"no-shell-injection"(){return require("./rules/no-shell-injection").noShellInjection},get"no-dynamic-command-string"(){return require("./rules/no-dynamic-command-string").noDynamicCommandString},get"no-env-injection"(){return require("./rules/no-env-injection").noEnvInjection},get"no-dynamic-algorithm-selection"(){return require("./rules/no-dynamic-algorithm-selection").noDynamicAlgorithmSelection},get"detect-suspicious-dependencies"(){return require("./rules/detect-suspicious-dependencies").detectSuspiciousDependencies},get"lock-file"(){return require("./rules/lock-file").lockFile},get"no-dynamic-dependency-loading"(){return require("./rules/no-dynamic-dependency-loading").noDynamicDependencyLoading},get"require-dependency-integrity"(){return require("./rules/require-dependency-integrity").requireDependencyIntegrity},get"require-secure-credential-storage"(){return require("./rules/require-secure-credential-storage").requireSecureCredentialStorage},get"require-secure-deletion"(){return require("./rules/require-secure-deletion").requireSecureDeletion},get"require-storage-encryption"(){return require("./rules/require-storage-encryption").requireStorageEncryption},get"no-dynamic-require"(){return require("./rules/no-dynamic-require").noDynamicRequire},get"no-cryptojs"(){return require("./rules/no-cryptojs").noCryptojs},get"no-cryptojs-weak-random"(){return require("./rules/no-cryptojs-weak-random").noCryptojsWeakRandom},get"no-deprecated-cipher-method"(){return require("./rules/no-deprecated-cipher-method").noDeprecatedCipherMethod},get"no-ecb-mode"(){return require("./rules/no-ecb-mode").noEcbMode},get"no-insecure-key-derivation"(){return require("./rules/no-insecure-key-derivation").noInsecureKeyDerivation},get"no-insecure-rsa-padding"(){return require("./rules/no-insecure-rsa-padding").noInsecureRsaPadding},get"no-math-random-crypto"(){return require("./rules/no-math-random-crypto").noMathRandomCrypto},get"no-self-signed-certs"(){return require("./rules/no-self-signed-certs").noSelfSignedCerts},get"no-sha1-hash"(){return require("./rules/no-sha1-hash").noSha1Hash},get"no-static-iv"(){return require("./rules/no-static-iv").noStaticIv},get"no-timing-unsafe-compare"(){return require("./rules/no-timing-unsafe-compare").noTimingUnsafeCompare},get"no-weak-cipher-algorithm"(){return require("./rules/no-weak-cipher-algorithm").noWeakCipherAlgorithm},get"no-weak-dh-parameters"(){return require("./rules/no-weak-dh-parameters").noWeakDhParameters},get"no-weak-hash-algorithm"(){return require("./rules/no-weak-hash-algorithm").noWeakHashAlgorithm},get"prefer-native-crypto"(){return require("./rules/prefer-native-crypto").preferNativeCrypto},get"require-aead-tag-verification"(){return require("./rules/require-aead-tag-verification").requireAeadTagVerification},get"no-unbounded-decompression"(){return require("./rules/no-unbounded-decompression").noUnboundedDecompression},get"no-insecure-http-parser"(){return require("./rules/no-insecure-http-parser").noInsecureHttpParser},get"require-stream-error-handler"(){return require("./rules/require-stream-error-handler").requireStreamErrorHandler}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-node-security",exports.rules);exports.plugin={meta:{name:"eslint-plugin-node-security",version:"6.1.0"},rules:exports.rules};const recommendedRules={"node-security/detect-child-process":"error","node-security/detect-eval-with-expression":"error","node-security/detect-non-literal-fs-filename":"warn","node-security/no-unsafe-dynamic-require":"error","node-security/no-buffer-overread":"warn","node-security/no-deprecated-buffer":"error","node-security/no-unsafe-buffer-alloc":"warn","node-security/no-toctou-vulnerability":"error","node-security/no-zip-slip":"error","node-security/no-arbitrary-file-access":"error","node-security/no-data-in-temp-storage":"error","node-security/no-ssrf":"warn","node-security/no-shell-injection":"error","node-security/no-dynamic-command-string":"error","node-security/no-env-injection":"error","node-security/no-dynamic-algorithm-selection":"error","node-security/no-timing-unsafe-compare":"warn","node-security/detect-suspicious-dependencies":"warn","node-security/require-dependency-integrity":"error","node-security/no-weak-hash-algorithm":"error","node-security/no-weak-cipher-algorithm":"error","node-security/no-weak-dh-parameters":"error","node-security/no-static-iv":"error","node-security/no-ecb-mode":"error","node-security/no-math-random-crypto":"error","node-security/no-cryptojs":"error","node-security/no-self-signed-certs":"error","node-security/require-aead-tag-verification":"error","node-security/no-unbounded-decompression":"error","node-security/no-insecure-http-parser":"error","node-security/require-stream-error-handler":"error"};exports.configs={recommended:{plugins:{"node-security":exports.plugin},rules:recommendedRules},strict:{plugins:{"node-security":exports.plugin},rules:Object.fromEntries(Object.keys(exports.rules).map(ruleName=>[`node-security/${ruleName}`,"error"]))}};exports.default=exports.plugin;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMathRandomCrypto=void 0;const names_1=require("../../utils/names");const provenance_1=require("../../utils/provenance");const eslint_devkit_1=require("@interlace/eslint-devkit");const CSPRNG_CALLS=new Set(["getRandomValues","randomBytes","randomUUID","randomFillSync","randomFill","generateKey","subtle"]);const CRYPTO_WORDS=["token","tokens","key","keys","secret","secrets","password","passwd","salt","iv","nonce","seed","hash","cipher","auth","session","csrf","otp","pin","code","codes","verify","signature","credential","jwt","encryption","apikey","passphrase","mnemonic"];const DURATION_TAILS=new Set(["delay","timeout","interval","jitter","backoff","ms","millis","milliseconds","seconds","duration","wait","sleep","ttl","deadline","elapsed","latency","budget"]);const QUANTITY_TAILS=new Set(["count","counts","length","size","total","limit","quota","offset","index","rank","score","percent","ratio","rate","version","page"]);const NON_SECURITY_QUALIFIERS=new Map([["code",new Set(["http","status","error","err","exit","country","zip","postal","area","language","lang","locale","currency","promo","coupon","discount","color","colour","qr","bar","region","iso","mime","media","sort","source","char","unicode","ascii","airport"])],["key",new Set(["cache","map","object","row","index","partition","primary","foreign","sort","storage","translation","locale","i18n","react","idempotency","shortcut","keyboard","press","modifier"])]]);function nameSuggestsCrypto(name,vocab){if(!vocab.suggestsCrypto(name))return false;const words=(0,names_1.identifierWords)(name);const tail=words[words.length-1];if(DURATION_TAILS.has(tail)||QUANTITY_TAILS.has(tail))return false;const matched=words.filter(word=>vocab.words.has(word));if(matched.length===0)return true;return!matched.every(word=>{const qualifiers=NON_SECURITY_QUALIFIERS.get(word);return qualifiers!==void 0&&words.some(other=>qualifiers.has(other))})}const GLOBAL_OBJECTS=new Set(["globalThis","global","window","self"]);function isMathObject(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return node.name==="Math";return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&GLOBAL_OBJECTS.has(node.object.name)&&(0,eslint_devkit_1.propertyName)(node)==="Math"}function isMathRandomProperty(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&isMathObject(node.object)&&(0,eslint_devkit_1.propertyName)(node)==="random"}const NON_SECURITY_ID_QUALIFIERS=new Set(["request","req","correlation","trace","span","transaction","txn","message","msg","event","job","run","task","batch","element","node","row","record","instance","component","widget","dom","operation","call","invocation","frame","render"]);function isCorrelationIdFactory(name,vocab){const words=(0,names_1.identifierWords)(name);if(words[words.length-1]!=="id")return false;if(words.some(word=>vocab.words.has(word)))return false;return words.some(word=>vocab.correlationWords.has(word))}function functionNameSuggestsCrypto(name,vocab){if(!CRYPTO_FUNCTION_PATTERNS.some(pattern=>pattern.test(name)))return false;return!isCorrelationIdFactory(name,vocab)}const CRYPTO_FUNCTION_PATTERNS=[/generate.*token/i,/generate.*key/i,/generate.*id/i,/create.*secret/i,/create.*token/i,/random.*string/i,/get.*random.*(string|bytes|token|key|secret|value|id)/i,/make.*salt/i,/gen.*password/i];exports.noMathRandomCrypto=(0,eslint_devkit_1.createRule)({name:"no-math-random-crypto",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-math-random-crypto.md",description:"Disallow Math.random() for cryptographic purposes",cwe:"CWE-338",cvss:7.5,confidence:"medium"},messages:{pseudoRandomBytes:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Non-cryptographic random bytes",cwe:"CWE-338",owasp:"A02:2021",cvss:7.5,description:"crypto.pseudoRandomBytes() is not cryptographically secure. The name is the API's own warning: it was deprecated in Node 4 precisely because callers assumed otherwise.",severity:"HIGH",compliance:["SOC2","PCI-DSS","ISO27001"],fix:"Use crypto.randomBytes(n), or crypto.randomUUID() for identifiers.",documentationLink:"https://cwe.mitre.org/data/definitions/338.html"}),mathRandomCrypto:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Math.random() used for crypto",cwe:"CWE-338",description:"Math.random() is not cryptographically secure. It uses a PRNG that can be predicted. Never use it for tokens, keys, passwords, or any security-sensitive values.",severity:"CRITICAL",fix:"Use crypto.randomBytes() or crypto.randomUUID() instead",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html#secure-random-number-generation"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true,description:"Allow Math.random() in test files. Default: true"},secretWords:{type:"array",items:{type:"string"},default:[...CRYPTO_WORDS],description:"Words that name a security value in this codebase. Replaces the default list."},correlationIdWords:{type:"array",items:{type:"string"},default:[...NON_SECURITY_ID_QUALIFIERS],description:"Words that mark a trailing `id` as a correlation id rather than a credential. Replaces the default list."}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,secretWords:[...CRYPTO_WORDS],correlationIdWords:[...NON_SECURITY_ID_QUALIFIERS]}],createOnce(context,currentOptions){let vocab;let sourceCode;let isTestFile;function stableDeclarator(id){const variable=(0,provenance_1.findVariable)(sourceCode,id);if(!variable||variable.defs.length!==1)return void 0;const def=variable.defs[0];if(def.type!=="Variable")return void 0;const reassigned=variable.references.some(reference=>reference.writeExpr!=null&&!reference.init);return reassigned?void 0:def.node}function isCsprngFallback(node){let scope=node.parent;while(scope.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&scope.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression&&scope.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&scope.type!==eslint_devkit_1.AST_NODE_TYPES.Program){scope=scope.parent}let found=false;const stack=[scope];while(stack.length>0&&!found){const current=stack.pop();if(current.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&¤t.range[1]<=node.range[0]){const callee=current.callee;const name=callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?(0,eslint_devkit_1.propertyName)(callee)??"":callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.name:"";if(CSPRNG_CALLS.has(name))found=true}for(const key of Object.keys(current)){if(key==="parent")continue;const value=current[key];for(const child of Array.isArray(value)?value:[value]){if(child!==null&&typeof child==="object"&&typeof child.type==="string"){stack.push(child)}}}}return found}function isMathRandomCallee(callee){if(isMathRandomProperty(callee))return true;const wanted=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&wanted!==null){const init2=stableDeclarator(callee.object)?.init;if(!init2||init2.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return false;return init2.properties.some(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(0,eslint_devkit_1.objectKeyName)(property)===wanted&&isMathRandomProperty(property.value))}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const declarator=stableDeclarator(callee);const init=declarator?.init;if(!declarator||!init)return false;if(declarator.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return isMathRandomProperty(init)}if(declarator.id.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern)return false;if(!isMathObject(init))return false;return declarator.id.properties.some(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&property.value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.value.name===callee.name&&(0,eslint_devkit_1.objectKeyName)(property)==="random")}function usedInCryptoContext(id,followed){const variable=(0,provenance_1.findVariable)(sourceCode,id);if(!variable||followed.has(variable))return false;followed.add(variable);return variable.references.some(reference=>!reference.init&&isCryptoContext(reference.identifier,followed))}function escapesFunction(fn,cameFrom,passedReturn){if(fn.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&fn.expression&&fn.body===cameFrom){return true}return passedReturn}function isCryptoContext(node,followed=new Set){let child=node;let current=node.parent;let namesThisValue=true;let passedReturn=false;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){if(!escapesFunction(current,child,passedReturn))namesThisValue=false;passedReturn=false}if(current.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)passedReturn=true;if(namesThisValue&¤t.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator){if(current.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const varName=current.id.name;if(nameSuggestsCrypto(varName,vocab)){return true}if(usedInCryptoContext(current.id,followed)){return true}}}if(current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&¤t.id){const funcName=current.id.name;if(functionNameSuggestsCrypto(funcName,vocab)){return true}}if(namesThisValue&¤t.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression){const propName=(0,eslint_devkit_1.memberPropertyName)(current.left);if(propName!==null){if(nameSuggestsCrypto(propName,vocab)){return true}}if(current.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(nameSuggestsCrypto(current.left.name,vocab)){return true}}}if(namesThisValue&¤t.type===eslint_devkit_1.AST_NODE_TYPES.Property){if(current.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const propName=current.key.name;if(nameSuggestsCrypto(propName,vocab)){return true}}}if(current.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement){const funcName=findContainingFunction(current)?.id?.name;if(funcName!==void 0&&(functionNameSuggestsCrypto(funcName,vocab)||nameSuggestsCrypto(funcName,vocab))){return true}}child=current;current=current.parent}return false}function findContainingFunction(node){let current=node.parent;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){return current}current=current.parent}return null}return{before(){const[options={}]=currentOptions();const{allowInTests=true,secretWords=CRYPTO_WORDS,correlationIdWords=[...NON_SECURITY_ID_QUALIFIERS]}=options;vocab={words:new Set(secretWords),correlationWords:new Set(correlationIdWords),suggestsCrypto:(0,names_1.makeNameTest)(secretWords)};sourceCode=context.sourceCode;const filename=context.filename;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename)},CallExpression(node){if(isTestFile)return;if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(node.callee)==="pseudoRandomBytes"){context.report({node,messageId:"pseudoRandomBytes"});return}if(isMathRandomCallee(node.callee)){if(isCryptoContext(node)&&!isCsprngFallback(node)){context.report({node,messageId:"mathRandomCrypto"})}}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMathRandomCrypto=void 0;const names_1=require("../../utils/names");const provenance_1=require("../../utils/provenance");const eslint_devkit_1=require("@interlace/eslint-devkit");const CSPRNG_CALLS=new Set(["getRandomValues","randomBytes","randomUUID","randomFillSync","randomFill","generateKey","subtle"]);const CRYPTO_WORDS=["token","tokens","key","keys","secret","secrets","password","passwd","salt","iv","nonce","seed","hash","cipher","auth","session","csrf","otp","pin","code","codes","verify","signature","credential","jwt","encryption","apikey","passphrase","mnemonic"];const DURATION_TAILS=new Set(["delay","timeout","interval","jitter","backoff","ms","millis","milliseconds","seconds","duration","wait","sleep","ttl","deadline","elapsed","latency","budget"]);const QUANTITY_TAILS=new Set(["count","counts","length","size","total","limit","quota","offset","index","rank","score","percent","ratio","rate","version","page"]);const NON_SECURITY_QUALIFIERS=new Map([["code",new Set(["http","status","error","err","exit","country","zip","postal","area","language","lang","locale","currency","promo","coupon","discount","color","colour","qr","bar","region","iso","mime","media","sort","source","char","unicode","ascii","airport"])],["key",new Set(["cache","map","object","row","index","partition","primary","foreign","sort","storage","translation","locale","i18n","react","idempotency","shortcut","keyboard","press","modifier","dom","element","node","item","list","child","component","render","data","color","colour"])]]);function nameSuggestsCrypto(name,vocab){if(!vocab.suggestsCrypto(name))return false;const words=(0,names_1.identifierWords)(name);const tail=words[words.length-1];if(DURATION_TAILS.has(tail)||QUANTITY_TAILS.has(tail))return false;const matched=words.filter(word=>vocab.words.has(word));if(matched.length===0)return true;return!matched.every(word=>{const qualifiers=NON_SECURITY_QUALIFIERS.get(word);return qualifiers!==void 0&&words.some(other=>qualifiers.has(other))})}const GLOBAL_OBJECTS=new Set(["globalThis","global","window","self"]);function isMathObject(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return node.name==="Math";return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&GLOBAL_OBJECTS.has(node.object.name)&&(0,eslint_devkit_1.propertyName)(node)==="Math"}function isMathRandomProperty(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&isMathObject(node.object)&&(0,eslint_devkit_1.propertyName)(node)==="random"}const NON_SECURITY_ID_QUALIFIERS=new Set(["request","req","correlation","trace","span","transaction","txn","message","msg","event","job","run","task","batch","element","node","row","record","instance","component","widget","dom","operation","call","invocation","frame","render"]);function isCorrelationIdFactory(name,vocab){const words=(0,names_1.identifierWords)(name);if(words[words.length-1]!=="id")return false;if(words.some(word=>vocab.words.has(word)))return false;return words.some(word=>vocab.correlationWords.has(word))}const NAME_VALUE_SETTERS=new Set(["set","append","setHeader","header","cookie","setCookie","setItem"]);const QUERY_RECEIVER=/param|query|search/i;const OAUTH_REQUEST_KEYS=new Set(["clientid","redirecturi","responsetype","codechallenge","scope"]);const normalizeKey=key=>key.toLowerCase().replaceAll(/[_-]/g,"");const TRANSPARENT_WRAPPERS=new Set(["encodeURIComponent","encodeURI","String"]);function functionNameSuggestsCrypto(name,vocab){if(!CRYPTO_FUNCTION_PATTERNS.some(pattern=>pattern.test(name)))return false;return!isCorrelationIdFactory(name,vocab)}const CRYPTO_FUNCTION_PATTERNS=[/generate.*token/i,/generate.*key/i,/generate.*id/i,/create.*secret/i,/create.*token/i,/random.*string/i,/get.*random.*(string|bytes|token|key|secret|value|id)/i,/make.*salt/i,/gen.*password/i];exports.noMathRandomCrypto=(0,eslint_devkit_1.createRule)({name:"no-math-random-crypto",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-math-random-crypto.md",description:"Disallow Math.random() for cryptographic purposes",cwe:"CWE-338",cvss:7.5,confidence:"medium"},messages:{pseudoRandomBytes:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Non-cryptographic random bytes",cwe:"CWE-338",owasp:"A02:2021",cvss:7.5,description:"crypto.pseudoRandomBytes() is not cryptographically secure. The name is the API's own warning: it was deprecated in Node 4 precisely because callers assumed otherwise.",severity:"HIGH",compliance:["SOC2","PCI-DSS","ISO27001"],fix:"Use crypto.randomBytes(n), or crypto.randomUUID() for identifiers.",documentationLink:"https://cwe.mitre.org/data/definitions/338.html"}),mathRandomCrypto:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Math.random() used for crypto",cwe:"CWE-338",description:"Math.random() is not cryptographically secure. It uses a PRNG that can be predicted. Never use it for tokens, keys, passwords, or any security-sensitive values.",severity:"CRITICAL",fix:"Use crypto.randomBytes() or crypto.randomUUID() instead",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html#secure-random-number-generation"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true,description:"Allow Math.random() in test files. Default: true"},secretWords:{type:"array",items:{type:"string"},default:[...CRYPTO_WORDS],description:"Words that name a security value in this codebase. Replaces the default list."},correlationIdWords:{type:"array",items:{type:"string"},default:[...NON_SECURITY_ID_QUALIFIERS],description:"Words that mark a trailing `id` as a correlation id rather than a credential. Replaces the default list."}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,secretWords:[...CRYPTO_WORDS],correlationIdWords:[...NON_SECURITY_ID_QUALIFIERS]}],createOnce(context,currentOptions){let vocab;let sourceCode;let isTestFile;function stableDeclarator(id){const variable=(0,provenance_1.findVariable)(sourceCode,id);if(!variable||variable.defs.length!==1)return void 0;const def=variable.defs[0];if(def.type!=="Variable")return void 0;const reassigned=variable.references.some(reference=>reference.writeExpr!=null&&!reference.init);return reassigned?void 0:def.node}function isCsprngFallback(node){let scope=node.parent;while(scope.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&scope.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression&&scope.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&scope.type!==eslint_devkit_1.AST_NODE_TYPES.Program){scope=scope.parent}let found=false;const stack=[scope];while(stack.length>0&&!found){const current=stack.pop();if(current.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&¤t.range[1]<=node.range[0]){const callee=current.callee;const name=callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?(0,eslint_devkit_1.propertyName)(callee)??"":callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.name:"";if(CSPRNG_CALLS.has(name))found=true}for(const key of Object.keys(current)){if(key==="parent")continue;const value=current[key];for(const child of Array.isArray(value)?value:[value]){if(child!==null&&typeof child==="object"&&typeof child.type==="string"){stack.push(child)}}}}return found}function isMathRandomCallee(callee){if(isMathRandomProperty(callee))return true;const wanted=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&wanted!==null){const init2=stableDeclarator(callee.object)?.init;if(!init2||init2.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return false;return init2.properties.some(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(0,eslint_devkit_1.objectKeyName)(property)===wanted&&isMathRandomProperty(property.value))}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const declarator=stableDeclarator(callee);const init=declarator?.init;if(!declarator||!init)return false;if(declarator.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return isMathRandomProperty(init)}if(declarator.id.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern)return false;if(!isMathObject(init))return false;return declarator.id.properties.some(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&property.value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.value.name===callee.name&&(0,eslint_devkit_1.objectKeyName)(property)==="random")}function usedInCryptoContext(id,followed){const variable=(0,provenance_1.findVariable)(sourceCode,id);if(!variable||followed.has(variable))return false;followed.add(variable);return variable.references.some(reference=>!reference.init&&isCryptoContext(reference.identifier,followed))}function escapesFunction(fn,cameFrom,passedReturn){if(fn.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&fn.expression&&fn.body===cameFrom){return true}return passedReturn}function trailingText(start){let node=start;while(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){node=node.right}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal){return String(node.value)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.at(-1).value.raw}return""}function looksLikeAuthorizeRequest(object){return object.properties.some(property=>{if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property)return false;const key=(0,eslint_devkit_1.objectKeyName)(property);return key!==null&&OAUTH_REQUEST_KEYS.has(normalizeKey(key))})}function isOAuthStateUse(reference){let node=reference;while(node.parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.parent.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&TRANSPARENT_WRAPPERS.has(node.parent.callee.name)&&node.parent.arguments[0]===node){node=node.parent}const parent=node.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const at=parent.expressions.indexOf(node);return/state=$/i.test(parent.quasis[at].value.raw)}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&parent.operator==="+"&&parent.right===node){return/state=$/i.test(trailingText(parent.left))}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.value===node&&(0,eslint_devkit_1.objectKeyName)(parent)==="state"&&parent.parent.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){return looksLikeAuthorizeRequest(parent.parent)}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&["set","append"].includes((0,eslint_devkit_1.propertyName)(parent.callee)??"")&&parent.arguments[1]===node){return(0,eslint_devkit_1.staticString)(parent.arguments[0])?.toLowerCase()==="state"}return false}function isOAuthStateBinding(id){const words=(0,names_1.identifierWords)(id.name);if(words[words.length-1]!=="state")return false;const variable=(0,provenance_1.findVariable)(sourceCode,id);return variable.references.some(reference=>!reference.init&&isOAuthStateUse(reference.identifier))}function isSecuritySlot(call,child){const callee=call.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null||!NAME_VALUE_SETTERS.has(method))return false;const at=call.arguments.indexOf(child);if(at<1)return false;const slot=(0,eslint_devkit_1.staticString)(call.arguments[0]);if(slot===null)return false;if(nameSuggestsCrypto(slot,vocab))return true;const receiver=callee.object;const receiverName=receiver.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?receiver.name:(0,eslint_devkit_1.memberPropertyName)(receiver)??"";return slot.toLowerCase()==="state"&&["set","append"].includes(method)&&QUERY_RECEIVER.test(receiverName)}function isShuffleComparator(node){let current=node.parent;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){const call=current.parent;return call.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&call.arguments[0]===current&&call.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&((0,eslint_devkit_1.propertyName)(call.callee)==="sort"||(0,eslint_devkit_1.propertyName)(call.callee)==="toSorted")}current=current.parent}return false}function isCryptoContext(node,followed=new Set){let child=node;let current=node.parent;let namesThisValue=true;let passedReturn=false;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){if(!escapesFunction(current,child,passedReturn))namesThisValue=false;passedReturn=false}if(current.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)passedReturn=true;if(namesThisValue&¤t.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator){if(current.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const varName=current.id.name;if(nameSuggestsCrypto(varName,vocab)){return true}if(isOAuthStateBinding(current.id)){return true}if(usedInCryptoContext(current.id,followed)){return true}}}if(current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&¤t.id){const funcName=current.id.name;if(functionNameSuggestsCrypto(funcName,vocab)){return true}}if(namesThisValue&¤t.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression){const propName=(0,eslint_devkit_1.memberPropertyName)(current.left);if(propName!==null){if(nameSuggestsCrypto(propName,vocab)){return true}}if(current.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(nameSuggestsCrypto(current.left.name,vocab)){return true}}}if(namesThisValue&¤t.type===eslint_devkit_1.AST_NODE_TYPES.Property){const propName=(0,eslint_devkit_1.objectKeyName)(current);if(propName!==null){if(nameSuggestsCrypto(propName,vocab)){return true}if(propName==="state"&¤t.parent.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression&&looksLikeAuthorizeRequest(current.parent)){return true}}}if(namesThisValue&¤t.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&isSecuritySlot(current,child)){return true}if(current.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement){const funcName=findContainingFunction(current)?.id?.name;if(funcName!==void 0&&(functionNameSuggestsCrypto(funcName,vocab)||nameSuggestsCrypto(funcName,vocab))){return true}}child=current;current=current.parent}return false}function findContainingFunction(node){let current=node.parent;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){return current}current=current.parent}return null}return{before(){const[options={}]=currentOptions();const{allowInTests=true,secretWords=CRYPTO_WORDS,correlationIdWords=[...NON_SECURITY_ID_QUALIFIERS]}=options;vocab={words:new Set(secretWords),correlationWords:new Set(correlationIdWords),suggestsCrypto:(0,names_1.makeNameTest)(secretWords)};sourceCode=context.sourceCode;const filename=context.filename;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename)},CallExpression(node){if(isTestFile)return;if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(node.callee)==="pseudoRandomBytes"){context.report({node,messageId:"pseudoRandomBytes"});return}if(isMathRandomCallee(node.callee)){if(!isShuffleComparator(node)&&isCryptoContext(node)&&!isCsprngFallback(node)){context.report({node,messageId:"mathRandomCrypto"})}}}}}});
|