Skip to content

Best Practices

Secure and effective reaction development.

Security

Input Validation

Always validate and sanitize input data:

javascript
function process(data) {
    if (!data || typeof data !== 'object') {
        Error("Invalid data received");
        return;
    }

    if (data.process) {
        let cmd = data.process.cmd || "unknown";
        cmd = cmd.replace(/[\x00-\x1f\x7f-\x9f]/g, '');
        cmd = cmd.length > 500 ? cmd.substring(0, 500) + "..." : cmd;
        Info("Command: " + cmd);
    }

    if (data.file && data.file.file) {
        let path = data.file.file;
        if (!path.startsWith('/') || path.includes('../')) {
            Error("Invalid file path: " + path);
            return;
        }
    }
}

Principle of Least Privilege

Use minimum required privileges:

javascript
function process(data) {
    if (data.metadata && data.metadata.importance === "critical") {
        KillCurrent();
        Info("Critical threat terminated");
    } else {
        Warn("Suspicious activity logged");
        DataSet("suspicious_" + new Date().getTime(), 
                JSON.stringify({process: data.process.cmd}));
    }
}

Safe File Operations

Implement secure file handling:

javascript
function process(data) {
    let forensicDir = CreateTempDir("incident-*");
    if (forensicDir === "") {
        Error("Failed to create temp directory");
        return;
    }

    if (!forensicDir.startsWith("/tmp/")) {
        Error("Unexpected directory location");
        return;
    }

    let evidence = {
        timestamp: new Date().toISOString(),
        event_id: uuid,
        process_name: data.process ? data.process.exe : "unknown"
    };

    WriteFile(forensicDir + "/evidence.json", JSON.stringify(evidence));
}

Network Security

Apply whitelisting for network operations:

javascript
function process(data) {
    let remoteIps = [];
    if (data.background?.flows?.protocols) {
        for (let protocol of data.background.flows.protocols) {
            if (protocol.pairs) {
                for (let pair of protocol.pairs) {
                    if (pair.nodes?.remote?.address) {
                        remoteIps.push(pair.nodes.remote.address);
                    }
                }
            }
        }
    }

    let whitelist = ["127.0.0.1", /^10\./, /^192\.168\./];
    let safeToBlock = [];

    for (let ip of remoteIps) {
        let shouldBlock = true;
        for (let pattern of whitelist) {
            if (pattern instanceof RegExp ? pattern.test(ip) : ip === pattern) {
                shouldBlock = false;
                break;
            }
        }
        if (shouldBlock) safeToBlock.push(ip);
    }

    if (safeToBlock.length > 0) {
        NetBlockIp();
    }
}

Performance

Efficient Processing

Optimize data processing:

javascript
function process(data) {
    let processCmd = data.process ? data.process.cmd : "";
    let fileName = data.file ? data.file.basename : "";

    if (!processCmd && !fileName) {
        return;
    }

    let suspiciousPatterns = ["wget", "curl", "nc"];
    let isSuspicious = suspiciousPatterns.some(p => processCmd.includes(p));

    if (isSuspicious) {
        let count = parseInt(DataGet("suspicious_count") || "0") + 1;
        DataSet("suspicious_count", String(count));

        if (count > 10) {
            Warn("High frequency activity - escalating");
            NetBlockIp();
        }
    }
}

Memory Management

Manage memory efficiently:

javascript
function process(data) {
    let summary = {
        timestamp: new Date().toISOString(),
        process: data.process ? data.process.exe : "unknown",
        event_type: kind
    };

    let dateKey = new Date().toDateString();
    let countKey = "events_" + dateKey;
    let eventCount = parseInt(DataGet(countKey) || "0") + 1;
    DataSet(countKey, String(eventCount));

    // Clean old data periodically
    if (eventCount % 100 === 0) {
        let cutoff = new Date();
        cutoff.setDate(cutoff.getDate() - 7);
        let keys = JSON.parse(DataKeys());

        for (let key of keys) {
            if (key.startsWith("events_")) {
                let keyDate = new Date(key.replace("events_", ""));
                if (keyDate < cutoff) {
                    DataDelete(key);
                }
            }
        }
    }
}

Concurrent Execution

Design for parallel execution:

javascript
function process(data) {
    let reactionId = name + "_" + uuid.slice(-8);
    let lockKey = "processing_" + reactionId;

    if (DataHasKey(lockKey)) {
        return;
    }

    DataSet(lockKey, new Date().toISOString());

    try {
        let globalCount = parseInt(DataGet("global_count") || "0") + 1;
        DataSet("global_count", String(globalCount));
    } finally {
        DataDelete(lockKey);
    }
}

Testing

Comprehensive Testing

Test thoroughly before deployment:

javascript
function process(data) {
    let testMode = DataGet("test_mode") === "true";

    if (testMode) {
        Info("=== TEST MODE ===");
        testHelperFunctions();
        testDataProcessing(data);
        return;
    }

    processEvent(data);
}

function testHelperFunctions() {
    Info("Testing logging");
    DataSet("test_key", "test_value");
    let retrieved = DataGet("test_key");
    Info("Data store: " + (retrieved === "test_value" ? "PASS" : "FAIL"));
    DataDelete("test_key");

    let tmpDir = CreateTempDir("test-*");
    if (tmpDir !== "") {
        WriteFile(tmpDir + "/test.txt", "content");
        let content = ReadFile(tmpDir + "/test.txt");
        Info("File I/O: " + (content === "content" ? "PASS" : "FAIL"));
    }
}

function testDataProcessing(data) {
    Info("Testing data validation");
    Info("Data type: " + typeof data);
    Info("Data keys: " + Object.keys(data).join(", "));
}

Monitoring

Track Metrics

Monitor reaction health:

javascript
function process(data) {
    let startTime = new Date().getTime();

    try {
        performReactionLogic(data);

        let successCount = parseInt(DataGet("success_count") || "0") + 1;
        DataSet("success_count", String(successCount));
    } catch (error) {
        let failureCount = parseInt(DataGet("failure_count") || "0") + 1;
        DataSet("failure_count", String(failureCount));
        Error("Failed: " + error.toString());
    } finally {
        let executionTime = new Date().getTime() - startTime;
        let avgTime = parseFloat(DataGet("avg_time") || "0");
        let newAvg = (avgTime * 0.9) + (executionTime * 0.1);
        DataSet("avg_time", String(newAvg));

        if (executionTime > 5000) {
            Warn("Slow execution: " + executionTime + "ms");
        }
    }
}

Documentation

Document all reactions:

javascript
/**
 * Advanced Incident Response
 *
 * Purpose: Comprehensive incident response with containment,
 *          evidence collection, and alerting
 *
 * Triggers: Critical security events
 *
 * Dependencies:
 *   - netpolicy feature
 *   - Write access to /var/log/security/
 *
 * Performance:
 *   - Target: < 2 seconds
 *   - Memory: < 50MB temp storage
 *
 * Version: 2.0
 * Author: Security Team
 * Last Updated: 2025-07-23
 */
function process(data) {
    implementIncidentResponse(data);
}

Compliance

Audit Trails

Maintain audit records:

javascript
function process(data) {
    let auditRecord = {
        timestamp: new Date().toISOString(),
        reaction_name: name,
        event_uuid: uuid,
        actions_taken: [],
        data_accessed: []
    };

    if (data.process) auditRecord.data_accessed.push("process_data");
    if (data.file) auditRecord.data_accessed.push("file_data");

    if (shouldTerminateProcess(data)) {
        let result = KillCurrent();
        auditRecord.actions_taken.push({
            action: "process_termination",
            result: result === 0 ? "success" : "failed"
        });
    }

    WriteFile("/var/log/jibril/audit.log", JSON.stringify(auditRecord) + "\n");
    DataSet("audit_" + uuid, JSON.stringify(auditRecord));
}

Deployment

Version Control

Maintain proper versioning:

yaml
- kind: production_reaction
  name: managed_security_response
  enabled: true
  version: 2.1.0
  description: |
    Production security response

    Change Log:
    v2.1.0 - Enhanced error handling
    v2.0.0 - Graduated response system
    v1.0.0 - Initial implementation

  reactions:
    - format: js
      code: |
        function process(data) {
          const VERSION = "2.1.0";
          Info("Reaction v" + VERSION);
          // Implementation
        }

Deployment Strategy

  1. Test Environment - Deploy with enabled: false
  2. Limited Scope - Start with specific patterns
  3. Monitoring - Watch logs carefully
  4. Gradual Expansion - Slowly expand scope
  5. Production - Deploy fully tested only