The user wants a "runtime feature policy enforcer" that validates "capability usage" against "declared intents" across different platforms (browsers, mobile, desktop).
This sounds like a security and compliance mechanism. It needs to:
- Define Intents: A way to declare what features an application intends to use (e.g., "I need camera access," "I need local storage," "I need network access to specific domains").
- Runtime Monitoring: A mechanism to intercept actual calls to these capabilities during execution.
- Validation: Comparing the actual usage against the declared policy.
- Enforcement: Taking action if a violation occurs (block, log, alert, sanitize).
- Cross-Platform: Needs to work (conceptually or via code examples) on Web (JS), Mobile (conceptually native/bridge), and Desktop (Electron/Tauri context).
Key Components:
- Policy Definition (The Schema): JSON or YAML is best. It needs to define subjects (who), resources (what), and actions (how).
- The Enforcer Core: The logic engine. This is platform-agnostic logic or a central service.
- Platform Hooks (The Interceptors):
- Browser: Service Workers, Proxy objects, wrapping native APIs (navigator, window).
- Mobile/Desktop: Native module bridging (React Native, Flutter, Electron main process).
High-Level Architecture:
- Policy Manifest (
policy.json): The source of truth.
- Enforcer Library (Core): Parses the manifest and answers "Can I do X?".
- Platform Adapter:
- JS (Web/Node): Wraps global objects using
Proxy.
- Native (Concept): Middleware layers or method swizzling.
Detailed Design - Step-by-Step:
-
Step 1: The Policy Schema. Let's define a simple but extensible schema.
feature: The name (e.g., geolocation, fetch, fs).
allow: Boolean or specific params (e.g., specific domains for fetch).
limit: Rate limiting or quotas.
-
Step 2: The Core Engine (TypeScript/JavaScript is the most "universal" language for this context, running on Web, Node/Electron, and React Native).
- Class
PolicyEnforcer.
- Method
check(intent: string, context?: object).
-
Step 3: The Interceptors (The "Magic").
- Browser: We need to wrap
navigator.geolocation, fetch, localStorage.
- Desktop (Electron): We can intercept IPC calls.
Drafting the Solution:
I'll create a solution primarily in TypeScript because it compiles to JS (Web), works in Node (Desktop/Electron), and is similar to what you'd use in React Native/ Capacitor.
- Module 1:
PolicySchema - Defining the rules.
- Module 2:
Enforcer - The logic engine.
- Module 3:
RuntimeInterceptor - The actual monkey-patching/proxying of global APIs.
Refining the "Cross-Platform" aspect:
Since I can't write Swift/Kotlin and C++ in one go efficiently for a single snippet, I will focus on a JavaScript/TypeScript Runtime Agnostic approach. This covers:
- Browsers: Direct.
- Desktop: Electron / Tauri (JS layer).
- Mobile: React Native / Capacitor / Ionic.
Code Structure:
- Configuration: A JSON manifest.
- The Enforcer Class: Handles the logic.
- The Instrumentation Layer: Uses
Proxy to wrap global objects (window, navigator, document). This is the "Runtime" part.
Crucial "Gotcha" to handle: How do you stop code from accessing navigator.geolocation if you haven't loaded the enforcer yet?
- Real-world answer: This must be the very first script executed, or injected by a Service Worker / CSP. For this exercise, I will simulate the injection mechanism.
Adding specific features:
- Intent Verification: Did the code declare it wants Geolocation? If yes, allow.
- Contextual Validation: If accessing Network, is the domain allowed?
- Audit Logging: Report violations.
Let's write the code.
- Interface:
FeaturePolicy
- Core:
PolicyEnforcer
- Setup:
SecureRuntime.init(policy)
Example Scenario:
An app declares it needs fetch but only to api.example.com. If a 3rd party script tries to fetch('evil.com'), the enforcer blocks it and logs an alert.
Self-Correction during drafting:
Monkey-patching global objects (like window.fetch) is fragile.
- Better approach: Use JavaScript
Proxy objects. They are more robust for trapping access.
Structure of the Output:
- Conceptual Overview: How it works.
- The Policy Manifest: Example JSON.
- The Implementation (TypeScript):
- Core Logic.
- Browser Adapter (Proxy pattern).
- Native Bridge Adapter (Conceptual stub).
- Usage Example: Showing it block an action.
Let's refine the API.
Enforcer.check(action: string, target: any, args: any[])
Mobile/Desktop Nuance:
In React Native or Electron, you often go through a bridge.
- Desktop: Intercept IPC.
- Mobile: Wrap NativeModules.
I will include a generic "Bridge Interceptor" pattern.
Final Polish:
Ensure the code looks professional, uses modern JS features (Proxy, Reflect), and includes comments explaining why this adds security (principle of least privilege).
Let's compose.
This solution implements a Runtime Feature Policy Enforcer (RFPE).
This architecture ensures that even if a malicious script (or a compromised dependency) attempts to access sensitive capabilities (like the camera, filesystem, or location), the runtime blocks the action because it wasn't explicitly declared in the application's manifest.
Architecture Overview
- The Manifest (
policy.json): A declarative list of required permissions and intents.
- The Core Enforcer: A logic engine that compares runtime requests against the manifest.
- The Interceptor Layer: Platform-specific code that intercepts API calls (Browser globals, Native Bridges) before they execute.
1. The Policy Manifest
First, we define the intents. This file travels with your application.
// policy.json
{
"appId": "com.example.secure-app",
"version": "1.0.0",
"permissions": {
"network": {
"allow": true,
"domains": ["api.example.com", "cdn.trusted.com"]
},
"geolocation": {
"allow": true,
"intent": "User initiated navigation"
},
"media": {
"camera": false,
"microphone": true
},
"filesystem": {
"allow": true,
"scope": ["$DOWNLOADS", "$PICTURES"]
}
}
}
2. The Implementation (TypeScript)
This code is designed to run in a generic JavaScript environment (Browser, React Native, or Electron).
/**
* RUNTIME FEATURE POLICY ENFORCER
*
* Validates capability usage against declared intents.
*/
// --- Types ---
type PermissionConfig = {
allow: boolean;
[key: string]: any; // Specific constraints (e.g., domains, scope)
};
type PolicyManifest = {
appId: string;
permissions: Record<string, PermissionConfig>;
};
type EnforcementAction = 'ALLOW' | 'DENY' | 'AUDIT';
// --- Core Enforcer Class ---
class FeaturePolicyEnforcer {
private manifest: PolicyManifest;
private auditLog: string[] = [];
constructor(manifest: PolicyManifest) {
this.manifest = manifest;
console.log(`[Policy] Enforcer initialized for ${manifest.appId}`);
}
/**
* The Gatekeeper Method.
* Checks if a specific action is permitted by the manifest.
*/
public validateRequest(
capability: string,
context?: any
): EnforcementAction {
const permission = this.manifest.permissions[capability];
// 1. Capability Not Declared
if (!permission) {
this.audit(`DENY: Capability '${capability}' not declared in manifest.`);
return 'DENY';
}
// 2. Explicit Denial
if (!permission.allow) {
this.audit(`DENY: Capability '${capability}' is disabled by policy.`);
return 'DENY';
}
// 3. Contextual Validation (Advanced Rules)
if (capability === 'network' && context?.domain) {
if (!permission.domains.includes(context.domain)) {
this.audit(`DENY: Network request to blocked domain '${context.domain}'`);
return 'DENY';
}
}
// 4. Allow
this.audit(`ALLOW: ${capability}`);
return 'ALLOW';
}
private audit(message: string) {
const timestamp = new Date().toISOString();
this.auditLog.push(`[${timestamp}] ${message}`);
// In production, send this to a secure logging endpoint
console.log(`[Audit] ${message}`);
}
}
// --- Runtime Interceptor (The "Glue") ---
/**
* Applies the policy to the environment.
* Intercepts global API calls and routes them through the enforcer.
*/
export function initializePolicyEnforcer(manifest: PolicyManifest) {
const enforcer = new FeaturePolicyEnforcer(manifest);
// --- BROWSER & WEBVIEW INTERCEPTORS ---
// 1. Intercept Fetch (Network Policy)
const originalFetch = window.fetch;
window.fetch = (url: RequestInfo, init?: RequestInit): Promise<Response> => {
let domain = '*';
try {
domain = new URL(url.toString()).hostname;
} catch (e) { /* Relative URL or invalid */ }
const decision = enforcer.validateRequest('network', { domain });
if (decision === 'DENY') {
return Promise.reject(new Error(`Security Policy: Blocked request to ${domain}`));
}
return originalFetch(url, init);
};
// 2. Intercept Geolocation
if (navigator.geolocation) {
const originalGetCurrentPosition = navigator.geolocation.getCurrentPosition.bind(navigator.geolocation);
// Overwrite the method
navigator.geolocation.getCurrentPosition = (success, error, options) => {
const decision = enforcer.validateRequest('geolocation');
if (decision === 'DENY') {
if (error) error({ code: 1, message: 'Permission denied by runtime policy', PERMISSION_DENIED: 1 });
return;
}
originalGetCurrentPosition(success, error, options);
};
}
// --- DESKTOP / MOBILE BRIDGE INTERCEPTOR (Generic) ---
// This pattern works for Electron (IPC), React Native (NativeModules), or Capactor.
const genericBridge = (window as any).NativeBridge || (window as any).electronAPI;
if (genericBridge) {
const originalSend = genericBridge.send;
genericBridge.send = (action: string, payload: any) => {
// Example: blocking file system access
if (action.startsWith('fs.')) {
const decision = enforcer.validateRequest('filesystem', payload);
if (decision === 'DENY') {
throw new Error(`Security Policy: Blocked filesystem action ${action}`);
}
}
return originalSend(action, payload);
};
}
return enforcer;
}
3. Integration Example
Here is how you bootstrap this enforcer in your application entry point.
Browser / Electron / Hybrid Mobile (index.ts)
import { initializePolicyEnforcer } from './FeaturePolicyEnforcer';
import policyManifest from './policy.json';
// 1. Initialize the Enforcer FIRST before other scripts load
const enforcer = initializePolicyEnforcer(policyManifest);
// 2. Test Valid Request
// This succeeds because 'api.example.com' is in the manifest
fetch('https://api.example.com/v1/data')
.then(() => console.log('Request Allowed'))
.catch(e => console.error(e.message));
// 3. Test Invalid Request (Security Violation)
// This fails because 'evil.com' is NOT in the manifest
fetch('https://evil.com/steal-cookies')
.then(() => console.log('Request Allowed'))
.catch(e => console.error(e.message));
// Output: "Security Policy: Blocked request to evil.com"
// 4. Test Disabled Feature
// This fails because 'camera' is set to false in manifest
navigator.mediaDevices.getUserMedia({ video: true })
.catch(e => console.log("Camera blocked successfully"));
How this works across platforms
-
Browser:
- It relies on Monkey Patching (Proxy pattern) standard globals like
window.fetch, navigator.geolocation, and navigator.mediaDevices.
- This creates a "sandbox" around the running web application.
-
Desktop (Electron):
- In an Electron app, you typically expose an IPC (Inter-Process Communication) bridge to the renderer process (e.g.,
contextBridge.exposeInMainWorld).
- The interceptor wraps this bridge. Even if a compromised renderer process tries to read a file via
electronAPI.readSecureFile(), the enforcer checks the filesystem permission in the JSON manifest before allowing the IPC message to reach the main process.
-
Mobile (React Native / Capacitor):
- Mobile apps often communicate with native code via a "Bridge."
- By wrapping the generic
NativeBridge or utilizing a Proxy around global native modules, you enforce that only declared intents (like "Access Contacts") pass through to the native OS layer.
Security Considerations
- Timing: This script must be the first script executed in the application bundle. If an attacker can execute code before the enforcer is initialized, they can capture references to the original (unprotected) APIs.
- Tampering: In a pure client-side web app, an attacker can modify the
policy.json or the enforcement logic. For high security, this pattern is best combined with CSP (Content Security Policy) headers and Subresource Integrity (SRI), or run within a Web Worker where the global scope is more isolated.