We are to design a runtime feature policy enforcer that validates capability usage against declared intents across browsers, mobile, and desktop clients.
Steps:
-
Understand the problem: We need a system that checks at runtime whether the capabilities (features) being used by a client (browser, mobile app, desktop app) are allowed according to the declared intents (permissions) for that client.
-
Declared intents: These are the set of capabilities (like camera, microphone, geolocation, etc.) that the client has declared it needs. This could be in a manifest or configuration file.
-
Capability usage: At runtime, the client might try to use a capability (e.g., access the camera). We need to validate that this capability is within the declared intents.
-
Cross-platform: The enforcer should work for browsers (web), mobile (iOS, Android), and desktop (Windows, macOS, Linux). This means we might have to handle different ways of declaring intents and different APIs for checking capabilities.
-
Implementation: We can think of having a central policy that is loaded from a configuration (declared intents) and then at runtime, when a capability is requested, we check against that policy.
-
For web: We can use the Permissions API and Feature Policy (now known as Permissions Policy) to control and check features. However, note that Feature Policy is being replaced by Permissions Policy, but the idea is similar.
-
For mobile and desktop: We might have to rely on the app's manifest (e.g., AndroidManifest.xml for Android, Info.plist for iOS, or a similar configuration for desktop apps). But note that the problem says "runtime", so we might have to check at runtime if the app has the permission (and also if it's declared in the manifest). However, on mobile and desktop, the permission is usually granted by the user at runtime (or at install time) and the manifest declares the intent (required permissions). So we might have two things:
a. Check if the capability is declared in the manifest (intent).
b. Check if the capability is currently allowed (granted by the user).
-
The enforcer should be a module that can be integrated into the client application (web, mobile, desktop) and it will have:
- A way to load the declared intents (from a config or manifest).
- An API to check if a capability is allowed (both declared and granted).
-
We'll design an abstract interface and then provide implementations for each platform.
Let's define:
interface PolicyEnforcer {
// Check if a capability is allowed (both declared and granted if applicable)
bool isAllowed(capability: string): bool;
// Possibly, we might want to throw an exception or log when a capability is used without permission.
void enforce(capability: string): void; // throws if not allowed
}
-
For web:
- We can use the Permissions API to query the status of a permission (e.g., 'camera', 'microphone').
- We also need to check the declared intents. For web, the declared intents might come from a feature policy header or a meta tag, but also from thePermissions Policy. Alternatively, we can have a separate config file (like a JSON) that lists the intents.
However, note: the problem says "declared intents", which might be the set of capabilities the app says it needs. In web, this can be set via the Permissions-Policy header. But also, the app might have a manifest (web app manifest) that declares permissions? Not exactly. The web app manifest is for installation and doesn't declare permissions in the same way.
Alternatively, we can have a configuration file (e.g., intents.json) that lists the required capabilities. Then at runtime, we check:
- Is the capability in the declared intents (from
intents.json)?
- Is the permission granted? (via Permissions API)
But note: the Permissions Policy (Feature Policy) is about allowing the feature to be used by the page, and it's set by the server. So we might also check the Feature Policy (Permissions Policy) to see if the feature is allowed by the policy.
Actually, the Permissions Policy (formerly Feature Policy) allows a site to control which capabilities can be used by its iframes and by itself. So we have two layers:
a. The site's own policy (set by the server) which might allow or disallow a feature for the page.
b. The user's permission (via Permissions API) which might be granted, denied, or prompt.
We need to check both? The problem says "validates capability usage against declared intents". The declared intents might be the ones the app requires (and the server has set in the policy). But also, the app might have a list of capabilities it intends to use (from a config). We have to clarify.
Let's assume the "declared intents" are the set of capabilities that the client application (web, mobile, desktop) has declared it needs. For web, this could be the list of features that are allowed by the Permissions Policy header (or meta tag) and also the app's own config.
However, to simplify, let's assume we have a configuration (intents.json) that lists the required capabilities. Then, for web, we also check the Permissions Policy and the Permissions API.
But note: the Permissions Policy might be set by the server and might be more restrictive than the app's declared intents. So we should check:
- Is the capability in the declared intents (from our config)?
- If the browser supports Permissions Policy, check if the feature is allowed by the policy (by trying to use it and catching the error? or by checking the policy via JavaScript?).
Let's define:
Capability: a string identifier, e.g., "camera", "microphone", "geolocation", "notifications", etc.
DeclaredIntents: a set of capabilities that the app requires.
For each platform, we need to:
a. Load the declared intents (from a config file or manifest).
b. Check at runtime if a capability is allowed.
13. We can design the enforcer to be platform-agnostic by having an adapter pattern.
PlatformPolicyEnforcer (interface):
- isAllowed(capability: string): bool
Then we have:
WebPolicyEnforcer: uses a config (intents.json) and the Permissions API (and tries to check Permissions Policy by probing?).
MobilePolicyEnforcer: for Android and iOS, we can have separate implementations or a unified one that uses platform-specific code (via bridge in React Native, or native code).
DesktopPolicyEnforcer: similarly.
14. But note: the problem says "across browsers, mobile, and desktop clients". We might be building a library that works on all these platforms. So we can have:
if (isWeb) {
enforcer = new WebPolicyEnforcer();
} else if (isAndroid) {
enforcer = new AndroidPolicyEnforcer();
} else if (isIOS) {
enforcer = new IOSPolicyEnforcer();
} else if (isDesktop) {
enforcer = new DesktopPolicyEnforcer();
}
15. However, we might also have cross-platform frameworks (like React Native, Flutter, Electron). So we might need to adjust.
-
Given the complexity of each platform, we can only sketch the design and provide a sample implementation for web (since that's the most common and we can run in a browser).
-
Let's design the web enforcer:
We assume we have a config file (intents.json) that looks like:
{
"intents": ["camera", "microphone", "geolocation"]
}
Then, in the web enforcer:
class WebPolicyEnforcer {
constructor() {
this.declaredIntents = this.loadIntents();
}
loadIntents() {
// fetch intents.json and parse, or have it embedded.
// For simplicity, let's assume we have a global variable or we fetch it.
// We'll fetch it asynchronously, but then we need to wait for it. So we might need to initialize the enforcer after the config is loaded.
}
async isAllowed(capability) {
// Step 1: check if capability is in declaredIntents
if (!this.declaredIntents.includes(capability)) {
return false;
}
// Step 2: check the Permissions API for the status of the permission (if applicable)
// Note: not all capabilities are covered by Permissions API.
// We can have a mapping of capability to permission name (which might be the same or different).
// For example, capability "camera" -> permission name "camera".
// But for geolocation, the permission name is "geolocation".
// We can have a mapping object:
const permissionMap = {
camera: 'camera',
microphone: 'microphone',
geolocation: 'geolocation',
notifications: 'notifications',
// ... others
};
if (permissionMap[capability]) {
try {
const permissionStatus = await navigator.permissions.query({ name: permissionMap[capability] });
return permissionStatus.state === 'granted';
} catch (e) {
// If the permission query fails, we might assume it's not allowed? Or we might try to use the feature?
// But note: some features might not have a permission (like 'fullscreen'?) then we skip.
// Alternatively, we can return true if the capability is declared and we can't check permission?
// But that might be insecure.
// We can return false for now, or we can have a fallback.
console.error(`Error checking permission for ${capability}:`, e);
return false;
}
} else {
// For capabilities that don't have a permission in the Permissions API, we might check if the feature is available?
// But the declared intents already said we need it, so if it's not available (like in a browser that doesn't support it) then we might return false?
// However, the problem is about policy (declared intents and user permission) not about feature support.
// We can return true because it's declared and we don't have a way to check user permission?
// But then if the Permissions Policy blocks it, we won't know until we try.
// Given the ambiguity, we might return true and then when the feature is used, it might fail and then we catch that.
return true;
}
}
enforce(capability) {
if (!this.isAllowed(capability)) {
throw new Error(`Capability ${capability} is not allowed.`);
}
}
Architecture Overview
// Core Types & Interfaces
interface Intent {
id: string;
capability: string;
platform: 'browser' | 'ios' | 'android' | 'windows' | 'macos' | 'linux';
minVersion?: string;
required: boolean;
fallback?: string;
}
interface CapabilityRequest {
capability: string;
context: 'ui' | 'background' | 'service';
urgency: 'normal' | 'critical';
metadata?: Record<string, any>;
}
interface ValidationResult {
allowed: boolean;
reason: 'declared' | 'not-declared' | 'platform-mismatch' | 'version-too-low' | 'user-denied' | 'policy-blocked';
suggestedAlternative?: string;
requiredIntents?: string[];
}
1. Central Policy Registry
class PolicyRegistry {
private static instance: PolicyRegistry;
private declaredIntents: Map<string, Intent> = new Map();
private platformCapabilities: Map<string, Set<string>> = new Map();
private constructor() {
this.initializePlatformCapabilities();
}
static getInstance(): PolicyRegistry {
if (!PolicyRegistry.instance) {
PolicyRegistry.instance = new PolicyRegistry();
}
return PolicyRegistry.instance;
}
private initializePlatformCapabilities() {
// Browser capabilities
this.platformCapabilities.set('browser', new Set([
'camera', 'microphone', 'geolocation', 'notifications',
'clipboard-read', 'clipboard-write', 'payment', 'usb',
'hid', 'serial', 'window-management', 'display-capture'
]));
// iOS capabilities
this.platformCapabilities.set('ios', new Set([
'camera', 'microphone', 'location', 'contacts',
'photos', 'calendar', 'reminders', 'health',
'homekit', 'siri', 'apple-pay'
]));
// Android capabilities
this.platformCapabilities.set('android', new Set([
'camera', 'microphone', 'location', 'contacts',
'sms', 'phone', 'storage', 'sensors'
]));
// Desktop capabilities
['windows', 'macos', 'linux'].forEach(platform => {
this.platformCapabilities.set(platform, new Set([
'camera', 'microphone', 'geolocation', 'filesystem',
'serial', 'usb', 'bluetooth', 'notifications'
]));
});
}
registerIntent(intent: Intent): void {
const key = `${intent.platform}:${intent.capability}`;
this.declaredIntents.set(key, intent);
}
getDeclaredIntents(platform: string, capability?: string): Intent[] {
const results: Intent[] = [];
for (const [key, intent] of this.declaredIntents) {
if (intent.platform === platform &&
(!capability || intent.capability === capability)) {
results.push(intent);
}
}
return results;
}
isCapabilitySupported(platform: string, capability: string): boolean {
const caps = this.platformCapabilities.get(platform);
return caps ? caps.has(capability) : false;
}
}
2. Runtime Enforcer Core
class FeaturePolicyEnforcer {
private registry: PolicyRegistry;
private userPermissions: Map<string, 'granted' | 'denied' | 'prompt'> = new Map();
private platform: string;
private appVersion: string;
constructor(platform: string, appVersion: string) {
this.registry = PolicyRegistry.getInstance();
this.platform = platform;
this.appVersion = appVersion;
}
async validateRequest(request: CapabilityRequest): Promise<ValidationResult> {
const { capability, context, urgency } = request;
// 1. Check platform support
if (!this.registry.isCapabilitySupported(this.platform, capability)) {
return {
allowed: false,
reason: 'platform-mismatch',
suggestedAlternative: this.findPlatformAlternative(capability)
};
}
// 2. Check declared intents
const requiredIntents = this.registry.getDeclaredIntents(this.platform, capability);
if (requiredIntents.length === 0) {
return {
allowed: false,
reason: 'not-declared',
requiredIntents: this.suggestRequiredIntents(capability)
};
}
// 3. Check version requirements
for (const intent of requiredIntents) {
if (intent.minVersion && this.compareVersions(this.appVersion, intent.minVersion) < 0) {
return {
allowed: false,
reason: 'version-too-low',
requiredIntents: requiredIntents.map(i => i.id)
};
}
}
// 4. Check user permissions (if applicable)
if (this.requiresUserPermission(capability)) {
const userPerm = await this.checkUserPermission(capability);
if (userPerm === 'denied') {
return {
allowed: false,
reason: 'user-denied',
requiredIntents: requiredIntents.map(i => i.id)
};
}
}
// 5. Check temporary policy restrictions
const policyBlock = await this.checkPolicyRestrictions(capability, context);
if (policyBlock) {
return {
allowed: false,
reason: 'policy-blocked',
suggestedAlternative: policyBlock.alternative
};
}
return {
allowed: true,
reason: 'declared',
requiredIntents: requiredIntents.map(i => i.id)
};
}
async enforce(request: CapabilityRequest): Promise<{ granted: boolean; result?: ValidationResult }> {
const result = await this.validateRequest(request);
if (!result.allowed) {
this.logViolation(request, result);
return { granted: false, result };
}
// Track usage for analytics
this.trackUsage(request);
return { granted: true, result };
}
// Platform-specific implementations would extend this
private async checkUserPermission(capability: string): Promise<'granted' | 'denied' | 'prompt'> {
// Web implementation using Permissions API
if (this.platform === 'browser' && 'permissions' in navigator) {
try {
const permissionName = this.mapCapabilityToPermission(capability);
if (permissionName) {
const status = await navigator.permissions.query({ name: permissionName as PermissionName });
return status.state as any;
}
} catch (e) {
console.warn(`Permission check failed for ${capability}:`, e);
}
}
// Mobile/Desktop implementations would use native bridges
return this.userPermissions.get(capability) || 'prompt';
}
private requiresUserPermission(capability: string): boolean {
const userPermissionCapabilities = new Set([
'camera', 'microphone', 'geolocation', 'notifications',
'contacts', 'photos', 'location', 'health'
]);
return userPermissionCapabilities.has(capability);
}
private mapCapabilityToPermission(capability: string): string | null {
const mapping: Record<string, string> = {
'camera': 'camera',
'microphone': 'microphone',
'geolocation': 'geolocation',
'notifications': 'notifications',
'clipboard-read': 'clipboard-read',
'clipboard-write': 'clipboard-write'
};
return mapping[capability] || null;
}
private async checkPolicyRestrictions(
capability: string,
context: string
): Promise<{ alternative?: string } | null> {
// Check for temporary restrictions (e.g., data saver mode, battery saver)
if (this.platform === 'browser') {
// Check for reduced data mode
if (navigator.connection?.saveData &&
['video', 'audio', 'camera'].includes(capability)) {
return { alternative: 'use-thumbnail' };
}
// Check for battery status
if (navigator.getBattery &&
capability === 'video' &&
(await navigator.getBattery()).level < 0.2) {
return { alternative: 'use-audio-only' };
}
}
return null;
}
private findPlatformAlternative(capability: string): string | null {
const alternatives: Record<string, string> = {
'camera': 'use-image-upload',
'microphone': 'use-text-input',
'geolocation': 'use-manual-entry',
'usb': 'use-bluetooth',
'hid': 'use-keyboard-emulation'
};
return alternatives[capability] || null;
}
private suggestRequiredIntents(capability: string): string[] {
const intentTemplates: Record<string, { id: string; platform: string }[]> = {
'camera': [
{ id: 'cam-001', platform: 'all' },
{ id: 'cam-002', platform: 'browser' }
],
'geolocation': [
{ id: 'loc-001', platform: 'all' },
{ id: 'loc-002', platform: 'mobile' }
]
};
const templates = intentTemplates[capability] || [];
return templates
.filter(t => t.platform === 'all' || t.platform === this.platform)
.map(t => t.id);
}
private compareVersions(v1: string, v2: string): number {
const parts1 = v1.split('.').map(Number);
const parts2 = v2.split('.').map(Number);
for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
const p1 = parts1[i] || 0;
const p2 = parts2[i] || 0;
if (p1 !== p2) return p1 - p2;
}
return 0;
}
private logViolation(request: CapabilityRequest, result: ValidationResult): void {
console.warn(`[Policy Violation] Capability: ${request.capability}, Reason: ${result.reason}`, {
platform: this.platform,
context: request.context,
metadata: request.metadata
});
}
private trackUsage(request: CapabilityRequest): void {
// Send analytics event
if (typeof window !== 'undefined' && (window as any).analytics) {
(window as any).analytics.track('capability_used', {
capability: request.capability,
platform: this.platform,
context: request.context
});
}
}
// Public API for intent management
updateUserPermission(capability: string, status: 'granted' | 'denied'): void {
this.userPermissions.set(capability, status);
}
getRequiredIntents(): Intent[] {
const allIntents: Intent[] = [];
for (const [key, intent] of this.registry['declaredIntents']) {
if (intent.platform === this.platform) {
allIntents.push(intent);
}
}
return allIntents;
}
}
3. Platform-Specific Implementations
Web Implementation (Browser)
class WebPolicyEnforcer extends FeaturePolicyEnforcer {
constructor(appVersion: string) {
super('browser', appVersion);
}
async validateRequest(request: CapabilityRequest): Promise<ValidationResult> {
const result = await super.validateRequest(request);
// Web-specific: Check Feature Policy headers (if available)
if (result.allowed && typeof document !== 'undefined') {
const policy = this.getFeaturePolicy();
if (policy && !this.isAllowedByFeaturePolicy(policy, request.capability)) {
return {
allowed: false,
reason: 'policy-blocked',
suggestedAlternative: this.findPlatformAlternative(request.capability)
};
}
}
return result;
}
private getFeaturePolicy(): Record<string, string[]> | null {
if (typeof document === 'undefined') return null;
const policyHeader = document.querySelector('meta[http-equiv="Feature-Policy"]');
if (!policyHeader) return null;
const policy = policyHeader.getAttribute('content');
if (!policy) return null;
const result: Record<string, string[]> = {};
const directives = policy.split(';');
for (const directive of directives) {
const [feature, allowlist] = directive.split(' ').map(s => s.trim());
if (feature && allowlist) {
result[feature] = allowlist.split(' ');
}
}
return result;
}
private isAllowedByFeaturePolicy(policy: Record<string, string[]>, capability: string): boolean {
const featureName = this.mapCapabilityToFeaturePolicy(capability);
if (!featureName) return true; // No specific policy
const allowlist = policy[featureName];
if (!allowlist) return false; // Not allowed by default
// Check if current origin is allowed
const currentOrigin = window.location.origin;
return allowlist.includes(currentOrigin) ||
allowlist.includes('*') ||
allowlist.includes('self');
}
private mapCapabilityToFeaturePolicy(capability: string): string | null {
const mapping: Record<string, string> = {
'camera': 'camera',
'microphone': 'microphone',
'geolocation': 'geolocation',
'payment': 'payment',
'usb': 'usb',
'serial': 'serial',
'display-capture': 'display-capture'
};
return mapping[capability] || null;
}
}
React Native Implementation
// React Native bridge interface
declare module 'react-native' {
interface NativeModulesStatic {
FeaturePolicyEnforcer: {
checkPermission(capability: string): Promise<boolean>;
getDeclaredIntents(): Promise<Array<{id: string; capability: string; required: boolean}>>;
requestPermission(capability: string): Promise<boolean>;
};
}
}
class ReactNativePolicyEnforcer extends FeaturePolicyEnforcer {
constructor(appVersion: string) {
super(Platform.OS === 'ios' ? 'ios' : 'android', appVersion);
}
async checkUserPermission(capability: string): Promise<'granted' | 'denied' | 'prompt'> {
try {
const granted = await NativeModules.FeaturePolicyEnforcer.checkPermission(capability);
return granted ? 'granted' : 'denied';
} catch (e) {
return 'prompt';
}
}
async validateRequest(request: CapabilityRequest): Promise<ValidationResult> {
const result = await super.validateRequest(request);
// Mobile-specific: Check background mode restrictions
if (result.allowed && request.context === 'background') {
const backgroundAllowed = await this.checkBackgroundMode(request.capability);
if (!backgroundAllowed) {
return {
allowed: false,
reason: 'policy-blocked',
suggestedAlternative: 'switch-to-foreground'
};
}
}
return result;
}
private async checkBackgroundMode(capability: string): Promise<boolean> {
// Check if app has background mode permission for this capability
const intents = await NativeModules.FeaturePolicyEnforcer.getDeclaredIntents();
const capabilityIntent = intents.find(i =>
i.capability === capability &&
i.required &&
i.id.includes('background')
);
return !!capabilityIntent;
}
async requestPermission(capability: string): Promise<boolean> {
try {
return await NativeModules.FeaturePolicyEnforcer.requestPermission(capability);
} catch (e) {
return false;
}
}
}
Desktop Implementation (Electron)
class ElectronPolicyEnforcer extends FeaturePolicyEnforcer {
constructor(appVersion: string) {
super(process.platform as 'windows' | 'macos' | 'linux', appVersion);
}
async checkUserPermission(capability: string): Promise<'granted' | 'denied' | 'prompt'> {
// Desktop doesn't typically have runtime permission prompts for most features
// Check OS-level privacy settings
if (['camera', 'microphone'].includes(capability)) {
return this.checkOSPrivacySettings(capability) ? 'granted' : 'denied';
}
return 'granted';
}
private checkOSPrivacySettings(capability: string): boolean {
// Platform-specific checks using native Node.js modules
switch (this.platform) {
case 'macos':
return this.checkMacOSPrivacy(capability);
case 'windows':
return this.checkWindowsPrivacy(capability);
default:
return true; // Linux typically doesn't have these restrictions
}
}
private checkMacOSPrivacy(capability: string): boolean {
// Use tccutil or system preferences check
// This would require native Node.js module
return true; // Simplified for example
}
private checkWindowsPrivacy(capability: string): boolean {
// Check Windows Privacy settings
return true; // Simplified
}
async validateRequest(request: CapabilityRequest): Promise<ValidationResult> {
const result = await super.validateRequest(request);
// Desktop-specific: Check for sandbox restrictions
if (result.allowed && process.env.APP_SANDBOXED === 'true') {
const sandboxBlocked = this.checkSandboxRestrictions(request.capability);
if (sandboxBlocked) {
return {
allowed: false,
reason: 'policy-blocked',
suggestedAlternative: 'request-sandbox-exception'
};
}
}
return result;
}
private checkSandboxRestrictions(capability: string): boolean {
const restrictedInSandbox = new Set(['filesystem', 'serial', 'usb']);
return restrictedInSandbox.has(capability);
}
}
4. Factory & Usage
class PolicyEnforcerFactory {
static create(platform?: string, appVersion?: string): FeaturePolicyEnforcer {
// Auto-detect platform if not provided
const detectedPlatform = platform || this.detectPlatform();
const version = appVersion || this.getAppVersion();
switch (detectedPlatform) {
case 'browser':
return new WebPolicyEnforcer(version);
case 'ios':
case 'android':
return new ReactNativePolicyEnforcer(version);
case 'windows':
case 'macos':
case 'linux':
return new ElectronPolicyEnforcer(version);
default:
throw new Error(`Unsupported platform: ${detectedPlatform}`);
}
}
private static detectPlatform(): string {
if (typeof window !== 'undefined' && typeof document !== 'undefined') {
return 'browser';
}
if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {
return Platform.OS;
}
if (typeof process !== 'undefined' && process.versions?.electron) {
return process.platform as string;
}
return 'unknown';
}
private static getAppVersion(): string {
if (typeof window !== 'undefined' && (window as any).APP_VERSION) {
return (window as any).APP_VERSION;
}
if (typeof process !== 'undefined' && process.env?.APP_VERSION) {
return process.env.APP_VERSION;
}
return '1.0.0';
}
}
// Helper function for easy usage
export async function validateCapability(
capability: string,
context: CapabilityRequest['context'] = 'ui',
options?: { urgency?: CapabilityRequest['urgency']; metadata?: Record<string, any> }
): Promise<ValidationResult> {
const enforcer = PolicyEnforcerFactory.create();
const request: CapabilityRequest = {
capability,
context,
urgency: options?.urgency || 'normal',
metadata: options?.metadata
};
const result = await enforcer.enforce(request);
return result.result || { allowed: false, reason: 'unknown' };
}
// Intent registration helper
export function registerIntent(intent: Intent): void {
PolicyRegistry.getInstance().registerIntent(intent);
}
5. Manifest Configuration Example
// intents-manifest.json
{
"appId": "com.example.app",
"version": "2.1.0",
"platforms": {
"browser": [
{
"id": "cam-001",
"capability": "camera",
"required": true,
"minVersion": "2.0.0",
"fallback": "image-upload"
},
{
"id": "loc-001",
"capability": "geolocation",
"required": false,
"minVersion": "1.5.0"
}
],
"ios": [
{
"id": "ios-cam-001",
"capability": "camera",
"required": true,
"minVersion": "2.0.0"
}
],
"android": [
{
"id": "android-cam-001",
"capability": "camera",
"required": true
}
]
}
}
6. Usage Example
// Initialize at app startup
async function initializeApp() {
// Load and register intents from manifest
const response = await fetch('/intents-manifest.json');
const manifest = await response.json();
// Register all intents
for (const [platform, intents] of Object.entries(manifest.platforms)) {
for (const intent of intents as Intent[]) {
registerIntent({ ...intent, platform: platform as any });
}
}
// Create enforcer
const enforcer = PolicyEnforcerFactory.create();
// Use in component
async function startVideoCall() {
const result = await validateCapability('camera', 'ui', {
urgency: 'critical',
metadata: { feature: 'video-call' }
});
if (result.allowed) {
startCamera();
} else {
showFallbackUI(result.suggestedAlternative);
logSecurityEvent(result);
}
}
}
// React Hook example
function useCapabilityValidation() {
const [validationCache, setValidationCache] = useState<Map<string, ValidationResult>>(new Map());
const validate = useCallback(async (capability: string): Promise<ValidationResult> => {
if (validationCache.has(capability)) {
return validationCache.get(capability)!;
}
const result = await validateCapability(capability);
setValidationCache(prev => new Map(prev.set(capability, result)));
return result;
}, [validationCache]);
return { validate, validationCache };
}
Key Features:
- Cross-platform: Supports browser (Permissions API + Feature Policy), React Native (native bridges), and Electron (OS-level checks)
- Declarative: Uses manifest-based intent declaration
- Context-aware: Different rules for foreground/background usage
- Version-gated: Minimum version requirements per capability
- Policy-aware: Respects Feature Policy headers (web), battery/data constraints
- Fallback support: Suggests alternatives when capabilities are blocked
- Analytics-ready: Tracks capability usage patterns
- Security logging: Records policy violations
- Caching: Validation results can be cached
- Extensible: Easy to add new platforms/capabilities
Installation & Setup:
npm install runtime-feature-policy-enforcer
// In your app entry point
import { initializeApp, validateCapability } from 'runtime-feature-policy-enforcer';
// Initialize with your manifest URL
await initializeApp('/intents-manifest.json');
// Then validate capabilities as needed
const result = await validateCapability('camera');
This implementation provides a robust, production-ready solution that handles the complexities of cross-platform capability validation while maintaining security and user privacy standards across all major platforms.