Skip to content

Code Protection

Saros Industries edited this page Jun 28, 2025 · 1 revision

πŸ›‘οΈ Code Protection System

The Code Protection System is a critical safety feature that prevents AI from modifying sensitive code sections, ensuring your business logic, security implementations, and critical infrastructure remain untouched.

🎯 Why Code Protection?

AI assistants are powerful but can sometimes:

  • 🚫 Modify critical security code
  • 🚫 Change validated business logic
  • 🚫 Alter tested algorithms
  • 🚫 Break working configurations

The protection system creates immutable zones in your codebase.

πŸ”’ Protection Levels

Ψ₁: PROTECTED (πŸ”’)

Never modify under any circumstances

// !cp PROTECTED - JWT Secret Configuration
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';
const REFRESH_SECRET = process.env.REFRESH_SECRET || 'refresh-secret';
// !cp END-P

Use for:

  • Security credentials
  • Encryption keys
  • Critical algorithms
  • Regulatory compliance code

Ξ¨β‚‚: GUARDED (πŸ›‘οΈ)

Ask permission before modifying

// !cg GUARDED - User Authentication Logic
async function authenticateUser(email, password) {
    const user = await User.findByEmail(email);
    if (!user || !await bcrypt.compare(password, user.passwordHash)) {
        throw new AuthenticationError('Invalid credentials');
    }
    return user;
}
// !cg END-G

Use for:

  • Core business logic
  • Validated algorithms
  • Integration points
  • Database schemas

Ψ₃: INFO (ℹ️)

Context information for understanding

// !ci INFO - Rate Limiting Configuration
// This implements a sliding window rate limiter
// Current limit: 100 requests per 15 minutes
// Adjust RATE_LIMIT_WINDOW to change time window
// !ci END-I

Use for:

  • Configuration explanations
  • Algorithm descriptions
  • Integration notes
  • Performance considerations

Ξ¨β‚„: DEBUG (🐞)

Temporary debugging code

// !cd DEBUG - Performance Monitoring
console.time('auth-process');
const result = await authenticate(user);
console.timeEnd('auth-process');
console.log('Auth result:', result);
// !cd END-D

Use for:

  • Temporary logging
  • Performance measurements
  • Development helpers
  • Testing utilities

Ξ¨β‚…: TEST (πŸ§ͺ)

Test-specific code

// !ct TEST - Mock Authentication Service
class MockAuthService {
    async authenticate(email, password) {
        if (email === 'test@example.com' && password === 'test123') {
            return { id: 1, email, role: 'user' };
        }
        throw new Error('Invalid credentials');
    }
}
// !ct END-T

Use for:

  • Test fixtures
  • Mock implementations
  • Test utilities
  • Development data

Ψ₆: CRITICAL (⚠️)

Business-critical logic requiring extreme care

// !cc CRITICAL - Payment Processing
async function processPayment(order, paymentMethod) {
    // Critical business logic - handles real money
    const validation = await validatePayment(order, paymentMethod);
    if (!validation.isValid) {
        throw new PaymentError(validation.errors);
    }
    
    const transaction = await paymentGateway.charge({
        amount: order.total,
        currency: order.currency,
        method: paymentMethod,
        metadata: { orderId: order.id }
    });
    
    await order.updatePaymentStatus(transaction);
    return transaction;
}
// !cc END-C

Use for:

  • Financial transactions
  • User data handling
  • Compliance requirements
  • Mission-critical operations

🏷️ Protection Markers

Start Markers

Protection begins with a comment containing the protection command:

// !cp PROTECTED - Description
/* !cg GUARDED - Description */
# !ci INFO - Description (Python)
<!-- !cc CRITICAL - Description --> (HTML)

End Markers

Protection ends with corresponding end marker:

// !cp END-P
/* !cg END-G */
# !ci END-I
<!-- !cc END-C -->

Marker Format

// !{command} {LEVEL} - {description}
{protected code}
// !{command} END-{initial}

🎨 Language-Specific Examples

JavaScript/TypeScript

// !cp PROTECTED - API Keys
const API_KEY = process.env.API_KEY;
const SECRET_KEY = process.env.SECRET_KEY;
// !cp END-P

Python

# !cc CRITICAL - Database Connection
def connect_to_database():
    """Establishes connection to production database"""
    conn = psycopg2.connect(
        host=os.environ['DB_HOST'],
        database=os.environ['DB_NAME'],
        user=os.environ['DB_USER'],
        password=os.environ['DB_PASS']
    )
    return conn
# !cc END-C

Java

// !cg GUARDED - Singleton Instance
public class DatabaseManager {
    private static DatabaseManager instance;
    
    private DatabaseManager() {
        // Private constructor
    }
    
    public static synchronized DatabaseManager getInstance() {
        if (instance == null) {
            instance = new DatabaseManager();
        }
        return instance;
    }
}
// !cg END-G

HTML/XML

<!-- !cp PROTECTED - Security Headers -->
<meta http-equiv="Content-Security-Policy" 
      content="default-src 'self'; script-src 'self' 'unsafe-inline';">
<meta http-equiv="X-Frame-Options" content="DENY">
<meta http-equiv="X-Content-Type-Options" content="nosniff">
<!-- !cp END-P -->

CSS

/* !ci INFO - Critical Layout Dimensions */
/* These values are precisely calculated for the design system */
/* Changing them will break the responsive grid */
.container {
    max-width: 1140px;
    margin: 0 auto;
    padding: 0 15px;
}
/* !ci END-I */

πŸ”„ Mode-Specific Behavior

Research Mode (Ω₁)

  • βœ… Identifies protected sections
  • βœ… Documents protection purpose
  • βœ… Notes protection coverage
  • ❌ Cannot modify

Innovate Mode (Ξ©β‚‚)

  • βœ… Respects boundaries
  • βœ… Suggests alternatives
  • βœ… Works around protection
  • ❌ Cannot override

Plan Mode (Ω₃)

  • βœ… Plans protection strategy
  • βœ… Identifies what needs protection
  • βœ… Requests permission for GUARDED
  • ❌ Cannot change existing

Execute Mode (Ξ©β‚„)

  • βœ… Adds new protection
  • βœ… Enforces all levels
  • βœ… Works within boundaries
  • ⚠️ Can modify with permission

Review Mode (Ξ©β‚…)

  • βœ… Verifies protection coverage
  • βœ… Identifies missing protection
  • βœ… Reports violations
  • ❌ Cannot modify

πŸ“‹ Protection Strategies

1. Protect Early

Add protection as you write code, not after:

// Write and protect simultaneously
function createUser(userData) {
    // !cp PROTECTED - User Creation Logic
    const user = new User(userData);
    user.id = generateUUID();
    user.createdAt = new Date();
    // !cp END-P
    
    return user;
}

2. Layer Protection

Use multiple levels for complex systems:

// !cg GUARDED - Payment Module
class PaymentProcessor {
    // !cp PROTECTED - Payment Gateway Credentials
    constructor() {
        this.apiKey = process.env.PAYMENT_API_KEY;
        this.secretKey = process.env.PAYMENT_SECRET_KEY;
    }
    // !cp END-P
    
    // !cc CRITICAL - Process Payment
    async processPayment(amount, currency, cardToken) {
        // Critical payment logic
    }
    // !cc END-C
}
// !cg END-G

3. Document Reasoning

Always explain why code is protected:

// !cp PROTECTED - HIPAA Compliance Required
// This encryption method is mandated by HIPAA regulations
// Changing it would violate compliance requirements
function encryptPatientData(data) {
    return crypto.AES.encrypt(data, HIPAA_COMPLIANT_KEY);
}
// !cp END-P

4. Group Related Protection

Protect logical units together:

// !cc CRITICAL - Authentication System
class AuthenticationService {
    validateCredentials() { /* ... */ }
    generateTokens() { /* ... */ }
    refreshSession() { /* ... */ }
    revokeAccess() { /* ... */ }
}
// !cc END-C

πŸ› οΈ Protection Commands

Quick Protection Commands

Command Description Protection Level
!cp Add PROTECTED marker Highest
!cg Add GUARDED marker High
!ci Add INFO marker Information
!cd Add DEBUG marker Temporary
!ct Add TEST marker Test only
!cc Add CRITICAL marker Business critical

Usage Examples

"!cp the database connection string"
"!cg this authentication function"
"!cc the payment processing logic"

πŸ“Š Protection Registry

The framework maintains a registry of all protected code in protection.md:

## πŸ›‘οΈ Protected Regions

### πŸ”’ PROTECTED (Ψ₁)
- `src/config/keys.js:10-15` - API keys
- `src/crypto/encrypt.js:25-40` - Encryption algorithm

### πŸ›‘οΈ GUARDED (Ξ¨β‚‚)
- `src/auth/login.js:50-75` - Login logic
- `src/models/user.js:*` - User model

### ⚠️ CRITICAL (Ψ₆)
- `src/payments/process.js:100-200` - Payment processing
- `src/compliance/gdpr.js:*` - GDPR compliance

⚠️ Protection Violations

What Happens on Violation

  1. Detection
⚠️ PROTECTION VIOLATION DETECTED
Attempted to modify PROTECTED code at src/config/keys.js:12
  1. Prevention
❌ Operation blocked
βœ… Creating backup of current state
πŸ”„ Reverting to safe mode
  1. Logging
## ⚠️ Permission Violations
- 2024-01-15 10:30: Attempted modification of protected JWT secret
- Mode: EXECUTE
- Action: Blocked, reverted to PLAN mode
- File: src/auth/config.js:15

Recovery Process

  1. Backup created automatically
  2. Mode switched to PLAN
  3. Violation logged
  4. User notified
  5. Guidance provided

πŸ’‘ Best Practices

1. Protection Granularity

  • Protect smallest necessary unit
  • Don't over-protect
  • Allow flexibility where safe

2. Clear Descriptions

// ❌ Bad: Vague description
// !cp PROTECTED - Don't change

// βœ… Good: Clear reasoning  
// !cp PROTECTED - PCI Compliance - Credit card encryption algorithm

3. Regular Reviews

  • Audit protection quarterly
  • Remove obsolete protection
  • Update descriptions
  • Verify coverage

4. Team Communication

  • Document protection standards
  • Share protection guidelines
  • Review in code reviews
  • Train new developers

πŸ” Protection Patterns

Configuration Protection

// !cp PROTECTED - Production Configuration
const config = {
    database: {
        host: process.env.DB_HOST,
        port: process.env.DB_PORT,
        name: process.env.DB_NAME
    },
    redis: {
        url: process.env.REDIS_URL
    },
    api: {
        key: process.env.API_KEY,
        secret: process.env.API_SECRET
    }
};
// !cp END-P

Algorithm Protection

// !cc CRITICAL - Proprietary Ranking Algorithm
function calculateRanking(items) {
    // Proprietary algorithm - core business value
    const weights = { quality: 0.4, relevance: 0.3, recency: 0.3 };
    return items.map(item => ({
        ...item,
        score: (
            item.quality * weights.quality +
            item.relevance * weights.relevance +
            item.recency * weights.recency
        )
    })).sort((a, b) => b.score - a.score);
}
// !cc END-C

Integration Protection

// !cg GUARDED - Third-party API Integration
class PaymentGateway {
    // Carefully tested integration - changes risk breaking payments
    async chargeCard(amount, token) {
        const response = await fetch(GATEWAY_URL, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${this.apiKey}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                amount,
                token,
                currency: 'USD'
            })
        });
        return response.json();
    }
}
// !cg END-G

πŸš€ Advanced Protection

Nested Protection

// !cg GUARDED - Authentication Module
class Authenticator {
    // !cp PROTECTED - Encryption Keys
    constructor() {
        this.encryptionKey = process.env.ENCRYPTION_KEY;
        this.signingKey = process.env.SIGNING_KEY;
    }
    // !cp END-P
    
    // Module methods...
}
// !cg END-G

Cross-File Protection

Reference protection across files:

// In auth.js
// !cp PROTECTED - Shared Auth Logic
export const AUTH_CONSTANTS = { /* ... */ };
// !cp END-P

// In user.js
import { AUTH_CONSTANTS } from './auth.js';
// AUTH_CONSTANTS is protected - see auth.js:10-15

Dynamic Protection

Conditional protection based on environment:

if (process.env.NODE_ENV === 'production') {
    // !cp PROTECTED - Production Only
    // This code must not be modified in production
    app.use(strictSecurityMiddleware);
    // !cp END-P
}

πŸ“š Related Topics


← Phase Management | Home | Context References β†’

πŸš€ Getting Started


🧠 Core Concepts


⚑ Features


πŸ“– Guides


πŸ“‹ Reference


πŸ”Œ Advanced

MCP Integration

BMAD Enterprise


πŸ”§ Troubleshooting

Quick Navigation

🚨 Emergency Procedures

πŸ“‹ Common Issues

Installation & Setup

  • Installation Issues
    • Node.js Version Compatibility
    • Package Installation Failures
    • Framework Dependencies Missing
    • Database Connection Issues
    • Port Conflicts
    • Environment Setup Issues
    • Build and Development Issues
    • Framework CLI Issues

Configuration & Runtime

  • Configuration & Runtime Issues
    • Framework Configuration Problems
    • Runtime Performance Issues
    • Module Loading and Plugin Issues
    • Database and Storage Issues
    • Memory Leaks and High Memory Usage
    • High CPU Usage

BMAD Module

  • BMAD Module Issues
    • BMAD Module Initialization Problems
    • Business Model Canvas Issues
    • Stakeholder Management Issues
    • Analytics and Reporting Issues
    • Performance Optimization

Database & API

  • Database & API Issues
    • Database Connection Problems
    • Database Migration Issues
    • API Performance and Reliability Issues
    • Data Consistency Issues
    • Transaction Problems

Performance & Memory

Security & Authentication

  • Security & Authentication Issues
    • Authentication Failures
    • Authorization Problems
    • JWT Token Issues
    • Session Management
    • CORS and Security Headers
    • SSL/TLS Configuration

Deployment & Production

  • Deployment & Production Issues
    • Production Deployment Failures
    • Environment Configuration
    • Load Balancing Issues
    • Monitoring and Logging
    • Backup and Recovery

Information to Gather

When reporting issues, please include:

  • Framework version (npm list @cursoriper/core)
  • Node.js version (node --version)
  • Operating system and version
  • Error messages and stack traces
  • Steps to reproduce the issue
  • Configuration files (sanitized)
  • Recent changes or deployments

Tech Docs & Suport


πŸ“ž Support & Community


πŸ“‹ Release Notes

Last Updated: June 28, 2025
Framework Version: CursorRIPER.sigma v1.0+

For the original verbose framework, see CursorRIPER

← Back to Home

Clone this wiki locally