Skip to content

Commit

Permalink
Update exp handling and added header validation
Browse files Browse the repository at this point in the history
  • Loading branch information
ahmadnasriya committed Oct 2, 2024
1 parent 7671821 commit 701a10e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 17 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@nasriya/authcrypto",
"version": "1.1.2",
"version": "1.1.3",
"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.",
"main": "./dist/cjs/manager.js",
"module": "./dist/esm/manager.js",
Expand Down
32 changes: 16 additions & 16 deletions src/assets/jwt/jwt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,32 +142,32 @@ class JWTManager {

const [headerEncoded, payloadEncoded, signature] = parts;

// Decode the header/payload
const header = JSON.parse(Buffer.from(headerEncoded, 'base64').toString());
const payload = JSON.parse(Buffer.from(payloadEncoded, 'base64').toString());

// Verify the algorithm matches expected (e.g., HS512)
if (header.alg !== 'HS512') {
return { valid: false, message: `Unexpected algorithm: ${header.alg}` };
}

// Verify the signature
const expectedSignature = this.#_helpers.createSignature(`${headerEncoded}.${payloadEncoded}`);
if (signature !== this.#_helpers.base64ToUrlEncoded(expectedSignature)) {
return { valid: false, message: "Invalid token signature" };
}

// Decode the header/payload
const header = JSON.parse(Buffer.from(headerEncoded, 'base64').toString());
const payload = JSON.parse(Buffer.from(payloadEncoded, 'base64').toString());

if ('exp' in payload) {
if (typeof payload.exp === 'string' && payload.exp.endsWith('Z')) {
let expiryDate: Date;

try {
expiryDate = new Date(payload.exp);
const now = new Date();
if (expiryDate <= now) {
return { valid: false, message: "The token is expired" };
}
} catch {
return { valid: false, message: "Invalid expiry date value" };
if (typeof payload.exp === 'number') {
const now = Math.floor(Date.now() / 1000); // current time in seconds
if (payload.exp <= now) {
return { valid: false, message: "The token is expired" };
}
} else {
return { valid: false, message: "Invalid 'exp' claim type" };
}
} else {
return { valid: false, message: "The token is missing the 'exp` property" };
return { valid: false, message: "Missing 'exp' claim" };
}

// Return the payload if the token is valid
Expand Down

0 comments on commit 701a10e

Please sign in to comment.