Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/decodejwt-malformed-token.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/backend': patch
---

Return a `TokenVerificationError` from `decodeJwt` and `verifyToken` for tokens whose header, payload, or signature cannot be decoded.
13 changes: 13 additions & 0 deletions packages/backend/src/jwt/__tests__/verifyJwt.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { TokenVerificationError } from '../../errors';
import {
createJwt,
mockJwks,
Expand Down Expand Up @@ -85,6 +86,18 @@ describe('decodeJwt(jwt)', () => {
const { errors: [error] = [] } = decodeJwt('42');
expect(error).toMatchObject(invalidTokenError);
});

it('returns an error if the token segments are not valid base64url', () => {
const { errors: [error] = [] } = decodeJwt('aaa.bbb.ccc');
expect(error).toBeInstanceOf(TokenVerificationError);
expect(error).toMatchObject({ reason: 'token-invalid' });
});

it('returns an error if the token segments do not decode to JSON', () => {
const { errors: [error] = [] } = decodeJwt('YWJj.YWJj.YWJj');
expect(error).toBeInstanceOf(TokenVerificationError);
expect(error).toMatchObject({ reason: 'token-invalid' });
});
});

describe('verifyJwt(jwt, options)', () => {
Expand Down
19 changes: 15 additions & 4 deletions packages/backend/src/jwt/verifyJwt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,21 @@ export function decodeJwt(token: string): JwtReturnType<Jwt, TokenVerificationEr
// encode - and _.

// More info at https://stackoverflow.com/questions/54062583/how-to-verify-a-signed-jwt-with-subtlecrypto-of-the-web-crypto-API
const header = JSON.parse(decoder.decode(base64url.parse(rawHeader, { loose: true })));
const payload = JSON.parse(decoder.decode(base64url.parse(rawPayload, { loose: true })));

const signature = base64url.parse(rawSignature, { loose: true });
let header, payload, signature;
try {
header = JSON.parse(decoder.decode(base64url.parse(rawHeader, { loose: true })));
payload = JSON.parse(decoder.decode(base64url.parse(rawPayload, { loose: true })));
signature = base64url.parse(rawSignature, { loose: true });
} catch {
return {
errors: [
new TokenVerificationError({
reason: TokenVerificationErrorReason.TokenInvalid,
message: `Invalid JWT form. The header, payload, or signature could not be decoded.`,
}),
],
};
}
Comment on lines +82 to +96

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
printf '\n== verifyJwt.ts ==\n'
sed -n '1,220p' packages/backend/src/jwt/verifyJwt.ts
printf '\n== search JWT helpers/types ==\n'
rg -n "isJwtObject|type Jwt|interface Jwt|verifyJwt|decodeJwt|TokenVerificationErrorReason" packages/backend/src/jwt packages/backend/src -g '!**/dist/**'

Repository: clerk/javascript

Length of output: 32062


🏁 Script executed:

#!/bin/bash
set -euo pipefail
sed -n '1,220p' packages/backend/src/jwt/verifyJwt.ts
printf '\n---\n'
rg -n "isJwtObject|type Jwt|interface Jwt|verifyJwt|decodeJwt|TokenVerificationErrorReason" packages/backend/src/jwt packages/backend/src -g '!**/dist/**'

Repository: clerk/javascript

Length of output: 32015


🏁 Script executed:

#!/bin/bash
set -euo pipefail
pwd
ls

Repository: clerk/javascript

Length of output: 517


🏁 Script executed:

#!/bin/bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
p = Path('packages/backend/src/jwt/verifyJwt.ts')
print(p.exists())
print(p)
print(p.read_text()[:4000])
PY

Repository: clerk/javascript

Length of output: 4198


🏁 Script executed:

#!/bin/bash
set -euo pipefail
printf '== assertions.ts ==\n'
sed -n '1,260p' packages/backend/src/jwt/assertions.ts
printf '\n== Jwt types from shared package references ==\n'
rg -n "export type Jwt|export interface Jwt|type JwtPayload|interface JwtPayload" packages -g '!**/dist/**'

Repository: clerk/javascript

Length of output: 7586


🏁 Script executed:

#!/bin/bash
set -euo pipefail
printf '== assertions.ts ==\n'
sed -n '1,260p' packages/backend/src/jwt/assertions.ts
printf '\n== Jwt types search ==\n'
rg -n "export type Jwt|export interface Jwt|type JwtPayload|interface JwtPayload" packages -g '!**/dist/**'

Repository: clerk/javascript

Length of output: 7562


Reject non-object JWT parts before returning. JSON.parse can return null or a primitive here, and verifyJwt later destructures header/payload inside a catch, so tokens like bnVsbA.bnVsbA. surface a plain TypeError in errors instead of the invalid-form JWT error.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/backend/src/jwt/verifyJwt.ts` around lines 82 - 96, The JWT parsing
flow in verifyJwt must validate that the decoded header and payload are non-null
objects before continuing. After JSON.parse in the try block, reject null or
primitive values using the existing Invalid JWT form TokenVerificationError
path, ensuring malformed tokens such as null parts cannot reach later
destructuring and produce a TypeError.

Sources: Coding guidelines, MCP tools


const data = {
header,
Expand Down
Loading