// runtime-feature-policy-enforcer.ts
// A cross-platform runtime Feature Policy (Permissions Policy) enforcer.
// Validates capability usage against declared intents at runtime.
//
// Platforms supported:
// - Browsers: Web APIs (geolocation, camera, microphone, notifications, etc.)
// - Mobile/Desktop: PWAs, Electron, Capacitor/Ionic, Tauri via WebView or injected JS.
//
// Usage:
// 1. Define intents.json (or fetch from server/manifest).
// 2. Initialize Enforcer with manifest.
// 3. Use proxied APIs instead of native ones.
//
// Enforcement:
// - Strict mode: Throws on undeclared usage.
// - Log mode: Logs violations but allows (for dev).
// - Integrates with Permissions Policy headers/meta for browser enforcement.
//
// Extensibility: Add custom capabilities via `registerCapability()`.
interface CapabilityManifest {
capabilities: string[];
policy?: {
strict?: boolean; // Throw on violation
logViolations?: boolean;
reportTo?: string; // Reporting endpoint (e.g., '/violation-report')
};
}
interface CapabilityHandler {
check?: () => Promise<boolean>; // Pre-check (e.g., permissions.query)
invoke: (...args: any[]) => Promise<any>;
allowed: (manifest: CapabilityManifest) => boolean;
}
type CapabilityRegistry = Record<string, CapabilityHandler>;
class RuntimeFeaturePolicyEnforcer {
private manifest: CapabilityManifest;
private registry: CapabilityRegistry = {};
private strict: boolean;
private logViolations: boolean;
private reportTo: string | null;
constructor(manifest: CapabilityManifest | Promise<CapabilityManifest>) {
this.initializeManifest(manifest);
this.registerCoreCapabilities();
}
private async initializeManifest(manifest: CapabilityManifest | Promise<CapabilityManifest>) {
this.manifest = await manifest;
this.strict = this.manifest.policy?.strict ?? false;
this.logViolations = this.manifest.policy?.logViolations ?? true;
this.reportTo = this.manifest.policy?.reportTo ?? null;
}
// Register a custom capability
registerCapability(name: string, handler: CapabilityHandler): void {
this.registry[name] = handler;
}
// Core validation
private async validateCapability(capability: string): Promise<boolean> {
const allowed = this.manifest.capabilities.includes(capability);
if (!allowed) {
const violation = { capability, timestamp: Date.now(), origin: location.origin };
if (this.logViolations) {
console.error('[FeaturePolicyEnforcer] Violation:', violation);
}
if (this.reportTo) {
navigator.sendBeacon(this.reportTo, JSON.stringify(violation));
}
if (this.strict) {
throw new Error(`Capability '${capability}' not declared in intents manifest.`);
}
return false;
}
return true;
}
// Proxied invoke
async invoke(capability: string, ...args: any[]): Promise<any> {
if (!this.registry[capability]) {
throw new Error(`Unknown capability: ${capability}`);
}
const allowed = await this.validateCapability(capability);
if (!allowed && this.strict) return null;
const handler = this.registry[capability];
if (handler.check) {
const hasPermission = await handler.check();
if (!hasPermission) {
throw new Error(`Permission denied for ${capability}`);
}
}
return handler.invoke(...args);
}
// Batch check
async checkCapabilities(capabilities: string[]): Promise<Record<string, boolean>> {
const results: Record<string, boolean> = {};
for (const cap of capabilities) {
results[cap] = await this.validateCapability(cap);
}
return results;
}
private registerCoreCapabilities(): void {
// Geolocation
this.registerCapability('geolocation', {
check: () => navigator.permissions?.query({ name: 'geolocation' }).then(p => p.state === 'granted'),
invoke: (...args) => new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(
pos => resolve(pos),
err => reject(err),
...args as any
);
}),
allowed: (m) => m.capabilities.includes('geolocation')
});
// Camera/Microphone (MediaDevices)
this.registerCapability('camera', {
check: () => navigator.permissions?.query({ name: 'camera' }).then(p => p.state === 'granted'),
invoke: (constraints?: MediaStreamConstraints) => navigator.mediaDevices.getUserMedia({ video: true, ...constraints }),
allowed: (m) => m.capabilities.includes('camera')
});
this.registerCapability('microphone', {
check: () => navigator.permissions?.query({ name: 'microphone' }).then(p => p.state === 'granted'),
invoke: (constraints?: MediaStreamConstraints) => navigator.mediaDevices.getUserMedia({ audio: true, ...constraints }),
allowed: (m) => m.capabilities.includes('microphone')
});
// Notifications
this.registerCapability('notifications', {
check: () => Notification.requestPermission().then(() => Notification.permission === 'granted'),
invoke: (title: string, options?: NotificationOptions) => new Notification(title, options),
allowed: (m) => m.capabilities.includes('notifications')
});
// Clipboard (read/write)
this.registerCapability('clipboard-read', {
check: () => navigator.permissions?.query({ name: 'clipboard-read' }).then(p => p.state === 'granted'),
invoke: () => navigator.clipboard.read(),
allowed: (m) => m.capabilities.includes('clipboard-read')
});
this.registerCapability('clipboard-write', {
check: () => navigator.permissions?.query({ name: 'clipboard-write' }).then(p => p.state === 'granted'),
invoke: (...args: any[]) => navigator.clipboard.write(...args),
allowed: (m) => m.capabilities.includes('clipboard-write')
});
// Storage (localStorage, IndexedDB) - quota check
this.registerCapability('storage', {
invoke: () => {
// Placeholder: Actual quota check via navigator.storage.estimate()
return navigator.storage?.estimate();
},
allowed: (m) => m.capabilities.includes('storage')
});
// Custom: Add more like 'payment', 'midi', 'vr', etc.
}
}
// Example intents.json (load via fetch or bundler)
const intentsManifest: CapabilityManifest = {
capabilities: ['geolocation', 'camera'], // Declare only what's needed
policy: {
strict: true,
logViolations: true,
reportTo: '/api/policy-violations'
}
};
// Initialization (e.g., in app bootstrap)
async function bootstrapEnforcer() {
const enforcer = new RuntimeFeaturePolicyEnforcer(intentsManifest);
// Usage examples
try {
const position = await enforcer.invoke('geolocation');
console.log('Position:', position);
const stream = await enforcer.invoke('camera', { video: { facingMode: 'user' } });
// Attach stream to video element...
// Violation: This will throw/log if not declared
// await enforcer.invoke('microphone');
} catch (err) {
console.error(err);
}
// Pre-check
const checks = await enforcer.checkCapabilities(['geolocation', 'notifications']);
console.log('Capability checks:', checks);
}
// Cross-platform integration notes:
// 1. Browsers/PWAs: Use directly. Combine with <meta http-equiv="Permissions-Policy"> for declarative enforcement.
// e.g., <meta http-equiv="Permissions-Policy" content="geolocation=(self), camera=()">
// 2. Electron: Inject this script via webPreferences.preload. Override native APIs if needed.
// 3. Capacitor/Ionic (Mobile): Register as plugin or use Capacitor's Permissions API wrapper.
// Map native permissions to this enforcer.
// 4. Tauri (Desktop): Expose via WebView JS bridge; enforce in Rust backend for native caps.
// 5. Service Worker: Proxy fetch/XMLHttpRequest for network policies.
// 6. Production: Minify, tree-shake unused capabilities. Fetch manifest dynamically from CDN.
// Service Worker extension (for network/COEP/COOP enforcement)
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(reg => {
// In sw.js: Enforce fetch policies based on manifest.
});
}
// sw.js snippet:
self.addEventListener('fetch', event => {
// Validate if request uses declared capabilities (e.g., block cross-origin if not allowed)
// Integrate with enforcer via postMessage.
});
bootstrapEnforcer();
Key Features
- Declarative Manifest: JSON-based intents for easy auditing/deployment.
- Runtime Proxying: Wraps Web APIs; throws/logs on violations.
- Permission Awareness: Queries browser permissions before access.
- Reporting: Beacon to endpoint for violation telemetry.
- Extensible: Register custom handlers (e.g., Web Payments API, WebXR).
- Cross-Platform:
| Platform | Integration |
|---|
| Browsers | Native Web APIs + Permissions Policy headers. |
| PWAs/Mobile Web | Works out-of-box. |
| Electron | Preload script. |
| Capacitor | Bridge to native permissions. |
| Tauri | JS bridge + Rust enforcer. |
- Security: Strict mode prevents undeclared usage. Complements browser policies.
- Performance: Async, non-blocking checks.
Deploy by bundling with Vite/Webpack. Test with undeclared capabilities to verify enforcement!