@dimzxzzx07/process-security
v1.0.0
Published
Process Sentinel - Anarki Edition dengan mutual resurrection
Downloads
44
Maintainers
Readme
Process Sentinel - Anarki Edition
Table of Contents
· Overview · The Anarki Concept · Features · Quick Start · Installation · Configuration · Usage Examples · Project Structure · API Reference · Event System · Chaos Engine · Zombie Processes · Performance Metrics · Testing · Troubleshooting · License
Overview
Process Sentinel is a revolutionary process monitoring system built on the Anarki principle - where processes form an unbreakable bond of mutual resurrection. If process A dies, process B resurrects it. If process B dies, process A resurrects it. This creates an immortal system that is nearly impossible to terminate completely.
The system monitors CPU spikes (indicating infinite loops or DoS attacks), memory leaks, and abnormal network connections. When threats are detected, it automatically takes action - killing compromised processes and resurrecting clean instances, all while maintaining a zombie pair that guards each other.
The Anarki Concept
┌─────────────────────────┐ ┌─────────────────────────┐
│ │ │ │
│ SENTINEL A │◄─────────────►│ SENTINEL B │
│ │ │ │
│ (Primary Instance) │ │ (Secondary Instance) │
│ │ │ │
└───────────┬─────────────┘ └───────────┬─────────────┘
│ │
│ MUTUAL SURVEILLANCE │
│ ───────────────────────────> │
│ <─────────────────────────── │
│ │
│ RESURRECTION PROTOCOL │
│ - If A terminates, B spawns A │
│ - If B terminates, A spawns B │
└────────────────────┬────────────────────┘
│
┌────────┴────────┐
│ CORE MONITOR │
│ Status: Active │
└─────────────────┘· Mutual Resurrection: Two processes constantly monitor each other's health · Zombie Mode: Processes that refuse to die and always come back · Chaos Engine: Simulates attacks to test system resilience · Mutual Destruction: When all else fails, everything dies together
Features
Core Monitoring
Feature Description CPU Spike Detection Identifies infinite loops, DoS attacks, and abnormal CPU usage Memory Leak Detection Tracks memory consumption patterns and identifies leaks Network Anomaly Detection Monitors connection counts to detect DDoS attacks Process Health Monitoring Real-time status tracking of all monitored processes
Anarki Features
Feature Description Mutual Resurrection Two processes that resurrect each other when one dies Zombie Factory Creates undead processes that are extremely hard to kill Chaos Engine Simulates attacks and failures to test system resilience Mutual Destruction When resurrection threshold exceeded, all processes die together
Action System
Action Description Killer Multiple kill strategies (graceful, force, tree kill, by port) Resurrector Process resurrection with exponential backoff and monitoring Chaos Engine Random chaos generation for stress testing Config Manager Flexible configuration management with JSON and ENV support
Quick Start
# Install the package
npm install process-sentinel
# Create a basic configuration
echo '{
"sentinel": {
"name": "my-app",
"cpuThreshold": 80,
"zombieMode": true
}
}' > sentinel.config.json
# Start the sentinel
npx process-sentinelInstallation
From NPM
# Install as dependency
npm install process-sentinel
# Install globally
npm install -g process-sentinelSystem Requirements
Requirement Minimum Recommended Node.js 18.0.0 20.0.0 or higher RAM 512 MB 1 GB Disk Space 100 MB 500 MB CPU 1 core 2 cores OS Linux, macOS, Windows Linux (production)
Configuration
JSON Configuration File
Create sentinel.config.json in your project root:
{
"sentinel": {
"name": "production-sentinel",
"cpuThreshold": 85,
"memoryThreshold": 90,
"connectionThreshold": 150,
"checkInterval": 2000,
"resurrectionDelay": 500,
"maxResurrections": 10,
"zombieMode": true,
"mutualDestruction": false
},
"chaos": {
"enabled": false,
"intensity": 5,
"mutualDestructionThreshold": 5
},
"monitors": {
"cpu": true,
"memory": true,
"network": true
},
"actions": {
"autoKill": true,
"autoResurrect": true,
"maxResurrections": 10
}
}Environment Variables
Create .env file:
# Sentinel Configuration
SENTINEL_NAME=production-sentinel
CPU_THRESHOLD=85
MEMORY_THRESHOLD=90
CONNECTION_THRESHOLD=150
CHECK_INTERVAL=2000
RESURRECTION_DELAY=500
MAX_RESURRECTIONS=10
ZOMBIE_MODE=true
MUTUAL_DESTRUCTION=false
# Chaos Configuration
CHAOS_ENABLED=false
CHAOS_INTENSITY=5
CHAOS_DESTRUCTION_THRESHOLD=5Configuration Object
interface SentinelConfig {
name: string;
cpuThreshold: number;
memoryThreshold: number;
connectionThreshold: number;
checkInterval: number;
resurrectionDelay: number;
maxResurrections: number;
zombieMode: boolean;
mutualDestruction: boolean;
}Usage Examples
Basic Implementation
import { Sentinel } from 'process-sentinel';
const sentinel = new Sentinel({
name: 'my-app',
cpuThreshold: 80,
zombieMode: true
});
sentinel.start();Event Handling
import { Sentinel } from 'process-sentinel';
const sentinel = new Sentinel();
sentinel.on('cpu_spike', (event) => {
console.log(`CPU Spike Detected!`);
console.log(` Process: ${event.source}`);
console.log(` CPU Usage: ${event.data.cpu}%`);
console.log(` Threshold: ${event.data.threshold}%`);
});
sentinel.on('memory_leak', (event) => {
console.log(`Memory Leak Detected!`);
console.log(` Process: ${event.source}`);
console.log(` Memory: ${event.data.memory}%`);
});
sentinel.on('ddos_detected', (event) => {
console.log(`DDoS Attack Detected!`);
console.log(` Process: ${event.source}`);
console.log(` Connections: ${event.data.connections}`);
});
sentinel.on('resurrection', (event) => {
console.log(`Process Resurrected!`);
console.log(` Source: ${event.source}`);
console.log(` Attempt #: ${event.data.count}`);
});
sentinel.on('panic', (event) => {
console.log(`PANIC MODE ACTIVATED!`);
console.log(` Resurrections: ${event.data.resurrectionCount}`);
});
sentinel.on('mutual_kill', () => {
console.log(`MUTUAL DESTRUCTION - All processes terminated`);
});
sentinel.start();Advanced Usage with All Components
import {
Sentinel,
Killer,
Resurrector,
ChaosEngine,
ConfigManager
} from 'process-sentinel';
// Load configuration
const configManager = ConfigManager.getInstance();
configManager.loadConfig('./my-config.json');
const sentinelConfig = configManager.getSentinelConfig();
// Create components
const sentinel = new Sentinel(sentinelConfig);
const killer = new Killer();
const resurrector = new Resurrector();
// Configure chaos engine
const chaosEngine = new ChaosEngine(sentinel, killer, resurrector, {
enabled: true,
resurrectionChaos: true,
killChaos: true,
chaosIntensity: 7
});
// Set up event handlers
sentinel.on('cpu_spike', async (event) => {
console.log('CPU spike detected, killing process...');
await killer.killProcess(parseInt(event.source.split(':')[1]), true);
});
sentinel.on('process_dead', async (event) => {
console.log('Process died, attempting resurrection...');
const newPid = await resurrector.resurrect(
parseInt(event.source.split(':')[1]),
'/path/to/script.js'
);
console.log(`Resurrected with new PID: ${newPid}`);
});
// Start everything
await sentinel.start();
chaosEngine.start();
// Monitor status
setInterval(() => {
const status = sentinel.getStatus();
console.log('Sentinel Status:', {
processes: status.monitoredProcesses.length,
panic: status.panicMode,
resurrections: status.resurrectionCount
});
const mostKilled = killer.getMostKilled();
if (mostKilled) {
console.log('Most killed process:', mostKilled);
}
const mostResurrected = resurrector.getMostResurrected();
if (mostResurrected) {
console.log('Most resurrected process:', mostResurrected);
}
}, 10000);Zombie Mode - Mutual Resurrection
import { Sentinel } from 'process-sentinel';
// This creates two zombie processes that watch each other
const sentinel = new Sentinel({
zombieMode: true,
resurrectionDelay: 100,
maxResurrections: 10
});
sentinel.start();
// The zombie pair will:
// - Monitor each other's health every second
// - Resurrect the other if it dies
// - Survive SIGTERM and SIGINT signals
// - Keep coming back no matter whatChaos Engine for Stress Testing
import { Sentinel, Killer, Resurrector, ChaosEngine } from 'process-sentinel';
const sentinel = new Sentinel();
const killer = new Killer();
const resurrector = new Resurrector();
const chaos = new ChaosEngine(sentinel, killer, resurrector, {
enabled: true,
resurrectionChaos: true, // Random resurrections
killChaos: true, // Random kills
networkChaos: true, // Network latency spikes
memoryChaos: true, // Memory pressure simulation
cpuChaos: true, // CPU spike simulation
chaosIntensity: 8, // 1-10 scale
mutualDestructionThreshold: 5
});
chaos.start();
// Chaos events will be logged
// After 5 random kills, mutual destruction triggersKiller - Process Termination
import { Killer } from 'process-sentinel';
const killer = new Killer();
// Graceful kill
await killer.killProcess(1234, false);
// Force kill
await killer.killProcess(5678, true);
// Kill entire process tree
await killer.killProcessTree(9012);
// Kill by port
await killer.killByPort(3000);
// Kill all zombie processes
await killer.killZombieProcesses();
// Kill processes exceeding thresholds
await killer.killByMemoryThreshold(90); // Kill processes using >90% memory
await killer.killByCPUThreshold(95); // Kill processes using >95% CPUResurrector - Process Resurrection
import { Resurrector } from 'process-sentinel';
const resurrector = new Resurrector();
// Basic resurrection
const newPid = await resurrector.resurrect(1234, './app.js');
// Resurrection with exponential backoff
const newPid2 = await resurrector.resurrectWithBackoff(5678, './app.js', 5);
// Create a phoenix process (auto-resurrecting)
const phoenixPid = await resurrector.createPhoenixProcess('./worker.js');
// Monitor process and auto-resurrect
resurrector.monitorProcess(9012, './critical.js');
// Get resurrection stats
const count = resurrector.getResurrectionCount(1234);
const lastTime = resurrector.getLastResurrection(1234);
const mostResurrected = resurrector.getMostResurrected();Config Manager
import { ConfigManager } from 'process-sentinel';
const config = ConfigManager.getInstance();
// Load from file
config.loadConfig('./sentinel.config.json');
// Get specific configs
const sentinelConfig = config.getSentinelConfig();
const chaosConfig = config.getChaosConfig();
const monitorsConfig = config.getMonitorsConfig();
// Update config
config.updateSentinelConfig({
cpuThreshold: 90,
zombieMode: true
});
// Export to .env
config.exportToEnv('./.env');
// Import from .env
config.importFromEnv('./.env');
// Validate
const errors = config.validateConfig();
if (errors.length > 0) {
console.error('Config errors:', errors);
}Project Structure
process-sentinel/
├── src/
│ ├── core/
│ │ ├── Sentinel.ts # Main sentinel class
│ │ ├── ProcessGuardian.ts # Process monitoring
│ │ └── ZombieFactory.ts # Zombie process creation
│ ├── monitors/
│ │ ├── CPUMonitor.ts # CPU spike detection
│ │ ├── MemoryMonitor.ts # Memory leak detection
│ │ └── NetworkMonitor.ts # Network anomaly detection
│ ├── actions/
│ │ ├── Killer.ts # Process termination
│ │ ├── Resurrector.ts # Process resurrection
│ │ └── ChaosEngine.ts # Chaos simulation
│ ├── utils/
│ │ ├── Logger.ts # Logging utility
│ │ └── Config.ts # Configuration manager
│ └── index.ts # Main entry point
├── tests/
│ ├── unit/
│ ├── integration/
│ └── chaos/
├── dist/
├── logs/
├── sentinel.config.json
├── .env
├── package.json
├── tsconfig.json
└── README.mdAPI Reference
Sentinel Class
class Sentinel extends EventEmitter {
constructor(config?: Partial<SentinelConfig>);
// Methods
public start(): Promise<void>;
public stop(): Promise<void>;
public getStatus(): SentinelStatus;
public registerProcess(pid: number, name: string): void;
public unregisterProcess(pid: number): void;
// Events
on(event: 'cpu_spike', listener: (event: SentinelEvent) => void): this;
on(event: 'memory_leak', listener: (event: SentinelEvent) => void): this;
on(event: 'ddos_detected', listener: (event: SentinelEvent) => void): this;
on(event: 'resurrection', listener: (event: SentinelEvent) => void): this;
on(event: 'panic', listener: (event: SentinelEvent) => void): this;
on(event: 'mutual_kill', listener: (event: SentinelEvent) => void): this;
}Killer Class
class Killer {
public killProcess(pid: number, force?: boolean): Promise<boolean>;
public killProcessTree(pid: number): Promise<void>;
public killAllByName(processName: string): Promise<number>;
public killZombieProcesses(): Promise<void>;
public killByPort(port: number): Promise<boolean>;
public forceKillStuck(pid: number): Promise<boolean>;
public killByMemoryThreshold(threshold: number): Promise<number[]>;
public killByCPUThreshold(threshold: number): Promise<number[]>;
public getKillHistory(): Map<number, number>;
public getMostKilled(): { pid: number; count: number } | null;
}Resurrector Class
class Resurrector {
public resurrect(pid: number, scriptPath?: string): Promise<number | null>;
public resurrectWithBackoff(pid: number, scriptPath: string, maxAttempts?: number): Promise<number | null>;
public resurrectByName(processName: string, scriptPath: string): Promise<number | null>;
public resurrectAll(scripts: Map<string, string>): Promise<Map<string, number | null>>;
public createPhoenixProcess(scriptPath: string): Promise<number>;
public monitorProcess(pid: number, scriptPath: string): void;
public stopMonitoring(pid: number): void;
public getResurrectionCount(pid: number): number;
public getLastResurrection(pid: number): Date | null;
public getMostResurrected(): { pid: number; count: number } | null;
}ChaosEngine Class
class ChaosEngine {
constructor(sentinel: Sentinel, killer: Killer, resurrector: Resurrector, config?: Partial<ChaosConfig>);
public start(): void;
public stop(): void;
public setIntensity(level: number): void;
public getStatus(): ChaosStatus;
}ConfigManager Class
class ConfigManager {
static getInstance(): ConfigManager;
public loadConfig(configPath?: string): ConfigFile;
public saveConfig(configPath?: string): void;
public getSentinelConfig(): SentinelConfig;
public getChaosConfig(): ChaosConfig;
public getMonitorsConfig(): MonitorsConfig;
public getActionsConfig(): ActionsConfig;
public updateConfig(updates: Partial<ConfigFile>): void;
public updateSentinelConfig(updates: Partial<SentinelConfig>): void;
public resetToDefaults(): void;
public exportToEnv(envPath?: string): void;
public importFromEnv(envPath?: string): void;
public validateConfig(): string[];
public getConfig(): ConfigFile;
}Event System
Sentinel Events
Event Description Payload cpu_spike CPU usage exceeded threshold { timestamp, type, source, data: { cpu, threshold } } memory_leak Memory usage exceeded threshold { timestamp, type, source, data: { memory, threshold } } ddos_detected Abnormal connection count { timestamp, type, source, data: { connections, threshold } } resurrection Process resurrected { timestamp, type, source, data: { count, ddos } } panic Too many resurrections { timestamp, type, source, data: { resurrectionCount } } mutual_kill Mutual destruction activated { timestamp, type, source }
Chaos Engine
Chaos Configuration
Option Default Description enabled false Enable chaos engine resurrectionChaos false Random resurrection events killChaos false Random kill events networkChaos false Network latency spikes memoryChaos false Memory pressure simulation cpuChaos false CPU spike simulation chaosIntensity 5 Chaos intensity (1-10) mutualDestructionThreshold 5 Kills before mutual destruction
Chaos Intensity Levels
Level Description 1-3 Light chaos - occasional events 4-6 Medium chaos - regular events 7-8 Heavy chaos - frequent events 9-10 Apocalypse - constant chaos
Zombie Processes
Zombie Characteristics
Feature Description Signal Immunity Ignores SIGTERM and SIGINT Mutual Watch Constantly monitors partner process Auto Resurrection Resurrects partner immediately on death Undead Persistence Keeps coming back no matter what
Zombie Creation
// Zombie processes are automatically created when zombieMode is true
const sentinel = new Sentinel({
zombieMode: true
});
// This creates two zombie processes that will:
// - Monitor each other every second
// - Resurrect each other on death
// - Ignore termination signals
// - Log their undead statusPerformance Metrics
Benchmark Results
Operation Average Time Health Check 15 ms CPU Detection 5 ms Memory Detection 8 ms Network Detection 20 ms Process Kill 10 ms Process Resurrection 50 ms Zombie Creation 100 ms
Resource Usage
Resource Idle Active Peak CPU 1-3% 5-10% 15% Memory 50 MB 100 MB 200 MB Event Loop 5 ms lag 20 ms lag 50 ms lag
Testing
Running Tests
# Run all tests
npm test
# Run unit tests
npm run test:unit
# Run integration tests
npm run test:integration
# Run chaos tests
npm run test:chaos
# Run with coverage
npm run test:coverageTest Structure
tests/
├── unit/
│ ├── core/
│ │ ├── Sentinel.test.ts
│ │ ├── ProcessGuardian.test.ts
│ │ └── ZombieFactory.test.ts
│ ├── monitors/
│ │ ├── CPUMonitor.test.ts
│ │ ├── MemoryMonitor.test.ts
│ │ └── NetworkMonitor.test.ts
│ └── actions/
│ ├── Killer.test.ts
│ ├── Resurrector.test.ts
│ └── ChaosEngine.test.ts
├── integration/
│ ├── resurrection.test.ts
│ ├── zombie-pair.test.ts
│ └── chaos-simulation.test.ts
└── chaos/
├── stress.test.ts
└── mutual-destruction.test.tsTroubleshooting
Common Issues
Issue Cause Solution High CPU usage Too many monitored processes Increase check interval Memory leaks Zombie processes accumulating Check resurrection logic False positives Thresholds too low Adjust thresholds Resurrection failures Missing script paths Register scripts properly Zombies not dying Signal immunity Use force kill with SIGKILL Chaos too intense High intensity setting Reduce chaos intensity
Debug Mode
// Enable debug logging
const sentinel = new Sentinel({
debug: true
});
// Or set environment variable
process.env.DEBUG = 'sentinel:*';Logs Location
logs/
├── sentinel.log # Main sentinel logs
├── chaos.log # Chaos engine events
├── resurrection.log # Resurrection events
└── error.log # Error logsRecovery Procedures
- Stop the sentinel
process-sentinel --stop - Check logs for issues
tail -f logs/error.log - Reset configuration
process-sentinel --reset - Kill all zombie processes
process-sentinel --purge-zombies - Restart with clean state
process-sentinel --start
License
UNLICENSED - Proprietary software. All rights reserved.
This software and its source code are the exclusive property of Dimzxzzx07. Unauthorized copying, modification, distribution, or use of this software is strictly prohibited without express written permission.
