eslint-plugin-secure-coding 3.3.3 → 3.4.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/CHANGELOG.md CHANGED
@@ -1,3 +1,80 @@
1
+ ## 3.4.0
2
+
3
+ ### Minor Changes
4
+
5
+ - [#288](https://github.com/ofri-peretz/eslint/pull/288) [`89bea05`](https://github.com/ofri-peretz/eslint/commit/89bea05c6c48f5f1bdbcc3c87b301d967d962051) Thanks [@ofri-peretz](https://github.com/ofri-peretz)! - Cut false positives in five security rules, measured against a 1,470-file corpus (webpack `lib/`, lodash, eslint-plugin-import `src/`, and two NestJS boilerplates).
6
+
7
+ **`secure-coding/no-hardcoded-credentials` — decide on the value, not the key name.** The rule reported any string in a credential-named slot, so `errors: { password: 'incorrectPassword' }` (an i18n error key) was a CVSS 9.8 finding — 5 of its 10 corpus hits. Detection is now driven by the value's shape: entropy, character-class mix, charset, and a "natural word string" test that rejects identifier- and message-shaped values. A credential-shaped name is still consulted, but only to promote an already-secret-shaped value. Corpus: **10 → 7 findings, and all 7 are true positives** — including two the old logic missed, because a 25-character random `key:` is now found by shape rather than by being on a name allowlist.
8
+
9
+ **`secure-coding/no-unsafe-deserialization` — `setTimeout` is not a deserializer.** `await new Promise(resolve => setTimeout(resolve, 1000))` was rated CVSS 9.8 CRITICAL. `setTimeout` / `setInterval` now only report in their implied-`eval` form (string first argument), and calls inside a function named `deserialize` / `unserialize` / `fromJSON` / `fromBuffer` — a class implementing a serialization protocol — are exempt. Corpus: **35 → 4**.
10
+
11
+ **`secure-coding/no-graphql-injection` — require real GraphQL syntax.** Any template literal containing a nested brace or the word `type` was a CVSS 9.8 GraphQL injection. Operation and schema keywords must now start a line, schema keywords require a body, and a bare selection set must be the entire string. Concatenations are matched on their reassembled static value rather than on their source text. Corpus: **41 → 0**.
12
+
13
+ **`node-security/require-secure-deletion` — only sensitive properties.** The rule fired on every `delete obj.prop`. It now reports only a statically known, sensitive property name (`password`, `token`, `apiKey`, `privateKey`, `sessionId`, …), configurable via the new `additionalSensitiveProperties` option, and understands computed access and optional chaining. Corpus: **25 → 1** (a genuine `delete userDto.oldPassword`).
14
+
15
+ **`secure-coding/no-insecure-comparison` — removed from `recommended`, `recommended-strict` and `owasp-top-10`.** It is deprecated in favour of `node-security/no-timing-unsafe-compare`, and its loose-equality half re-reports core `eqeqeq` under a CWE-697 banner — 433 corpus findings, all duplicates. No narrowing fixes that, so the honest change is to stop switching it on for people; it remains exported and available via `strict` or explicit opt-in. Its timing-attack half was also narrowed to match secret keywords on identifier **word segments** instead of substrings of the whole expression text, which stops `if (key === "__non_webpack_require__")` (and `monkey`, `keyword`, `machine`, `author`) from being reported: **443 → 221**.
16
+
17
+ ### Patch Changes
18
+
19
+ - [#294](https://github.com/ofri-peretz/eslint/pull/294) [`659f6dc`](https://github.com/ofri-peretz/eslint/commit/659f6dc0181b03b675f72b5949fcf123dd066358) Thanks [@ofri-peretz](https://github.com/ofri-peretz)! - Rewrite `description` and `keywords` on every published package for npm search discovery. npm ranks on name, description, and keywords, and the registry only picks up these fields at publish — so this is metadata-only and takes effect for each package on its next release.
20
+
21
+ **Descriptions now lead with the search phrase.** Every one starts `ESLint plugin for <the thing you'd search>` instead of a brand-first or category-first framing, and names the concrete vulnerabilities the plugin actually detects. Three were corrected while doing so:
22
+
23
+ - `eslint-plugin-import-next` claimed "100x faster no-cycle detection". No 100x measurement exists: `CLAIMS.md` records **3.1x end-to-end** (8x in pure rule execution) on a 5,483-file React codebase, and the highest number in any benchmark result is 54.9x on the synthetic corpus. The description now states the real-codebase figure.
24
+ - `eslint-plugin-secure-coding` claimed SQL injection, XSS and CSRF coverage — none of which are its rules. It now names what it does detect: LDAP, XPath, XXE, GraphQL and template injection, unsafe deserialization, ReDoS, missing authentication, and PII in logs.
25
+ - `eslint-plugin-secure-coding` ("89 rules") and `eslint-plugin-react-a11y` ("37 rules") hard-coded rule counts that had drifted from reality. Counts are generated into `interlace-numbers.json`; hand-typed copies are removed rather than corrected.
26
+
27
+ **Keywords now match the vocabulary of the plugins that rank.** `eslint-plugin-security`, `eslint-plugin-jsx-a11y`, `eslint-plugin-n` and `eslint-plugin-import` all carry the `eslint` / `eslintplugin` / `eslint-plugin` trio — six of our packages were missing `eslintplugin`, and every one now carries all three plus `static-analysis`, `linting` and `code-quality`. Security plugins add `sast`, `appsec` and `vulnerability`; `node-security` and `secure-coding` also carry `nodesecurity`, the exact keyword `eslint-plugin-security` ranks on. Each plugin gained the CWE identifiers and attack names for what it detects (`cwe-78` command injection, `cwe-22` path traversal, `cwe-89` SQL injection, `cwe-79` XSS, `cwe-347` JWT algorithm confusion, `cwe-352` CSRF, `cwe-943` NoSQL injection), and `node-security` gained the crypto vocabulary it had been missing entirely despite absorbing the crypto rule set (`crypto`, `cryptography`, `weak-hash`, `md5`, `sha1`, `timing-attack`).
28
+
29
+ No rule behavior, exports, or configuration changes.
30
+
31
+ - [#296](https://github.com/ofri-peretz/eslint/pull/296) [`0c7a208`](https://github.com/ofri-peretz/eslint/commit/0c7a208f568436cc55ac6732641df46e8f44af1f) Thanks [@ofri-peretz](https://github.com/ofri-peretz)! - Cut two false positives confirmed against the benchmark corpus SAFE fixtures.
32
+
33
+ **`node-security/no-ssrf`** — the user-input gate only ran when the URL argument
34
+ was a bare identifier, so every other shape reported unconditionally. A Node
35
+ options object built from a helper's own parameters —
36
+ `https.request({ host, path, method: 'GET' })`, from
37
+ `benchmarks/corpus/CWE-444/safe/request-default-parser.js` — was flagged with no
38
+ user data anywhere in the flow.
39
+
40
+ The gate now applies to every argument shape and requires evidence: a
41
+ user-input-named identifier standing as the URL, a read off a request object
42
+ (`req` / `request` / `ctx` / `event`), or a template literal or concatenation
43
+ interpolating either. Options-object fields count when they are request-sourced,
44
+ or when a `url` / `href` / `uri` key holds a user-input-named identifier.
45
+
46
+ Newly ignored: options objects and interpolations built purely from locals.
47
+ Still reported: `fetch(userUrl)`, `fetch(req.query.url)`,
48
+ `https.request({ host: req.query.host })`, ``fetch(`https://${userHost}/x`)``.
49
+
50
+ **`secure-coding/no-hardcoded-credentials`** — `secret: '<your-secret-here>'`
51
+ from `benchmarks/corpus/CWE-798/safe/test-placeholder-values.js` was reported at
52
+ CVSS 9.8. The angle brackets are two character classes, which is all the shape
53
+ gate asks for once the slot is credential-named.
54
+
55
+ Self-evident placeholders are now skipped: bracketed template slots (`<…>`,
56
+ `{{…}}`, `${…}`, `[…]`), placeholder words standing as their own token
57
+ (`changeme`, `YOUR_API_KEY`, `example`), and one character repeated
58
+ (`xxxxxxxxxxxx`). Whole-token matching only, so a real secret that merely
59
+ contains such a substring is unaffected.
60
+
61
+ The allowlist applies to non-structural findings only — a JWT, an `sk_live_`
62
+ key, or a `postgres://user:pass@host` string still reports whatever words it
63
+ contains. Set the new `allowPlaceholders: false` option to restore the previous
64
+ behaviour.
65
+
66
+ - Updated dependencies [[`e1cdf83`](https://github.com/ofri-peretz/eslint/commit/e1cdf83e3db761907f0ab06f7fc6c1f1da7513a5), [`659f6dc`](https://github.com/ofri-peretz/eslint/commit/659f6dc0181b03b675f72b5949fcf123dd066358)]:
67
+ - @interlace/eslint-devkit@1.4.3
68
+
69
+ ## 3.3.4
70
+
71
+ ### Patch Changes
72
+
73
+ - [#269](https://github.com/ofri-peretz/eslint/pull/269) [`7028fe2`](https://github.com/ofri-peretz/eslint/commit/7028fe2668a42266d831014184dcef70e73101ad) Thanks [@ofri-peretz](https://github.com/ofri-peretz)! - docs: dual-logo README header (Interlace mark + ESLint mark side by side) and closing Interlace footer — refreshes the README rendered on npmjs.com. No runtime changes.
74
+
75
+ - Updated dependencies [[`7028fe2`](https://github.com/ofri-peretz/eslint/commit/7028fe2668a42266d831014184dcef70e73101ad)]:
76
+ - @interlace/eslint-devkit@1.4.2
77
+
1
78
  ## 3.3.3
2
79
 
3
80
  ### Patch Changes
package/README.md CHANGED
@@ -1,5 +1,7 @@
1
1
  <p align="center">
2
- <a href="https://eslint.interlace.tools/?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding" target="blank"><img src="https://eslint.interlace.tools/eslint-interlace-logo-light.svg" alt="ESLint Interlace Logo" width="120" /></a>
2
+ <a href="https://eslint.interlace.tools/?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding" target="blank"><img src="https://eslint.interlace.tools/icon-light.svg" alt="Interlace" height="90" /></a>
3
+ &nbsp;&nbsp;
4
+ <a href="https://eslint.org" target="_blank"><img src="https://eslint.interlace.tools/eslint-logo.svg" alt="ESLint" height="90" /></a>
3
5
  </p>
4
6
 
5
7
  <p align="center">
@@ -126,13 +128,13 @@ See the [ESLint Version Support Policy](../../docs/ESLINT_VERSION_SUPPORT.md)
126
128
  | [no-hardcoded-session-tokens](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-hardcoded-session-tokens?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-798 | | | This rule detects hardcoded JWT tokens (starting with eyJ), Bearer tokens, and session identifiers | 🟢 | | | | | |
127
129
  | [no-improper-sanitization](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-improper-sanitization?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-116 | | | Detects improper sanitization of user input | 🟢 | | | | | |
128
130
  | [no-improper-type-validation](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-improper-type-validation?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-1287 | | | Detects improper type validation in user input handling | 🟢 | 💼 | | | | |
129
- | [no-insecure-comparison](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-insecure-comparison?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-697 | | | Detects insecure comparison operators (==, !=) that can lead to type coercion vulnerabilities | 🟢 | 💼 | | | | |
131
+ | [no-insecure-comparison](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-insecure-comparison?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-697 | | | Detects insecure comparison operators (==, !=) that can lead to type coercion vulnerabilities | 🟢 | | | | | |
130
132
  | [no-ldap-injection](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-ldap-injection?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-90 | | | Detects LDAP injection vulnerabilities | 🟢 | 💼 | | | | |
131
- | [no-missing-authentication](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-missing-authentication?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-287 | | | CWE: [CWE-287](https://cwe.mitre.org/data/definitions/287.html) | 🟢 | 💼 | | | | |
133
+ | [no-missing-authentication](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-missing-authentication?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-287 | | | CWE: [CWE-287](https://cwe.mitre.org/data/definitions/287.html) | 🟢 | | | | | |
132
134
  | [no-pii-in-logs](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-pii-in-logs?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-359 | | | Prevent personally identifiable information (PII) — emails, SSNs, credit cards, phone numbers — from reachi… | 🟢 | | | | 💡 | |
133
- | [no-privilege-escalation](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-privilege-escalation?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-269 | | | Detects potential privilege escalation vulnerabilities where user input is used to assign roles or permissi… | 🟢 | 💼 | | | | |
135
+ | [no-privilege-escalation](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-privilege-escalation?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-269 | | | Detects potential privilege escalation vulnerabilities where user input is used to assign roles or permissi… | 🟢 | | ⚠️ | | | |
134
136
  | [no-redos-vulnerable-regex](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-redos-vulnerable-regex?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-400 | | | ESLint Rule: no-redos-vulnerable-regex | 🟢 | | | | | |
135
- | [no-sensitive-data-exposure](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-sensitive-data-exposure?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-532 | | | ESLint Rule: no-sensitive-data-exposure | 🟢 | 💼 | | | | |
137
+ | [no-sensitive-data-exposure](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-sensitive-data-exposure?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-532 | | | ESLint Rule: no-sensitive-data-exposure | 🟢 | | ⚠️ | | | |
136
138
  | [no-unchecked-loop-condition](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-unchecked-loop-condition?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-400 | | | Detects unchecked loop conditions that could cause DoS | 🟢 | | | | | |
137
139
  | [no-unlimited-resource-allocation](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-unlimited-resource-allocation?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-770 | | | Detects unlimited resource allocation that could cause DoS | 🟢 | | | | | |
138
140
  | [no-unsafe-deserialization](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-unsafe-deserialization?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-502 | | | Detects unsafe deserialization of untrusted data | 🟢 | 💼 | | | | |
@@ -176,4 +178,8 @@ MIT © [Ofri Peretz](https://github.com/ofri-peretz)
176
178
 
177
179
  <p align="center">
178
180
  <a href="https://eslint.interlace.tools/docs/security/plugin-secure-coding?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding"><img src="https://eslint.interlace.tools/images/og-secure-coding.png" alt="ESLint Interlace Plugin" width="100%" /></a>
179
- </p>
181
+ </p>
182
+
183
+ <p align="center">
184
+ <a href="https://eslint.interlace.tools/?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding" target="blank"><img src="https://eslint.interlace.tools/icon-light.svg" alt="Interlace" height="70" /></a>
185
+ </p>
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "eslint-plugin-secure-coding",
3
- "version": "3.3.3",
4
- "description": "Security-focused ESLint plugin with 89 AI-parseable rules for detecting and preventing vulnerabilities. OWASP Top 10 2021 + Mobile Top 10 2024 coverage, CWE references, and AI-assisted fix guidance.",
3
+ "version": "3.4.0",
4
+ "description": "ESLint plugin for secure coding — detects LDAP, XPath, XXE, GraphQL and template injection, unsafe deserialization, ReDoS, missing authentication, and PII in logs.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
7
7
  "types": "./src/index.d.ts",
@@ -43,32 +43,38 @@
43
43
  ],
44
44
  "keywords": [
45
45
  "eslint",
46
- "eslint-plugin",
47
46
  "eslintplugin",
48
- "interlace-security",
47
+ "eslint-plugin",
48
+ "static-analysis",
49
+ "linting",
50
+ "code-quality",
49
51
  "security",
50
- "secure-coding",
52
+ "sast",
53
+ "appsec",
54
+ "vulnerability",
51
55
  "owasp",
52
- "owasp-top-10",
53
56
  "cwe",
54
- "vulnerability",
55
- "sql-injection",
56
- "xss",
57
- "csrf",
57
+ "interlace-security",
58
+ "secure-coding",
59
+ "nodesecurity",
60
+ "owasp-top-10",
58
61
  "injection",
62
+ "ldap-injection",
63
+ "xpath-injection",
64
+ "xxe",
65
+ "graphql-injection",
66
+ "template-injection",
67
+ "object-injection",
68
+ "redos",
69
+ "deserialization",
70
+ "hardcoded-credentials",
71
+ "pii",
72
+ "authentication",
73
+ "authorization",
59
74
  "llm-optimized",
60
75
  "ai-assistant",
61
- "auto-fix",
62
76
  "typescript",
63
- "linting",
64
- "code-quality",
65
- "ast",
66
- "static-analysis",
67
- "mcp",
68
- "model-context-protocol",
69
- "github-copilot",
70
- "cursor-ai",
71
- "claude-ai"
77
+ "auto-fix"
72
78
  ],
73
79
  "engines": {
74
80
  "node": ">=18.0.0"
@@ -81,7 +87,7 @@
81
87
  },
82
88
  "dependencies": {
83
89
  "tslib": "^2.3.0",
84
- "@interlace/eslint-devkit": "^1.4.1",
90
+ "@interlace/eslint-devkit": "^1.4.3",
85
91
  "scslre": "^0.3.0",
86
92
  "@eslint-community/regexpp": "^4.10.0"
87
93
  },
package/src/index.js CHANGED
@@ -103,7 +103,7 @@ exports.rules = {
103
103
  exports.plugin = {
104
104
  meta: {
105
105
  name: 'eslint-plugin-secure-coding',
106
- version: '3.3.3',
106
+ version: '3.4.0',
107
107
  },
108
108
  rules: exports.rules,
109
109
  };
@@ -131,7 +131,23 @@ const recommendedRules = {
131
131
  'secure-coding/detect-object-injection': 'warn',
132
132
  // Critical - Credentials
133
133
  'secure-coding/no-hardcoded-credentials': 'error',
134
- 'secure-coding/no-insecure-comparison': 'warn',
134
+ // NOTE: `no-insecure-comparison` is intentionally NOT in `recommended`
135
+ // (removed 2026-07-31). It is `deprecated` in favour of
136
+ // `node-security/no-timing-unsafe-compare`, and what it actually reports on
137
+ // ordinary code is every `==` / `!=` — 876 findings on a 1,470-file corpus
138
+ // (webpack, lodash, eslint-plugin-import, two NestJS boilerplates), 100% of
139
+ // them already covered by core `eqeqeq`. Re-reporting another rule's
140
+ // findings under a CWE-697 security banner is noise, not signal, and no
141
+ // narrowing fixes that: the loose-equality half of this rule is a style
142
+ // check wearing a security hat.
143
+ //
144
+ // The timing-attack half (a secret compared with `===`) is the part worth
145
+ // keeping, and `node-security/no-timing-unsafe-compare` is where it lives —
146
+ // in that plugin's `recommended` preset since 2026-08-02, so consumers on
147
+ // presets keep CWE-697 coverage. It does mean the coverage now lives in a
148
+ // different package: a project that installs only `eslint-plugin-secure-coding`
149
+ // needs `eslint-plugin-node-security` as well to keep it.
150
+ // The rule remains exported and available via `strict` / explicit opt-in.
135
151
  // Critical - Template injection
136
152
  'secure-coding/no-template-injection': 'error',
137
153
  // Critical - Data integrity
@@ -233,7 +249,9 @@ exports.configs = {
233
249
  'secure-coding/no-weak-password-recovery': 'error',
234
250
  'secure-coding/no-improper-type-validation': 'error',
235
251
  // A07:2021 – Identification and Authentication Failures
236
- 'secure-coding/no-insecure-comparison': 'error',
252
+ // no-insecure-comparison removed for the same reason as in
253
+ // `recommended`: it re-reports `eqeqeq` under a security banner. Use
254
+ // `node-security/no-timing-unsafe-compare` for the timing-attack half.
237
255
  // A08:2021 – Software and Data Integrity Failures
238
256
  'secure-coding/no-unsafe-deserialization': 'error',
239
257
  },
@@ -180,7 +180,6 @@ exports.noGraphqlInjection = (0, eslint_devkit_1.createRule)({
180
180
  create(context) {
181
181
  const options = context.options[0] || {};
182
182
  const { allowIntrospection = false, maxQueryDepth = 10, trustedGraphqlLibraries = ['graphql', 'apollo-server', 'graphql-tools', 'graphql-tag'], validationFunctions = ['validate', 'sanitize', 'isValid', 'assertValid'], safeTemplateLiteralCallers = [], trustedSanitizers = [], trustedAnnotations = [], strictMode = false, } = options;
183
- const sourceCode = context.sourceCode;
184
183
  const filename = context.filename;
185
184
  // Create safety checker for false positive detection
186
185
  const safetyChecker = (0, eslint_devkit_3.createSafetyChecker)({
@@ -278,6 +277,53 @@ exports.noGraphqlInjection = (0, eslint_devkit_1.createRule)({
278
277
  const GRAPHQL_OP_KEYWORDS = ['query', 'mutation', 'subscription'];
279
278
  /** Schema keywords that must be followed by a type name */
280
279
  const GRAPHQL_SCHEMA_KEYWORDS = ['type', 'interface', 'enum', 'scalar', 'input'];
280
+ /**
281
+ * A GraphQL document declares its operations and type definitions at the
282
+ * START of a line. An English sentence mentions them mid-clause.
283
+ *
284
+ * Without this, the keyword scan matched `type` (and `input`, `enum`, ...)
285
+ * anywhere in any string, which is how ordinary message templates became
286
+ * CVSS 9.8 GraphQL-injection findings on a 1,470-file corpus:
287
+ * `Please specify --type ${a} or ${b}` (ack-nestjs-boilerplate)
288
+ * `Invalid type annotation` (generic)
289
+ * 24 of 41 corpus findings came from this one relaxation.
290
+ */
291
+ // oxlint-disable-next-line consistent-function-scoping
292
+ const isAtLineStart = (text, idx) => {
293
+ for (let i = idx - 1; i >= 0; i--) {
294
+ const ch = text[i];
295
+ if (ch === '\n')
296
+ return true;
297
+ if (!isWhitespace(ch))
298
+ return false;
299
+ }
300
+ return true;
301
+ };
302
+ /**
303
+ * A bare selection set (`{ users { name } }`) is only a GraphQL document
304
+ * when it IS the whole string. Nested braces appearing inside a larger
305
+ * message or a generated-code template are not selection sets — that is
306
+ * webpack's `resolve.fallback: { "${request}": ... }` and every other
307
+ * brace-bearing message string in the corpus (17 of 41 findings).
308
+ */
309
+ // oxlint-disable-next-line consistent-function-scoping
310
+ const isStandaloneSelectionSet = (text) => {
311
+ const trimmed = text.trim();
312
+ if (!trimmed.startsWith('{') || !trimmed.endsWith('}'))
313
+ return false;
314
+ let braceDepth = 0;
315
+ for (const ch of trimmed) {
316
+ if (ch === '{') {
317
+ braceDepth++;
318
+ if (braceDepth >= 2)
319
+ return true;
320
+ }
321
+ else if (ch === '}') {
322
+ braceDepth = Math.max(0, braceDepth - 1);
323
+ }
324
+ }
325
+ return false;
326
+ };
281
327
  /**
282
328
  * Find keyword at word boundary in text. Returns index or -1.
283
329
  * Uses simple character checks instead of regex \b.
@@ -323,6 +369,8 @@ exports.noGraphqlInjection = (0, eslint_devkit_1.createRule)({
323
369
  if (idx === -1)
324
370
  break;
325
371
  pos = idx + 1;
372
+ if (!isAtLineStart(staticText, idx))
373
+ continue;
326
374
  // Scan past keyword, skip whitespace, skip optional name, skip whitespace, expect { or (
327
375
  let scan = idx + keyword.length;
328
376
  while (scan < staticText.length && isWhitespace(staticText[scan]))
@@ -344,6 +392,8 @@ exports.noGraphqlInjection = (0, eslint_devkit_1.createRule)({
344
392
  if (idx === -1)
345
393
  break;
346
394
  pos = idx + 1;
395
+ if (!isAtLineStart(staticText, idx))
396
+ continue;
347
397
  let scan = idx + 8; // 'fragment'.length
348
398
  while (scan < staticText.length && isWhitespace(staticText[scan]))
349
399
  scan++;
@@ -360,37 +410,33 @@ exports.noGraphqlInjection = (0, eslint_devkit_1.createRule)({
360
410
  }
361
411
  }
362
412
  // 2. Check for schema definition keywords (type User, interface Foo, etc.)
363
- for (const keyword of GRAPHQL_SCHEMA_KEYWORDS) {
364
- let pos = 0;
365
- while (pos < staticText.length) {
366
- const idx = findKeywordAtBoundary(staticText, keyword, pos);
367
- if (idx === -1)
368
- break;
369
- pos = idx + 1;
370
- let scan = idx + keyword.length;
371
- // Must have whitespace then a word (type name)
372
- if (scan >= staticText.length || !isWhitespace(staticText[scan]))
373
- continue;
374
- while (scan < staticText.length && isWhitespace(staticText[scan]))
375
- scan++;
376
- if (scan < staticText.length && isWordChar(staticText[scan])) {
377
- return true;
413
+ // A schema definition always has a body, so the text must contain a
414
+ // brace. Without this, `enum value with ',' delimiter. Available values:
415
+ // ${...}` (ack-nestjs-boilerplate's Swagger docs) reads as an `enum`
416
+ // definition named `value`.
417
+ if (staticText.includes('{'))
418
+ for (const keyword of GRAPHQL_SCHEMA_KEYWORDS) {
419
+ let pos = 0;
420
+ while (pos < staticText.length) {
421
+ const idx = findKeywordAtBoundary(staticText, keyword, pos);
422
+ if (idx === -1)
423
+ break;
424
+ pos = idx + 1;
425
+ if (!isAtLineStart(staticText, idx))
426
+ continue;
427
+ let scan = idx + keyword.length;
428
+ // Must have whitespace then a word (type name)
429
+ if (scan >= staticText.length || !isWhitespace(staticText[scan]))
430
+ continue;
431
+ while (scan < staticText.length && isWhitespace(staticText[scan]))
432
+ scan++;
433
+ if (scan < staticText.length && isWordChar(staticText[scan])) {
434
+ return true;
435
+ }
378
436
  }
379
437
  }
380
- }
381
438
  // 3. Check for selection sets (nested braces): { users { name } }
382
- let braceDepth = 0;
383
- for (let i = 0; i < staticText.length; i++) {
384
- if (staticText[i] === '{') {
385
- braceDepth++;
386
- if (braceDepth >= 2)
387
- return true;
388
- }
389
- else if (staticText[i] === '}') {
390
- braceDepth = Math.max(0, braceDepth - 1);
391
- }
392
- }
393
- return false;
439
+ return isStandaloneSelectionSet(staticText);
394
440
  };
395
441
  /**
396
442
  * Check if a TemplateLiteral contains introspection patterns.
@@ -435,6 +481,8 @@ exports.noGraphqlInjection = (0, eslint_devkit_1.createRule)({
435
481
  const idx = findKeywordAtBoundary(lower, keyword);
436
482
  if (idx === -1)
437
483
  continue;
484
+ if (!isAtLineStart(lower, idx))
485
+ continue;
438
486
  let scan = idx + keyword.length;
439
487
  while (scan < lower.length && isWhitespace(lower[scan]))
440
488
  scan++;
@@ -447,7 +495,7 @@ exports.noGraphqlInjection = (0, eslint_devkit_1.createRule)({
447
495
  }
448
496
  // Check fragment
449
497
  const fragIdx = findKeywordAtBoundary(lower, 'fragment');
450
- if (fragIdx !== -1) {
498
+ if (fragIdx !== -1 && isAtLineStart(lower, fragIdx)) {
451
499
  let scan = fragIdx + 8;
452
500
  while (scan < lower.length && isWhitespace(lower[scan]))
453
501
  scan++;
@@ -461,32 +509,39 @@ exports.noGraphqlInjection = (0, eslint_devkit_1.createRule)({
461
509
  return true;
462
510
  }
463
511
  }
464
- // Check schema keywords
465
- for (const keyword of GRAPHQL_SCHEMA_KEYWORDS) {
466
- const idx = findKeywordAtBoundary(lower, keyword);
467
- if (idx === -1)
468
- continue;
469
- let scan = idx + keyword.length;
470
- if (scan >= lower.length || !isWhitespace(lower[scan]))
471
- continue;
472
- while (scan < lower.length && isWhitespace(lower[scan]))
473
- scan++;
474
- if (scan < lower.length && isWordChar(lower[scan]))
475
- return true;
476
- }
477
- // Check nested braces
478
- let braceDepth = 0;
479
- for (let i = 0; i < text.length; i++) {
480
- if (text[i] === '{') {
481
- braceDepth++;
482
- if (braceDepth >= 2)
512
+ // Check schema keywords — a schema definition always has a body.
513
+ if (lower.includes('{'))
514
+ for (const keyword of GRAPHQL_SCHEMA_KEYWORDS) {
515
+ const idx = findKeywordAtBoundary(lower, keyword);
516
+ if (idx === -1)
517
+ continue;
518
+ if (!isAtLineStart(lower, idx))
519
+ continue;
520
+ let scan = idx + keyword.length;
521
+ if (scan >= lower.length || !isWhitespace(lower[scan]))
522
+ continue;
523
+ while (scan < lower.length && isWhitespace(lower[scan]))
524
+ scan++;
525
+ if (scan < lower.length && isWordChar(lower[scan]))
483
526
  return true;
484
527
  }
485
- else if (text[i] === '}') {
486
- braceDepth = Math.max(0, braceDepth - 1);
487
- }
528
+ // Check nested braces — only as a standalone selection set.
529
+ return isStandaloneSelectionSet(text);
530
+ };
531
+ /**
532
+ * Flatten a `+` concatenation to the string it would produce, keeping only
533
+ * the statically known parts. Interpolated identifiers contribute nothing.
534
+ */
535
+ const concatenatedStaticText = (node) => {
536
+ if (node.type === 'BinaryExpression' && node.operator === '+') {
537
+ return concatenatedStaticText(node.left) + concatenatedStaticText(node.right);
488
538
  }
489
- return false;
539
+ if (node.type === 'Literal' && typeof node.value === 'string')
540
+ return node.value;
541
+ if (node.type === 'TemplateLiteral') {
542
+ return node.quasis.map((q) => q.value.cooked ?? q.value.raw).join('');
543
+ }
544
+ return '';
490
545
  };
491
546
  /**
492
547
  * Check if input is validated before use
@@ -624,7 +679,12 @@ exports.noGraphqlInjection = (0, eslint_devkit_1.createRule)({
624
679
  if (node.operator !== '+') {
625
680
  return;
626
681
  }
627
- const fullText = sourceCode.getText(node);
682
+ // Use the concatenation's STATIC STRING VALUE, not its source text.
683
+ // `sourceCode.getText()` includes the JS quoting and the `+ ident +`
684
+ // scaffolding, so a query starting at the very beginning of the string
685
+ // is preceded by a `"` — which defeats the start-of-line check that
686
+ // keeps ordinary message strings from being read as GraphQL.
687
+ const fullText = concatenatedStaticText(node);
628
688
  if (!containsGraphqlText(fullText)) {
629
689
  return;
630
690
  }
@@ -36,8 +36,59 @@ export interface Options {
36
36
  }>;
37
37
  /** Strategy for fixing hardcoded credentials: 'env', 'config', 'vault', 'auto' */
38
38
  strategy?: 'env' | 'config' | 'vault' | 'auto';
39
+ /** Skip self-evident placeholder values (`<your-secret-here>`, `changeme`, `xxxxxxxx`). Default: true */
40
+ allowPlaceholders?: boolean;
39
41
  }
40
42
  type RuleOptions = [Options?];
43
+ /**
44
+ * True when the string is made purely of dictionary-ish words joined by word
45
+ * separators or camelCase — i.e. an identifier, an i18n key, or an error
46
+ * message constant. No digits, no symbols, every ≥3-character token
47
+ * pronounceable.
48
+ *
49
+ * `incorrectPassword` → true (the corpus false positive)
50
+ * `SessionCacheProvider` → true
51
+ * `experimental_onToolExecutionStart` → true
52
+ * `aaAA@123` → false (symbols + digits)
53
+ * `qbp7LmCxYUTHFwKvHnxGW1aTyjSNU6ytN21etK89MaP2Dj2KZP` → false (digits)
54
+ */
55
+ export declare function isNaturalWordString(value: string): boolean;
56
+ /**
57
+ * High-confidence random blob: a contiguous alphanumeric token, mixed case,
58
+ * containing digits, high per-character entropy, and not a charset constant.
59
+ * That is the shape of a real committed API secret.
60
+ *
61
+ * The charset is deliberately strict (`[A-Za-z0-9]` only). Every non-secret
62
+ * that reached this tier on the corpus failed exactly here: generated-code
63
+ * strings (`installedChunkData[1](error);`), comma-separated keyword lists,
64
+ * and Postgres constraint names (`PK_b36bcfe02fc8de3c57a8b2391c2`) all carry
65
+ * punctuation that no API key does. JWTs and dotted identifiers are excluded
66
+ * for the same reason and handled by their own, more specific tier.
67
+ */
68
+ export declare function looksRandom(value: string): boolean;
69
+ /**
70
+ * Shape gate for the "assigned to a credential-named binding" path. The name
71
+ * says *what the slot is for*; this says *whether the value is plausibly a
72
+ * secret rather than a message, label, or identifier*.
73
+ */
74
+ export declare function isSecretShaped(value: string, minLength: number): boolean;
75
+ /**
76
+ * True when the value is a self-evident stand-in rather than a secret.
77
+ *
78
+ * Three shapes, each unambiguous on its own:
79
+ * 1. Bracketed template slots — `<your-secret-here>`, `{{API_KEY}}`,
80
+ * `${SECRET}`, `[token]`. No real credential is delimited this way, and
81
+ * the brackets are what push the string past `isSecretShaped`'s
82
+ * two-character-class gate in the first place.
83
+ * 2. A placeholder word standing as its own token — `changeme`,
84
+ * `YOUR_API_KEY`, `example.com`. Substring matching is deliberately
85
+ * avoided: a real key may contain `bar` by chance.
86
+ * 3. One character repeated — `xxxxxxxxxxxx`, `********`, `00000000`.
87
+ *
88
+ * Verified against benchmarks/corpus/CWE-798/safe/test-placeholder-values.js,
89
+ * where `secret: '<your-secret-here>'` was reported at CVSS 9.8.
90
+ */
91
+ export declare function isPlaceholderValue(value: string): boolean;
41
92
  export declare const noHardcodedCredentials: TSESLint.RuleModule<MessageIds, RuleOptions, unknown, TSESLint.RuleListener> & {
42
93
  name: string;
43
94
  };
@@ -6,6 +6,10 @@
6
6
  */
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
8
  exports.noHardcodedCredentials = void 0;
9
+ exports.isNaturalWordString = isNaturalWordString;
10
+ exports.looksRandom = looksRandom;
11
+ exports.isSecretShaped = isSecretShaped;
12
+ exports.isPlaceholderValue = isPlaceholderValue;
9
13
  const eslint_devkit_1 = require("@interlace/eslint-devkit");
10
14
  const eslint_devkit_2 = require("@interlace/eslint-devkit");
11
15
  /**
@@ -48,6 +52,208 @@ const CREDENTIAL_VARIABLE_NAMES = new Set([
48
52
  'connectionstring', 'connection_string', 'connectionString', 'connectionuri', 'connectionURI',
49
53
  'dburl', 'db_url', 'dbUrl', 'databaseurl', 'database_url', 'databaseUrl',
50
54
  ]);
55
+ /**
56
+ * ---------------------------------------------------------------------------
57
+ * VALUE-SHAPE HEURISTICS
58
+ * ---------------------------------------------------------------------------
59
+ * The rule decides on the *value*, never on the key name alone. A
60
+ * credential-shaped name (`password`, `apiKey`, `secret`) is treated as a
61
+ * necessary-but-not-sufficient signal: it can promote an ambiguous value, but
62
+ * it can never make a message constant into a finding.
63
+ *
64
+ * This exists because name-only matching produced a 50% false-positive rate on
65
+ * a 1,470-file corpus (webpack, lodash, eslint-plugin-import, two NestJS
66
+ * boilerplates): 5 of 10 findings were i18n error constants such as
67
+ * `errors: { password: 'incorrectPassword' }`, while the genuine 50-character
68
+ * committed API secret in the same corpus was found by *shape*, not name.
69
+ */
70
+ /** Characters that join words inside an identifier-like string. */
71
+ const WORD_SEPARATORS = new Set(['_', '-', '.', ' ']);
72
+ /** Shannon entropy in bits per character. */
73
+ function shannonEntropy(value) {
74
+ const freq = new Map();
75
+ for (const ch of value)
76
+ freq.set(ch, (freq.get(ch) ?? 0) + 1);
77
+ let entropy = 0;
78
+ for (const count of freq.values()) {
79
+ const p = count / value.length;
80
+ entropy -= p * Math.log2(p);
81
+ }
82
+ return entropy;
83
+ }
84
+ /**
85
+ * Classify the characters present in a string. Word separators (`_ - . ` and
86
+ * space) are deliberately NOT counted as symbols — `snake_case_names` and
87
+ * `kebab-case-names` are identifiers, not passwords.
88
+ *
89
+ * Callers reject whitespace-bearing strings before reaching here, so no
90
+ * whitespace class is tracked.
91
+ */
92
+ function charClasses(value) {
93
+ const classes = { lower: false, upper: false, digit: false, symbol: false };
94
+ for (const ch of value) {
95
+ if (WORD_SEPARATORS.has(ch))
96
+ continue;
97
+ if (ch >= 'a' && ch <= 'z')
98
+ classes.lower = true;
99
+ else if (ch >= 'A' && ch <= 'Z')
100
+ classes.upper = true;
101
+ else if (ch >= '0' && ch <= '9')
102
+ classes.digit = true;
103
+ else
104
+ classes.symbol = true;
105
+ }
106
+ return classes;
107
+ }
108
+ function classCount(classes) {
109
+ return Number(classes.lower) + Number(classes.upper) + Number(classes.digit) + Number(classes.symbol);
110
+ }
111
+ /** A token is "pronounceable" if it has a vowel and no long consonant run. */
112
+ function isPronounceable(token) {
113
+ const lower = token.toLowerCase();
114
+ if (!/[aeiouy]/.test(lower))
115
+ return false;
116
+ if (/[bcdfghjklmnpqrstvwxz]{4,}/.test(lower))
117
+ return false;
118
+ return true;
119
+ }
120
+ /**
121
+ * True when the string is made purely of dictionary-ish words joined by word
122
+ * separators or camelCase — i.e. an identifier, an i18n key, or an error
123
+ * message constant. No digits, no symbols, every ≥3-character token
124
+ * pronounceable.
125
+ *
126
+ * `incorrectPassword` → true (the corpus false positive)
127
+ * `SessionCacheProvider` → true
128
+ * `experimental_onToolExecutionStart` → true
129
+ * `aaAA@123` → false (symbols + digits)
130
+ * `qbp7LmCxYUTHFwKvHnxGW1aTyjSNU6ytN21etK89MaP2Dj2KZP` → false (digits)
131
+ */
132
+ function isNaturalWordString(value) {
133
+ if (!/^[A-Za-z][A-Za-z_\-. ]*$/.test(value))
134
+ return false;
135
+ const tokens = value
136
+ .replace(/([a-z])([A-Z])/g, '$1 $2')
137
+ .split(/[^A-Za-z]+/)
138
+ .filter(Boolean);
139
+ const meaningful = tokens.filter(t => t.length >= 3);
140
+ if (meaningful.length === 0)
141
+ return false;
142
+ return meaningful.every(isPronounceable);
143
+ }
144
+ /**
145
+ * True when the string contains a monotonically ascending run of `min`
146
+ * characters (`abcdef`, `012345`). Charset constants — the alphabets that
147
+ * random-string generators and hash encoders declare inline — have maximal
148
+ * entropy while being the opposite of a secret. webpack's
149
+ * `lib/util/hash/hash-digest.js` and ack-nestjs-boilerplate's
150
+ * `helper.service.ts` each declare several.
151
+ */
152
+ function hasSequentialRun(value, min = 5) {
153
+ let run = 1;
154
+ for (let i = 1; i < value.length; i++) {
155
+ run = value.charCodeAt(i) === value.charCodeAt(i - 1) + 1 ? run + 1 : 1;
156
+ if (run >= min)
157
+ return true;
158
+ }
159
+ return false;
160
+ }
161
+ /**
162
+ * High-confidence random blob: a contiguous alphanumeric token, mixed case,
163
+ * containing digits, high per-character entropy, and not a charset constant.
164
+ * That is the shape of a real committed API secret.
165
+ *
166
+ * The charset is deliberately strict (`[A-Za-z0-9]` only). Every non-secret
167
+ * that reached this tier on the corpus failed exactly here: generated-code
168
+ * strings (`installedChunkData[1](error);`), comma-separated keyword lists,
169
+ * and Postgres constraint names (`PK_b36bcfe02fc8de3c57a8b2391c2`) all carry
170
+ * punctuation that no API key does. JWTs and dotted identifiers are excluded
171
+ * for the same reason and handled by their own, more specific tier.
172
+ */
173
+ function looksRandom(value) {
174
+ if (value.length < 20)
175
+ return false;
176
+ if (!/^[A-Za-z0-9]+$/.test(value))
177
+ return false;
178
+ const classes = charClasses(value);
179
+ if (!classes.lower || !classes.upper || !classes.digit)
180
+ return false;
181
+ if (hasSequentialRun(value))
182
+ return false;
183
+ return shannonEntropy(value) >= 3.5;
184
+ }
185
+ /**
186
+ * Length at which a random-looking blob is reported with NO naming context.
187
+ * Below it the shape is still required, but so is a credential-named slot:
188
+ * `CreateUser1715028537217` (a TypeORM migration class name, 23 chars) passes
189
+ * every shape test there is, and only the absence of a credential-named slot
190
+ * separates it from a 25-character API key.
191
+ */
192
+ const CONTEXT_FREE_RANDOM_LENGTH = 32;
193
+ /**
194
+ * Shape gate for the "assigned to a credential-named binding" path. The name
195
+ * says *what the slot is for*; this says *whether the value is plausibly a
196
+ * secret rather than a message, label, or identifier*.
197
+ */
198
+ function isSecretShaped(value, minLength) {
199
+ if (value.length < minLength)
200
+ return false;
201
+ // Sentences and phrases are messages, never credentials.
202
+ if (/\s/.test(value))
203
+ return false;
204
+ // Pure word strings are identifiers / i18n keys / message constants.
205
+ if (isNaturalWordString(value))
206
+ return false;
207
+ // A credential mixes at least two character classes, or — for single-charset
208
+ // secrets like a 21-character lowercase blob — is long and high-entropy.
209
+ if (classCount(charClasses(value)) >= 2)
210
+ return true;
211
+ return value.length >= 20 && shannonEntropy(value) >= 3.0;
212
+ }
213
+ /**
214
+ * Words that only ever appear in a value a developer expects to replace.
215
+ * Matched as whole words inside the string, so `changeme`, `change-me`,
216
+ * `YOUR_API_KEY`, and `<your-secret-here>` are all covered.
217
+ */
218
+ const PLACEHOLDER_WORDS = new Set([
219
+ 'changeme', 'change', 'replaceme', 'replace', 'yours', 'your',
220
+ 'placeholder', 'example', 'sample', 'dummy', 'todo', 'tbd',
221
+ 'redacted', 'notreal', 'xxx',
222
+ ]);
223
+ /**
224
+ * True when the value is a self-evident stand-in rather than a secret.
225
+ *
226
+ * Three shapes, each unambiguous on its own:
227
+ * 1. Bracketed template slots — `<your-secret-here>`, `{{API_KEY}}`,
228
+ * `${SECRET}`, `[token]`. No real credential is delimited this way, and
229
+ * the brackets are what push the string past `isSecretShaped`'s
230
+ * two-character-class gate in the first place.
231
+ * 2. A placeholder word standing as its own token — `changeme`,
232
+ * `YOUR_API_KEY`, `example.com`. Substring matching is deliberately
233
+ * avoided: a real key may contain `bar` by chance.
234
+ * 3. One character repeated — `xxxxxxxxxxxx`, `********`, `00000000`.
235
+ *
236
+ * Verified against benchmarks/corpus/CWE-798/safe/test-placeholder-values.js,
237
+ * where `secret: '<your-secret-here>'` was reported at CVSS 9.8.
238
+ */
239
+ function isPlaceholderValue(value) {
240
+ const trimmed = value.trim();
241
+ if (trimmed.length === 0)
242
+ return false;
243
+ // 1. Bracketed template slots.
244
+ if (/^(?:<.*>|\{\{.*\}\}|\$\{.*\}|\[.*\])$/.test(trimmed))
245
+ return true;
246
+ // 3. One character repeated (4+).
247
+ if (trimmed.length >= 4 && new Set(trimmed).size === 1)
248
+ return true;
249
+ // 2. Placeholder word as a whole token.
250
+ const tokens = trimmed
251
+ .replace(/([a-z])([A-Z])/g, '$1 $2')
252
+ .toLowerCase()
253
+ .split(/[^a-z0-9]+/)
254
+ .filter(Boolean);
255
+ return tokens.some(token => PLACEHOLDER_WORDS.has(token));
256
+ }
51
257
  /**
52
258
  * Check if a string literal looks like a hardcoded credential.
53
259
  * Returns `confidence: 'ambiguous'` when only a permissive pattern matched —
@@ -94,10 +300,9 @@ function looksLikeCredential(value, options, ignorePatterns) {
94
300
  }
95
301
  // Secret keys (base64/hex 32+) — context-required. Long base64 / hex
96
302
  // strings appear in source maps, generated IDs, hash digests; without
97
- // a credential-named context they're FPs.
98
- if (value.length >= 32 && CREDENTIAL_PATTERNS.secretKey.test(value)) {
99
- return { isCredential: true, type: 'Secret key', confidence: 'ambiguous' };
100
- }
303
+ // a credential-named context they're FPs. Word-shaped strings are excluded
304
+ // outright: `experimental_onToolExecutionStart` is 33 chars of [A-Za-z_]
305
+ // and matches the charset, but it is an identifier, not a key.
101
306
  // Structural: AWS access key has a fixed prefix
102
307
  if (options.detectApiKeys && CREDENTIAL_PATTERNS.awsAccessKey.test(value)) {
103
308
  return { isCredential: true, type: 'AWS access key', confidence: 'structural' };
@@ -111,10 +316,26 @@ function looksLikeCredential(value, options, ignorePatterns) {
111
316
  /^(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9_-]{16,}$/.test(value)) {
112
317
  return { isCredential: true, type: 'API key', confidence: 'structural' };
113
318
  }
319
+ // Structural by SHAPE, not by name: a long, mixed-case, digit-bearing,
320
+ // high-entropy blob with no separators is a random secret whatever the
321
+ // slot it sits in. This is the tier that finds the genuine 50-character
322
+ // API secret committed in ack-nestjs-boilerplate's migration seed data —
323
+ // and it also finds the 25-character `key:` next to it, which the old
324
+ // name-driven logic missed because `key` was not on the allowlist.
325
+ if (options.detectApiKeys && looksRandom(value)) {
326
+ return {
327
+ isCredential: true,
328
+ type: 'Secret key',
329
+ confidence: value.length >= CONTEXT_FREE_RANDOM_LENGTH ? 'structural' : 'ambiguous',
330
+ };
331
+ }
332
+ if (value.length >= 32 && CREDENTIAL_PATTERNS.secretKey.test(value) && !isNaturalWordString(value)) {
333
+ return { isCredential: true, type: 'Secret key', confidence: 'ambiguous' };
334
+ }
114
335
  // Generic 32+-char alphanumeric — AMBIGUOUS. This is the FP source on
115
336
  // vercel/ai's TS union types and error class names. Caller must verify
116
- // a credential-named context.
117
- if (options.detectApiKeys && /^[A-Za-z0-9_-]{32,}$/.test(value)) {
337
+ // a credential-named context, and the value must not be word-shaped.
338
+ if (options.detectApiKeys && /^[A-Za-z0-9_-]{32,}$/.test(value) && !isNaturalWordString(value)) {
118
339
  return { isCredential: true, type: 'API key', confidence: 'ambiguous' };
119
340
  }
120
341
  return NONE;
@@ -254,6 +475,11 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
254
475
  default: 'auto',
255
476
  description: 'Strategy for fixing hardcoded credentials (auto = smart detection)'
256
477
  },
478
+ allowPlaceholders: {
479
+ type: 'boolean',
480
+ default: true,
481
+ description: 'Skip self-evident placeholder values (<your-secret-here>, changeme, xxxxxxxx)',
482
+ },
257
483
  },
258
484
  additionalProperties: false,
259
485
  },
@@ -270,11 +496,12 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
270
496
  detectDatabaseStrings: true,
271
497
  customPatterns: [],
272
498
  strategy: 'auto',
499
+ allowPlaceholders: true,
273
500
  },
274
501
  ],
275
502
  create(context) {
276
503
  const options = context.options[0] || {};
277
- const { ignorePatterns = [], allowInTests = false, minLength = 8, detectApiKeys = true, detectPasswords = true, detectTokens = true, detectDatabaseStrings = true, customPatterns = [], } = options;
504
+ const { ignorePatterns = [], allowInTests = false, minLength = 8, detectApiKeys = true, detectPasswords = true, detectTokens = true, detectDatabaseStrings = true, customPatterns = [], allowPlaceholders = true, } = options;
278
505
  const filename = context.filename;
279
506
  const isTestFile = allowInTests && (filename.includes('.test.') ||
280
507
  filename.includes('.spec.') ||
@@ -462,6 +689,15 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
462
689
  return false;
463
690
  const matches = (name) => {
464
691
  const lower = name.toLowerCase();
692
+ // Bare `key` / `keys` is a WEAK credential name: it labels cache keys,
693
+ // map keys, i18n keys and object keys far more often than API keys
694
+ // (`const key = "memCache2"` in webpack's Compilation.js). It counts as
695
+ // credential context only when the value is already a random blob by
696
+ // shape — which is what makes `{ key: 'fyFGb7ywyM37TqDY8nuhAmGW5' }`
697
+ // (ack-nestjs-boilerplate's seeded API key) reportable.
698
+ if (lower === 'key' || lower === 'keys') {
699
+ return node.type === 'Literal' && typeof node.value === 'string' && looksRandom(node.value);
700
+ }
465
701
  // Try the literal name AND its singular form (drop trailing 's')
466
702
  // so collections like `tokens`, `apiKeys`, `secrets`, `passwords`
467
703
  // are recognised. Closes the audit FN where
@@ -562,11 +798,24 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
562
798
  if (isCredential && confidence === 'ambiguous' && !isCredentialContext(node, parent)) {
563
799
  finalIsCredential = false;
564
800
  }
565
- // Context-positive: any non-trivial string assigned to a
801
+ // Self-evident placeholders are not secrets. Gated to non-structural
802
+ // findings only: a JWT, an `sk_live_` key, or a DB connection string
803
+ // keeps its shape whatever words it contains, so those still report.
804
+ const isPlaceholder = allowPlaceholders && isPlaceholderValue(value);
805
+ if (isPlaceholder && confidence !== 'structural') {
806
+ finalIsCredential = false;
807
+ }
808
+ // Context-positive: a *secret-shaped* string assigned to a
566
809
  // credential-named variable/property is a credential, even when no
567
- // regex pattern matches. Catches passwords like 'SuperSecret123!'
568
- // that don't fit any structural pattern but are clearly secrets
569
- // by virtue of where they're stored.
810
+ // structural pattern matches. Catches passwords like 'aaAA@123' that
811
+ // don't fit any known key format but are clearly secrets.
812
+ //
813
+ // `isSecretShaped` is the load-bearing half of this condition. Without
814
+ // it the rule fires on every string ≥ minLength that happens to sit in
815
+ // a credential-named slot — which is how `errors: { password:
816
+ // 'incorrectPassword' }` (an i18n error key, 5 of 10 corpus findings)
817
+ // got reported at CVSS 9.8. The name says what the slot is for; the
818
+ // shape says whether the value is a secret.
570
819
  //
571
820
  // The detection-disable options (detectApiKeys / detectPasswords /
572
821
  // detectTokens / detectDatabaseStrings) MUST gate this path too —
@@ -574,7 +823,10 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
574
823
  // `const password = "..."` because the var-name match alone
575
824
  // bypasses the option. Map the var name back to its category and
576
825
  // honour the option.
577
- if (!finalIsCredential && value.length >= detectionOptions.minLength &&
826
+ if (!finalIsCredential &&
827
+ !isPlaceholder &&
828
+ !compiledIgnorePatterns.some((pattern) => pattern.test(value)) &&
829
+ isSecretShaped(value, detectionOptions.minLength) &&
578
830
  isCredentialContext(node, parent)) {
579
831
  // isCredentialContext(node, parent) just returned true, which
580
832
  // requires a truthy parent.
@@ -618,14 +870,14 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
618
870
  suggest: [
619
871
  {
620
872
  messageId: 'useEnvironmentVariable',
621
- data: { envVarName, credentialType: type },
873
+ data: { envVarName, credentialType: finalType },
622
874
  fix: (fixer) => {
623
875
  return fixer.replaceText(node, `process.env.${envVarName} || '${value}'`);
624
876
  },
625
877
  },
626
878
  {
627
879
  messageId: 'useSecretManager',
628
- data: { credentialType: type },
880
+ data: { credentialType: finalType },
629
881
  fix: (fixer) => {
630
882
  return fixer.replaceText(node, `await getSecret('${envVarName.toLowerCase()}')`);
631
883
  },
@@ -136,7 +136,52 @@ exports.noInsecureComparison = (0, eslint_devkit_2.createRule)({
136
136
  if (isCodemodFile) {
137
137
  return;
138
138
  }
139
- const secretKeywords = ['secret', 'token', 'password', 'apikey', 'api_key', 'signature', 'auth', 'key', 'hash', 'digest', 'mac'];
139
+ // Word-level, not substring-level. The bare keywords `key`, `auth` and
140
+ // `mac` used to be matched as substrings of the whole expression's source
141
+ // text, which made `if (key === "__non_webpack_require__")` a "timing
142
+ // attack" and swept in `monkey`, `keyword`, `machine`, `author`. A secret
143
+ // is named by a *word*, so match words.
144
+ const secretKeywords = new Set([
145
+ 'secret', 'secrets', 'token', 'tokens', 'password', 'passwd', 'pwd',
146
+ 'apikey', 'api_key', 'secretkey', 'secret_key', 'privatekey', 'private_key',
147
+ 'signature', 'hmac', 'digest', 'checksum', 'nonce', 'otp',
148
+ 'passwordhash', 'password_hash', 'hashedpassword', 'hashed_password',
149
+ ]);
150
+ /**
151
+ * Split an identifier-ish name into lowercase word segments:
152
+ * `expectedPassword` → ['expected', 'password'], `api_key` → ['api','key'].
153
+ * The joined form is kept too so `apiKey` also matches the `apikey` entry.
154
+ */
155
+ // oxlint-disable-next-line consistent-function-scoping
156
+ const nameSegments = (name) => {
157
+ const parts = name
158
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
159
+ .split(/[^A-Za-z0-9]+/)
160
+ .filter(Boolean)
161
+ .map((p) => p.toLowerCase());
162
+ return [...parts, parts.join(''), parts.join('_'), name.toLowerCase()];
163
+ };
164
+ /** Every identifier / property name appearing inside an expression. */
165
+ // oxlint-disable-next-line consistent-function-scoping
166
+ const namesIn = (expr) => {
167
+ const out = [];
168
+ const walk = (n) => {
169
+ if (n.type === 'Identifier')
170
+ out.push(n.name);
171
+ else if (n.type === 'MemberExpression') {
172
+ walk(n.object);
173
+ if (!n.computed && n.property.type === 'Identifier')
174
+ out.push(n.property.name);
175
+ else
176
+ walk(n.property);
177
+ }
178
+ else if (n.type === 'CallExpression') {
179
+ walk(n.callee);
180
+ }
181
+ };
182
+ walk(expr);
183
+ return out;
184
+ };
140
185
  const isSecurityContext = (() => {
141
186
  let current = node;
142
187
  while (current) {
@@ -158,13 +203,13 @@ exports.noInsecureComparison = (0, eslint_devkit_2.createRule)({
158
203
  return false;
159
204
  })();
160
205
  const isPotentialSecret = (expr) => {
161
- const text = sourceCode.getText(expr).toLowerCase();
162
- if (secretKeywords.some(keyword => text.includes(keyword)))
206
+ const segments = namesIn(expr).flatMap(nameSegments);
207
+ if (segments.some(segment => secretKeywords.has(segment)))
163
208
  return true;
164
209
  // In security contexts, treat generic terms as potential secrets
165
210
  if (isSecurityContext) {
166
- const contextKeywords = ['provided', 'expected', 'actual', 'input', 'value', 'data'];
167
- return contextKeywords.some(keyword => text.includes(keyword));
211
+ const contextKeywords = new Set(['provided', 'expected', 'actual', 'input', 'value', 'data']);
212
+ return segments.some(segment => contextKeywords.has(segment));
168
213
  }
169
214
  return false;
170
215
  };
@@ -9,6 +9,29 @@ exports.noUnsafeDeserialization = void 0;
9
9
  const eslint_devkit_1 = require("@interlace/eslint-devkit");
10
10
  const eslint_devkit_2 = require("@interlace/eslint-devkit");
11
11
  const eslint_devkit_3 = require("@interlace/eslint-devkit");
12
+ /**
13
+ * Timer functions that double as an implied-`eval` sink — but only when the
14
+ * first argument is a string. `setTimeout(fn, 0)` is a scheduler, not a
15
+ * deserializer.
16
+ */
17
+ const TIMER_FUNCTIONS = new Set(['setTimeout', 'setInterval']);
18
+ /**
19
+ * True when the expression can only evaluate to a string, i.e. the argument
20
+ * would actually be compiled by `setTimeout` / `setInterval`. A function
21
+ * reference, an arrow function, or anything else is never implied-eval.
22
+ */
23
+ function isStringValued(arg) {
24
+ if (!arg)
25
+ return false;
26
+ if (arg.type === 'Literal')
27
+ return typeof arg.value === 'string';
28
+ if (arg.type === 'TemplateLiteral')
29
+ return true;
30
+ if (arg.type === 'BinaryExpression' && arg.operator === '+') {
31
+ return isStringValued(arg.left) || isStringValued(arg.right);
32
+ }
33
+ return false;
34
+ }
12
35
  exports.noUnsafeDeserialization = (0, eslint_devkit_1.createRule)({
13
36
  name: 'no-unsafe-deserialization',
14
37
  meta: {
@@ -193,12 +216,36 @@ exports.noUnsafeDeserialization = (0, eslint_devkit_1.createRule)({
193
216
  const callee = node.callee;
194
217
  // Check for dangerous function calls
195
218
  if (callee.type === 'Identifier' && dangerousFunctions.includes(callee.name)) {
219
+ // `setTimeout` / `setInterval` are only a code-execution sink in their
220
+ // implied-eval form — when the FIRST argument is a *string* that the
221
+ // engine compiles. `setTimeout(callback, 1000)` is the ordinary timer
222
+ // form and is not deserialization of anything.
223
+ //
224
+ // Without this gate the rule reported
225
+ // `await new Promise(resolve => setTimeout(resolve, 1000))` at CVSS
226
+ // 9.8 CRITICAL, because `resolve` is an enclosing arrow-function
227
+ // parameter and every parameter is treated as untrusted input.
228
+ if (TIMER_FUNCTIONS.has(callee.name)) {
229
+ return isStringValued(node.arguments[0]);
230
+ }
196
231
  return true;
197
232
  }
198
233
  // Check for member expressions like yaml.load, serialize.unserialize
199
234
  if (callee.type === 'MemberExpression') {
200
235
  const memberName = callee.property.type === 'Identifier' ? callee.property.name : '';
201
236
  const objectName = callee.object.type === 'Identifier' ? callee.object.name : '';
237
+ // `super.deserialize(context)` / `this.deserialize(context)` is a class
238
+ // *implementing* a (de)serialization protocol and chaining to its own
239
+ // base implementation — webpack's serialization layer does this in
240
+ // every Dependency subclass. The argument is the framework's own
241
+ // context object, not attacker-controlled data.
242
+ if (callee.object.type === 'Super' || callee.object.type === 'ThisExpression') {
243
+ return false;
244
+ }
245
+ // Same implied-eval reasoning as above for `window.setTimeout(...)`.
246
+ if (TIMER_FUNCTIONS.has(memberName)) {
247
+ return isStringValued(node.arguments[0]);
248
+ }
202
249
  // Check dangerous methods
203
250
  if (dangerousFunctions.includes(memberName)) {
204
251
  return true;
@@ -225,6 +272,16 @@ exports.noUnsafeDeserialization = (0, eslint_devkit_1.createRule)({
225
272
  * Check if input comes from untrusted source
226
273
  */
227
274
  const isUntrustedInput = (inputNode) => {
275
+ // Concatenations and template literals carry their operands' trust:
276
+ // `setTimeout("alert(" + userCode + ")", 100)` is implied eval on
277
+ // untrusted input even though the argument node itself is a
278
+ // BinaryExpression rather than an Identifier.
279
+ if (inputNode.type === 'BinaryExpression' && inputNode.operator === '+') {
280
+ return isUntrustedInput(inputNode.left) || isUntrustedInput(inputNode.right);
281
+ }
282
+ if (inputNode.type === 'TemplateLiteral') {
283
+ return inputNode.expressions.some((e) => isUntrustedInput(e));
284
+ }
228
285
  // Check for MemberExpression patterns like req.body, req.query, etc.
229
286
  if (inputNode.type === 'MemberExpression') {
230
287
  if (inputNode.object.type === 'Identifier' && inputNode.object.name === 'req') {
@@ -299,6 +356,48 @@ exports.noUnsafeDeserialization = (0, eslint_devkit_1.createRule)({
299
356
  }
300
357
  return false;
301
358
  };
359
+ /**
360
+ * True when the call sits inside a function that is itself named
361
+ * `deserialize` / `unserialize` / `fromJSON` — i.e. the file is
362
+ * *implementing* a (de)serialization protocol and delegating to the next
363
+ * layer of it, which is what webpack's whole `lib/serialization` tree and
364
+ * every `static deserialize(context)` factory does:
365
+ *
366
+ * static deserialize(context) {
367
+ * const obj = new CssModule({ ... });
368
+ * obj.deserialize(context); // ← not attacker-controlled
369
+ * return obj;
370
+ * }
371
+ *
372
+ * A rule that cannot see the protocol cannot judge it, and 33 of 35 corpus
373
+ * findings were exactly this shape.
374
+ */
375
+ // oxlint-disable-next-line consistent-function-scoping
376
+ const isInsideDeserializerImplementation = (node) => {
377
+ const DESERIALIZER_NAMES = new Set(['deserialize', 'unserialize', 'fromJSON', 'fromBuffer']);
378
+ let current = node.parent;
379
+ while (current) {
380
+ if (current.type === 'FunctionDeclaration' ||
381
+ current.type === 'FunctionExpression' ||
382
+ current.type === 'ArrowFunctionExpression') {
383
+ const fn = current;
384
+ if ('id' in fn && fn.id?.name && DESERIALIZER_NAMES.has(fn.id.name))
385
+ return true;
386
+ const owner = fn.parent;
387
+ if (owner?.type === 'MethodDefinition' && owner.key.type === 'Identifier' &&
388
+ DESERIALIZER_NAMES.has(owner.key.name))
389
+ return true;
390
+ if (owner?.type === 'Property' && owner.key.type === 'Identifier' &&
391
+ DESERIALIZER_NAMES.has(owner.key.name))
392
+ return true;
393
+ if (owner?.type === 'VariableDeclarator' && owner.id.type === 'Identifier' &&
394
+ DESERIALIZER_NAMES.has(owner.id.name))
395
+ return true;
396
+ }
397
+ current = current.parent;
398
+ }
399
+ return false;
400
+ };
302
401
  const checkCallExpression = (node) => {
303
402
  // 1. Check Function Constructor (NewExpression or CallExpression)
304
403
  if ((node.type === 'NewExpression' || node.type === 'CallExpression') &&
@@ -323,7 +422,7 @@ exports.noUnsafeDeserialization = (0, eslint_devkit_1.createRule)({
323
422
  }
324
423
  }
325
424
  // 2. Check CallExpressions (eval, unserialize, yaml, etc.)
326
- if (isDangerousDeserialization(node)) {
425
+ if (isDangerousDeserialization(node) && !isInsideDeserializerImplementation(node)) {
327
426
  const args = node.arguments;
328
427
  const hasUntrustedInput = args.some((arg) => isUntrustedInput(arg));
329
428
  // Check if explicit validation is present