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 πŸ™

Β© 2025 – Pkg Stats / Ryan Hefner

@tezx/rbac

v1.0.2

Published

πŸ” Flexible Role-Based Access Control (RBAC) middleware for the TezX framework with support for dynamic role IDs.

Readme

πŸ” @tezx/rbac

A powerful, fully type-safe Role-Based Access Control (RBAC) plugin for TezX, designed to help you control access to routes, APIs, and resources using simple, template-based permission keys with full IntelliSense support.


πŸš€ Highlights

  • 🎯 Type-safe permission system (T extends string[])
  • 🧠 IntelliSense-based permission enforcement
  • πŸ” Multi-role support (ctx.user.role can be string | string[])
  • βš™οΈ Middleware-driven, plug-and-play
  • ❌ Built-in denial handling + custom onDeny() support
  • 🧩 Easy integration with auth middlewares (like authChecker)
  • πŸ§ͺ Battle-tested in production apps
  • πŸ”‘ Use role IDs(Dynamically generated, flexible)
  • πŸ” Clean merge of all permissions (No manual logic needed)
  • 🏷️ Static roles still supported (Easy for default usage)

πŸ“¦ Installation

npm install @tezx/rbac

🧠 How It Works

[Your Middleware]
    ⬇️ sets ctx.user.role
[RBAC Plugin]
    ⬇️ loads permission map
[Route Guard]
    ⬇️ checks permission key
[βœ“ ALLOW] or [❌ DENY]

⚠️ Required: ctx.user.role

To work correctly, you must set ctx.user.role before using RBAC.

βœ… Example:

ctx.user = {
  id: 'user_001',
  role: 'admin',  // βœ… Required
  email: '[email protected]'
};

βœ… If roles can be multiple:

ctx.user = {
  role: ['editor', 'viewer']
};

πŸ’‘ Use authChecker() middleware to assign ctx.user from token/session.


πŸ§‘β€πŸ’» Usage Example


import RBAC from '@tezx/rbac';
type Permissions = ['user:create', 'user:delete', 'order:read', 'property:approve'];

const rbac = new RBAC<Permissions>();

app.use(authChecker()); // βœ… Assigns ctx.user + ctx.user.role

app.use(rbac.plugin({
  loadPermissions: async () => ({
    admin: ['user:create', 'user:delete', 'order:read', 'property:approve'],
    editor: ['order:read'],
    guest: []
  })
}));

app.get('/admin/users', rbac.authorize('user:create'), async (ctx) => {
  return ctx.text('You can create users.');
});

πŸ“Œ RBAC Lifecycle

| Step | Action | | ---- | ----------------------------------------------------------------- | | 1️⃣ | ctx.user.role assigned by auth middleware | | 2️⃣ | rbac.plugin() loads Roleβ†’Permission map | | 3️⃣ | rbac.authorize('permission:key') checks merged role permissions | | 4️⃣ | If not allowed β†’ return 403 (with onDeny if provided) |


πŸ” Replace role with Unique Role IDs (Advanced)

RBAC system supports mapping dynamic role identifiers (like database IDs or UUIDs) instead of hardcoded role names.

This is helpful when:

  • βœ… Roles are created dynamically from a dashboard or DB
  • βœ… You want to map user roles like "role_8FaHq1" instead of just "admin"
  • βœ… Permission sets are assigned to these dynamic IDs

πŸ§ͺ Example

ctx.user = {
  id: 'user_xyz',
  role: 'role_8FaHq1' // βœ… Your actual role ID from database
};
// Load role-permission map based on DB role IDs
loadPermissions: async () => ({
  role_8FaHq1: ['user:create', 'order:read'],
  role_7NbQt55: ['user:delete']
})

βœ… Internally, RBAC merges all permissions based on the provided ctx.user.role, whether it's string or string[].

⚠️ Important

Make sure the role ID you assign in ctx.user.role exactly matches the keys in your permission map.


Bonus: Hybrid Role Support

You can even mix static roles with dynamic IDs if needed:

ctx.user = {
  role: ['admin', 'role_7bXy91']
};

loadPermissions: async () => ({
  admin: ['dashboard:access'],
  role_7bXy91: ['product:create']
});

🧩 Plugin API

rbac.plugin(config)

Initializes the permission map.

Config options:

| Field | Type | Required | Description | | ----------------- | ---------------------------- | -------- | --------------------- | | loadPermissions | (ctx) => RolePermissionMap | βœ… | Role β†’ permission map | | isAuthorized | (roles, permissions, ctx) | ❌ | Custom check hook | | onDeny | (error, ctx) | ❌ | Custom deny response |


rbac.authorize('permission:key')

Middleware to protect routes.

app.post('/orders', rbac.authorize('order:read'), handler);

πŸ’‘ IntelliSense with Template Types

type Permissions = ['user:create', 'order:read', 'admin:panel'];

const rbac = new RBAC<Permissions>();

βœ… Now rbac.authorize(...) will auto-suggest only those permission keys.


❌ Custom Deny Example

rbac.plugin({
  loadPermissions: ...,
  onDeny: (error, ctx) => {
    return ctx.json({
      success: false,
      reason: error.message,
      permission: error.permission
    });
  }
});

πŸ” Real-World Structure

const permissionMap = {
  admin: ['user:create', 'user:delete'],
  editor: ['order:read'],
  viewer: [],
};

User may have:

ctx.user = {
  id: 'u-001',
  role: ['editor', 'viewer']
};

RBAC will combine permissions from both roles.


πŸ”₯ Debug Tip

To check permissions being applied at runtime:

console.log(ctx.user.permissions); // all merged permissions

πŸ“š Types Summary

type RolePermissionMap<T extends string[]> = Record<string, T[number][]>;
type DenyError<T extends string[]> = {
  error: string;
  message: string;
  permission: T[number];
};

πŸ“¦ Exported API

import RBAC, { plugin, authorize } from '@tezx/rbac';

πŸ§ͺ Test Route Example

app.get('/secure', rbac.authorize('admin:panel'), async (ctx) => {
  ctx.body = { status: 'Access granted.' };
});

βœ… Best Practices

  • πŸ”„ Always assign ctx.user.role in authChecker
  • 🧠 Define permissions centrally as union literal type
  • πŸ” Protect all critical routes using rbac.authorize()
  • πŸ§ͺ Add logging inside onDeny for better traceability