TezXTezX
ToolkitUtilities

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: 'rakib@example.com'
};

βœ… 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

StepAction
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:

FieldTypeRequiredDescription
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