@dollhousemcp/mcp-server
Version:
DollhouseMCP - A Model Context Protocol (MCP) server that enables dynamic AI persona management from markdown files, allowing Claude and other compatible AI assistants to activate and switch between different behavioral personas.
202 lines • 8.28 kB
TypeScript
/**
* DefaultElementProvider - Populates portfolio with default elements from bundled data
*
* This class handles copying default personas, skills, templates, and other elements
* from the NPM package or Git repository to the user's portfolio on first run.
* It ensures users have example content to work with immediately after installation.
*/
import { IFileOperationsService } from '../services/FileOperationsService.js';
export declare const FILE_CONSTANTS: {
readonly ELEMENT_EXTENSION: ".md";
readonly YAML_EXTENSION: ".yaml";
readonly YML_EXTENSION: ".yml";
readonly JSON_EXTENSION: ".json";
readonly MAX_FILE_SIZE: number;
readonly CHECKSUM_ALGORITHM: "sha256";
readonly FILE_PERMISSIONS: 420;
readonly CHUNK_SIZE: number;
};
export interface DefaultElementProviderConfig {
/** Custom data directory paths to search (checked before default paths) */
customDataPaths?: string[];
/** Whether to use default search paths after custom paths */
useDefaultPaths?: boolean;
/** Whether to load test/example data from repository (default: false in dev mode) */
loadTestData?: boolean;
/** FileOperationsService for centralized file operations */
fileOperations?: IFileOperationsService;
}
export declare class DefaultElementProvider {
private readonly __dirname;
private static cachedDataDir;
private static populateInProgress;
private readonly config;
private readonly fileOperations?;
private static logListener?;
static addLogListener(fn: (level: 'debug' | 'info' | 'warn' | 'error', message: string, data?: Record<string, unknown>) => void): () => void;
private static metadataCache;
private static readonly MAX_CACHE_SIZE;
constructor(config?: DefaultElementProviderConfig);
/**
* Read data/HASHES.json (shipped with the npm package) and register each
* SHA-256 hash with ContentValidator as trusted bundled content.
*
* Only files whose on-disk hash matches the manifest entry are registered —
* any post-install modification breaks the hash and revokes trust automatically.
*/
private registerBundledHashes;
/**
* Get the current loadTestData configuration value
* @returns Whether test data loading is enabled
*/
get isTestDataLoadingEnabled(): boolean;
/**
* Get whether the system is in development mode
* @returns Whether running in development mode
*/
get isDevelopmentMode(): boolean;
private statFile;
private listDir;
private fileExists;
private makeDirectory;
private copyFileOp;
private chmodFile;
private deleteFileOp;
private readFileContent;
/**
* Search paths for bundled data directory
* Ordered by priority - custom paths first, then development/git, then NPM locations
*/
private get dataSearchPaths();
/**
* Find the bundled data directory by checking each search path
* Uses Promise.allSettled for better performance and caches the result
*/
private findDataDirectory;
/**
* Helper to check if a directory exists
*/
private directoryExists;
/**
* Validate file path to prevent path traversal attacks
* SECURITY FIX: Added file path validation to prevent directory traversal
* Previously: File paths were used without validation, allowing potential ../../../ attacks
* Now: Strict validation ensures paths stay within allowed directories
* @param filePath The file path to validate
* @param allowedBasePaths Array of allowed base paths (optional)
* @returns true if path is safe, false otherwise
*/
private validateFilePath;
/**
* Cached compiled regex patterns for performance optimization
* @deprecated Use metadata-based detection instead
*/
/**
* Get compiled test patterns with caching for better performance
* @deprecated Use metadata-based detection instead
* @returns Array of compiled regex patterns
*/
/**
* Check if a filename matches test data patterns that should never be copied to production
* @deprecated Use isDollhouseMCPTestElement() for metadata-based detection instead
* @param filename The filename to check
* @returns true if the filename matches test patterns that should be blocked
*/
/**
* Read metadata from YAML frontmatter only (never reads content body)
* Uses a small buffer to safely extract only the frontmatter between --- markers
* @param filePath Path to the file to read metadata from
* @returns Parsed metadata object or null if no frontmatter found
*/
private static readonly bufferPool;
private static readonly MAX_POOL_SIZE;
private static bufferPoolStats;
private getBuffer;
private releaseBuffer;
/**
* Clean up buffer pool and cache to free memory
* PERFORMANCE FIX: Added cleanup method to prevent memory leaks
* This should be called during application shutdown or periodic cleanup
*/
static cleanup(): void;
/**
* Get performance statistics for monitoring
* PERFORMANCE MONITORING: Added statistics method for performance tracking
* This provides insights into buffer pool efficiency and cache performance
* @returns Object containing performance metrics
*/
static getPerformanceStats(): {
bufferPool: {
hits: number;
misses: number;
created: number;
hitRate: number;
poolSize: number;
maxPoolSize: number;
};
metadataCache: {
size: number;
maxSize: number;
};
};
/**
* Read only the YAML frontmatter metadata from a file (first 4KB)
*
* SECURITY NOTE (Issue #1228): This method MUST use validateContent: true when calling
* SecureYamlParser.parse() to ensure Unicode security validation runs. Setting validateContent
* to false would disable ALL content validation including zero-width character detection,
* creating a security bypass vulnerability.
*
* @param filePath - Absolute path to the file to read
* @param retries - Number of retries for transient failures (default: 2)
* @returns Parsed metadata object or null if no valid frontmatter found
*/
private readMetadataOnly;
/**
* Check if a file is a DollhouseMCP test element based on metadata
* This replaces filename pattern detection with accurate metadata-based detection
* @param filePath Path to the file to check
* @returns true if the file contains _dollhouseMCPTest: true metadata
*/
private isDollhouseMCPTestElement;
/**
* Detect if we're in a production environment by checking for production indicators
* Uses a confidence-based approach requiring multiple indicators for better accuracy
* @returns true if this appears to be a production environment
*/
private isProductionEnvironment;
/**
* Copy all files from source directory to destination directory
* Skips files that already exist to preserve user modifications
*/
private copyElementFiles;
/**
* Copy a file with integrity verification
* Ensures the file was copied correctly by comparing sizes
*/
/**
* Calculate checksum of a file for integrity verification
* @param filePath Path to the file
* @returns Hex-encoded checksum
*/
private calculateChecksum;
/**
* Copy file with integrity verification and retry logic
* @param sourcePath Source file path
* @param destPath Destination file path
* @throws Error if copy fails after all retry attempts
*/
private copyFileWithVerification;
/**
* Populate the portfolio with default elements from bundled data
* This is called during portfolio initialization for new installations
* Protected against concurrent calls to prevent race conditions
*/
populateDefaults(portfolioBaseDir: string): Promise<void>;
/**
* Perform the actual population of default elements
* @param portfolioBaseDir Base directory of the portfolio
*/
private performPopulation;
}
//# sourceMappingURL=DefaultElementProvider.d.ts.map