@utilarium/cardigantime 0.0.24-dev.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +65 -0
- package/README.md +398 -0
- package/dist/cardigantime.cjs +2169 -0
- package/dist/cardigantime.cjs.map +1 -0
- package/dist/cardigantime.d.ts +92 -0
- package/dist/cardigantime.js +198 -0
- package/dist/cardigantime.js.map +1 -0
- package/dist/config/executable-security.d.ts +32 -0
- package/dist/config/format-detector.d.ts +59 -0
- package/dist/configure.d.ts +55 -0
- package/dist/configure.js +125 -0
- package/dist/configure.js.map +1 -0
- package/dist/constants.d.ts +25 -0
- package/dist/constants.js +38 -0
- package/dist/constants.js.map +1 -0
- package/dist/discovery/discoverer.d.ts +62 -0
- package/dist/discovery/hierarchical-modes.d.ts +64 -0
- package/dist/discovery/index.d.ts +15 -0
- package/dist/discovery/patterns.d.ts +77 -0
- package/dist/discovery/root-detection.d.ts +100 -0
- package/dist/discovery/traversal-security.d.ts +106 -0
- package/dist/env/errors.d.ts +18 -0
- package/dist/env/index.d.ts +7 -0
- package/dist/env/naming.d.ts +38 -0
- package/dist/env/parser.d.ts +61 -0
- package/dist/env/reader.d.ts +45 -0
- package/dist/env/resolver.d.ts +25 -0
- package/dist/env/schema-utils.d.ts +33 -0
- package/dist/env/types.d.ts +43 -0
- package/dist/error/ArgumentError.d.ts +31 -0
- package/dist/error/ArgumentError.js +48 -0
- package/dist/error/ArgumentError.js.map +1 -0
- package/dist/error/ConfigParseError.d.ts +26 -0
- package/dist/error/ConfigurationError.d.ts +21 -0
- package/dist/error/ConfigurationError.js +46 -0
- package/dist/error/ConfigurationError.js.map +1 -0
- package/dist/error/FileSystemError.d.ts +30 -0
- package/dist/error/FileSystemError.js +58 -0
- package/dist/error/FileSystemError.js.map +1 -0
- package/dist/error/index.d.ts +4 -0
- package/dist/mcp/discovery.d.ts +105 -0
- package/dist/mcp/errors.d.ts +75 -0
- package/dist/mcp/index.d.ts +22 -0
- package/dist/mcp/integration.d.ts +184 -0
- package/dist/mcp/parser.d.ts +141 -0
- package/dist/mcp/resolver.d.ts +165 -0
- package/dist/mcp/tools/check-config-types.d.ts +208 -0
- package/dist/mcp/tools/check-config.d.ts +85 -0
- package/dist/mcp/tools/index.d.ts +12 -0
- package/dist/mcp/types.d.ts +210 -0
- package/dist/parsers/index.d.ts +25 -0
- package/dist/parsers/javascript-parser.d.ts +12 -0
- package/dist/parsers/json-parser.d.ts +6 -0
- package/dist/parsers/typescript-parser.d.ts +15 -0
- package/dist/parsers/yaml-parser.d.ts +6 -0
- package/dist/read.d.ts +56 -0
- package/dist/read.js +653 -0
- package/dist/read.js.map +1 -0
- package/dist/security/audit-logger.d.ts +135 -0
- package/dist/security/cli-validator.d.ts +73 -0
- package/dist/security/config-validator.d.ts +95 -0
- package/dist/security/defaults.d.ts +17 -0
- package/dist/security/index.d.ts +14 -0
- package/dist/security/numeric-guard.d.ts +111 -0
- package/dist/security/path-guard.d.ts +53 -0
- package/dist/security/profiles.d.ts +127 -0
- package/dist/security/security-validator.d.ts +109 -0
- package/dist/security/string-guard.d.ts +92 -0
- package/dist/security/types.d.ts +126 -0
- package/dist/security/zod-secure-enum.d.ts +20 -0
- package/dist/security/zod-secure-number.d.ts +39 -0
- package/dist/security/zod-secure-path.d.ts +24 -0
- package/dist/security/zod-secure-string.d.ts +38 -0
- package/dist/types.d.ts +584 -0
- package/dist/types.js +56 -0
- package/dist/types.js.map +1 -0
- package/dist/util/hierarchical.d.ts +136 -0
- package/dist/util/hierarchical.js +436 -0
- package/dist/util/hierarchical.js.map +1 -0
- package/dist/util/schema-defaults.d.ts +80 -0
- package/dist/util/schema-defaults.js +118 -0
- package/dist/util/schema-defaults.js.map +1 -0
- package/dist/util/storage.d.ts +31 -0
- package/dist/util/storage.js +154 -0
- package/dist/util/storage.js.map +1 -0
- package/dist/validate.d.ts +113 -0
- package/dist/validate.js +260 -0
- package/dist/validate.js.map +1 -0
- package/package.json +84 -0
package/dist/read.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"read.js","sources":["../src/read.ts"],"sourcesContent":["import * as yaml from 'js-yaml';\nimport * as path from 'node:path';\nimport { z, ZodObject } from 'zod';\nimport { Args, ConfigSchema, Options } from './types';\nimport * as Storage from './util/storage';\nimport { loadHierarchicalConfig, DiscoveredConfigDir } from './util/hierarchical';\n\n/**\n * Removes undefined values from an object to create a clean configuration.\n * This is used to merge configuration sources while avoiding undefined pollution.\n * \n * @param obj - The object to clean\n * @returns A new object with undefined values filtered out\n */\nfunction clean(obj: any) {\n return Object.fromEntries(\n Object.entries(obj).filter(([_, v]) => v !== undefined)\n );\n}\n\n/**\n * Resolves relative paths in configuration values relative to the configuration file's directory.\n * \n * @param config - The configuration object to process\n * @param configDir - The directory containing the configuration file\n * @param pathFields - Array of field names (using dot notation) that contain paths to be resolved\n * @param resolvePathArray - Array of field names whose array elements should all be resolved as paths\n * @returns The configuration object with resolved paths\n */\nfunction resolveConfigPaths(\n config: any,\n configDir: string,\n pathFields: string[] = [],\n resolvePathArray: string[] = []\n): any {\n if (!config || typeof config !== 'object' || pathFields.length === 0) {\n return config;\n }\n\n const resolvedConfig = { ...config };\n\n for (const fieldPath of pathFields) {\n const value = getNestedValue(resolvedConfig, fieldPath);\n if (value !== undefined) {\n const shouldResolveArrayElements = resolvePathArray.includes(fieldPath);\n const resolvedValue = resolvePathValue(value, configDir, shouldResolveArrayElements);\n setNestedValue(resolvedConfig, fieldPath, resolvedValue);\n }\n }\n\n return resolvedConfig;\n}\n\n/**\n * Gets a nested value from an object using dot notation.\n */\nfunction getNestedValue(obj: any, path: string): any {\n return path.split('.').reduce((current, key) => current?.[key], obj);\n}\n\n/**\n * Checks if a key is unsafe for prototype pollution prevention.\n */\nfunction isUnsafeKey(key: string): boolean {\n return key === '__proto__' || key === 'constructor' || key === 'prototype';\n}\n\n/**\n * Sets a nested value in an object using dot notation.\n * Prevents prototype pollution by rejecting dangerous property names.\n */\nfunction setNestedValue(obj: any, path: string, value: any): void {\n const keys = path.split('.');\n const lastKey = keys.pop()!;\n\n // Prevent prototype pollution via special property names\n if (isUnsafeKey(lastKey) || keys.some(isUnsafeKey)) {\n return;\n }\n\n const target = keys.reduce((current, key) => {\n // Skip if this is an unsafe key (already checked above, but defensive)\n if (isUnsafeKey(key)) {\n return current;\n }\n if (!(key in current)) {\n current[key] = {};\n }\n return current[key];\n }, obj);\n target[lastKey] = value;\n}\n\n/**\n * Resolves a path value (string or array of strings) relative to the config directory.\n */\nfunction resolvePathValue(value: any, configDir: string, resolveArrayElements: boolean): any {\n if (typeof value === 'string') {\n return resolveSinglePath(value, configDir);\n }\n\n if (Array.isArray(value) && resolveArrayElements) {\n return value.map(item =>\n typeof item === 'string' ? resolveSinglePath(item, configDir) : item\n );\n }\n\n return value;\n}\n\n/**\n * Resolves a single path string relative to the config directory if it's a relative path.\n */\nfunction resolveSinglePath(pathStr: string, configDir: string): string {\n if (!pathStr || path.isAbsolute(pathStr)) {\n return pathStr;\n }\n\n return path.resolve(configDir, pathStr);\n}\n\n/**\n * Validates and secures a user-provided path to prevent path traversal attacks.\n * \n * Security checks include:\n * - Path traversal prevention (blocks '..')\n * - Absolute path detection\n * - Path separator validation\n * \n * @param userPath - The user-provided path component\n * @param basePath - The base directory to join the path with\n * @returns The safely joined and normalized path\n * @throws {Error} When path traversal or absolute paths are detected\n */\nfunction validatePath(userPath: string, basePath: string): string {\n if (!userPath || !basePath) {\n throw new Error('Invalid path parameters');\n }\n\n const normalized = path.normalize(userPath);\n\n // Prevent path traversal attacks\n if (normalized.includes('..') || path.isAbsolute(normalized)) {\n throw new Error('Invalid path: path traversal detected');\n }\n\n // Ensure the path doesn't start with a path separator\n if (normalized.startsWith('/') || normalized.startsWith('\\\\')) {\n throw new Error('Invalid path: absolute path detected');\n }\n\n return path.join(basePath, normalized);\n}\n\n/**\n * Validates a configuration directory path for security and basic formatting.\n * \n * Performs validation to prevent:\n * - Null byte injection attacks\n * - Extremely long paths that could cause DoS\n * - Empty or invalid directory specifications\n * \n * @param configDir - The configuration directory path to validate\n * @returns The normalized configuration directory path\n * @throws {Error} When the directory path is invalid or potentially dangerous\n */\nfunction validateConfigDirectory(configDir: string): string {\n if (!configDir) {\n throw new Error('Configuration directory is required');\n }\n\n // Check for null bytes which could be used for path injection\n if (configDir.includes('\\0')) {\n throw new Error('Invalid path: null byte detected');\n }\n\n const normalized = path.normalize(configDir);\n\n // Basic validation - could be expanded based on requirements\n if (normalized.length > 1000) {\n throw new Error('Configuration directory path too long');\n }\n\n return normalized;\n}\n\n/**\n * Reads configuration from files and merges it with CLI arguments.\n * \n * This function implements the core configuration loading logic:\n * 1. Validates and resolves the configuration directory path\n * 2. Attempts to read the YAML configuration file\n * 3. Safely parses the YAML content with security protections\n * 4. Merges file configuration with runtime arguments\n * 5. Returns a typed configuration object\n * \n * The function handles missing files gracefully and provides detailed\n * logging for troubleshooting configuration issues.\n * \n * @template T - The Zod schema shape type for configuration validation\n * @param args - Parsed command-line arguments containing potential config overrides\n * @param options - Cardigantime options with defaults, schema, and logger\n * @returns Promise resolving to the merged and typed configuration object\n * @throws {Error} When configuration directory is invalid or required files cannot be read\n * \n * @example\n * ```typescript\n * const config = await read(cliArgs, {\n * defaults: { configDirectory: './config', configFile: 'app.yaml' },\n * configShape: MySchema.shape,\n * logger: console,\n * features: ['config']\n * });\n * // config is fully typed based on your schema\n * ```\n */\nexport const read = async <T extends z.ZodRawShape>(args: Args, options: Options<T>): Promise<z.infer<ZodObject<T & typeof ConfigSchema.shape>>> => {\n const logger = options.logger;\n\n const rawConfigDir = args.configDirectory || options.defaults?.configDirectory;\n if (!rawConfigDir) {\n throw new Error('Configuration directory must be specified');\n }\n\n const resolvedConfigDir = validateConfigDirectory(rawConfigDir);\n logger.verbose('Resolved config directory');\n\n let rawFileConfig: object = {};\n let discoveredConfigDirs: string[] = [];\n let resolvedConfigDirs: string[] = [];\n\n // Check if hierarchical configuration discovery is enabled\n // Use optional chaining for safety although options.features is defaulted\n if (options.features && options.features.includes('hierarchical')) {\n logger.verbose('Hierarchical configuration discovery enabled');\n\n try {\n // Extract the config directory name from the path for hierarchical discovery\n const configDirName = path.basename(resolvedConfigDir);\n const startingDir = path.dirname(resolvedConfigDir);\n\n logger.debug(`Using hierarchical discovery: configDirName=${configDirName}, startingDir=${startingDir}`);\n\n const hierarchicalResult = await loadHierarchicalConfig({\n configDirName,\n configFileName: options.defaults.configFile,\n startingDir,\n encoding: options.defaults.encoding,\n logger,\n pathFields: options.defaults.pathResolution?.pathFields,\n resolvePathArray: options.defaults.pathResolution?.resolvePathArray,\n fieldOverlaps: options.defaults.fieldOverlaps\n });\n\n rawFileConfig = hierarchicalResult.config;\n discoveredConfigDirs = hierarchicalResult.discoveredDirs.map(dir => dir.path);\n resolvedConfigDirs = hierarchicalResult.resolvedConfigDirs.map(dir => dir.path);\n\n if (hierarchicalResult.discoveredDirs.length > 0) {\n logger.verbose(`Hierarchical discovery found ${hierarchicalResult.discoveredDirs.length} configuration directories`);\n hierarchicalResult.discoveredDirs.forEach(dir => {\n logger.debug(` Level ${dir.level}: ${dir.path}`);\n });\n } else {\n logger.verbose('No configuration directories found in hierarchy');\n }\n\n if (hierarchicalResult.resolvedConfigDirs.length > 0) {\n logger.verbose(`Found ${hierarchicalResult.resolvedConfigDirs.length} directories with actual configuration files`);\n hierarchicalResult.resolvedConfigDirs.forEach(dir => {\n logger.debug(` Config dir level ${dir.level}: ${dir.path}`);\n });\n }\n\n if (hierarchicalResult.errors.length > 0) {\n hierarchicalResult.errors.forEach(error => logger.warn(`Hierarchical config warning: ${error}`));\n }\n\n } catch (error: any) {\n logger.error('Hierarchical configuration loading failed: ' + (error.message || 'Unknown error'));\n // Fall back to single directory mode\n logger.verbose('Falling back to single directory configuration loading');\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n\n // Include the directory in both arrays (discovered but check if it had config)\n discoveredConfigDirs = [resolvedConfigDir];\n if (rawFileConfig && Object.keys(rawFileConfig).length > 0) {\n resolvedConfigDirs = [resolvedConfigDir];\n } else {\n resolvedConfigDirs = [];\n }\n }\n } else {\n // Use traditional single directory configuration loading\n logger.verbose('Using single directory configuration loading');\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n\n // Include the directory in discovered, and in resolved only if it had config\n discoveredConfigDirs = [resolvedConfigDir];\n if (rawFileConfig && Object.keys(rawFileConfig).length > 0) {\n resolvedConfigDirs = [resolvedConfigDir];\n } else {\n resolvedConfigDirs = [];\n }\n }\n\n // Apply path resolution if configured\n let processedConfig = rawFileConfig;\n if (options.defaults.pathResolution?.pathFields) {\n processedConfig = resolveConfigPaths(\n rawFileConfig,\n resolvedConfigDir,\n options.defaults.pathResolution.pathFields,\n options.defaults.pathResolution.resolvePathArray || []\n );\n }\n\n const config: z.infer<ZodObject<T & typeof ConfigSchema.shape>> = clean({\n ...processedConfig,\n ...{\n configDirectory: resolvedConfigDir,\n discoveredConfigDirs,\n resolvedConfigDirs,\n }\n }) as z.infer<ZodObject<T & typeof ConfigSchema.shape>>;\n\n return config;\n}\n\n/**\n * Tries to find a config file with alternative extensions (.yaml or .yml).\n * \n * @param storage Storage instance to use for file operations\n * @param configDir The directory containing the config file\n * @param configFileName The base config file name (may have .yaml or .yml extension)\n * @param logger Logger for debugging\n * @returns Promise resolving to the found config file path or null if not found\n */\nasync function findConfigFileWithExtension(\n storage: any,\n configDir: string,\n configFileName: string,\n logger: any\n): Promise<string | null> {\n // Validate the config file name to prevent path traversal\n const configFilePath = validatePath(configFileName, configDir);\n \n // First try the exact filename as specified\n const exists = await storage.exists(configFilePath);\n if (exists) {\n const isReadable = await storage.isFileReadable(configFilePath);\n if (isReadable) {\n return configFilePath;\n }\n }\n \n // If the exact filename doesn't exist or isn't readable, try alternative extensions\n // Only do this if the filename has a .yaml or .yml extension\n const ext = path.extname(configFileName);\n if (ext === '.yaml' || ext === '.yml') {\n const baseName = path.basename(configFileName, ext);\n const alternativeExt = ext === '.yaml' ? '.yml' : '.yaml';\n const alternativeFileName = baseName + alternativeExt;\n const alternativePath = validatePath(alternativeFileName, configDir);\n \n logger.debug(`Config file not found at ${configFilePath}, trying alternative: ${alternativePath}`);\n \n const altExists = await storage.exists(alternativePath);\n if (altExists) {\n const altIsReadable = await storage.isFileReadable(alternativePath);\n if (altIsReadable) {\n logger.debug(`Found config file with alternative extension: ${alternativePath}`);\n return alternativePath;\n }\n }\n }\n \n return null;\n}\n\n/**\n * Loads configuration from a single directory (traditional mode).\n * \n * @param resolvedConfigDir - The resolved configuration directory path\n * @param options - Cardigantime options\n * @param logger - Logger instance\n * @returns Promise resolving to the configuration object\n */\nasync function loadSingleDirectoryConfig<T extends z.ZodRawShape>(\n resolvedConfigDir: string,\n options: Options<T>,\n logger: any\n): Promise<object> {\n const storage = Storage.create({ log: logger.debug });\n logger.verbose('Attempting to load config file for cardigantime');\n\n let rawFileConfig: object = {};\n\n try {\n // Try to find the config file with alternative extensions\n const configFilePath = await findConfigFileWithExtension(\n storage,\n resolvedConfigDir,\n options.defaults.configFile,\n logger\n );\n \n if (!configFilePath) {\n logger.verbose('Configuration file not found. Using empty configuration.');\n return rawFileConfig;\n }\n\n const yamlContent = await storage.readFile(configFilePath, options.defaults.encoding);\n\n // SECURITY FIX: Use safer parsing options to prevent code execution vulnerabilities\n const parsedYaml = yaml.load(yamlContent);\n\n if (parsedYaml !== null && typeof parsedYaml === 'object') {\n rawFileConfig = parsedYaml;\n logger.verbose('Loaded configuration file successfully');\n } else if (parsedYaml !== null) {\n logger.warn('Ignoring invalid configuration format. Expected an object, got ' + typeof parsedYaml);\n }\n } catch (error: any) {\n // Re-throw security-related errors (path validation failures)\n if (error.message && /Invalid path|path traversal|absolute path/i.test(error.message)) {\n throw error;\n }\n \n if (error.code === 'ENOENT' || /not found|no such file/i.test(error.message)) {\n logger.verbose('Configuration file not found. Using empty configuration.');\n } else {\n // SECURITY FIX: Don't expose internal paths or detailed error information\n logger.error('Failed to load or parse configuration file: ' + (error.message || 'Unknown error'));\n }\n }\n\n return rawFileConfig;\n}\n\n/**\n * Represents a configuration value with its source information.\n */\ninterface ConfigSourceInfo {\n /** The configuration value */\n value: any;\n /** Path to the configuration file that provided this value */\n sourcePath: string;\n /** Hierarchical level (0 = closest/highest precedence) */\n level: number;\n /** Short description of the source for display */\n sourceLabel: string;\n}\n\n/**\n * Tracks configuration values to their sources during hierarchical loading.\n */\ninterface ConfigSourceTracker {\n [key: string]: ConfigSourceInfo;\n}\n\n/**\n * Recursively tracks the source of configuration values from hierarchical loading.\n * \n * @param config - The configuration object to track\n * @param sourcePath - Path to the configuration file\n * @param level - Hierarchical level\n * @param prefix - Current object path prefix for nested values\n * @param tracker - The tracker object to populate\n */\nfunction trackConfigSources(\n config: any,\n sourcePath: string,\n level: number,\n prefix: string = '',\n tracker: ConfigSourceTracker = {}\n): ConfigSourceTracker {\n if (!config || typeof config !== 'object' || Array.isArray(config)) {\n // For primitives and arrays, track the entire value\n tracker[prefix] = {\n value: config,\n sourcePath,\n level,\n sourceLabel: `Level ${level}: ${path.basename(path.dirname(sourcePath))}`\n };\n return tracker;\n }\n\n // For objects, recursively track each property\n for (const [key, value] of Object.entries(config)) {\n const fieldPath = prefix ? `${prefix}.${key}` : key;\n trackConfigSources(value, sourcePath, level, fieldPath, tracker);\n }\n\n return tracker;\n}\n\n/**\n * Merges multiple configuration source trackers with proper precedence.\n * Lower level numbers have higher precedence.\n * \n * @param trackers - Array of trackers from different config sources\n * @returns Merged tracker with proper precedence\n */\nfunction mergeConfigTrackers(trackers: ConfigSourceTracker[]): ConfigSourceTracker {\n const merged: ConfigSourceTracker = {};\n\n for (const tracker of trackers) {\n for (const [key, info] of Object.entries(tracker)) {\n // Only update if we don't have this key yet, or if this source has higher precedence (lower level)\n if (!merged[key] || info.level < merged[key].level) {\n merged[key] = info;\n }\n }\n }\n\n return merged;\n}\n\n/**\n * Formats a configuration value for display, handling different types appropriately.\n * \n * @param value - The configuration value to format\n * @returns Formatted string representation\n */\nfunction formatConfigValue(value: any): string {\n if (value === null) return 'null';\n if (value === undefined) return 'undefined';\n if (typeof value === 'string') return `\"${value}\"`;\n if (typeof value === 'boolean') return value.toString();\n if (typeof value === 'number') return value.toString();\n if (Array.isArray(value)) {\n if (value.length === 0) return '[]';\n if (value.length <= 3) {\n return `[${value.map(formatConfigValue).join(', ')}]`;\n }\n return `[${value.slice(0, 2).map(formatConfigValue).join(', ')}, ... (${value.length} items)]`;\n }\n if (typeof value === 'object') {\n const keys = Object.keys(value);\n if (keys.length === 0) return '{}';\n if (keys.length <= 2) {\n return `{${keys.slice(0, 2).join(', ')}}`;\n }\n return `{${keys.slice(0, 2).join(', ')}, ... (${keys.length} keys)}`;\n }\n return String(value);\n}\n\n/**\n * Displays configuration with source tracking in a git blame-like format.\n * \n * @param config - The resolved configuration object\n * @param tracker - Configuration source tracker\n * @param discoveredDirs - Array of discovered configuration directories\n * @param logger - Logger instance for output\n */\nfunction displayConfigWithSources(\n config: any,\n tracker: ConfigSourceTracker,\n discoveredDirs: DiscoveredConfigDir[],\n logger: any\n): void {\n logger.info('\\n' + '='.repeat(80));\n logger.info('CONFIGURATION SOURCE ANALYSIS');\n logger.info('='.repeat(80));\n\n // Display discovered configuration hierarchy\n logger.info('\\nDISCOVERED CONFIGURATION HIERARCHY:');\n if (discoveredDirs.length === 0) {\n logger.info(' No configuration directories found in hierarchy');\n } else {\n discoveredDirs\n .sort((a, b) => a.level - b.level) // Sort by precedence (lower level = higher precedence)\n .forEach(dir => {\n const precedence = dir.level === 0 ? '(highest precedence)' :\n dir.level === Math.max(...discoveredDirs.map(d => d.level)) ? '(lowest precedence)' :\n '';\n logger.info(` Level ${dir.level}: ${dir.path} ${precedence}`);\n });\n }\n\n // Display resolved configuration with sources\n logger.info('\\nRESOLVED CONFIGURATION WITH SOURCES:');\n logger.info('Format: [Source] key: value\\n');\n\n const sortedKeys = Object.keys(tracker).sort();\n const maxKeyLength = Math.max(...sortedKeys.map(k => k.length), 20);\n const maxSourceLength = Math.max(...Object.values(tracker).map(info => info.sourceLabel.length), 25);\n\n for (const key of sortedKeys) {\n const info = tracker[key];\n const paddedKey = key.padEnd(maxKeyLength);\n const paddedSource = info.sourceLabel.padEnd(maxSourceLength);\n const formattedValue = formatConfigValue(info.value);\n\n logger.info(`[${paddedSource}] ${paddedKey}: ${formattedValue}`);\n }\n\n // Display summary\n logger.info('\\n' + '-'.repeat(80));\n logger.info('SUMMARY:');\n logger.info(` Total configuration keys: ${Object.keys(tracker).length}`);\n logger.info(` Configuration sources: ${discoveredDirs.length}`);\n\n // Count values by source\n const sourceCount: { [source: string]: number } = {};\n for (const info of Object.values(tracker)) {\n sourceCount[info.sourceLabel] = (sourceCount[info.sourceLabel] || 0) + 1;\n }\n\n logger.info(' Values by source:');\n for (const [source, count] of Object.entries(sourceCount)) {\n logger.info(` ${source}: ${count} value(s)`);\n }\n\n logger.info('='.repeat(80));\n}\n\n/**\n * Checks and displays the resolved configuration with detailed source tracking.\n * \n * This function provides a git blame-like view of configuration resolution,\n * showing which file and hierarchical level contributed each configuration value.\n * \n * @template T - The Zod schema shape type for configuration validation\n * @param args - Parsed command-line arguments\n * @param options - Cardigantime options with defaults, schema, and logger\n * @returns Promise that resolves when the configuration check is complete\n * \n * @example\n * ```typescript\n * await checkConfig(cliArgs, {\n * defaults: { configDirectory: './config', configFile: 'app.yaml' },\n * configShape: MySchema.shape,\n * logger: console,\n * features: ['config', 'hierarchical']\n * });\n * // Outputs detailed configuration source analysis\n * ```\n */\nexport const checkConfig = async <T extends z.ZodRawShape>(\n args: Args,\n options: Options<T>\n): Promise<void> => {\n const logger = options.logger;\n\n logger.info('Starting configuration check...');\n\n const rawConfigDir = args.configDirectory || options.defaults?.configDirectory;\n if (!rawConfigDir) {\n throw new Error('Configuration directory must be specified');\n }\n\n const resolvedConfigDir = validateConfigDirectory(rawConfigDir);\n logger.verbose(`Resolved config directory: ${resolvedConfigDir}`);\n\n let rawFileConfig: object = {};\n let discoveredDirs: DiscoveredConfigDir[] = [];\n let resolvedConfigDirs: DiscoveredConfigDir[] = [];\n let tracker: ConfigSourceTracker = {};\n\n // Check if hierarchical configuration discovery is enabled\n // Use optional chaining for safety although options.features is defaulted\n if (options.features && options.features.includes('hierarchical')) {\n logger.verbose('Using hierarchical configuration discovery for source tracking');\n\n try {\n // Extract the config directory name from the path for hierarchical discovery\n const configDirName = path.basename(resolvedConfigDir);\n const startingDir = path.dirname(resolvedConfigDir);\n\n logger.debug(`Using hierarchical discovery: configDirName=${configDirName}, startingDir=${startingDir}`);\n\n const hierarchicalResult = await loadHierarchicalConfig({\n configDirName,\n configFileName: options.defaults.configFile,\n startingDir,\n encoding: options.defaults.encoding,\n logger,\n pathFields: options.defaults.pathResolution?.pathFields,\n resolvePathArray: options.defaults.pathResolution?.resolvePathArray,\n fieldOverlaps: options.defaults.fieldOverlaps\n });\n\n rawFileConfig = hierarchicalResult.config;\n discoveredDirs = hierarchicalResult.discoveredDirs;\n resolvedConfigDirs = hierarchicalResult.resolvedConfigDirs;\n\n // Build detailed source tracking by re-loading each config individually\n const trackers: ConfigSourceTracker[] = [];\n\n // Sort by level (highest level first = lowest precedence first) to match merge order\n const sortedDirs = [...resolvedConfigDirs].sort((a, b) => b.level - a.level);\n\n for (const dir of sortedDirs) {\n const storage = Storage.create({ log: logger.debug });\n const configFilePath = path.join(dir.path, options.defaults.configFile);\n\n try {\n const exists = await storage.exists(configFilePath);\n if (!exists) continue;\n\n const isReadable = await storage.isFileReadable(configFilePath);\n if (!isReadable) continue;\n\n const yamlContent = await storage.readFile(configFilePath, options.defaults.encoding);\n const parsedYaml = yaml.load(yamlContent);\n\n if (parsedYaml !== null && typeof parsedYaml === 'object') {\n const levelTracker = trackConfigSources(parsedYaml, configFilePath, dir.level);\n trackers.push(levelTracker);\n }\n } catch (error: any) {\n logger.debug(`Error loading config for source tracking from ${configFilePath}: ${error.message}`);\n }\n }\n\n // Merge trackers with proper precedence\n tracker = mergeConfigTrackers(trackers);\n\n if (hierarchicalResult.errors.length > 0) {\n logger.warn('Configuration loading warnings:');\n hierarchicalResult.errors.forEach(error => logger.warn(` ${error}`));\n }\n\n } catch (error: any) {\n logger.error('Hierarchical configuration loading failed: ' + (error.message || 'Unknown error'));\n logger.verbose('Falling back to single directory configuration loading');\n\n // Fall back to single directory mode for source tracking\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n const configFilePath = path.join(resolvedConfigDir, options.defaults.configFile);\n tracker = trackConfigSources(rawFileConfig, configFilePath, 0);\n\n // Include the directory in discovered, and in resolved only if it had config\n discoveredDirs = [{\n path: resolvedConfigDir,\n level: 0\n }];\n if (rawFileConfig && Object.keys(rawFileConfig).length > 0) {\n resolvedConfigDirs = [{\n path: resolvedConfigDir,\n level: 0\n }];\n } else {\n resolvedConfigDirs = [];\n }\n }\n } else {\n // Use traditional single directory configuration loading\n logger.verbose('Using single directory configuration loading for source tracking');\n rawFileConfig = await loadSingleDirectoryConfig(resolvedConfigDir, options, logger);\n const configFilePath = path.join(resolvedConfigDir, options.defaults.configFile);\n tracker = trackConfigSources(rawFileConfig, configFilePath, 0);\n\n // Include the directory in discovered, and in resolved only if it had config\n discoveredDirs = [{\n path: resolvedConfigDir,\n level: 0\n }];\n if (rawFileConfig && Object.keys(rawFileConfig).length > 0) {\n resolvedConfigDirs = [{\n path: resolvedConfigDir,\n level: 0\n }];\n } else {\n resolvedConfigDirs = [];\n }\n }\n\n // Apply path resolution if configured (this doesn't change source tracking)\n let processedConfig = rawFileConfig;\n if (options.defaults.pathResolution?.pathFields) {\n processedConfig = resolveConfigPaths(\n rawFileConfig,\n resolvedConfigDir,\n options.defaults.pathResolution.pathFields,\n options.defaults.pathResolution.resolvePathArray || []\n );\n }\n\n // Build final configuration including built-in values\n const finalConfig = clean({\n ...processedConfig,\n configDirectory: resolvedConfigDir,\n discoveredConfigDirs: discoveredDirs.map(dir => dir.path),\n resolvedConfigDirs: resolvedConfigDirs.map(dir => dir.path),\n });\n\n // Add built-in configuration to tracker\n tracker['configDirectory'] = {\n value: resolvedConfigDir,\n sourcePath: 'built-in',\n level: -1,\n sourceLabel: 'Built-in (runtime)'\n };\n\n tracker['discoveredConfigDirs'] = {\n value: discoveredDirs.map(dir => dir.path),\n sourcePath: 'built-in',\n level: -1,\n sourceLabel: 'Built-in (runtime)'\n };\n\n tracker['resolvedConfigDirs'] = {\n value: resolvedConfigDirs.map(dir => dir.path),\n sourcePath: 'built-in',\n level: -1,\n sourceLabel: 'Built-in (runtime)'\n };\n\n // Display the configuration with source information\n displayConfigWithSources(finalConfig, tracker, discoveredDirs, logger);\n};"],"names":["clean","obj","Object","fromEntries","entries","filter","_","v","undefined","resolveConfigPaths","config","configDir","pathFields","resolvePathArray","length","resolvedConfig","fieldPath","value","getNestedValue","shouldResolveArrayElements","includes","resolvedValue","resolvePathValue","setNestedValue","path","split","reduce","current","key","isUnsafeKey","keys","lastKey","pop","some","target","resolveArrayElements","resolveSinglePath","Array","isArray","map","item","pathStr","isAbsolute","resolve","validatePath","userPath","basePath","Error","normalized","normalize","startsWith","join","validateConfigDirectory","read","args","options","logger","rawConfigDir","configDirectory","defaults","resolvedConfigDir","verbose","rawFileConfig","discoveredConfigDirs","resolvedConfigDirs","features","configDirName","basename","startingDir","dirname","debug","hierarchicalResult","loadHierarchicalConfig","configFileName","configFile","encoding","pathResolution","fieldOverlaps","discoveredDirs","dir","forEach","level","errors","error","warn","message","loadSingleDirectoryConfig","processedConfig","findConfigFileWithExtension","storage","configFilePath","exists","isReadable","isFileReadable","ext","extname","baseName","alternativeExt","alternativeFileName","alternativePath","altExists","altIsReadable","Storage","log","yamlContent","readFile","parsedYaml","yaml","load","test","code","trackConfigSources","sourcePath","prefix","tracker","sourceLabel","mergeConfigTrackers","trackers","merged","info","formatConfigValue","toString","slice","String","displayConfigWithSources","repeat","sort","a","b","precedence","Math","max","d","sortedKeys","maxKeyLength","k","maxSourceLength","values","paddedKey","padEnd","paddedSource","formattedValue","sourceCount","source","count","checkConf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I,CAAA;QACzCwF,UAAAA,EAAY,UAAA;AACZ/B,QAAAA,KAAAA,EAAO,EAAC;QACRkC,WAAAA,EAAa;AACjB,KAAA;IAEAD,OAAO,CAAC,qBAAqB,GAAG;AAC5BjG,QAAAA,KAAAA,EAAO+C,mBAAmBzB,GAAG,CAACwC,CAAAA,GAAAA,GAAOA,IAAIvD,IAAI,CAAA;QAC7CwF,UAAAA,EAAY,UAAA;AACZ/B,QAAAA,KAAAA,EAAO,EAAC;QACRkC,WAAAA,EAAa;AACjB,KAAA;;IAGAS,wBAAAA,CAAyByB,WAAAA,EAAanC,SAASpC,cAAAA,EAAgBtB,MAAAA,CAAAA;AACnE;;;;"}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { Logger } from '../types';
|
|
2
|
+
import { SecurityValidationError, SecurityErrorCode, SecurityProfile } from './types';
|
|
3
|
+
/**
|
|
4
|
+
* Security event types for audit logging.
|
|
5
|
+
*/
|
|
6
|
+
export type SecurityEventType = 'VALIDATION_STARTED' | 'VALIDATION_PASSED' | 'VALIDATION_FAILED' | 'PATH_BLOCKED' | 'NUMERIC_REJECTED' | 'STRING_REJECTED' | 'PROFILE_CHANGED' | 'CONFIG_LOADED' | 'SUSPICIOUS_PATTERN';
|
|
7
|
+
/**
|
|
8
|
+
* Security event severity levels.
|
|
9
|
+
*/
|
|
10
|
+
export type SecuritySeverity = 'info' | 'warning' | 'error' | 'critical';
|
|
11
|
+
/**
|
|
12
|
+
* Security audit event.
|
|
13
|
+
*/
|
|
14
|
+
export interface SecurityAuditEvent {
|
|
15
|
+
/** Event type */
|
|
16
|
+
type: SecurityEventType;
|
|
17
|
+
/** Event severity */
|
|
18
|
+
severity: SecuritySeverity;
|
|
19
|
+
/** ISO timestamp */
|
|
20
|
+
timestamp: string;
|
|
21
|
+
/** Source of the event (cli, config, etc.) */
|
|
22
|
+
source: string;
|
|
23
|
+
/** Human-readable message */
|
|
24
|
+
message: string;
|
|
25
|
+
/** Structured event details */
|
|
26
|
+
details: Record<string, unknown>;
|
|
27
|
+
/** Associated error code if applicable */
|
|
28
|
+
errorCode?: SecurityErrorCode;
|
|
29
|
+
/** Request/session ID for correlation */
|
|
30
|
+
correlationId?: string;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Audit logger configuration.
|
|
34
|
+
*/
|
|
35
|
+
export interface AuditLoggerConfig {
|
|
36
|
+
/** Whether audit logging is enabled */
|
|
37
|
+
enabled: boolean;
|
|
38
|
+
/** Minimum severity level to log */
|
|
39
|
+
minSeverity: SecuritySeverity;
|
|
40
|
+
/** Whether to include sensitive details (sanitized in production) */
|
|
41
|
+
includeSensitiveDetails: boolean;
|
|
42
|
+
/** Custom correlation ID generator */
|
|
43
|
+
correlationIdGenerator?: () => string;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* SecurityAuditLogger provides structured security event logging.
|
|
47
|
+
*/
|
|
48
|
+
export declare class SecurityAuditLogger {
|
|
49
|
+
private config;
|
|
50
|
+
private logger?;
|
|
51
|
+
private correlationId?;
|
|
52
|
+
private eventBuffer;
|
|
53
|
+
private maxBufferSize;
|
|
54
|
+
constructor(logger?: Logger, config?: Partial<AuditLoggerConfig>);
|
|
55
|
+
/**
|
|
56
|
+
* Set correlation ID for event grouping.
|
|
57
|
+
*/
|
|
58
|
+
setCorrelationId(id: string): this;
|
|
59
|
+
/**
|
|
60
|
+
* Generate a new correlation ID.
|
|
61
|
+
*/
|
|
62
|
+
generateCorrelationId(): string;
|
|
63
|
+
/**
|
|
64
|
+
* Log validation started.
|
|
65
|
+
*/
|
|
66
|
+
validationStarted(source: string, fieldCount: number): void;
|
|
67
|
+
/**
|
|
68
|
+
* Log validation passed.
|
|
69
|
+
*/
|
|
70
|
+
validationPassed(source: string, warningCount?: number): void;
|
|
71
|
+
/**
|
|
72
|
+
* Log validation failed.
|
|
73
|
+
*/
|
|
74
|
+
validationFailed(source: string, errors: SecurityValidationError[]): void;
|
|
75
|
+
/**
|
|
76
|
+
* Log path blocked.
|
|
77
|
+
*/
|
|
78
|
+
pathBlocked(path: string, reason: string, source: string, errorCode?: SecurityErrorCode): void;
|
|
79
|
+
/**
|
|
80
|
+
* Log numeric value rejected.
|
|
81
|
+
*/
|
|
82
|
+
numericRejected(field: string, _value: number, reason: string, source: string): void;
|
|
83
|
+
/**
|
|
84
|
+
* Log string value rejected.
|
|
85
|
+
*/
|
|
86
|
+
stringRejected(field: string, reason: string, source: string, errorCode?: SecurityErrorCode): void;
|
|
87
|
+
/**
|
|
88
|
+
* Log profile change.
|
|
89
|
+
*/
|
|
90
|
+
profileChanged(oldProfile: SecurityProfile, newProfile: SecurityProfile): void;
|
|
91
|
+
/**
|
|
92
|
+
* Log config loaded.
|
|
93
|
+
*/
|
|
94
|
+
configLoaded(filePath: string, fieldCount: number): void;
|
|
95
|
+
/**
|
|
96
|
+
* Log suspicious pattern detected.
|
|
97
|
+
*/
|
|
98
|
+
suspiciousPattern(field: string, pattern: string, source: string): void;
|
|
99
|
+
/**
|
|
100
|
+
* Get buffered events (for testing/export).
|
|
101
|
+
*/
|
|
102
|
+
getBufferedEvents(): SecurityAuditEvent[];
|
|
103
|
+
/**
|
|
104
|
+
* Clear event buffer.
|
|
105
|
+
*/
|
|
106
|
+
clearBuffer(): void;
|
|
107
|
+
/**
|
|
108
|
+
* Core event logging.
|
|
109
|
+
*/
|
|
110
|
+
private logEvent;
|
|
111
|
+
/**
|
|
112
|
+
* Format event for logging.
|
|
113
|
+
*/
|
|
114
|
+
private formatLogMessage;
|
|
115
|
+
/**
|
|
116
|
+
* Sanitize path for logging (remove sensitive parts).
|
|
117
|
+
*/
|
|
118
|
+
private sanitizePath;
|
|
119
|
+
/**
|
|
120
|
+
* Sanitize errors for logging.
|
|
121
|
+
*/
|
|
122
|
+
private sanitizeErrors;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Create an audit logger.
|
|
126
|
+
*/
|
|
127
|
+
export declare function createAuditLogger(logger?: Logger, config?: Partial<AuditLoggerConfig>): SecurityAuditLogger;
|
|
128
|
+
/**
|
|
129
|
+
* Get the global audit logger.
|
|
130
|
+
*/
|
|
131
|
+
export declare function getAuditLogger(): SecurityAuditLogger;
|
|
132
|
+
/**
|
|
133
|
+
* Configure the global audit logger.
|
|
134
|
+
*/
|
|
135
|
+
export declare function configureAuditLogger(logger?: Logger, config?: Partial<AuditLoggerConfig>): void;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { SecurityValidationConfig, SecurityValidationResult } from './types';
|
|
3
|
+
/**
|
|
4
|
+
* Metadata about a CLI option for security validation.
|
|
5
|
+
*/
|
|
6
|
+
export interface CLIOptionSecurityMeta {
|
|
7
|
+
/** Option name (e.g., '--config-directory') */
|
|
8
|
+
name: string;
|
|
9
|
+
/** Type of validation to apply */
|
|
10
|
+
type: 'path' | 'number' | 'string' | 'enum' | 'boolean';
|
|
11
|
+
/** Whether this is a path that needs security validation */
|
|
12
|
+
isPath?: boolean;
|
|
13
|
+
/** Numeric bounds if type is 'number' */
|
|
14
|
+
bounds?: {
|
|
15
|
+
min: number;
|
|
16
|
+
max: number;
|
|
17
|
+
integer?: boolean;
|
|
18
|
+
};
|
|
19
|
+
/** Pattern if type is 'string' */
|
|
20
|
+
pattern?: RegExp;
|
|
21
|
+
/** Allowed values if type is 'enum' */
|
|
22
|
+
allowedValues?: string[];
|
|
23
|
+
/** Whether the option is required */
|
|
24
|
+
required?: boolean;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* CLIValidator provides security validation for Commander.js options.
|
|
28
|
+
*/
|
|
29
|
+
export declare class CLIValidator {
|
|
30
|
+
private pathGuard;
|
|
31
|
+
private numericGuard;
|
|
32
|
+
private stringGuard;
|
|
33
|
+
private config;
|
|
34
|
+
private optionMeta;
|
|
35
|
+
constructor(config?: Partial<SecurityValidationConfig>);
|
|
36
|
+
/**
|
|
37
|
+
* Register security metadata for a CLI option.
|
|
38
|
+
*/
|
|
39
|
+
registerOption(meta: CLIOptionSecurityMeta): this;
|
|
40
|
+
/**
|
|
41
|
+
* Register multiple options at once.
|
|
42
|
+
*/
|
|
43
|
+
registerOptions(metas: CLIOptionSecurityMeta[]): this;
|
|
44
|
+
/**
|
|
45
|
+
* Extract security metadata from a Zod schema.
|
|
46
|
+
* Looks for special markers in the schema to determine validation requirements.
|
|
47
|
+
*/
|
|
48
|
+
registerFromSchema<T extends z.ZodRawShape>(schema: z.ZodObject<T>, optionMapping?: Record<string, string>): this;
|
|
49
|
+
/**
|
|
50
|
+
* Validate all CLI arguments against registered security metadata.
|
|
51
|
+
*/
|
|
52
|
+
validateArgs(args: Record<string, unknown>): SecurityValidationResult;
|
|
53
|
+
/**
|
|
54
|
+
* Validate a single value against its security metadata.
|
|
55
|
+
*/
|
|
56
|
+
private validateValue;
|
|
57
|
+
/**
|
|
58
|
+
* Extract validation metadata from a Zod field schema.
|
|
59
|
+
*/
|
|
60
|
+
private extractMetaFromZod;
|
|
61
|
+
/**
|
|
62
|
+
* Convert camelCase to kebab-case.
|
|
63
|
+
*/
|
|
64
|
+
private camelToKebab;
|
|
65
|
+
/**
|
|
66
|
+
* Convert option name (--config-directory) to arg key (configDirectory).
|
|
67
|
+
*/
|
|
68
|
+
private optionNameToArgKey;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Create a CLI validator with the given configuration.
|
|
72
|
+
*/
|
|
73
|
+
export declare function createCLIValidator(config?: Partial<SecurityValidationConfig>): CLIValidator;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { SecurityValidationConfig, SecurityValidationResult } from './types';
|
|
3
|
+
/**
|
|
4
|
+
* Field-level security metadata for config validation.
|
|
5
|
+
*/
|
|
6
|
+
export interface ConfigFieldSecurityMeta {
|
|
7
|
+
/** Field path in dot notation (e.g., 'api.timeout') */
|
|
8
|
+
fieldPath: string;
|
|
9
|
+
/** Type of validation to apply */
|
|
10
|
+
type: 'path' | 'number' | 'string' | 'enum' | 'array' | 'object';
|
|
11
|
+
/** Whether this field contains a path */
|
|
12
|
+
isPath?: boolean;
|
|
13
|
+
/** Numeric bounds if type is 'number' */
|
|
14
|
+
bounds?: {
|
|
15
|
+
min: number;
|
|
16
|
+
max: number;
|
|
17
|
+
integer?: boolean;
|
|
18
|
+
};
|
|
19
|
+
/** Pattern if type is 'string' */
|
|
20
|
+
pattern?: RegExp;
|
|
21
|
+
/** Allowed values if type is 'enum' */
|
|
22
|
+
allowedValues?: string[];
|
|
23
|
+
/** Array element validation (recursive) */
|
|
24
|
+
arrayElementMeta?: Omit<ConfigFieldSecurityMeta, 'fieldPath'>;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Context about where a config value came from.
|
|
28
|
+
*/
|
|
29
|
+
export interface ConfigValueSource {
|
|
30
|
+
/** Which config file the value came from */
|
|
31
|
+
file: string;
|
|
32
|
+
/** Line number in the file (if available) */
|
|
33
|
+
line?: number;
|
|
34
|
+
/** Hierarchical level (0 = most specific) */
|
|
35
|
+
level: number;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* ConfigValidator provides security validation for configuration file values.
|
|
39
|
+
*/
|
|
40
|
+
export declare class ConfigValidator {
|
|
41
|
+
private pathGuard;
|
|
42
|
+
private numericGuard;
|
|
43
|
+
private stringGuard;
|
|
44
|
+
private config;
|
|
45
|
+
private fieldMeta;
|
|
46
|
+
constructor(config?: Partial<SecurityValidationConfig>);
|
|
47
|
+
/**
|
|
48
|
+
* Register security metadata for a config field.
|
|
49
|
+
*/
|
|
50
|
+
registerField(meta: ConfigFieldSecurityMeta): this;
|
|
51
|
+
/**
|
|
52
|
+
* Register multiple fields at once.
|
|
53
|
+
*/
|
|
54
|
+
registerFields(metas: ConfigFieldSecurityMeta[]): this;
|
|
55
|
+
/**
|
|
56
|
+
* Extract security metadata from a Zod schema.
|
|
57
|
+
*/
|
|
58
|
+
registerFromSchema<T extends z.ZodRawShape>(schema: z.ZodObject<T>): this;
|
|
59
|
+
/**
|
|
60
|
+
* Validate a configuration object with source tracking.
|
|
61
|
+
*/
|
|
62
|
+
validateConfig(config: Record<string, unknown>, sources?: Map<string, ConfigValueSource>): SecurityValidationResult;
|
|
63
|
+
/**
|
|
64
|
+
* Validate a single config file's content before merging.
|
|
65
|
+
*/
|
|
66
|
+
validateSingleFile(content: Record<string, unknown>, filePath: string, level?: number): SecurityValidationResult;
|
|
67
|
+
/**
|
|
68
|
+
* Recursively validate an object and its nested values.
|
|
69
|
+
*/
|
|
70
|
+
private validateObject;
|
|
71
|
+
/**
|
|
72
|
+
* Validate a single value against its security metadata.
|
|
73
|
+
*/
|
|
74
|
+
private validateValue;
|
|
75
|
+
/**
|
|
76
|
+
* Check for fields not covered by security metadata.
|
|
77
|
+
*/
|
|
78
|
+
private checkUnregisteredFields;
|
|
79
|
+
/**
|
|
80
|
+
* Walk a Zod schema to extract field metadata.
|
|
81
|
+
*/
|
|
82
|
+
private walkSchema;
|
|
83
|
+
/**
|
|
84
|
+
* Extract field metadata from a Zod schema.
|
|
85
|
+
*/
|
|
86
|
+
private extractMetaFromZod;
|
|
87
|
+
/**
|
|
88
|
+
* Walk an object and call a callback for each field path.
|
|
89
|
+
*/
|
|
90
|
+
private walkObject;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Create a config validator with the given configuration.
|
|
94
|
+
*/
|
|
95
|
+
export declare function createConfigValidator(config?: Partial<SecurityValidationConfig>): ConfigValidator;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { SecurityValidationConfig } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Development profile - permissive, warnings instead of errors.
|
|
4
|
+
*/
|
|
5
|
+
export declare const DEVELOPMENT_SECURITY_CONFIG: SecurityValidationConfig;
|
|
6
|
+
/**
|
|
7
|
+
* Production profile - strict validation, fail on any violation.
|
|
8
|
+
*/
|
|
9
|
+
export declare const PRODUCTION_SECURITY_CONFIG: SecurityValidationConfig;
|
|
10
|
+
/**
|
|
11
|
+
* Get security configuration for a profile.
|
|
12
|
+
*/
|
|
13
|
+
export declare function getSecurityConfig(profile: 'development' | 'production'): SecurityValidationConfig;
|
|
14
|
+
/**
|
|
15
|
+
* Merge user config with defaults for a profile.
|
|
16
|
+
*/
|
|
17
|
+
export declare function mergeSecurityConfig(userConfig: Partial<SecurityValidationConfig>, profile?: 'development' | 'production'): SecurityValidationConfig;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export * from './types';
|
|
2
|
+
export * from './defaults';
|
|
3
|
+
export * from './zod-secure-path';
|
|
4
|
+
export * from './zod-secure-number';
|
|
5
|
+
export * from './zod-secure-string';
|
|
6
|
+
export * from './zod-secure-enum';
|
|
7
|
+
export * from './path-guard';
|
|
8
|
+
export * from './numeric-guard';
|
|
9
|
+
export * from './string-guard';
|
|
10
|
+
export * from './cli-validator';
|
|
11
|
+
export * from './config-validator';
|
|
12
|
+
export * from './security-validator';
|
|
13
|
+
export * from './profiles';
|
|
14
|
+
export * from './audit-logger';
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { NumericSecurityOptions } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Common numeric ranges for security-sensitive options.
|
|
4
|
+
*/
|
|
5
|
+
export declare const SAFE_RANGES: {
|
|
6
|
+
/** Port numbers: 1-65535 */
|
|
7
|
+
readonly port: {
|
|
8
|
+
readonly min: 1;
|
|
9
|
+
readonly max: 65535;
|
|
10
|
+
};
|
|
11
|
+
/** Timeout in ms: 0 to 5 minutes */
|
|
12
|
+
readonly timeout: {
|
|
13
|
+
readonly min: 0;
|
|
14
|
+
readonly max: 300000;
|
|
15
|
+
};
|
|
16
|
+
/** Retry count: 0-10 */
|
|
17
|
+
readonly retries: {
|
|
18
|
+
readonly min: 0;
|
|
19
|
+
readonly max: 10;
|
|
20
|
+
};
|
|
21
|
+
/** Percentage: 0-100 */
|
|
22
|
+
readonly percentage: {
|
|
23
|
+
readonly min: 0;
|
|
24
|
+
readonly max: 100;
|
|
25
|
+
};
|
|
26
|
+
/** Concurrency: 1-100 */
|
|
27
|
+
readonly concurrency: {
|
|
28
|
+
readonly min: 1;
|
|
29
|
+
readonly max: 100;
|
|
30
|
+
};
|
|
31
|
+
/** Temperature (AI): 0-2 */
|
|
32
|
+
readonly temperature: {
|
|
33
|
+
readonly min: 0;
|
|
34
|
+
readonly max: 2;
|
|
35
|
+
};
|
|
36
|
+
/** Max tokens: 1 to 1M */
|
|
37
|
+
readonly maxTokens: {
|
|
38
|
+
readonly min: 1;
|
|
39
|
+
readonly max: 1000000;
|
|
40
|
+
};
|
|
41
|
+
/** File size in bytes: 0 to 100MB */
|
|
42
|
+
readonly fileSize: {
|
|
43
|
+
readonly min: 0;
|
|
44
|
+
readonly max: number;
|
|
45
|
+
};
|
|
46
|
+
/** Line count: 0 to 1M */
|
|
47
|
+
readonly lineCount: {
|
|
48
|
+
readonly min: 0;
|
|
49
|
+
readonly max: 1000000;
|
|
50
|
+
};
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* NumericGuard provides secure numeric validation with bounds checking.
|
|
54
|
+
*/
|
|
55
|
+
export declare class NumericGuard {
|
|
56
|
+
private options;
|
|
57
|
+
constructor(options?: Partial<NumericSecurityOptions>);
|
|
58
|
+
/**
|
|
59
|
+
* Validate a numeric value against bounds and edge cases.
|
|
60
|
+
*
|
|
61
|
+
* @param value - The value to validate (can be string for CLI parsing)
|
|
62
|
+
* @param bounds - Min/max bounds for the value
|
|
63
|
+
* @param fieldName - Field name for error messages
|
|
64
|
+
* @returns The validated number
|
|
65
|
+
* @throws Error if validation fails
|
|
66
|
+
*/
|
|
67
|
+
validate(value: unknown, bounds: {
|
|
68
|
+
min: number;
|
|
69
|
+
max: number;
|
|
70
|
+
integer?: boolean;
|
|
71
|
+
}, fieldName?: string): number;
|
|
72
|
+
/**
|
|
73
|
+
* Validate using a predefined safe range.
|
|
74
|
+
*/
|
|
75
|
+
validateRange(value: unknown, rangeName: keyof typeof SAFE_RANGES, fieldName?: string): number;
|
|
76
|
+
/**
|
|
77
|
+
* Validate with optional default value.
|
|
78
|
+
*/
|
|
79
|
+
validateWithDefault(value: unknown, bounds: {
|
|
80
|
+
min: number;
|
|
81
|
+
max: number;
|
|
82
|
+
integer?: boolean;
|
|
83
|
+
}, defaultValue: number, fieldName?: string): number;
|
|
84
|
+
/**
|
|
85
|
+
* Parse and validate a CLI numeric argument.
|
|
86
|
+
*/
|
|
87
|
+
parseCliArg(value: string | undefined, bounds: {
|
|
88
|
+
min: number;
|
|
89
|
+
max: number;
|
|
90
|
+
integer?: boolean;
|
|
91
|
+
default?: number;
|
|
92
|
+
}, fieldName: string): number;
|
|
93
|
+
/**
|
|
94
|
+
* Validate multiple numeric fields at once.
|
|
95
|
+
*/
|
|
96
|
+
validateMany(values: Record<string, unknown>, schemas: Record<string, {
|
|
97
|
+
min: number;
|
|
98
|
+
max: number;
|
|
99
|
+
integer?: boolean;
|
|
100
|
+
optional?: boolean;
|
|
101
|
+
}>): Record<string, number>;
|
|
102
|
+
private createError;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Get the default NumericGuard instance.
|
|
106
|
+
*/
|
|
107
|
+
export declare function getNumericGuard(): NumericGuard;
|
|
108
|
+
/**
|
|
109
|
+
* Create a new NumericGuard with custom options.
|
|
110
|
+
*/
|
|
111
|
+
export declare function createNumericGuard(options: Partial<NumericSecurityOptions>): NumericGuard;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { PathSecurityOptions, SecurityValidationError } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* PathGuard provides comprehensive path security validation.
|
|
4
|
+
*/
|
|
5
|
+
export declare class PathGuard {
|
|
6
|
+
private options;
|
|
7
|
+
private resolvedBaseDirs;
|
|
8
|
+
constructor(options?: Partial<PathSecurityOptions>);
|
|
9
|
+
/**
|
|
10
|
+
* Validate a path for security issues.
|
|
11
|
+
*
|
|
12
|
+
* @param inputPath - The path to validate
|
|
13
|
+
* @param operation - The intended operation (for error messages)
|
|
14
|
+
* @returns The validated and normalized path
|
|
15
|
+
* @throws Error if validation fails
|
|
16
|
+
*/
|
|
17
|
+
validate(inputPath: string, operation?: string): string;
|
|
18
|
+
/**
|
|
19
|
+
* Validate a path or throw with security error details.
|
|
20
|
+
*/
|
|
21
|
+
validateOrThrow(inputPath: string, operation?: string): string;
|
|
22
|
+
/**
|
|
23
|
+
* Validate a path and return result without throwing.
|
|
24
|
+
*/
|
|
25
|
+
validateSafe(inputPath: string): {
|
|
26
|
+
valid: boolean;
|
|
27
|
+
path?: string;
|
|
28
|
+
errors: SecurityValidationError[];
|
|
29
|
+
};
|
|
30
|
+
private checkDangerousChars;
|
|
31
|
+
private checkPathLength;
|
|
32
|
+
private checkTraversalPatterns;
|
|
33
|
+
private checkAbsolutePath;
|
|
34
|
+
private checkTraversalAfterNormalize;
|
|
35
|
+
private checkHiddenFiles;
|
|
36
|
+
private checkExtension;
|
|
37
|
+
private checkBaseDirConstraints;
|
|
38
|
+
private checkSymlinks;
|
|
39
|
+
private sanitizeForError;
|
|
40
|
+
private createError;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Get the default PathGuard instance.
|
|
44
|
+
*/
|
|
45
|
+
export declare function getPathGuard(): PathGuard;
|
|
46
|
+
/**
|
|
47
|
+
* Create a new PathGuard with custom options.
|
|
48
|
+
*/
|
|
49
|
+
export declare function createPathGuard(options: Partial<PathSecurityOptions>): PathGuard;
|
|
50
|
+
/**
|
|
51
|
+
* Configure the default PathGuard instance.
|
|
52
|
+
*/
|
|
53
|
+
export declare function configurePathGuard(options: Partial<PathSecurityOptions>): void;
|