@fire-shield/core
v2.2.2
Published
Fire Shield - A powerful, flexible RBAC (Role-Based Access Control) library with lightning-fast bit-based permissions, wildcards, audit logging, and zero dependencies
Maintainers
Readme
🛡️ Fire Shield
A powerful, flexible, and type-safe Role-Based Access Control (RBAC) library for TypeScript/JavaScript applications. Features a high-performance bit-based permission system with dynamic role hierarchies and zero storage dependencies.
Fire Shield - Protect your application with lightning-fast permission checks ⚡
✨ Features
- ⚡ Bit-based Permission System - Lightning-fast permission checks using bitwise operations
- 🎯 Wildcard Permissions - Pattern matching for flexible permission management (
admin:*,*:read) - 📊 Audit Logging - Comprehensive logging for security, compliance, and debugging
- 🚫 Deny Permissions - Explicit permission denials that override allows
- 🏗️ Dynamic Roles & Permissions - No hardcoded roles, fully configurable
- 📊 Role Hierarchy - Level-based hierarchy system for role inheritance
- 💾 State Persistence - Built-in serialization/deserialization (storage-agnostic)
- 📘 Type-Safe - Full TypeScript support with comprehensive type definitions
- ⚙️ Zero Dependencies - Pure logic with no storage coupling
- 🚀 Lazy Role Evaluation - On-demand role loading for memory efficiency (v2.2.0)
- 💾 Permission Caching - Smart caching with TTL and automatic cleanup (v2.2.0)
- 🔧 Memory Optimization - Advanced memory profiling and optimization tools (v2.2.0)
- ✅ Comprehensive Testing - 275+ tests with 100% pass rate
📦 Installation
npm install @fire-shield/core
# or
yarn add @fire-shield/core
# or
pnpm add @fire-shield/core🚀 Quick Start
import { RBAC } from '@fire-shield/core';
// Create RBAC instance
const rbac = new RBAC();
// Register permissions
rbac.registerPermission('post:read');
rbac.registerPermission('post:write');
rbac.registerPermission('post:delete');
// Create roles with permissions
rbac.createRole('viewer', ['post:read']);
rbac.createRole('editor', ['post:read', 'post:write']);
rbac.createRole('admin', ['post:*']); // Wildcard - all post permissions
// Check permissions
const editor = { id: 'user-1', roles: ['editor'] };
console.log(rbac.hasPermission(editor, 'post:read')); // true
console.log(rbac.hasPermission(editor, 'post:write')); // true
console.log(rbac.hasPermission(editor, 'post:delete')); // false📚 Documentation
Comprehensive documentation is available in the docs/ folder:
Getting Started
- Installation & Quick Start - Setup guide and basic usage
Core Documentation
- API Reference - Complete API documentation
- Core Concepts - Understanding bit-based permissions, hierarchies, etc.
- Advanced Features - Wildcards, Audit Logging, Deny Permissions
Guides
- Best Practices - Recommended patterns and anti-patterns
- Migration Guide - Upgrading from older versions
- Examples Guide - Real-world use cases and patterns
Reference
- TypeScript Types - Type definitions and interfaces
- Performance Guide - Optimization tips and benchmarks
💡 Key Features
Wildcard Permissions
// Grant all admin permissions
rbac.createRole('admin', ['admin:*']);
// Grant all read permissions
rbac.createRole('reader', ['*:read']);
// Super admin
rbac.createRole('super-admin', ['*']);Audit Logging
import { RBAC, ConsoleAuditLogger } from '@fire-shield/core';
const rbac = new RBAC({
auditLogger: new ConsoleAuditLogger()
});
// All permission checks are automatically logged
rbac.hasPermission(user, 'admin:delete');
// [AUDIT] ✗ DENIED: User user-123 - admin:delete
// Reason: User lacks permission: admin:deleteDeny Permissions
// Admin has all permissions
rbac.createRole('admin', ['*']);
const admin = { id: 'admin-1', roles: ['admin'] };
// Deny specific permission
rbac.denyPermission('admin-1', 'system:delete');
rbac.hasPermission(admin, 'user:read'); // true
rbac.hasPermission(admin, 'system:delete'); // false (denied!)Role Hierarchy
const hierarchy = rbac.getRoleHierarchy();
hierarchy.setRoleLevel('user', 1);
hierarchy.setRoleLevel('moderator', 5);
hierarchy.setRoleLevel('admin', 10);
// Check if admin can act as moderator
rbac.canActAsRole('admin', 'moderator'); // true
rbac.canActAsRole('moderator', 'admin'); // false🆕 Lazy Role Evaluation (v2.2.0)
// Enable lazy role loading for large applications
const rbac = new RBAC({
lazyRoles: true,
preset: largeConfigWithThousandsOfRoles
});
// Roles are loaded on-demand only when needed
const stats = rbac.getLazyRoleStats();
console.log(stats);
// { enabled: true, pending: 1000, evaluated: 5, total: 1005 }
// Force evaluation of all pending roles if needed
rbac.evaluateAllRoles();
// Check if a role is still pending
rbac.isRolePending('rarely-used-role'); // true/false
// Get list of pending roles
const pendingRoles = rbac.getPendingRoles();🆕 Permission Caching (v2.2.0)
// Enable smart caching with TTL
const rbac = new RBAC({
enableCache: true,
cacheTTL: 60000, // 60 seconds
cacheCleanupInterval: 300000 // 5 minutes
});
// Permission checks are automatically cached
rbac.hasPermission(user, 'post:read'); // Cache miss - computed
rbac.hasPermission(user, 'post:read'); // Cache hit - instant!
// Get cache statistics
const cacheStats = rbac.getCacheStats();
console.log(cacheStats);
// { hits: 1250, misses: 50, size: 100, hitRate: 96.15 }
// Clear cache when roles/permissions change
rbac.clearPermissionCache();🆕 Memory Optimization (v2.2.0)
// Enable memory profiling
const rbac = new RBAC({
optimizeMemory: true
});
// Get memory usage statistics
const memoryStats = rbac.getMemoryStats();
console.log(memoryStats);
// {
// totalMemory: 1024000,
// usedMemory: 512000,
// roles: 100,
// permissions: 500,
// estimatedBytes: 102400
// }
// Memory optimizer automatically:
// - Deduplicates permission strings
// - Optimizes role storage
// - Manages cache size📖 Examples
Blog Application
import { RBAC } from '@fire-shield/core';
const rbac = new RBAC();
rbac.registerPermission('post:read');
rbac.registerPermission('post:write');
rbac.registerPermission('post:publish');
rbac.createRole('author', ['post:read', 'post:write']);
rbac.createRole('editor', ['post:read', 'post:write', 'post:publish']);
const author = { id: 'user-1', roles: ['author'] };
rbac.hasPermission(author, 'post:write'); // true
rbac.hasPermission(author, 'post:publish'); // falseE-commerce Platform
import { RBACBuilder } from '@fire-shield/core';
const rbac = new RBACBuilder()
.addPermission('product:view', 1)
.addPermission('product:create', 2)
.addPermission('order:process', 4)
.addRole('customer', ['product:view'], { level: 1 })
.addRole('vendor', ['product:view', 'product:create'], { level: 5 })
.addRole('admin', ['*'], { level: 100 })
.build();Multi-Tenant SaaS
const rbac = new RBAC({ enableWildcards: true });
// Tenant-specific permissions
rbac.createRole('tenant-owner', ['tenant:*']);
rbac.createRole('tenant-admin', ['tenant:users:*', 'tenant:data:*']);
const user = {
id: 'user-1',
roles: [],
permissions: ['tenant:123:*'] // Full access to tenant 123
};
rbac.hasPermission(user, 'tenant:123:users:read'); // true
rbac.hasPermission(user, 'tenant:456:users:read'); // falseMore examples: See examples/ folder and Examples Guide
⚡ Performance
The bit-based permission system is highly optimized:
- Permission Check: O(1) - Single bitwise AND operation
- Throughput: up to 10 million ops/sec for exact matches
- Memory: ~1 MB for 10,000 users with bit-based system
See: Performance Guide for detailed benchmarks and optimization tips.
🔧 API Overview
Main Classes
RBAC- Main class for managing permissions and rolesRBACBuilder- Fluent API for building RBAC configurationsBitPermissionManager- Low-level bit-based permission managementRoleHierarchy- Role hierarchy managementWildcardMatcher- Wildcard pattern matching utility
Audit Loggers
ConsoleAuditLogger- Logs to console (development)BufferedAuditLogger- Batches logs for performance (production)MultiAuditLogger- Logs to multiple destinations
Complete API: API Reference
📝 TypeScript Types
interface RBACUser {
id: string;
roles: string[];
permissions?: string[];
permissionMask?: number;
}
interface AuthorizationResult {
allowed: boolean;
reason?: string;
user?: RBACUser;
}
interface AuditEvent {
type: 'permission_check' | 'authorization' | 'role_check';
userId: string;
permission: string;
allowed: boolean;
reason?: string;
context?: Record<string, any>;
timestamp: number;
}Complete types: TypeScript Types
🎯 Use Cases
- Blog/CMS - Content management with author, editor, admin roles
- E-commerce - Customer, vendor, admin permissions
- SaaS - Multi-tenant permission isolation
- API Gateway - Endpoint-level access control
- Healthcare - HIPAA-compliant audit logging
- Enterprise - Complex role hierarchies and workflows
Real-world examples: Examples Guide
🔄 Migration
Upgrading to v2.0? Check out our Migration Guide.
Zero breaking changes! All existing code continues to work.
🤝 Contributing
Contributions are welcome! Please:
- Read our contributing guidelines
- Submit pull requests with tests
- Follow existing code style
📄 License
DIB
🔗 Links
- Documentation:
docs/ - Examples:
examples/ - GitHub: github.com/khapu2906/fire-shield
- Issues: github.com/khapu2906/fire-shield/issues
- NPM: npmjs.com/package/@fire-shield/core
Ready to get started? → Quick Start Guide
