New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details
Socket
Book a DemoSign in
Socket

token-auth-edu

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

token-auth-edu

Educational JWT-style token authentication module

latest
Source
npmnpm
Version
1.0.5
Version published
Weekly downloads
0
-100%
Maintainers
1
Weekly downloads
 
Created
Source

Token-Auth Module

A lightweight, dependency-free JavaScript module for issuing, verifying, and revoking JWT-style authentication tokens. Designed for educational purposes and small-scale applications requiring basic token-based authentication with key rotation, expiration handling, evocation and refreshToken capabilities.

Features

  • Token Creation: Generate signed tokens with custom payloads and expiration times

  • Token Verification: Validate token signatures and check revocation status

  • Token Revocation: Maintain a revocation list for

  • Refresh Token: Refreshes a token by verify the old one and request a new one.

invalidated tokens

  • Key Rotation: Automatic key rotation with configurable intervals
  • Base64URL Encoding: RFC 4648 compliant encoding/decoding
  • Zero Dependencies: No external libraries required

Installation

From npm

npm i token-auth-edu

From GitHub

git clone https://github.com/BackEndByAlex/token-auth.git
cd token-auth

As ES6 Module

import { issueToken, verifyToken, decodeToken, revokeToken } from './src/TokenService.js'

Usage Examples

Basic Token Operations

import { issueToken, verifyToken, decodeToken, revokeToken } from './src/TokenService.js'

// Create a token
const payload = { 
  userId: 123, 
  role: 'admin', 
  permissions: ['read', 'write'] 
}
const token = issueToken(payload, 3600) // 1 hour expiration
console.log('Token:', token)

// Verify a token
const verification = verifyToken(token)
if (verification.valid) {
  console.log('Token is valid:', verification.payload)
} else {
  console.log('Token invalid:', verification.error)
}

// Decode token payload (without verification)
const decodedPayload = decodeToken(token)
console.log('Decoded payload:', decodedPayload)

// Revoke a token
const success = revokeToken(decodedPayload.jti, 'User logged out')
console.log('Revocation successful:', success)

Authentication Middleware Example

function authenticateRequest(token) {
  const result = verifyToken(token)
  
  if (!result.valid) {
    throw new Error(`Authentication failed: ${result.error}`)
  }
  
  // Check if token is expired
  if (result.payload.exp < Math.floor(Date.now() / 1000)) {
    throw new Error('Token has expired')
  }
  
  return result.payload
}

// Usage
try {
  const userInfo = authenticateRequest(userToken)
  console.log(`Authenticated user: ${userInfo.userId}`)
} catch (error) {
  console.error('Authentication error:', error.message)
}

Session Management Example

class SessionManager {
  constructor() {
    this.activeSessions = new Map()
  }
  
  login(userId, userData) {
    const payload = { userId, ...userData }
    const token = issueToken(payload, 24 * 60 * 60) // 24 hours
    const decoded = decodeToken(token)
    
    this.activeSessions.set(userId, decoded.jti)
    return token
  }
  
  logout(userId) {
    const jti = this.activeSessions.get(userId)
    if (jti) {
      revokeToken(jti, 'User logout')
      this.activeSessions.delete(userId)
      return true
    }
    return false
  }
  
  validateSession(token) {
    const result = verifyToken(token)
    if (result.valid) {
      return result.payload
    }
    return null
  }
}

API Reference

issueToken(payload, ttlSeconds)

Creates a new JWT token with the specified payload and expiration time.

Parameters:

  • payload (Object): Data to include in the token
  • ttlSeconds (Number): Time-to-live in seconds

Returns: String - The signed JWT token

Example:

const token = issueToken({ userId: 123, role: 'user' }, 3600)

verifyToken(token)

Verifies a token's signature and checks if it has been revoked.

Parameters:

  • token (String): The JWT token to verify

Returns: Object with properties:

  • valid (Boolean): Whether the token is valid
  • payload (Object): Token payload if valid
  • error (String): Error message if invalid

Example:

const result = verifyToken(token)
if (result.valid) {
  console.log('User ID:', result.payload.userId)
}

decodeToken(token)

Decodes a token's payload without verification.

Parameters:

  • token (String): The JWT token to decode

Returns: Object - The decoded payload

Example:

const payload = decodeToken(token)
console.log('Token expires at:', new Date(payload.exp * 1000))

revokeToken(jti, reason)

Adds a token to the revocation list.

Parameters:

  • jti (String): The token's unique identifier
  • reason (String): Reason for revocation

Returns: Boolean - Always returns true

Example:

const payload = decodeToken(token)
revokeToken(payload.jti, 'Security breach')

rotateKey()

Manually triggers key rotation.

Example:

rotateKey() // Forces generation of new signing key

refreshToken(oldToken, newTtl)

Refreshes an existing valid token with a new expiration time.

Parameters:

  • oldToken (String): The token to refresh
  • newTtl (Number): New time-to-live in seconds

Returns: Object with properties:

  • token (String): The new token
  • oldTokenExpiry (Number): When the old token expires

Example:

const refreshed = refreshToken(oldToken, 7200)
console.log('New token:', refreshed.token)

Token Structure

Tokens follow JWT format with three base64url-encoded sections:

header.payload.signature

Header

{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "1609459200000"
}

Payload

{
  "userId": 123,
  "role": "admin",
  "iat": 1609459200,
  "exp": 1609462800,
  "jti": "16094592000001a2b3c4"
}

Security Considerations

⚠️ Educational Use Only: This implementation uses simplified cryptography and is intended for learning purposes. For production applications, use established libraries like jsonwebtoken or jose.

Key Limitations

  • Uses basic hash-based signatures instead of RSA/ECDSA
  • No key persistence across application restarts
  • In-memory revocation store (not persistent)
  • No rate limiting or brute force protection

Best Practices When Using

  • Use HTTPS in production environments
  • Implement short token expiration times
  • Store tokens securely (httpOnly cookies recommended)
  • Implement proper session management
  • Use environment variables for sensitive configuration
  • Implement token refresh workflows for long-lived sessions

Development

Running Tests

node test-app/app-test.js
node test-app/functions-test.js

OR

npm test
npm run functions-test

Contributing

This is an educational project. Feel free to:

  • Fork the repository
  • Create a feature branch
  • Make your changes
  • Add tests for new functionality
  • Submit a pull request

License

MIT License - see LICENSE file for details.

Technical References

JWT Standards

Security Best Practices

Encoding Standards

Implementation References

Version History

  • v1.0.5 - Initial release with basic token operations
  • Features: Token creation, verification, revocation, key rotation, refreshToken.

Keywords

jwt

FAQs

Package last updated on 16 Oct 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts