@natsubate/secrets-token-generator
v1.0.0
Published
A lightweight utility for generating cryptographically secure random tokens in Node.js, similar to Python's secrets module.
Downloads
104
Maintainers
Readme
@natsubate/secrets-token-generator 
A lightweight utility for generating cryptographically secure random tokens in Node.js, similar to Python's secrets module.
Install
npm install @natsubate/secrets-token-generatorUsage
import { tokenBytes, tokenHex, tokenUrlSafe } from "@natsubate/secrets-token-generator";
const tokenByBuffer = tokenBytes(32); // 32bytes secure random bytes
const tokenByHex = tokenHex(32); // 32bytes secure random HEX string
console.log(tokenByHex); // -> 7b6d3b21cd1a40b3baf2013c475247fa2c577bfef691e4661cce35fc846f328f
const tokenByUrlSafeBase64 = tokenUrlSafe(32); // 32bytes secure random by Base64URL
console.log(tokenByUrlSafeBase64); // -> 7H8lLtZ6A5C96rfpxtbsRiB2lmXj3ctukOM4kywRIwYAPI
tokenBytes(bytes: number): Buffer
Generates a random value of the specified byte count using cryptographically secure pseudo-random number generator (CSPRNG) and returns the buffer.
bytes:number- Random bytes length (e.g., 32).- Returns:
Buffer- Raw bytes.
tokenHex(bytes: number): string
Generates a random value of the specified byte length using CSPRNG and returns the HEX string.
bytes:number- Random bytes length (e.g., 32).- Returns:
string- HEX encoded token.
tokenUrlSafe(bytes: number): string
Generates a random value of the specified byte length using CSPRNG and returns a Base64 URL string.
bytes:number- Random bytes length (e.g., 32).- Returns:
string- Base64URL encoded token.
Supported Environments
- Node.js 18 or later
TypeScript Type Definition
Included.
Security Notice
- The implementation uses the Node.js standard module
crypto.randomBytes. - While it can be used for security-critical purposes such as CSRF tokens, session IDs, and API keys, ensure the required entropy amount (byte length) is appropriately set according to your use case.
- Also consider the storage and transmission methods for generated tokens (e.g., using HTTPS, setting the Secure cookie flag).
Notes
- All functions are synchronous.
License
- MIT License
