src — elevated-mode

Module: src-elevated-mode Cohesion: 0.80 Members: 0

src — elevated-mode

This document provides a comprehensive overview of the src/elevated-mode module, designed for developers who need to understand, use, or contribute to its functionality.


Elevated Mode Module Documentation

The elevated-mode module provides a robust system for managing permissions and privileged operations within the application. It introduces a hierarchical permission model, allowing different parts of the system to request specific capabilities, which can then be granted or denied based on the current session's security context and user interaction.

Purpose

The primary goals of this module are:

Core Concepts

The module revolves around several key concepts:

Architecture Overview

The elevated-mode module is centered around the ElevatedModeManager class, which is typically accessed as a singleton instance via getElevatedMode(). This manager maintains the current ElevatedSession, processes permission requests, manages grants, and handles privilege elevation/de-elevation.

graph TD
    A[Application Component] --> B{getElevatedMode()};
    B --> C[ElevatedModeManager Singleton];
    C -- Emits Events --> D[Event Listeners];

    subgraph Permission Request Flow
        C --> E[requestPermission(category, options)];
        E --> F{hasPermission() or auto-grant?};
        F -- Yes --> G[Return existing/new Grant];
        F -- No --> H[Create PermissionRequest];
        H --> I[Emit 'permission-request'];
        I --> J[Store pending request];
        J --> K[Return Promise<PermissionGrant | null>];
        L[User/System UI] --> M[grantRequest(requestId) / denyRequest(requestId)];
        M --> J;
        M --> N[Resolve Promise];
    end

    subgraph Level Management
        C --> O[elevate(level, durationMs)];
        O --> P[Set session.level, expiresAt];
        P --> Q[Start expiration timer];
        Q --> R[dropElevation() on timeout];
        C --> S[dropElevation()];
        S --> T[Reset session.level, clear session grants];
    end

Key Components and Functionality

Types

The module defines several interfaces and types to structure its data:

Permission Utilities

A set of helper functions for working with permissions:

ElevatedModeManager Class

This is the central class for managing elevated mode. It extends EventEmitter to provide a publish-subscribe mechanism for important events.

Constructor and Initialization:

Permission Checking:

  1. If the session.level meets the permission.level.
  2. If an exact PermissionGrant exists and is not expired.
  3. If any existing PermissionGrant with a resource pattern matches the requested resource.

Permission Requests:

Level Management:

Grant Management:

Session Management:

Configuration:

Singleton Access

The module provides singleton access to the ElevatedModeManager to ensure a single, consistent security context across the application.

Integration and Usage

Obtaining the Manager

Most interactions will start by getting the singleton instance:

import { getElevatedMode } from &#39;./elevated-mode&#39;;

const elevatedMode = getElevatedMode();

Requesting Permissions

To perform an operation that requires a specific permission:

import { getElevatedMode, PermissionCategory } from &#39;./elevated-mode&#39;;

async function readFileWithPermission(filePath: string) {
  const elevatedMode = getElevatedMode();
  const permission = { category: &#39;file:read&#39; as PermissionCategory, resource: filePath, level: &#39;user&#39; };

  if (elevatedMode.hasPermission(permission)) {
    console.log(`Permission to read ${filePath} already granted.`);
    class="hl-cmt">// Proceed with file read
    return;
  }

  console.log(`Requesting permission to read ${filePath}...`);
  const grant = await elevatedMode.requestPermission(
    &#39;file:read&#39;,
    {
      resource: filePath,
      source: &#39;FileViewer&#39;,
      reason: &#39;User opened file for viewing&#39;,
    }
  );

  if (grant) {
    console.log(`Permission granted: ${grant.type}`);
    class="hl-cmt">// Proceed with file read
  } else {
    console.log(&#39;Permission denied or timed out.&#39;);
    class="hl-cmt">// Handle denial
  }
}

Handling Permission Requests (UI/System Integration)

External components (e.g., a UI dialog, a system daemon) will listen for 'permission-request' events and then call grantRequest or denyRequest.

import { getElevatedMode } from &#39;./elevated-mode&#39;;

const elevatedMode = getElevatedMode();

elevatedMode.on(&#39;permission-request&#39;, (request) => {
  console.log(`New permission request: ${request.permission.category} on ${request.permission.resource || &#39;*&#39;}`);
  console.log(`Reason: ${request.context.reason}`);

  class="hl-cmt">// In a real application, this would trigger a UI prompt
  class="hl-cmt">// For demonstration, auto-grant after a delay
  setTimeout(() => {
    if (confirm(`Grant permission for ${request.permission.category}?`)) {
      elevatedMode.grantRequest(request.id, &#39;allow-session&#39;, &#39;user-confirmed&#39;);
      console.log(&#39;Request granted by user.&#39;);
    } else {
      elevatedMode.denyRequest(request.id, &#39;User denied&#39;);
      console.log(&#39;Request denied by user.&#39;);
    }
  }, 1000);
});

Elevating Privileges

To temporarily elevate the session's level:

import { getElevatedMode } from &#39;./elevated-mode&#39;;

const elevatedMode = getElevatedMode();

class="hl-cmt">// Listen for level changes
elevatedMode.on(&#39;level-change&#39;, (from, to) => {
  console.log(`Permission level changed from ${from} to ${to}`);
});

class="hl-cmt">// Elevate to &#39;admin&#39; for 5 minutes
elevatedMode.elevate(&#39;admin&#39;, 5 * 60 * 1000);

class="hl-cmt">// Check current level
console.log(`Current level: ${elevatedMode.getLevel()}`);

class="hl-cmt">// Drop elevation manually
class="hl-cmt">// elevatedMode.dropElevation();

Configuration

The module can be configured at initialization or updated dynamically:

import { getElevatedMode } from &#39;./elevated-mode&#39;;

class="hl-cmt">// Initialize with custom config
const elevatedMode = getElevatedMode({
  elevationTimeoutMs: 10 * 60 * 1000, class="hl-cmt">// 10 minutes
  autoGrantSafe: false, class="hl-cmt">// Require confirmation even for safe ops
  dangerousCategories: [&#39;system:shutdown&#39;], class="hl-cmt">// Only this is dangerous
});

class="hl-cmt">// Update config later
elevatedMode.updateConfig({
  maxGrantsPerSession: 50,
});

Connections to the Codebase

This handler acts as the bridge between user commands/UI and the ElevatedModeManager.

Development Notes