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
- Detection
โ ๏ธ PROTECTION VIOLATION DETECTED
Attempted to modify PROTECTED code at src/config/keys.js:12
- Prevention
โ Operation blocked
โ
Creating backup of current state
๐ Reverting to safe mode
- 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
- Backup created automatically
- Mode switched to PLAN
- Violation logged
- User notified
- 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
}