Code Protection - johnpeterman72/CursorRIPER.sigma GitHub Wiki

๐Ÿ›ก๏ธ 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 === '[email protected]' && 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 โ†’