Skip to content

Latest commit

 

History

History
431 lines (346 loc) · 13.5 KB

File metadata and controls

431 lines (346 loc) · 13.5 KB

RuntimeUI Framework Architecture

Overview

RuntimeUI is a framework for building AI-assisted applications where coding agents can modify UI at runtime while maintaining strict security boundaries around critical components, data flows, and APIs.

Core Problems Solved

1. Component Protection

  • Problem: AI might modify critical business logic (auth, payments, core features)
  • Solution: Multi-level protection system with @Locked, @Protected, @AIModifiable decorators

2. Data Flow Security

  • Problem: AI could access sensitive APIs or data stores
  • Solution: API Guard proxy layer + Data Store Guard with allowlist/denylist

3. Code Generation Limits

  • Problem: Unbounded AI generation could create bloated, dangerous code
  • Solution: Configurable constraints on tokens, lines, components, and patterns

4. Runtime Safety

  • Problem: Malicious or buggy AI code could break the application
  • Solution: Multi-stage validation + sandbox testing + rollback mechanism

Architecture Layers

┌─────────────────────────────────────────────────────────┐
│                    USER QUERY                           │
│              "Make the grid 4 columns"                  │
└────────────────────┬────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────┐
│                  AI CODE ENGINE                         │
│         (GPT-4, Claude, or custom model)                │
│            Generates component code                     │
└────────────────────┬────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────┐
│              RUNTIME ENGINE                             │
│  ┌──────────────────────────────────────────────────┐   │
│  │  1. Constraint Validation                        │   │
│  │     - Check token limits                         │   │
│  │     - Check forbidden patterns                   │   │
│  │     - Check component size                       │   │
│  └──────────────────────────────────────────────────┘   │
│  ┌──────────────────────────────────────────────────┐   │
│  │  2. Component Protection Check                   │   │
│  │     - Query ComponentRegistry                    │   │
│  │     - Verify allowed operations                  │   │
│  │     - Reject locked component modifications      │   │
│  └──────────────────────────────────────────────────┘   │
│  ┌──────────────────────────────────────────────────┐   │
│  │  3. Security Analysis                            │   │
│  │     - Static code analysis                       │   │
│  │     - Check for XSS, injection risks             │   │
│  │     - Validate dependencies                      │   │
│  └──────────────────────────────────────────────────┘   │
│  ┌──────────────────────────────────────────────────┐   │
│  │  4. Sandbox Testing                              │   │
│  │     - Parse and test in isolated environment     │   │
│  │     - Verify no runtime errors                   │   │
│  └──────────────────────────────────────────────────┘   │
└────────────────────┬────────────────────────────────────┘
                     │
          ┌──────────┴──────────┐
          │                     │
      SUCCESS                 FAIL
          │                     │
          ▼                     ▼
    ┌─────────┐          ┌──────────┐
    │ APPLY   │          │ REJECT   │
    │ + Save  │          │ + Report │
    │ Rollback│          │  Errors  │
    │ Token   │          └──────────┘
    └─────────┘
          │
          ▼
┌─────────────────────────────────────────────────────────┐
│             UPDATED UI RENDERED                         │
└─────────────────────────────────────────────────────────┘

Key Components

1. Component Registry

Purpose: Central registry for all component metadata and protection rules

ComponentRegistry.getInstance()
  .register({
    id: 'PaymentForm_123',
    name: 'PaymentForm',
    protectionLevel: 'locked',
    allowedOperations: []
  });

Responsibilities:

  • Track all components and their protection levels
  • Provide lookup by component name or ID
  • Enable quick checks: isLocked(), isProtected(), isModifiable()

2. Runtime Engine

Purpose: Main orchestrator that processes AI modifications

Flow:

  1. Receives AI-generated code
  2. Validates against constraints
  3. Checks component protection rules
  4. Runs security analysis
  5. Tests in sandbox
  6. Applies or rejects modification
  7. Saves rollback point

API:

const engine = new RuntimeEngine({
  maxTokens: 4000,
  maxComponents: 10,
  maxLinesPerComponent: 200
});

const result = await engine.processModification({
  userQuery: "Make grid responsive",
  generatedCode: aiCode
});

if (result.success) {
  // Code applied, can rollback with result.rollbackToken
} else {
  // Show result.validation.errors to user
}

3. Constraint Manager

Purpose: Define and enforce code generation limits

Default Constraints:

  • Max 4000 tokens per generation
  • Max 10 components modified
  • Max 200 lines per component
  • Forbidden patterns: eval(), Function(), direct fetch(), etc.
  • Allowed libraries: React, React-DOM

Customization:

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

4. API Guard

Purpose: Secure proxy for all network requests

Features:

  • Register protected endpoints
  • Create secure fetch with policies
  • Enforce read/write permissions
  • Log all access attempts

Usage:

// Register protected endpoint
APIGuard.registerEndpoint({
  path: '/api/admin',
  method: 'POST',
  protected: true
});

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

// AI-generated code uses this instead of raw fetch
const data = await secureFetch('/api/products');

5. Data Store Guard

Purpose: Protect sensitive data in local stores

Features:

  • Mark keys as protected
  • Create proxied store objects
  • Enforce read/write policies

Usage:

// Protect sensitive keys
DataStoreGuard.protect('authToken');
DataStoreGuard.protect('creditCard');

// Create secure proxy
const secureStore = DataStoreGuard.createSecureStore(store, {
  canReadData: true,
  canWriteData: false
});

// AI code can read public data
console.log(secureStore.username); // ✓ Works

// But not protected data
console.log(secureStore.authToken); // ✗ Throws error

6. Code Validator

Purpose: Multi-stage validation of AI-generated code

Validation Stages:

  1. Constraint Check: Token limits, size limits, forbidden patterns
  2. Component Protection: Check if modifying locked/protected components
  3. Security Analysis: Static analysis for XSS, injection, unsafe patterns
  4. Sandbox Test: Parse and test execution in isolated environment

Output:

{
  valid: false,
  errors: [
    "Code contains forbidden pattern: /eval\\(/",
    "Cannot modify locked component: PaymentProcessor"
  ],
  warnings: [
    "Usage of dangerouslySetInnerHTML detected"
  ],
  metadata: {
    tokensUsed: 1250,
    componentsModified: 3
  }
}

Protection Levels

Level 1: Locked (@Locked)

  • Use Case: Critical business logic, authentication, payments
  • AI Permissions: NONE - Cannot read or modify
  • Example: Payment processors, authentication providers

Level 2: Protected (@Protected)

  • Use Case: Important components that need limited customization
  • AI Permissions: Restricted operations (style updates, prop changes)
  • Example: Navigation bars, headers, footers

Level 3: AI-Modifiable (@AIModifiable)

  • Use Case: UI components that should adapt to user preferences
  • AI Permissions: Full control within constraints
  • Example: Dashboards, product grids, content layouts

Data Access Control

Read-Only Access

@AIModifiable({
  dataAccess: {
    canReadData: true,
    canWriteData: false,
    allowedEndpoints: ['/api/products']
  }
})

Endpoint Allowlist/Denylist

{
  allowedEndpoints: ['/api/public/*', '/api/user-preferences'],
  forbiddenEndpoints: ['/api/admin', '/api/payment', '/api/auth']
}

Size and Scope Control

Token Limits

maxTokens: 4000  // ~1000 words of code

Component Limits

maxComponents: 10  // Max components modified per request
maxLinesPerComponent: 200  // Max lines per component

Operation Limits

allowedOperations: [
  'read-only',        // Can only read component
  'update-props',     // Can update props
  'update-style',     // Can update styles
  'update-children',  // Can modify children
  'full-control'      // Complete rewrite allowed
]

Rollback Mechanism

Every successful modification creates a rollback token:

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

if (result.success) {
  const rollbackToken = result.rollbackToken;

  // Later, if needed:
  engine.rollback(rollbackToken);
}

Keeps last 10 modifications in memory for quick rollback.


Best Practices

1. Start Restrictive

Begin with tight constraints and relax as needed:

maxTokens: 2000,
maxComponents: 5,
maxLinesPerComponent: 100

2. Explicit Allowlists

Prefer allowlists over denylists for better security:

allowedEndpoints: ['/api/safe1', '/api/safe2']
// Better than forbiddenEndpoints

3. Layer Protection

Use multiple protection layers:

  • Component decorators
  • API guards
  • Data store protection
  • Constraint validation

4. Monitor and Log

const log = APIGuard.getRequestLog();
const history = engine.getHistory();

5. Progressive Enhancement

Mark existing components gradually:

// Week 1: Mark critical components as @Locked
// Week 2: Mark semi-critical as @Protected
// Week 3: Mark customizable as @AIModifiable

Integration Example

// 1. Setup
const engine = new RuntimeEngine(customConstraints);

// 2. User query
const userQuery = "Make the dashboard cards bigger";

// 3. AI generates code
const aiCode = await callAIAPI(userQuery);

// 4. Validate and apply
const result = await engine.processModification({
  userQuery,
  generatedCode: aiCode
});

// 5. Handle result
if (result.success) {
  hotReloadComponent(result.appliedCode);
  showSuccess("UI updated!");
} else {
  showErrors(result.validation.errors);
}

Future Enhancements

  1. Fine-grained permissions: Per-user constraint profiles
  2. ML-based threat detection: Learn dangerous patterns over time
  3. Visual diff preview: Show changes before applying
  4. A/B testing integration: Test AI modifications with subset of users
  5. Undo/redo stack: Full history with time-travel debugging

Summary

RuntimeUI provides a secure, controlled environment for AI coding agents to modify UI at runtime while protecting:

✓ Critical business logic (locked components) ✓ Sensitive data and APIs (guards and proxies) ✓ Application stability (validation and constraints) ✓ User safety (rollback mechanism)

The framework is reusable, extensible, and production-ready for any AI-assisted UI application.