@pakoamadi/jwt-generator
v1.0.1
Published
A lightweight, ultra-fast, and secure HMAC-SHA256 JWT (JSON Web Token) generator and validator for Node.js. Built with **pure JavaScript** and zero external dependencies, making it perfect for V8-optimized environments and high-load microservices.
Readme
@pakoamadi/jwt-generator
A lightweight, ultra-fast, and secure HMAC-SHA256 JWT (JSON Web Token) generator and validator for Node.js. Built with pure JavaScript and zero external dependencies, making it perfect for V8-optimized environments and high-load microservices.
🔥 Features
- Zero Dependencies: Utilizes only the native
node:cryptomodule. - Timing Attack Protection: Validates cryptographic signatures using
crypto.timingSafeEqual. - High-Load Ready: Extremely low memory footprint and fast execution context.
- Modern ESM: Native support for ECMAScript Modules (
import/export). - Strict Compliance: Fully compliant with RFC 7519 structure (Header, Payload, Signature).
📦 Installation
npm install @pakoamadi/jwt-generator🚀 Usage
1. Generating a Token
Generate a cryptographically secure token with a custom expiration time (in seconds).
import { generateToken } from '@pakoamadi/jwt-generator';
const secret = 'your-secure-v8-secret-key';
const payload = { id: 1, role: 'customer' };
// Generates a token valid for 1 hour (3600 seconds)
const token = generateToken(payload, secret, 3600);
console.log('Generated JWT:', token);2. Verifying a Token
Verify the token's signature, structure, and expiration status in a fail-fast manner.
import { verifyToken } from '@pakoamadi/jwt-generator';
const secret = 'your-secure-v8-secret-key';
const token = 'your.jwt.token';
const decoded = verifyToken(token, secret);
if (decoded) {
console.log('Token is valid! User payload:', decoded);
// Output: { id: 1, role: 'customer', exp: 1718293021 }
} else {
console.error('Authentication Error: Token is invalid, tampered with, or expired.');
}🧪 Testing
The library includes a robust suite of integration tests using the native Node.js Test Runner. It thoroughly checks signature tampering, malformed structures, expiration boundaries, and RFC 7519 header compliance.
Run the tests locally:
npm test📄 API Reference
generateToken(payload, secret, expiresInSeconds)
payload(Object): The application data to embed into the token.secret(String): The secret key used to sign the HMAC-SHA256 signature.expiresInSeconds(Number, optional): Token lifespan. Default is3600(1 hour).
verifyToken(token, secret)
token(String): The raw JWT string to validate.secret(String): The secret key to verify the signature against.- Returns: Decoded (Object) payload if valid;
nullif expired, tampered, or malformed.
📝 License
Distributed under the MIT License. See LICENSE for more information.
