Skip to content

Commit 701a10e

Browse files
committed
Update exp handling and added header validation
1 parent 7671821 commit 701a10e

2 files changed

Lines changed: 17 additions & 17 deletions

File tree

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@nasriya/authcrypto",
3-
"version": "1.1.2",
3+
"version": "1.1.3",
44
"description": "AuthCrypto is a versatile cryptographic toolkit for handling JSON Web Tokens (JWT), password hashing, and secure token generation and verification. It provides robust methods for creating and managing JWTs, hashing and verifying passwords with secure algorithms, and generating cryptographically strong random values for various use cases.",
55
"main": "./dist/cjs/manager.js",
66
"module": "./dist/esm/manager.js",

src/assets/jwt/jwt.ts

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -142,32 +142,32 @@ class JWTManager {
142142

143143
const [headerEncoded, payloadEncoded, signature] = parts;
144144

145+
// Decode the header/payload
146+
const header = JSON.parse(Buffer.from(headerEncoded, 'base64').toString());
147+
const payload = JSON.parse(Buffer.from(payloadEncoded, 'base64').toString());
148+
149+
// Verify the algorithm matches expected (e.g., HS512)
150+
if (header.alg !== 'HS512') {
151+
return { valid: false, message: `Unexpected algorithm: ${header.alg}` };
152+
}
153+
145154
// Verify the signature
146155
const expectedSignature = this.#_helpers.createSignature(`${headerEncoded}.${payloadEncoded}`);
147156
if (signature !== this.#_helpers.base64ToUrlEncoded(expectedSignature)) {
148157
return { valid: false, message: "Invalid token signature" };
149158
}
150159

151-
// Decode the header/payload
152-
const header = JSON.parse(Buffer.from(headerEncoded, 'base64').toString());
153-
const payload = JSON.parse(Buffer.from(payloadEncoded, 'base64').toString());
154-
155160
if ('exp' in payload) {
156-
if (typeof payload.exp === 'string' && payload.exp.endsWith('Z')) {
157-
let expiryDate: Date;
158-
159-
try {
160-
expiryDate = new Date(payload.exp);
161-
const now = new Date();
162-
if (expiryDate <= now) {
163-
return { valid: false, message: "The token is expired" };
164-
}
165-
} catch {
166-
return { valid: false, message: "Invalid expiry date value" };
161+
if (typeof payload.exp === 'number') {
162+
const now = Math.floor(Date.now() / 1000); // current time in seconds
163+
if (payload.exp <= now) {
164+
return { valid: false, message: "The token is expired" };
167165
}
166+
} else {
167+
return { valid: false, message: "Invalid 'exp' claim type" };
168168
}
169169
} else {
170-
return { valid: false, message: "The token is missing the 'exp` property" };
170+
return { valid: false, message: "Missing 'exp' claim" };
171171
}
172172

173173
// Return the payload if the token is valid

0 commit comments

Comments
 (0)