Skip to content

Latest commit

 

History

History
347 lines (258 loc) · 10.6 KB

File metadata and controls

347 lines (258 loc) · 10.6 KB

RuntimeUI Framework

A production-ready TypeScript/React framework for AI-assisted runtime UI modification with multi-layered security boundaries.

TypeScript React License


🎯 Problem

When building AI-powered applications where coding agents modify UI at runtime, you need to:

  1. Protect critical components (auth, payments, core logic) from AI changes
  2. Secure data flows and API access from AI-generated code
  3. Control AI code generation with configurable size/scope limits
  4. Ensure runtime safety with validation and rollback

RuntimeUI solves all of these with a reusable, extensible framework.


🚀 Quick Start

Installation

npm install
npm run build

Basic Usage

import { RuntimeEngine, Locked, AIModifiable } from 'runtime-ui-framework';

// 1. Protect your components
@Locked
class PaymentForm extends React.Component {
  // AI cannot touch this
}

@AIModifiable({ maxSize: 300 })
class Dashboard extends React.Component {
  // AI can modify this
}

// 2. Initialize runtime engine
const engine = new RuntimeEngine({
  maxTokens: 4000,
  maxComponents: 10,
  maxLinesPerComponent: 200
});

// 3. Process AI modifications
const result = await engine.processModification({
  userQuery: "Make the dashboard cards bigger",
  generatedCode: aiGeneratedCode
});

if (result.success) {
  // Code validated and applied!
} else {
  // Show validation errors
  console.log(result.validation.errors);
}

Read the 5-minute Quick Start Guide →


🏗️ Architecture

┌─────────────────────────────────────────────────────────┐
│                    USER QUERY                           │
│              "Make the grid 4 columns"                  │
└────────────────────┬────────────────────────────────────┘
                     ↓
┌─────────────────────────────────────────────────────────┐
│                  AI CODE ENGINE                         │
│         (GPT-4, Claude, or custom model)                │
└────────────────────┬────────────────────────────────────┘
                     ↓
┌─────────────────────────────────────────────────────────┐
│              RUNTIME ENGINE                             │
│  ┌──────────────────────────────────────────────────┐   │
│  │  Layer 1: Constraint Validation                  │   │
│  │  - Token limits, size limits, patterns           │   │
│  ├──────────────────────────────────────────────────┤   │
│  │  Layer 2: Component Protection                   │   │
│  │  - Check locked/protected components             │   │
│  ├──────────────────────────────────────────────────┤   │
│  │  Layer 3: Security Analysis                      │   │
│  │  - XSS, injection, unsafe patterns               │   │
│  ├──────────────────────────────────────────────────┤   │
│  │  Layer 4: Sandbox Testing                        │   │
│  │  - Parse and validate in isolation               │   │
│  └──────────────────────────────────────────────────┘   │
└────────────────────┬────────────────────────────────────┘
                     ↓
              APPLY or REJECT

Read the Full Architecture Guide →


✨ Key Features

🔒 Component Protection

Three-tier protection system with decorators:

@Locked                    // AI cannot touch at all
@Protected({              // AI can only update styles/props
  allowedOperations: ['update-style', 'update-props']
})
@AIModifiable({           // AI has full control
  maxSize: 300,
  dataAccess: { canReadData: true, canWriteData: false }
})

🛡️ API & Data Security

Proxy-based access control:

// Secure API access
const secureFetch = APIGuard.createSecureFetch({
  canReadData: true,
  canWriteData: false,
  allowedEndpoints: ['/api/products'],
  forbiddenEndpoints: ['/api/admin']
});

// Protected data stores
DataStoreGuard.protect('authToken');
const secureStore = DataStoreGuard.createSecureStore(store, policy);

📏 Code Generation Limits

Configurable constraints:

{
  maxTokens: 4000,              // Max tokens per generation
  maxComponents: 10,            // Max components modified
  maxLinesPerComponent: 200,    // Max lines per component
  allowedLibraries: ['react'],  // Import whitelist
  forbiddenPatterns: [/eval\(/, /fetch\(/]  // Pattern blocklist
}

✅ Multi-Stage Validation

Every AI modification goes through:

  1. Constraint validation (size, tokens, patterns)
  2. Protection check (locked components)
  3. Security analysis (XSS, injection)
  4. Sandbox testing (safe execution)
  5. Rollback support (undo mechanism)

📊 Monitoring & Logging

// View request logs
const log = APIGuard.getRequestLog();

// View modification history
const history = engine.getHistory();

// Rollback to previous state
engine.rollback(rollbackToken);

📦 What's Included

RuntimeUI/
├── src/
│   ├── core/               # Core framework
│   │   ├── types.ts
│   │   ├── decorators.ts   # @Locked, @Protected, @AIModifiable
│   │   ├── registry.ts     # Component registry
│   │   ├── constraints.ts  # Generation limits
│   │   ├── api-guard.ts    # API security
│   │   ├── validator.ts    # Code validation
│   │   └── runtime-engine.ts
│   ├── react/              # React integration
│   └── utils/              # Helper utilities
├── examples/               # Complete examples
├── README.md
├── ARCHITECTURE.md         # Detailed architecture
├── QUICKSTART.md          # 5-minute guide
└── SOLUTION_SUMMARY.md    # Solution overview

📚 Documentation


🎓 Examples

Example 1: Component Protection

See examples/basic-usage.tsx

Example 2: Runtime Modification

See examples/runtime-modification.ts

Example 3: API Security

See examples/api-protection.tsx

Example 4: Complete Application

See examples/complete-app-example.tsx


🔐 Security Features

  • ✅ Multi-layered protection (4 validation stages)
  • ✅ Component-level access control
  • ✅ API endpoint allowlist/denylist
  • ✅ Forbidden pattern detection (eval, XSS, injection)
  • ✅ Token and size limits
  • ✅ Sandbox execution testing
  • ✅ Request logging and monitoring
  • ✅ Rollback mechanism

🎯 Use Cases

  1. AI-Powered Dashboards - Let users customize layouts via natural language
  2. Dynamic Forms - AI generates form fields based on user requirements
  3. Theme Customization - AI applies styling based on user preferences
  4. Content Layouts - AI arranges content based on viewport/device
  5. A/B Testing - AI generates UI variations for testing

🛠️ Advanced Usage

Custom Constraints

engine.updateConstraints({
  maxTokens: 8000,
  allowedLibraries: ['react', 'styled-components', 'lodash']
});

Validation Result Analysis

import { formatValidationResult, getCodeStats } from 'runtime-ui-framework';

const result = await engine.processModification({...});

console.log(formatValidationResult(result.validation));
console.log(getCodeStats(generatedCode));

Component Wrapper

import { withProtection } from 'runtime-ui-framework';

const SecureButton = withProtection(Button, 'Button', {
  canReadData: true,
  canWriteData: false
});

🤝 Integration

Works with any AI provider:

  • OpenAI (GPT-4, GPT-3.5)
  • Anthropic (Claude)
  • Google (Gemini)
  • Custom models

Simply pass the AI-generated code to engine.processModification().


📈 Benefits

Feature RuntimeUI Manual Implementation
Component Protection ✓ Built-in 3-tier ✗ Custom per-app
API Security ✓ Proxy + policies ~ Basic blocking
Size Limits ✓ Configurable ✗ Manual checks
Validation ✓ 4-stage pipeline ~ Basic
Rollback ✓ Automatic ✗ Manual
Monitoring ✓ Built-in ✗ Custom logging
Reusability ✓ Framework ✗ Copy-paste
Type Safety ✓ Full TypeScript ~ Partial

🚦 Getting Started

  1. Read QUICKSTART.md for a 5-minute tutorial
  2. Explore examples/ for real-world patterns
  3. Review ARCHITECTURE.md for deep dive
  4. Customize constraints for your use case
  5. Integrate with your AI provider
  6. Deploy with confidence

📝 License

MIT License - see LICENSE file for details


🙏 Contributing

Contributions welcome! Please read our contributing guidelines.


📧 Support

  • GitHub Issues for bug reports
  • Discussions for questions
  • Examples for common patterns

Built with ❤️ for safe AI-assisted development