npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

authorization-z

v1.0.2

Published

`Authorization-Z` is a comprehensive Express middleware package for validating JWT Authorization-Z tokens, attaching permissions to requests, verifying permissions, and granting access accordingly. This package provides a robust solution for implementing

Readme

Authorization-Z

Authorization-Z is a comprehensive Express middleware package for validating JWT Authorization-Z tokens, attaching permissions to requests, verifying permissions, and granting access accordingly. This package provides a robust solution for implementing role-based access control (RBAC) in Express applications.

🚀 Features

  • JWT Token Validation: Validates JWT tokens using Authorization-Z with comprehensive error handling
  • Permission Management: Attaches user permissions to the request object for easy access
  • Access Control: Grants access based on module and action permission checks
  • Multi-language Support: Built-in internationalization (i18n) support with customizable error messages
  • TypeScript Support: Full TypeScript support with type definitions
  • Express Integration: Seamlessly integrates into any Express-based application
  • Error Handling: Comprehensive error handling with proper HTTP status codes
  • Security: Secure token verification with proper secret validation

📦 Installation

Install the package via npm:

npm install authorization-z

🔧 Usage

Basic Setup

import express from 'express';
import { IsJWTAuthorizationZTokenValid, authorizeAccess } from 'authorization-z';

const app = express();

// Your JWT secret key
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';

// Apply the JWT validation middleware globally
app.use(IsJWTAuthorizationZTokenValid(JWT_SECRET));

// Your routes
app.get('/api/users', authorizeAccess('users', 'read'), (req, res) => {
  // This route requires 'read' permission for 'users' module
  res.json({ message: 'Users data' });
});

app.post('/api/users', authorizeAccess('users', 'create'), (req, res) => {
  // This route requires 'create' permission for 'users' module
  res.json({ message: 'User created' });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Advanced Usage

Custom Error Messages

The package supports internationalization. You can set the language for error messages:

// Set language middleware (before authorization middleware)
app.use((req, res, next) => {
  req.lang = req.headers['accept-language'] || 'en';
  next();
});

app.use(IsJWTAuthorizationZTokenValid(JWT_SECRET));

Permission Structure

The JWT token should contain permissions in the following format:

{
  "userId": "123",
  "email": "[email protected]",
  "role": "admin",
  "permissions": {
    "users": ["read", "create", "update", "delete"],
    "products": ["read", "create"],
    "orders": ["read", "update"]
  }
}

Multiple Permission Checks

// Check multiple actions for the same module
app.put('/api/users/:id', 
  authorizeAccess('users', 'update'),
  authorizeAccess('users', 'write'),
  (req, res) => {
    res.json({ message: 'User updated' });
  }
);

// Different modules
app.get('/api/dashboard', 
  authorizeAccess('users', 'read'),
  authorizeAccess('analytics', 'view'),
  (req, res) => {
    res.json({ message: 'Dashboard data' });
  }
);

Accessing Permissions in Routes

app.get('/api/profile', authorizeAccess('profile', 'read'), (req, res) => {
  // Access permissions from request object
  const userPermissions = req.permissions;
  
  // Check specific permissions
  const canDeleteUsers = userPermissions?.users?.includes('delete') || false;
  
  res.json({ 
    permissions: userPermissions,
    canDeleteUsers 
  });
});

🛠️ Development Setup

Prerequisites

  • Node.js (v14 or higher)
  • npm or yarn
  • TypeScript knowledge

Local Development

  1. Clone the repository

    git clone <repository-url>
    cd authorization-z
  2. Install dependencies

    npm install
  3. Build the package

    npm run build
  4. Test locally

    # Link the package locally for testing
    npm link
       
    # In your test project
    npm link authorization-z

Project Structure

authorization-z/
├── src/
│   ├── constants/
│   │   └── messages.ts          # Internationalization logic
│   ├── errors/
│   │   └── AppError.ts          # Custom error class
│   ├── locales/
│   │   ├── en.json             # English messages
│   │   ├── de.json             # German messages
│   │   └── it.json             # Italian messages
│   ├── middleware/
│   │   ├── authorizeAccessMiddleware.ts
│   │   └── isJWTAuthorizationZTokenValidMiddleware.ts
│   ├── types/
│   │   └── express/
│   │       └── index.d.ts       # TypeScript declarations
│   └── index.ts                 # Main export file
├── scripts/
│   └── copy-assets.js           # Build script for assets
├── package.json
├── tsconfig.json
└── README.md

📦 Package Publishing Guide

Initial Package Setup

  1. Create package.json

    {
      "name": "authorization-z",
      "version": "1.0.0",
      "description": "Express middleware for validating JWT Authorization-Z tokens",
      "main": "dist/index.js",
      "types": "dist/index.d.ts",
      "files": ["dist"],
      "scripts": {
        "build": "tsc && node ./scripts/copy-assets.js",
        "prepublishOnly": "npm run build"
      },
      "keywords": ["express", "middleware", "jwt", "authorization"],
      "author": "Your Name",
      "license": "MIT"
    }
  2. Configure TypeScript (tsconfig.json)

    {
      "compilerOptions": {
        "target": "ES2019",
        "module": "commonjs",
        "declaration": true,
        "outDir": "dist",
        "strict": true,
        "esModuleInterop": true,
        "skipLibCheck": true
      },
      "include": ["src"],
      "exclude": ["dist", "node_modules"]
    }
  3. Set up build script Create scripts/copy-assets.js to copy locale files during build.

Publishing to NPM

First Time Publishing

  1. Login to NPM

    npm login
  2. Check package name availability

    npm search authorization-z
  3. Build the package

    npm run build
  4. Publish

    npm publish

Updating the Package

  1. Update version

    # Patch version (1.0.0 -> 1.0.1)
    npm version patch
       
    # Minor version (1.0.0 -> 1.1.0)
    npm version minor
       
    # Major version (1.0.0 -> 2.0.0)
    npm version major
  2. Build and publish

    npm run build
    npm publish

Publishing Checklist

  • [ ] Update version in package.json
  • [ ] Update CHANGELOG.md (if applicable)
  • [ ] Test the build locally
  • [ ] Run npm run build
  • [ ] Check dist/ folder contains all necessary files
  • [ ] Run npm publish

🔧 Configuration

Environment Variables

# Required
JWT_SECRET=your-super-secret-jwt-key

# Optional
NODE_ENV=production

TypeScript Configuration

The package extends Express types to include:

interface Request {
  userId?: string;
  email?: string;
  tenantId?: string;
  tenantKnex?: any;
  permissions?: Record<string, string[]>;
  lang?: string;
}

🚨 Error Handling

The package provides comprehensive error handling with proper HTTP status codes:

  • 401 - Unauthorized (missing/invalid token)
  • 403 - Forbidden (insufficient permissions)
  • 400 - Bad Request (malformed permissions)
  • 500 - Internal Server Error (configuration issues)

Error Messages

All error messages support internationalization:

// English (default)
"AUTHORIZATION_Z_TOKEN_MISSING": "Authorization Z token is missing"

// German
"AUTHORIZATION_Z_TOKEN_MISSING": "Authorization Z Token fehlt"

// Italian
"AUTHORIZATION_Z_TOKEN_MISSING": "Token di autorizzazione Z mancante"

🧪 Testing

Manual Testing

  1. Generate a JWT token

    const jwt = require('jsonwebtoken');
       
    const token = jwt.sign({
      userId: '123',
      email: '[email protected]',
      permissions: {
        users: ['read', 'create'],
        products: ['read']
      }
    }, 'your-secret-key');
       
    console.log(token);
  2. Test with curl

    curl -H "Authorization-Z: YOUR_JWT_TOKEN" \
         -H "Accept-Language: en" \
         http://localhost:3000/api/users

📚 API Reference

IsJWTAuthorizationZTokenValid(secret: string)

Validates JWT tokens and attaches permissions to the request object.

Parameters:

  • secret (string): JWT secret key for token verification

Returns:

  • Express middleware function

authorizeAccess(moduleName: string, action: string)

Checks if the user has permission to perform a specific action on a module.

Parameters:

  • moduleName (string): The module to check permissions for
  • action (string): The action to check permissions for

Returns:

  • Express middleware function

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🆘 Support

For support and questions:

  • Create an issue on GitHub
  • Check the documentation
  • Review the examples in this README

🔄 Version History

  • 1.0.0 - Initial release with JWT validation and permission checking

  • 1.0.1 - Removed the language middleware dependency; language is now taken directly from the request.

  • 1.0.2 - Added super admin access control management, granting complete system access to super admin account.

  • Future versions will be documented here


Note: This package is designed for Express applications and requires Express as a peer dependency. Make sure you have Express installed in your project.