Core API Reference
Complete API reference for @fire-shield/core.
RBAC Class
The main class for managing roles, permissions, and access control.
Constructor
new RBAC(options?: RBACOptions)Parameters
options(optional): Configuration optionsconfig?: RBACConfigSchema- Config-based initializationpreset?: PresetConfig- Preset configurationuseBitSystem?: boolean- Enable bit-level permission checking (default: true)strictMode?: boolean- Enable strict mode for bit permissionsauditLogger?: AuditLogger- Custom audit loggerenableWildcards?: boolean- Enable wildcard permission matching (default: true)enableCache?: boolean- Enable permission caching (default: false) v2.2.0cacheOptions?: PermissionCacheOptions- Cache configuration v2.2.0lazyRoles?: boolean- Enable lazy role evaluation (default: false) v2.2.0optimizeMemory?: boolean- Enable memory optimization (default: false) v2.2.0
Example
import { RBAC, BufferedAuditLogger } from '@fire-shield/core'
// Basic usage
const rbac = new RBAC({
auditLogger: new BufferedAuditLogger(async (logs) => {
console.log('Audit logs:', logs)
}),
useBitSystem: true
})
// With v2.2.0 performance features
const rbacOptimized = new RBAC({
enableCache: true,
cacheOptions: {
ttl: 60000, // 1 minute
maxSize: 10000
},
lazyRoles: true,
optimizeMemory: true
})Static Methods
fromJSONConfig
v2.2.0 - Create RBAC instance from JSON configuration.
static fromJSONConfig(json: string, options?: RBACOptions): RBACParameters:
json- JSON string containing PresetConfigoptions- Additional RBAC options
Returns: New RBAC instance
Example:
const configJson = JSON.stringify({
permissions: [
{ name: 'posts:read' },
{ name: 'posts:write' }
],
roles: [
{ name: 'editor', permissions: ['posts:read', 'posts:write'] }
]
})
const rbac = RBAC.fromJSONConfig(configJson, {
enableCache: true
})fromFile
v2.2.0 - Create RBAC instance from file (Node.js only, async).
static async fromFile(filePath: string, options?: RBACOptions): Promise<RBAC>Parameters:
filePath- Path to JSON config fileoptions- Additional RBAC options
Returns: Promise<RBAC> instance
Example:
const rbac = await RBAC.fromFile('./config/rbac.json', {
enableCache: true,
lazyRoles: true
})fromFileSync
v2.2.0 - Create RBAC instance from file synchronously (Node.js only).
static fromFileSync(filePath: string, options?: RBACOptions): RBACExample:
const rbac = RBAC.fromFileSync('./config/rbac.json')validateConfig
v2.2.0 - Validate PresetConfig structure.
static validateConfig(config: PresetConfig): voidThrows: Error if config is invalid
Example:
try {
RBAC.validateConfig(myConfig)
console.log('Config is valid')
} catch (error) {
console.error('Invalid config:', error.message)
}Instance Methods
createRole
Create a new role with permissions.
createRole(roleName: string, permissions: string[]): voidParameters:
roleName- Name of the rolepermissions- Array of permission strings
Example:
rbac.createRole('admin', ['posts:*', 'users:*'])
rbac.createRole('editor', ['posts:read', 'posts:write'])deleteRole
Delete a role.
deleteRole(roleName: string): voidExample:
rbac.deleteRole('editor')grant
Grant additional permissions to an existing role.
grant(roleName: string, permissions: string[]): voidExample:
rbac.grant('editor', ['posts:delete'])revoke
Revoke permissions from a role.
revoke(roleName: string, permissions: string[]): voidExample:
rbac.revoke('editor', ['posts:delete'])hasPermission
Check if a user has a specific permission.
hasPermission(user: RBACUser, permission: string): booleanParameters:
user- User object with rolespermission- Permission string to check
Returns: true if user has permission, false otherwise
Example:
const user = { id: '1', roles: ['editor'] }
const canWrite = rbac.hasPermission(user, 'posts:write') // true
const canDelete = rbac.hasPermission(user, 'posts:delete') // falsesetRoleHierarchy
Define role inheritance chains.
setRoleHierarchy(hierarchy: Record<string, string[]>): voidParameters:
hierarchy- Object mapping roles to their parent roles
Example:
rbac.setRoleHierarchy({
admin: ['editor', 'moderator'],
editor: ['viewer'],
moderator: ['viewer']
})getRolePermissions
Get all permissions for a role (including inherited).
getRolePermissions(roleName: string): string[]Returns: Array of permission strings
Example:
const permissions = rbac.getRolePermissions('editor')
// ['posts:read', 'posts:write']getUserPermissions
Get all permissions for a user (across all roles).
getUserPermissions(user: RBACUser): string[]Returns: Array of permission strings
Example:
const user = { id: '1', roles: ['editor', 'moderator'] }
const permissions = rbac.getUserPermissions(user)hasAnyPermission
Check if user has any of the specified permissions.
hasAnyPermission(user: RBACUser, permissions: string[]): booleanExample:
const user = { id: '1', roles: ['editor'] }
const canEdit = rbac.hasAnyPermission(user, ['posts:write', 'posts:delete'])hasAllPermissions
Check if user has all of the specified permissions.
hasAllPermissions(user: RBACUser, permissions: string[]): booleanExample:
const user = { id: '1', roles: ['admin'] }
const hasFullAccess = rbac.hasAllPermissions(user, ['posts:read', 'posts:write', 'posts:delete'])Deny Permissions (v2.2.0)
Deny permissions allow you to explicitly revoke specific permissions for individual users, even if their roles grant them. Denies always take precedence over allows.
denyPermission
v2.2.0 - Deny a specific permission for a user.
denyPermission(userId: string, permission: string): voidParameters:
userId- User ID to deny permission forpermission- Permission to deny (supports wildcards)
Example:
// Deny specific permission
rbac.denyPermission('user-123', 'posts:delete')
// Deny with wildcard
rbac.denyPermission('user-456', 'admin:*')
// User will now be denied even if their role grants the permission
const user = { id: 'user-123', roles: ['admin'] }
rbac.hasPermission(user, 'posts:delete') // falseallowPermission
v2.2.0 - Remove a denied permission for a user.
allowPermission(userId: string, permission: string): voidExample:
// Remove the deny
rbac.allowPermission('user-123', 'posts:delete')
// User can now use the permission again
rbac.hasPermission(user, 'posts:delete') // true (if role grants it)getDeniedPermissions
v2.2.0 - Get all denied permissions for a user.
getDeniedPermissions(userId: string): string[]Returns: Array of denied permission strings
Example:
const deniedPerms = rbac.getDeniedPermissions('user-123')
console.log(deniedPerms) // ['posts:delete', 'users:ban']clearDeniedPermissions
v2.2.0 - Clear all denied permissions for a user.
clearDeniedPermissions(userId: string): voidExample:
rbac.clearDeniedPermissions('user-123')
// All denies removed, user permissions back to role-basedCache Management (v2.2.0)
When enableCache: true is set, permission checks are cached for better performance.
invalidateUserCache
v2.2.0 - Invalidate all cached permission checks for a specific user.
invalidateUserCache(userId: string): voidExample:
// User's roles changed, clear their cache
rbac.invalidateUserCache('user-123')invalidatePermissionCache
v2.2.0 - Invalidate cached checks for a specific permission across all users.
invalidatePermissionCache(permission: string): voidExample:
// Permission definition changed, clear all caches for it
rbac.invalidatePermissionCache('posts:delete')getCacheStats
v2.2.0 - Get cache statistics.
getCacheStats(): CacheStats | undefinedReturns: Cache statistics or undefined if cache is disabled
Example:
const stats = rbac.getCacheStats()
console.log(stats)
// {
// hits: 1250,
// misses: 50,
// hitRate: 0.96,
// size: 450,
// maxSize: 10000
// }Lazy Role Evaluation (v2.2.0)
When lazyRoles: true is set, roles are only evaluated when first accessed, reducing initial load time and memory usage.
getEvaluatedRoles
v2.2.0 - Get list of roles that have been evaluated.
getEvaluatedRoles(): string[]Example:
const evaluated = rbac.getEvaluatedRoles()
console.log(evaluated) // ['admin', 'editor']getPendingRoles
v2.2.0 - Get list of roles not yet evaluated.
getPendingRoles(): string[]Example:
const pending = rbac.getPendingRoles()
console.log(pending) // ['viewer', 'guest', 'moderator']getLazyRoleStats
v2.2.0 - Get lazy role evaluation statistics.
getLazyRoleStats(): LazyRoleStatsReturns: Object with lazy role statistics
Example:
const stats = rbac.getLazyRoleStats()
console.log(stats)
// {
// enabled: true,
// pending: 5,
// evaluated: 2,
// total: 7
// }isRolePending
v2.2.0 - Check if a role is pending evaluation.
isRolePending(roleName: string): booleanExample:
if (rbac.isRolePending('viewer')) {
console.log('Viewer role not yet loaded')
}evaluateAllRoles
v2.2.0 - Force evaluation of all pending roles.
evaluateAllRoles(): voidExample:
// Load all roles immediately
rbac.evaluateAllRoles()Memory Optimization (v2.2.0)
When optimizeMemory: true is set, Fire Shield uses string interning and other techniques to reduce memory usage.
getMemoryStats
v2.2.0 - Get memory optimization statistics.
getMemoryStats(): MemoryStatsReturns: Object with memory statistics
Example:
const stats = rbac.getMemoryStats()
console.log(stats)
// {
// enabled: true,
// stringPoolSize: 150,
// roleMaskCacheSize: 25,
// wildcardPatternCacheSize: 10,
// estimatedMemorySaved: 45000 // bytes
// }compactMemory
v2.2.0 - Compact memory by cleaning up unused resources.
compactMemory(): { stringsRemoved: number; cacheEntriesRemoved: number }Returns: Object with cleanup statistics
Example:
const result = rbac.compactMemory()
console.log(`Removed ${result.stringsRemoved} strings and ${result.cacheEntriesRemoved} cache entries`)Types
RBACUser
User object with role assignments.
interface RBACUser {
id: string
roles: string[]
[key: string]: any // Additional user properties
}Example:
const user: RBACUser = {
id: 'user-123',
roles: ['editor', 'moderator'],
email: 'user@example.com',
name: 'John Doe'
}RBACOptions
Configuration options for RBAC instance.
interface RBACOptions {
auditLogger?: AuditLogger
bitPermissions?: boolean
}AuditLogger
Interface for custom audit loggers.
interface AuditLogger {
log(event: AuditEvent): void | Promise<void>
}AuditEvent
Audit log event structure.
interface AuditEvent {
timestamp: Date
userId: string
action: 'permission_check' | 'role_grant' | 'role_revoke'
resource: string
permission?: string
result: boolean
metadata?: Record<string, any>
}Audit Logging
BufferedAuditLogger
Built-in audit logger with buffering.
new BufferedAuditLogger(
handler: (logs: AuditEvent[]) => Promise<void>,
options?: BufferedAuditLoggerOptions
)Parameters
handler- Function to process buffered logsoptions(optional):maxBufferSize?: number- Max buffer size (default: 100)flushIntervalMs?: number- Flush interval (default: 5000)
Example
import { BufferedAuditLogger } from '@fire-shield/core'
const auditLogger = new BufferedAuditLogger(
async (logs) => {
await saveLogsToDatabase(logs)
},
{
maxBufferSize: 50,
flushIntervalMs: 3000
}
)
const rbac = new RBAC({ auditLogger })Methods
flush
Manually flush buffered logs.
flush(): Promise<void>Example:
await auditLogger.flush()Custom Audit Logger
Implement custom audit logger:
class CustomAuditLogger implements AuditLogger {
async log(event: AuditEvent) {
console.log('Audit event:', event)
// Send to logging service
await fetch('/api/audit', {
method: 'POST',
body: JSON.stringify(event)
})
}
}
const rbac = new RBAC({
auditLogger: new CustomAuditLogger()
})RBAC Builder
Fluent API for building RBAC configurations.
import { RBACBuilder } from '@fire-shield/core'
const rbac = new RBACBuilder()
.role('admin')
.grant(['posts:*', 'users:*'])
.role('editor')
.grant(['posts:read', 'posts:write'])
.role('viewer')
.grant(['posts:read'])
.hierarchy({
admin: ['editor'],
editor: ['viewer']
})
.build()Methods
role
Start defining a role.
role(name: string): RBACBuildergrant
Grant permissions to current role.
grant(permissions: string[]): RBACBuilderhierarchy
Set role hierarchy.
hierarchy(hierarchy: Record<string, string[]>): RBACBuilderbuild
Build and return RBAC instance.
build(): RBACUtilities
matchPermission
Check if permission matches pattern (including wildcards).
import { matchPermission } from '@fire-shield/core'
matchPermission('posts:write', 'posts:*') // true
matchPermission('posts:write', 'posts:read') // false
matchPermission('admin:users:delete', 'admin:*') // trueparsePermission
Parse permission string into parts.
import { parsePermission } from '@fire-shield/core'
const parts = parsePermission('posts:write')
// { resource: 'posts', action: 'write' }
const nested = parsePermission('admin:users:delete')
// { resource: 'admin:users', action: 'delete' }Error Handling
RBACError
Base error class for RBAC errors.
class RBACError extends Error {
constructor(message: string, public code: string) {
super(message)
this.name = 'RBACError'
}
}Common Errors
// Permission denied
throw new RBACError('Insufficient permissions', 'PERMISSION_DENIED')
// Role not found
throw new RBACError('Role does not exist', 'ROLE_NOT_FOUND')
// Invalid permission format
throw new RBACError('Invalid permission format', 'INVALID_PERMISSION')Performance
Fire Shield v2.2.0 includes several performance optimizations for large-scale applications.
Bit-Level Permissions
Enable bit-level permission checking for better performance:
const rbac = new RBAC({ useBitSystem: true }) // Default: true
// Permissions are stored as bits
// Much faster for large permission sets
rbac.createRole('admin', ['posts:*'])
const user = { id: '1', roles: ['admin'] }
rbac.hasPermission(user, 'posts:write') // Optimized bit checkPermission Caching (v2.2.0)
v2.2.0 introduces explicit permission caching with TTL and size limits:
const rbac = new RBAC({
enableCache: true,
cacheOptions: {
ttl: 60000, // Cache for 1 minute
maxSize: 10000, // Max 10k entries
cleanupInterval: 30000 // Cleanup every 30 seconds
}
})
// First call - computes and caches
rbac.hasPermission(user, 'posts:write')
// Subsequent calls - served from cache (very fast)
rbac.hasPermission(user, 'posts:write') // < 1ms
// Monitor cache performance
const stats = rbac.getCacheStats()
console.log(`Hit rate: ${stats.hitRate * 100}%`)Lazy Role Evaluation (v2.2.0)
v2.2.0 supports lazy role evaluation for faster startup:
const rbac = new RBAC({
lazyRoles: true,
config: largeConfig // Config with 1000+ roles
})
// Only loads roles when first accessed
const stats = rbac.getLazyRoleStats()
console.log(`Loaded: ${stats.evaluated}/${stats.total} roles`)
// Force load all roles when needed
rbac.evaluateAllRoles()Memory Optimization (v2.2.0)
v2.2.0 includes memory optimization through string interning:
const rbac = new RBAC({
optimizeMemory: true,
config: largeConfig
})
// Monitor memory savings
const stats = rbac.getMemoryStats()
console.log(`Memory saved: ${stats.estimatedMemorySaved} bytes`)
console.log(`String pool: ${stats.stringPoolSize} unique strings`)
// Cleanup unused resources
const result = rbac.compactMemory()
console.log(`Cleaned up ${result.stringsRemoved} strings`)Performance Best Practices
For optimal performance in production:
const rbac = new RBAC({
useBitSystem: true, // Fast bit-based checks
enableCache: true, // Cache permission checks
cacheOptions: {
ttl: 300000, // 5 minute cache
maxSize: 50000 // Large cache for many users
},
lazyRoles: true, // Load roles on demand
optimizeMemory: true, // Reduce memory footprint
enableWildcards: true // Support flexible permissions
})
// Clear cache when roles change
rbac.createRole('newRole', ['posts:*'])
rbac.invalidatePermissionCache('posts:write')
// Monitor performance
setInterval(() => {
const cacheStats = rbac.getCacheStats()
const memoryStats = rbac.getMemoryStats()
console.log('Cache hit rate:', cacheStats.hitRate)
console.log('Memory saved:', memoryStats.estimatedMemorySaved)
}, 60000)Next Steps
- Learn about Permissions
- Understand Deny Permissions (v2.2.0)
- Explore Framework Integrations
- Use the CLI Tool for config validation (v2.2.0)
- Integrate with AI Agents via MCP (v2.2.0)
- Check out Examples
