eslint-plugin-jwt-security 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/AGENTS.md +102 -0
  2. package/CHANGELOG.md +161 -0
  3. package/LICENSE +23 -0
  4. package/README.md +158 -0
  5. package/dist/AGENTS.md +102 -0
  6. package/dist/CHANGELOG.md +161 -0
  7. package/dist/LICENSE +23 -0
  8. package/dist/README.md +158 -0
  9. package/dist/package.json +125 -0
  10. package/dist/src/index.d.ts +101 -0
  11. package/dist/src/index.js +171 -0
  12. package/dist/src/oxlint.d.ts +20 -0
  13. package/dist/src/oxlint.js +21 -0
  14. package/dist/src/rules/no-algorithm-confusion/index.d.ts +24 -0
  15. package/dist/src/rules/no-algorithm-confusion/index.js +165 -0
  16. package/dist/src/rules/no-algorithm-none/index.d.ts +24 -0
  17. package/dist/src/rules/no-algorithm-none/index.js +222 -0
  18. package/dist/src/rules/no-decode-without-verify/index.d.ts +23 -0
  19. package/dist/src/rules/no-decode-without-verify/index.js +131 -0
  20. package/dist/src/rules/no-hardcoded-secret/index.d.ts +23 -0
  21. package/dist/src/rules/no-hardcoded-secret/index.js +189 -0
  22. package/dist/src/rules/no-sensitive-payload/index.d.ts +20 -0
  23. package/dist/src/rules/no-sensitive-payload/index.js +103 -0
  24. package/dist/src/rules/no-timestamp-manipulation/index.d.ts +23 -0
  25. package/dist/src/rules/no-timestamp-manipulation/index.js +97 -0
  26. package/dist/src/rules/no-weak-secret/index.d.ts +23 -0
  27. package/dist/src/rules/no-weak-secret/index.js +165 -0
  28. package/dist/src/rules/require-algorithm-whitelist/index.d.ts +24 -0
  29. package/dist/src/rules/require-algorithm-whitelist/index.js +113 -0
  30. package/dist/src/rules/require-audience-validation/index.d.ts +20 -0
  31. package/dist/src/rules/require-audience-validation/index.js +100 -0
  32. package/dist/src/rules/require-expiration/index.d.ts +23 -0
  33. package/dist/src/rules/require-expiration/index.js +136 -0
  34. package/dist/src/rules/require-issued-at/index.d.ts +23 -0
  35. package/dist/src/rules/require-issued-at/index.js +113 -0
  36. package/dist/src/rules/require-issuer-validation/index.d.ts +20 -0
  37. package/dist/src/rules/require-issuer-validation/index.js +100 -0
  38. package/dist/src/rules/require-max-age/index.d.ts +24 -0
  39. package/dist/src/rules/require-max-age/index.js +93 -0
  40. package/dist/src/types/index.d.ts +82 -0
  41. package/dist/src/types/index.js +7 -0
  42. package/dist/src/utils/index.d.ts +98 -0
  43. package/dist/src/utils/index.js +238 -0
  44. package/package.json +125 -0
  45. package/src/__compatibility__/jwt-interface.spec.ts +192 -0
  46. package/src/index.test.ts +47 -0
  47. package/src/index.ts +209 -0
  48. package/src/oxlint.test.ts +61 -0
  49. package/src/oxlint.ts +23 -0
  50. package/src/rules/no-algorithm-confusion/index.ts +208 -0
  51. package/src/rules/no-algorithm-confusion/no-algorithm-confusion.test.ts +106 -0
  52. package/src/rules/no-algorithm-none/index.ts +270 -0
  53. package/src/rules/no-algorithm-none/no-algorithm-none.test.ts +146 -0
  54. package/src/rules/no-decode-without-verify/index.ts +162 -0
  55. package/src/rules/no-decode-without-verify/no-decode-without-verify.test.ts +76 -0
  56. package/src/rules/no-hardcoded-secret/index.ts +230 -0
  57. package/src/rules/no-hardcoded-secret/no-hardcoded-secret.test.ts +97 -0
  58. package/src/rules/no-sensitive-payload/index.ts +123 -0
  59. package/src/rules/no-sensitive-payload/no-sensitive-payload.test.ts +157 -0
  60. package/src/rules/no-timestamp-manipulation/index.ts +118 -0
  61. package/src/rules/no-timestamp-manipulation/no-timestamp-manipulation.test.ts +54 -0
  62. package/src/rules/no-weak-secret/index.ts +204 -0
  63. package/src/rules/no-weak-secret/no-weak-secret.test.ts +114 -0
  64. package/src/rules/require-algorithm-whitelist/index.ts +145 -0
  65. package/src/rules/require-algorithm-whitelist/require-algorithm-whitelist.test.ts +72 -0
  66. package/src/rules/require-audience-validation/index.ts +120 -0
  67. package/src/rules/require-audience-validation/require-audience-validation.test.ts +68 -0
  68. package/src/rules/require-expiration/index.ts +170 -0
  69. package/src/rules/require-expiration/require-expiration.test.ts +135 -0
  70. package/src/rules/require-issued-at/index.ts +143 -0
  71. package/src/rules/require-issued-at/require-issued-at.test.ts +64 -0
  72. package/src/rules/require-issuer-validation/index.ts +120 -0
  73. package/src/rules/require-issuer-validation/require-issuer-validation.test.ts +68 -0
  74. package/src/rules/require-max-age/index.ts +117 -0
  75. package/src/rules/require-max-age/require-max-age.test.ts +69 -0
  76. package/src/tests/coverage-dual-layer.test.ts +323 -0
  77. package/src/types/index.ts +107 -0
  78. package/src/utils/index.ts +285 -0
  79. package/src/utils/utils.test.ts +324 -0
package/src/index.ts ADDED
@@ -0,0 +1,209 @@
1
+ /**
2
+ * Copyright (c) 2025 Ofri Peretz
3
+ * Licensed under the MIT License. Use of this source code is governed by the
4
+ * MIT license that can be found in the LICENSE file.
5
+ */
6
+
7
+ /**
8
+ * eslint-plugin-jwt-security
9
+ *
10
+ * Comprehensive JWT security ESLint plugin for Node.js applications.
11
+ * Detects vulnerabilities across jsonwebtoken, jose, express-jwt,
12
+ * @nestjs/jwt, jwks-rsa, and jwt-decode libraries.
13
+ *
14
+ * Features:
15
+ * - Algorithm confusion attack detection (CVE-2022-23540)
16
+ * - "Back to the Future" replay attack prevention (LightSEC 2025)
17
+ * - Signature verification enforcement
18
+ * - Weak secret detection
19
+ * - Expiration and claim validation
20
+ * - AI-assisted fix guidance with CWE references
21
+ *
22
+ * @see https://tools.ietf.org/html/rfc8725
23
+ * @see https://securitypattern.com/post/jwt-back-to-the-future
24
+ */
25
+ import type { TSESLint } from '@interlace/eslint-devkit';
26
+
27
+ // Import rules - Core Security
28
+ import { noAlgorithmNone } from './rules/no-algorithm-none';
29
+ import { noAlgorithmConfusion } from './rules/no-algorithm-confusion';
30
+ import { requireAlgorithmWhitelist } from './rules/require-algorithm-whitelist';
31
+ import { noDecodeWithoutVerify } from './rules/no-decode-without-verify';
32
+ import { noWeakSecret } from './rules/no-weak-secret';
33
+ import { requireExpiration } from './rules/require-expiration';
34
+ import { noHardcodedSecret } from './rules/no-hardcoded-secret';
35
+
36
+ // Import rules - 2025 Vulnerability Research
37
+ import { requireIssuedAt } from './rules/require-issued-at';
38
+ import { requireIssuerValidation } from './rules/require-issuer-validation';
39
+ import { requireAudienceValidation } from './rules/require-audience-validation';
40
+ import { noTimestampManipulation } from './rules/no-timestamp-manipulation';
41
+ import { requireMaxAge } from './rules/require-max-age';
42
+ import { noSensitivePayload } from './rules/no-sensitive-payload';
43
+
44
+ /**
45
+ * Collection of all JWT security ESLint rules (13 rules)
46
+ */
47
+ export const rules: Record<string, TSESLint.RuleModule<string, readonly unknown[]>> = {
48
+ // Core Security Rules
49
+ 'no-algorithm-none': noAlgorithmNone,
50
+ 'no-algorithm-confusion': noAlgorithmConfusion,
51
+ 'require-algorithm-whitelist': requireAlgorithmWhitelist,
52
+ 'no-decode-without-verify': noDecodeWithoutVerify,
53
+ 'no-weak-secret': noWeakSecret,
54
+ 'require-expiration': requireExpiration,
55
+ 'no-hardcoded-secret': noHardcodedSecret,
56
+
57
+ // 2025 Vulnerability Research - "Back to the Future" & Replay Prevention
58
+ 'require-issued-at': requireIssuedAt,
59
+ 'require-issuer-validation': requireIssuerValidation,
60
+ 'require-audience-validation': requireAudienceValidation,
61
+ 'no-timestamp-manipulation': noTimestampManipulation,
62
+ 'require-max-age': requireMaxAge,
63
+ 'no-sensitive-payload': noSensitivePayload,
64
+ } satisfies Record<string, TSESLint.RuleModule<string, readonly unknown[]>>;
65
+
66
+ /**
67
+ * ESLint Plugin object
68
+ */
69
+ export const plugin: TSESLint.FlatConfig.Plugin = {
70
+ meta: {
71
+ name: 'eslint-plugin-jwt-security',
72
+ version: '2.2.9',
73
+ },
74
+ rules,
75
+ } satisfies TSESLint.FlatConfig.Plugin;
76
+
77
+ /**
78
+ * Recommended configuration - baseline security
79
+ * Critical rules as errors, high as warnings
80
+ */
81
+ const recommendedRules: Record<string, TSESLint.FlatConfig.RuleEntry> = {
82
+ // CRITICAL - Algorithm attacks
83
+ 'jwt/no-algorithm-none': 'error',
84
+ 'jwt/no-algorithm-confusion': 'error',
85
+
86
+ // HIGH - Verification and secrets
87
+ 'jwt/require-algorithm-whitelist': 'error',
88
+ 'jwt/no-decode-without-verify': 'error',
89
+ 'jwt/no-weak-secret': 'error',
90
+ 'jwt/no-hardcoded-secret': 'error',
91
+ 'jwt/no-timestamp-manipulation': 'error', // LightSEC 2025
92
+
93
+ // MEDIUM - Best practices
94
+ 'jwt/require-expiration': 'error',
95
+ 'jwt/no-sensitive-payload': 'warn',
96
+ };
97
+
98
+ /**
99
+ * Strict configuration - maximum security (2025 research)
100
+ * All rules as errors - includes replay attack prevention
101
+ */
102
+ const strictRules: Record<string, TSESLint.FlatConfig.RuleEntry> = {
103
+ // All core rules as errors
104
+ 'jwt/no-algorithm-none': 'error',
105
+ 'jwt/no-algorithm-confusion': 'error',
106
+ 'jwt/require-algorithm-whitelist': 'error',
107
+ 'jwt/no-decode-without-verify': 'error',
108
+ 'jwt/no-weak-secret': 'error',
109
+ 'jwt/no-hardcoded-secret': 'error',
110
+ 'jwt/require-expiration': 'error',
111
+
112
+ // 2025 Research - Full replay attack prevention
113
+ 'jwt/require-issued-at': 'error',
114
+ 'jwt/require-issuer-validation': 'error',
115
+ 'jwt/require-audience-validation': 'error',
116
+ 'jwt/no-timestamp-manipulation': 'error',
117
+ 'jwt/require-max-age': 'error',
118
+ 'jwt/no-sensitive-payload': 'error',
119
+ };
120
+
121
+ /**
122
+ * Legacy configuration - migration mode
123
+ * Only critical rules enabled
124
+ */
125
+ const legacyRules: Record<string, TSESLint.FlatConfig.RuleEntry> = {
126
+ // Only most critical rules
127
+ 'jwt/no-algorithm-none': 'error',
128
+ 'jwt/no-algorithm-confusion': 'error',
129
+ 'jwt/no-hardcoded-secret': 'warn',
130
+ };
131
+
132
+ /**
133
+ * Configuration presets for flat config
134
+ */
135
+ export const configs = {
136
+ /**
137
+ * Flagship preset — the rule from this plugin in the ecosystem-wide
138
+ * flagship list (`.agent/flagship-rules.md`). Use this when you want
139
+ * the highest-signal JWT subset shippable in CI gates.
140
+ */
141
+ flagship: {
142
+ plugins: {
143
+ jwt: plugin,
144
+ },
145
+ rules: {
146
+ 'jwt/no-algorithm-none': 'error',
147
+ },
148
+ } satisfies TSESLint.FlatConfig.Config,
149
+
150
+ /**
151
+ * Recommended preset - balanced security
152
+ */
153
+ recommended: {
154
+ plugins: {
155
+ jwt: plugin,
156
+ },
157
+ rules: recommendedRules,
158
+ } satisfies TSESLint.FlatConfig.Config,
159
+
160
+ /**
161
+ * Strict preset - maximum security (includes 2025 research)
162
+ */
163
+ strict: {
164
+ plugins: {
165
+ jwt: plugin,
166
+ },
167
+ rules: strictRules,
168
+ } satisfies TSESLint.FlatConfig.Config,
169
+
170
+ /**
171
+ * Legacy preset - migration mode
172
+ */
173
+ legacy: {
174
+ plugins: {
175
+ jwt: plugin,
176
+ },
177
+ rules: legacyRules,
178
+ } satisfies TSESLint.FlatConfig.Config,
179
+
180
+ /**
181
+ * All rules preset
182
+ */
183
+ all: {
184
+ plugins: {
185
+ jwt: plugin,
186
+ },
187
+ rules: strictRules,
188
+ } satisfies TSESLint.FlatConfig.Config,
189
+ };
190
+
191
+ // Default export for flat config usage
192
+ export default plugin;
193
+
194
+ // Named exports for flexibility
195
+ export {
196
+ noAlgorithmNone,
197
+ noAlgorithmConfusion,
198
+ requireAlgorithmWhitelist,
199
+ noDecodeWithoutVerify,
200
+ noWeakSecret,
201
+ requireExpiration,
202
+ noHardcodedSecret,
203
+ requireIssuedAt,
204
+ requireIssuerValidation,
205
+ requireAudienceValidation,
206
+ noTimestampManipulation,
207
+ requireMaxAge,
208
+ noSensitivePayload,
209
+ };
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Copyright (c) 2025 Ofri Peretz
3
+ * Licensed under the MIT License. Use of this source code is governed by the
4
+ * MIT license that can be found in the LICENSE file.
5
+ */
6
+
7
+ import { describe, it, expect } from 'vitest';
8
+ import * as fs from 'node:fs';
9
+ import * as path from 'node:path';
10
+ import { plugin as mainPlugin } from './index';
11
+
12
+ /**
13
+ * Smoke test for the `./oxlint` sub-export.
14
+ *
15
+ * Runtime shape: `oxlint.ts` uses `export = plugin`, which compiles to
16
+ * `module.exports = plugin`. From an ESM dynamic `import('./oxlint')` view,
17
+ * Node's CJS interop surfaces that value at `.default`. From oxlint's
18
+ * `require('eslint-plugin-jwt-security/oxlint')` view, it sits at the top of
19
+ * `module.exports` — exactly the `{ meta, rules }` shape oxlint's JS plugin
20
+ * loader expects.
21
+ */
22
+
23
+ type Plugin = typeof mainPlugin;
24
+
25
+ describe('eslint-plugin-jwt-security/oxlint sub-export', () => {
26
+ it('declares the ./oxlint sub-export in package.json', () => {
27
+ const pkgJson = JSON.parse(
28
+ fs.readFileSync(path.resolve(__dirname, '..', 'package.json'), 'utf8'),
29
+ );
30
+ expect(pkgJson.exports['./oxlint']).toEqual({
31
+ types: './src/oxlint.d.ts',
32
+ default: './src/oxlint.js',
33
+ });
34
+ });
35
+
36
+ it('re-exports the plugin object (meta + rules at top level)', async () => {
37
+ const oxlintModule = await import('./oxlint.js');
38
+ const oxlintPlugin = (oxlintModule as unknown as { default: Plugin }).default;
39
+ expect(oxlintPlugin).toBeDefined();
40
+ expect(oxlintPlugin.meta?.name).toBe('eslint-plugin-jwt-security');
41
+ expect(oxlintPlugin.rules).toBeDefined();
42
+ });
43
+
44
+ it('exposes the same rule names as the main entry (no rules dropped)', async () => {
45
+ const oxlintModule = await import('./oxlint.js');
46
+ const oxlintPlugin = (oxlintModule as unknown as { default: Plugin }).default;
47
+ expect(Object.keys(oxlintPlugin.rules || {}).toSorted()).toEqual(
48
+ Object.keys(mainPlugin.rules || {}).toSorted(),
49
+ );
50
+ });
51
+
52
+ it('exposes the same rule references (pass-through, not a copy)', async () => {
53
+ const oxlintModule = await import('./oxlint.js');
54
+ const oxlintPlugin = (oxlintModule as unknown as { default: Plugin }).default;
55
+ for (const ruleName of Object.keys(mainPlugin.rules || {})) {
56
+ expect(oxlintPlugin.rules?.[ruleName]).toBe(
57
+ (mainPlugin.rules as Record<string, unknown>)[ruleName],
58
+ );
59
+ }
60
+ });
61
+ });
package/src/oxlint.ts ADDED
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Copyright (c) 2025 Ofri Peretz
3
+ * Licensed under the MIT License. Use of this source code is governed by the
4
+ * MIT license that can be found in the LICENSE file.
5
+ */
6
+
7
+ /**
8
+ * oxlint sub-export.
9
+ *
10
+ * Consumers wire oxlint to this entry via:
11
+ * { "jsPlugins": ["eslint-plugin-jwt-security/oxlint"] }
12
+ *
13
+ * oxlint's JS plugin loader does `require('eslint-plugin-jwt-security/oxlint')` and reads
14
+ * `.rules` off the result. The compiled output of `export = plugin` is
15
+ * `module.exports = plugin`, which gives oxlint the plugin object directly
16
+ * (`{ meta, rules }`) — no wrapper, no `.default` indirection.
17
+ *
18
+ * Generated by scripts/generate-oxlint-shims.mjs. Do not edit by hand.
19
+ */
20
+
21
+ import { plugin } from './index';
22
+
23
+ export = plugin;
@@ -0,0 +1,208 @@
1
+ /**
2
+ * Copyright (c) 2025 Ofri Peretz
3
+ * Licensed under the MIT License. Use of this source code is governed by the
4
+ * MIT license that can be found in the LICENSE file.
5
+ */
6
+
7
+ /**
8
+ * ESLint Rule: no-algorithm-confusion
9
+ *
10
+ * Detects algorithm confusion attacks where symmetric algorithms (HS256/384/512)
11
+ * are used with asymmetric keys (public keys). This allows attackers to sign
12
+ * tokens using the public key as an HMAC secret.
13
+ *
14
+ * CWE-347: Improper Verification of Cryptographic Signature
15
+ *
16
+ * @see https://portswigger.net/web-security/jwt/algorithm-confusion
17
+ */
18
+ import type { TSESLint, TSESTree } from '@interlace/eslint-devkit';
19
+ import { createRule, formatLLMMessage, MessageIcons } from '@interlace/eslint-devkit';
20
+ import {
21
+ isVerifyOperation,
22
+ getOptionsArgument,
23
+ extractAlgorithms,
24
+ } from '../../utils';
25
+ import type { NoAlgorithmConfusionOptions } from '../../types';
26
+
27
+ type MessageIds =
28
+ | 'algorithmConfusion'
29
+ | 'symmetricWithPublicKey'
30
+ | 'useAsymmetricAlgorithm';
31
+
32
+ type RuleOptions = [NoAlgorithmConfusionOptions?];
33
+
34
+ // Patterns that indicate a public key
35
+ const PUBLIC_KEY_PATTERNS = [
36
+ /public/i,
37
+ /\.pub$/,
38
+ /\.pem$/,
39
+ /-----BEGIN PUBLIC KEY-----/,
40
+ /-----BEGIN RSA PUBLIC KEY-----/,
41
+ /-----BEGIN EC PUBLIC KEY-----/,
42
+ /getPublicKey/i,
43
+ /publicKey/i,
44
+ /jwks/i,
45
+ ];
46
+
47
+ export const noAlgorithmConfusion = createRule<RuleOptions, MessageIds>({
48
+ name: 'no-algorithm-confusion',
49
+ meta: {
50
+ type: 'problem',
51
+ docs: {
52
+ url: 'https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-jwt-security/docs/rules/no-algorithm-confusion.md',
53
+ description:
54
+ 'Prevent algorithm confusion attacks using symmetric algorithms with asymmetric keys',
55
+ cwe: 'CWE-347',
56
+ cvss: 9.5,
57
+ },
58
+ fixable: undefined,
59
+ hasSuggestions: false,
60
+ messages: {
61
+ algorithmConfusion: formatLLMMessage({
62
+ icon: MessageIcons.SECURITY,
63
+ issueName: 'JWT Algorithm Confusion Attack',
64
+ cwe: 'CWE-347',
65
+ description:
66
+ 'Symmetric algorithm (HS*) used with public key allows token forgery',
67
+ severity: 'CRITICAL',
68
+ fix: 'Use asymmetric algorithms (RS256, ES256) with public keys',
69
+ documentationLink:
70
+ 'https://portswigger.net/web-security/jwt/algorithm-confusion',
71
+ }),
72
+ symmetricWithPublicKey: formatLLMMessage({
73
+ icon: MessageIcons.SECURITY,
74
+ issueName: 'Symmetric Algorithm with Public Key',
75
+ cwe: 'CWE-347',
76
+ description:
77
+ 'HS256/384/512 should only be used with shared secrets, not public keys',
78
+ severity: 'CRITICAL',
79
+ fix: 'Switch to RS256 or ES256 for asymmetric key verification',
80
+ documentationLink:
81
+ 'https://portswigger.net/web-security/jwt/algorithm-confusion',
82
+ }),
83
+ useAsymmetricAlgorithm: formatLLMMessage({
84
+ icon: MessageIcons.INFO,
85
+ issueName: 'Use Asymmetric Algorithm',
86
+ description: 'Replace HS* with RS* or ES* algorithm',
87
+ severity: 'LOW',
88
+ fix: 'Use RS256 or ES256 with public key verification',
89
+ documentationLink: 'https://tools.ietf.org/html/rfc8725',
90
+ }),
91
+ },
92
+ schema: [
93
+ {
94
+ type: 'object',
95
+ properties: {
96
+ symmetricAlgorithms: {
97
+ type: 'array',
98
+ items: { type: 'string' },
99
+ default: ['HS256', 'HS384', 'HS512'],
100
+ description: 'Algorithms to flag when used with public keys',
101
+ },
102
+ trustedSanitizers: {
103
+ type: 'array',
104
+ items: { type: 'string' },
105
+ default: [],
106
+ },
107
+ trustedAnnotations: {
108
+ type: 'array',
109
+ items: { type: 'string' },
110
+ default: [],
111
+ },
112
+ strictMode: {
113
+ type: 'boolean',
114
+ default: false,
115
+ },
116
+ },
117
+ additionalProperties: false,
118
+ },
119
+ ],
120
+ },
121
+ defaultOptions: [
122
+ {
123
+ symmetricAlgorithms: ['HS256', 'HS384', 'HS512'],
124
+ trustedSanitizers: [],
125
+ trustedAnnotations: [],
126
+ strictMode: false,
127
+ },
128
+ ],
129
+ create(context: TSESLint.RuleContext<MessageIds, RuleOptions>) {
130
+ const options = context.options[0] ?? {};
131
+ const symmetricAlgSet = new Set(
132
+ options.symmetricAlgorithms ?? ['HS256', 'HS384', 'HS512']
133
+ );
134
+ const sourceCode = context.sourceCode;
135
+
136
+ /**
137
+ * Check if a node looks like a public key reference
138
+ */
139
+ const looksLikePublicKey = (node: TSESTree.Node): boolean => {
140
+ const text = sourceCode.getText(node);
141
+ return PUBLIC_KEY_PATTERNS.some((pattern) => pattern.test(text));
142
+ };
143
+
144
+ /**
145
+ * Check if algorithms include symmetric algorithms
146
+ */
147
+ const hasSymmetricAlgorithm = (algorithms: string[]): string | null => {
148
+ for (const alg of algorithms) {
149
+ if (symmetricAlgSet.has(alg)) {
150
+ return alg;
151
+ }
152
+ }
153
+ return null;
154
+ };
155
+
156
+ return {
157
+ CallExpression(node: TSESTree.CallExpression) {
158
+ // Only check verify operations
159
+ if (!isVerifyOperation(node)) {
160
+ return;
161
+ }
162
+
163
+ // Need at least 2 arguments: token, key
164
+ if (node.arguments.length < 2) {
165
+ return;
166
+ }
167
+
168
+ const keyArg = node.arguments[1];
169
+ const optionsArg = getOptionsArgument(node, 2);
170
+
171
+ // Check if key looks like a public key
172
+ if (!looksLikePublicKey(keyArg)) {
173
+ return;
174
+ }
175
+
176
+ // If there are options, check the algorithms
177
+ if (optionsArg) {
178
+ const algorithms = extractAlgorithms(optionsArg);
179
+ const symmetricAlg = hasSymmetricAlgorithm(algorithms);
180
+
181
+ if (symmetricAlg) {
182
+ // Find the algorithm node for precise error location
183
+ for (const prop of optionsArg.properties) {
184
+ if (
185
+ prop.type === 'Property' &&
186
+ prop.key.type === 'Identifier' &&
187
+ ['algorithms', 'algorithm', 'alg'].includes(prop.key.name)
188
+ ) {
189
+ context.report({
190
+ node: prop.value,
191
+ messageId: 'algorithmConfusion',
192
+ data: { algorithm: symmetricAlg },
193
+ });
194
+ return;
195
+ }
196
+ }
197
+ }
198
+ }
199
+
200
+ // If no options specified but key looks like public key,
201
+ // and we're in verify, flag as potential issue
202
+ // (verification without explicit algorithm with public key is risky)
203
+ },
204
+ };
205
+ },
206
+ });
207
+
208
+ export default noAlgorithmConfusion;
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Tests for no-algorithm-confusion rule
3
+ * Security: CWE-347 (Algorithm Confusion Attack)
4
+ */
5
+ import { RuleTester } from '@typescript-eslint/rule-tester';
6
+ import { describe, it, afterAll } from 'vitest';
7
+ import parser from '@typescript-eslint/parser';
8
+ import { noAlgorithmConfusion } from './index';
9
+
10
+ RuleTester.afterAll = afterAll;
11
+ RuleTester.it = it;
12
+ RuleTester.itOnly = it.only;
13
+ RuleTester.describe = describe;
14
+
15
+ const ruleTester = new RuleTester({
16
+ languageOptions: {
17
+ parser,
18
+ ecmaVersion: 2022,
19
+ sourceType: 'module',
20
+ },
21
+ });
22
+
23
+ describe('no-algorithm-confusion', () => {
24
+ describe('Valid Code - Safe Patterns', () => {
25
+ ruleTester.run('valid - asymmetric algorithms with public keys', noAlgorithmConfusion, {
26
+ valid: [
27
+ // RS256 with public key - SAFE
28
+ { code: `jwt.verify(token, publicKey, { algorithms: ['RS256'] });` },
29
+ // ES256 with public key - SAFE
30
+ { code: `jwt.verify(token, publicKey, { algorithms: ['ES256'] });` },
31
+ // Multiple asymmetric algorithms
32
+ { code: `jwt.verify(token, publicKey, { algorithms: ['RS256', 'ES256'] });` },
33
+ // HS256 with secret (not public key) - SAFE
34
+ { code: `jwt.verify(token, secret, { algorithms: ['HS256'] });` },
35
+ // HS256 with env var - SAFE
36
+ { code: `jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] });` },
37
+ // No options specified
38
+ { code: `jwt.verify(token, publicKey);` },
39
+ // Sign operation (not verify)
40
+ { code: `jwt.sign(payload, privateKey, { algorithm: 'HS256' });` },
41
+ // Only 1 argument (edge case - line 157 coverage)
42
+ { code: `jwt.verify(token);` },
43
+ // No key that looks like public key
44
+ { code: `jwt.verify(token, sharedSecret, { algorithms: ['HS256'] });` },
45
+ // Empty options object with public key (no algorithms)
46
+ { code: `jwt.verify(token, publicKey, {});` },
47
+ // Options without algorithms property
48
+ { code: `jwt.verify(token, publicKey, { complete: true });` },
49
+ ],
50
+ invalid: [],
51
+ });
52
+ });
53
+
54
+ describe('Invalid Code - Algorithm Confusion', () => {
55
+ ruleTester.run('invalid - symmetric with public key', noAlgorithmConfusion, {
56
+ valid: [],
57
+ invalid: [
58
+ // HS256 with publicKey variable
59
+ {
60
+ code: `jwt.verify(token, publicKey, { algorithms: ['HS256'] });`,
61
+ errors: [{ messageId: 'algorithmConfusion' }],
62
+ },
63
+ // HS384 with public key
64
+ {
65
+ code: `jwt.verify(token, publicKey, { algorithms: ['HS384'] });`,
66
+ errors: [{ messageId: 'algorithmConfusion' }],
67
+ },
68
+ // HS512 with public key
69
+ {
70
+ code: `jwt.verify(token, publicKey, { algorithms: ['HS512'] });`,
71
+ errors: [{ messageId: 'algorithmConfusion' }],
72
+ },
73
+ // Single algorithm option
74
+ {
75
+ code: `jwt.verify(token, publicKey, { algorithm: 'HS256' });`,
76
+ errors: [{ messageId: 'algorithmConfusion' }],
77
+ },
78
+ // Mixed algorithms with symmetric
79
+ {
80
+ code: `jwt.verify(token, publicKey, { algorithms: ['RS256', 'HS256'] });`,
81
+ errors: [{ messageId: 'algorithmConfusion' }],
82
+ },
83
+ // getPublicKey() function
84
+ {
85
+ code: `jwt.verify(token, getPublicKey(), { algorithms: ['HS256'] });`,
86
+ errors: [{ messageId: 'algorithmConfusion' }],
87
+ },
88
+ // JWKS pattern
89
+ {
90
+ code: `jwt.verify(token, jwksKey, { algorithms: ['HS256'] });`,
91
+ errors: [{ messageId: 'algorithmConfusion' }],
92
+ },
93
+ // alg shorthand with public key
94
+ {
95
+ code: `jwt.verify(token, publicKey, { alg: 'HS256' });`,
96
+ errors: [{ messageId: 'algorithmConfusion' }],
97
+ },
98
+ // jwtVerify with public key
99
+ {
100
+ code: `jwtVerify(token, publicKey, { algorithms: ['HS256'] });`,
101
+ errors: [{ messageId: 'algorithmConfusion' }],
102
+ },
103
+ ],
104
+ });
105
+ });
106
+ });