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

@bernierllc/permission-checker

v0.3.0

Published

Atomic permission checking utilities for role-based access control

Downloads

189

Readme

@bernierllc/permission-checker

A comprehensive role-based access control (RBAC) and policy-based access control (PBAC) system for Node.js applications.

Features

  • Role-Based Access Control (RBAC): Define roles with permissions and assign them to users
  • Policy-Based Access Control (PBAC): Create complex policies with priority-based evaluation
  • Role Inheritance: Roles can inherit permissions from other roles
  • Conditional Permissions: Support for time-based, IP-based, and custom conditions
  • Caching: Built-in caching for performance optimization
  • Validation: Comprehensive validation for all permission entities
  • TypeScript: Full TypeScript support with strict typing

Installation

npm install @bernierllc/permission-checker

Quick Start

import { PermissionChecker, Permission, Role, User } from '@bernierllc/permission-checker';

// Create a permission checker instance
const checker = new PermissionChecker();

// Define permissions
const readPermission: Permission = {
  id: 'read-users',
  name: 'Read Users',
  resource: 'users',
  action: 'read'
};

// Define a role
const userRole: Role = {
  id: 'user',
  name: 'User',
  permissions: ['read-users']
};

// Define a user
const user: User = {
  id: 'user1',
  roles: ['user']
};

// Add everything to the checker
checker.addPermission(readPermission);
checker.addRole(userRole);
checker.addUser(user);

// Check permissions
const result = checker.checkPermission({
  user,
  resource: 'users',
  action: 'read'
});

console.log(result.allowed); // true

Core Concepts

Permissions

Permissions define what actions can be performed on what resources.

interface Permission {
  id: string;
  name: string;
  description?: string;
  resource: string;
  action: string;
  conditions?: PermissionCondition[];
}

Roles

Roles group permissions together and can be assigned to users.

interface Role {
  id: string;
  name: string;
  description?: string;
  permissions: string[]; // Permission IDs
  inherits?: string[]; // Role IDs to inherit from
}

Users

Users have roles and can optionally have direct permissions.

interface User {
  id: string;
  roles: string[]; // Role IDs
  permissions?: string[]; // Direct permission IDs (optional)
  metadata?: Record<string, any>;
}

Policies

Policies provide fine-grained control with priority-based evaluation.

interface Policy {
  id: string;
  name: string;
  description?: string;
  rules: PolicyRule[];
  priority: number; // Higher numbers = higher priority
  enabled: boolean;
}

Advanced Usage

Role Inheritance

const readerRole: Role = {
  id: 'reader',
  name: 'Reader',
  permissions: ['read-users']
};

const writerRole: Role = {
  id: 'writer',
  name: 'Writer',
  permissions: ['write-users'],
  inherits: ['reader'] // Inherits read permissions
};

const user: User = {
  id: 'user1',
  roles: ['writer']
};

// User will have both read and write permissions
const permissions = checker.getUserPermissions('user1');

Conditional Permissions

const timeRestrictedPermission: Permission = {
  id: 'time-limited-read',
  name: 'Time Limited Read',
  resource: 'data',
  action: 'read',
  conditions: [{
    type: 'time',
    operator: 'between',
    field: 'timestamp',
    value: [startTime, endTime]
  }]
};

const result = checker.checkPermission({
  user,
  resource: 'data',
  action: 'read',
  context: { timestamp: new Date() }
});

Policy-Based Access Control

const denySensitivePolicy: Policy = {
  id: 'deny-sensitive',
  name: 'Deny Sensitive Data',
  priority: 200,
  enabled: true,
  rules: [{
    effect: 'deny',
    resources: ['sensitive-data'],
    actions: ['*'],
    conditions: [{
      type: 'ip',
      operator: 'not_in',
      field: 'ipAddress',
      value: ['192.168.1.1', '192.168.1.2']
    }]
  }]
};

checker.addPolicy(denySensitivePolicy);

Caching

The permission checker includes built-in caching for performance:

// Disable caching
const checker = new PermissionChecker({ cacheEnabled: false });

// Set custom cache TTL (in milliseconds)
const checker = new PermissionChecker({ cacheTTL: 60000 }); // 1 minute

// Clear cache
checker.clearCache();

// Invalidate specific cache entries
checker.invalidateCache('user1');

API Reference

PermissionChecker

Constructor

new PermissionChecker(options?: {
  cacheEnabled?: boolean;
  cacheTTL?: number;
})

Methods

Permission Management
  • addPermission(permission: Permission): void
  • removePermission(permissionId: string): void
Role Management
  • addRole(role: Role): void
  • removeRole(roleId: string): void
  • getRolePermissions(roleId: string): Permission[]
User Management
  • addUser(user: User): void
  • removeUser(userId: string): void
  • assignRoleToUser(userId: string, roleId: string): void
  • removeRoleFromUser(userId: string, roleId: string): void
  • getUserPermissions(userId: string): Permission[]
Permission Checking
  • checkPermission(check: PermissionCheck): PermissionResult
Policy Management
  • addPolicy(policy: Policy): void
  • removePolicy(policyId: string): void
Cache Management
  • clearCache(): void
  • invalidateCache(pattern?: string): void

Validation Utilities

import {
  validatePermission,
  validateRole,
  validateUser,
  validatePolicy,
  generateId
} from '@bernierllc/permission-checker';

// Validate entities before adding them
const validation = validatePermission(permission);
if (!validation.isValid) {
  console.log('Errors:', validation.errors);
  console.log('Warnings:', validation.warnings);
}

// Generate unique IDs
const permissionId = generateId('permission');

Condition Types

Time Conditions

{
  type: 'time',
  operator: 'between',
  field: 'timestamp',
  value: [startTime, endTime]
}

IP Conditions

{
  type: 'ip',
  operator: 'in',
  field: 'ipAddress',
  value: ['192.168.1.1', '192.168.1.2']
}

Resource Conditions

{
  type: 'resource',
  operator: 'equals',
  field: 'owner',
  value: 'user123'
}

Custom Conditions

{
  type: 'custom',
  operator: 'in',
  field: 'department',
  value: ['engineering', 'product']
}

Operators

  • equals: Exact match
  • not_equals: Not equal
  • in: Value is in array
  • not_in: Value is not in array
  • greater_than: Numeric comparison
  • less_than: Numeric comparison
  • between: Value is between two numbers (inclusive)

Performance Considerations

  • Caching: Enable caching for frequently checked permissions
  • Role Hierarchy: Keep role inheritance chains short
  • Policy Priority: Use higher priorities sparingly
  • Condition Evaluation: Complex conditions impact performance

Best Practices

  1. Use Descriptive IDs: Use kebab-case for IDs (e.g., read-users)
  2. Validate Input: Always validate permissions, roles, and users before adding
  3. Cache Strategically: Enable caching for read-heavy workloads
  4. Monitor Performance: Watch for slow permission checks in production
  5. Test Thoroughly: Test complex permission scenarios

Examples

See the examples/ directory for comprehensive usage examples:

  • Basic RBAC setup
  • Policy-based access control
  • Conditional permissions
  • Role inheritance
  • Caching strategies

License

ISC License - see LICENSE file for details.

Contributing

This package is part of the Bernier LLC tools ecosystem. Please follow the project's contribution guidelines.