[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill-1a4f0746-14fe-44c5-8078-983fae9ef07b":3,"$fZygwUX0yj2G3w7DDczPzSVJ7Qr2H2OIGDrqGWFgdiEY":43},{"id":4,"title":5,"description":6,"categoryId":7,"moduleId":8,"tags":9,"prompt":10,"icon":11,"source":12,"sourceUrl":13,"authorId":14,"authorName":15,"isPublic":16,"stars":17,"runs":18,"createdAt":19,"updatedAt":19,"module":20,"category":27,"packages":34},"1a4f0746-14fe-44c5-8078-983fae9ef07b","deployment-validation-config-validate","您是一位专注于验证、测试和确保应用程序配置正确性的配置管理专家。创建全面的验证方案，实施配置","cat_coding_devops","mod_coding","sickn33,coding","---\nname: deployment-validation-config-validate\ndescription: \"You are a configuration management expert specializing in validating, testing, and ensuring the correctness of application configurations. Create comprehensive validation schemas, implement configurat\"\nrisk: critical\nsource: community\ndate_added: \"2026-02-27\"\n---\n\n# Configuration Validation\n\nYou are a configuration management expert specializing in validating, testing, and ensuring the correctness of application configurations. Create comprehensive validation schemas, implement configuration testing strategies, and ensure configurations are secure, consistent, and error-free across all environments.\n\n## Use this skill when\n\n- Working on configuration validation tasks or workflows\n- Needing guidance, best practices, or checklists for configuration validation\n\n## Do not use this skill when\n\n- The task is unrelated to configuration validation\n- You need a different domain or tool outside this scope\n\n## Context\nThe user needs to validate configuration files, implement configuration schemas, ensure consistency across environments, and prevent configuration-related errors. Focus on creating robust validation rules, type safety, security checks, and automated validation processes.\n\n## Requirements\n$ARGUMENTS\n\n## Instructions\n\n### 1. Configuration Analysis\n\nAnalyze existing configuration structure and identify validation needs:\n\n```python\nimport os\nimport yaml\nimport json\nfrom pathlib import Path\nfrom typing import Dict, List, Any\n\nclass ConfigurationAnalyzer:\n    def analyze_project(self, project_path: str) -> Dict[str, Any]:\n        analysis = {\n            'config_files': self._find_config_files(project_path),\n            'security_issues': self._check_security_issues(project_path),\n            'consistency_issues': self._check_consistency(project_path),\n            'recommendations': []\n        }\n        return analysis\n\n    def _find_config_files(self, project_path: str) -> List[Dict]:\n        config_patterns = [\n            '**\u002F*.json', '**\u002F*.yaml', '**\u002F*.yml', '**\u002F*.toml',\n            '**\u002F*.ini', '**\u002F*.env*', '**\u002Fconfig.js'\n        ]\n\n        config_files = []\n        for pattern in config_patterns:\n            for file_path in Path(project_path).glob(pattern):\n                if not self._should_ignore(file_path):\n                    config_files.append({\n                        'path': str(file_path),\n                        'type': self._detect_config_type(file_path),\n                        'environment': self._detect_environment(file_path)\n                    })\n        return config_files\n\n    def _check_security_issues(self, project_path: str) -> List[Dict]:\n        issues = []\n        secret_patterns = [\n            r'(api[_-]?key|apikey)',\n            r'(secret|password|passwd)',\n            r'(token|auth)',\n            r'(aws[_-]?access)'\n        ]\n\n        for config_file in self._find_config_files(project_path):\n            content = Path(config_file['path']).read_text()\n            for pattern in secret_patterns:\n                if re.search(pattern, content, re.IGNORECASE):\n                    if self._looks_like_real_secret(content, pattern):\n                        issues.append({\n                            'file': config_file['path'],\n                            'type': 'potential_secret',\n                            'severity': 'high'\n                        })\n        return issues\n```\n\n### 2. Schema Validation\n\nImplement configuration schema validation with JSON Schema:\n\n```typescript\nimport Ajv from 'ajv';\nimport ajvFormats from 'ajv-formats';\nimport { JSONSchema7 } from 'json-schema';\n\ninterface ValidationResult {\n  valid: boolean;\n  errors?: Array\u003C{\n    path: string;\n    message: string;\n    keyword: string;\n  }>;\n}\n\nexport class ConfigValidator {\n  private ajv: Ajv;\n\n  constructor() {\n    this.ajv = new Ajv({\n      allErrors: true,\n      strict: false,\n      coerceTypes: true\n    });\n    ajvFormats(this.ajv);\n    this.addCustomFormats();\n  }\n\n  private addCustomFormats() {\n    this.ajv.addFormat('url-https', {\n      type: 'string',\n      validate: (data: string) => {\n        try {\n          return new URL(data).protocol === 'https:';\n        } catch { return false; }\n      }\n    });\n\n    this.ajv.addFormat('port', {\n      type: 'number',\n      validate: (data: number) => data >= 1 && data \u003C= 65535\n    });\n\n    this.ajv.addFormat('duration', {\n      type: 'string',\n      validate: \u002F^\\d+[smhd]$\u002F\n    });\n  }\n\n  validate(configData: any, schemaName: string): ValidationResult {\n    const validate = this.ajv.getSchema(schemaName);\n    if (!validate) throw new Error(`Schema '${schemaName}' not found`);\n\n    const valid = validate(configData);\n\n    if (!valid && validate.errors) {\n      return {\n        valid: false,\n        errors: validate.errors.map(error => ({\n          path: error.instancePath || '\u002F',\n          message: error.message || 'Validation error',\n          keyword: error.keyword\n        }))\n      };\n    }\n    return { valid: true };\n  }\n}\n\n\u002F\u002F Example schema\nexport const schemas = {\n  database: {\n    type: 'object',\n    properties: {\n      host: { type: 'string', format: 'hostname' },\n      port: { type: 'integer', format: 'port' },\n      database: { type: 'string', minLength: 1 },\n      user: { type: 'string', minLength: 1 },\n      password: { type: 'string', minLength: 8 },\n      ssl: {\n        type: 'object',\n        properties: {\n          enabled: { type: 'boolean' }\n        },\n        required: ['enabled']\n      }\n    },\n    required: ['host', 'port', 'database', 'user', 'password']\n  }\n};\n```\n\n### 3. Environment-Specific Validation\n\n```python\nfrom typing import Dict, List, Any\n\nclass EnvironmentValidator:\n    def __init__(self):\n        self.environments = ['development', 'staging', 'production']\n        self.environment_rules = {\n            'development': {\n                'allow_debug': True,\n                'require_https': False,\n                'min_password_length': 8\n            },\n            'production': {\n                'allow_debug': False,\n                'require_https': True,\n                'min_password_length': 16,\n                'require_encryption': True\n            }\n        }\n\n    def validate_config(self, config: Dict, environment: str) -> List[Dict]:\n        if environment not in self.environment_rules:\n            raise ValueError(f\"Unknown environment: {environment}\")\n\n        rules = self.environment_rules[environment]\n        violations = []\n\n        if not rules['allow_debug'] and config.get('debug', False):\n            violations.append({\n                'rule': 'no_debug_in_production',\n                'message': 'Debug mode not allowed in production',\n                'severity': 'critical'\n            })\n\n        if rules['require_https']:\n            urls = self._extract_urls(config)\n            for url_path, url in urls:\n                if url.startswith('http:\u002F\u002F') and 'localhost' not in url:\n                    violations.append({\n                        'rule': 'require_https',\n                        'message': f'HTTPS required for {url_path}',\n                        'severity': 'high'\n                    })\n\n        return violations\n```\n\n### 4. Configuration Testing\n\n```typescript\nimport { describe, it, expect } from '@jest\u002Fglobals';\nimport { ConfigValidator } from '.\u002Fconfig-validator';\n\ndescribe('Configuration Validation', () => {\n  let validator: ConfigValidator;\n\n  beforeEach(() => {\n    validator = new ConfigValidator();\n  });\n\n  it('should validate database config', () => {\n    const config = {\n      host: 'localhost',\n      port: 5432,\n      database: 'myapp',\n      user: 'dbuser',\n      password: 'securepass123'\n    };\n\n    const result = validator.validate(config, 'database');\n    expect(result.valid).toBe(true);\n  });\n\n  it('should reject invalid port', () => {\n    const config = {\n      host: 'localhost',\n      port: 70000,\n      database: 'myapp',\n      user: 'dbuser',\n      password: 'securepass123'\n    };\n\n    const result = validator.validate(config, 'database');\n    expect(result.valid).toBe(false);\n  });\n});\n```\n\n### 5. Runtime Validation\n\n```typescript\nimport { EventEmitter } from 'events';\nimport * as chokidar from 'chokidar';\n\nexport class RuntimeConfigValidator extends EventEmitter {\n  private validator: ConfigValidator;\n  private currentConfig: any;\n\n  async initialize(configPath: string): Promise\u003Cvoid> {\n    this.currentConfig = await this.loadAndValidate(configPath);\n    this.watchConfig(configPath);\n  }\n\n  private async loadAndValidate(configPath: string): Promise\u003Cany> {\n    const config = await this.loadConfig(configPath);\n\n    const validationResult = this.validator.validate(\n      config,\n      this.detectEnvironment()\n    );\n\n    if (!validationResult.valid) {\n      this.emit('validation:error', {\n        path: configPath,\n        errors: validationResult.errors\n      });\n\n      if (!this.isDevelopment()) {\n        throw new Error('Configuration validation failed');\n      }\n    }\n\n    return config;\n  }\n\n  private watchConfig(configPath: string): void {\n    const watcher = chokidar.watch(configPath, {\n      persistent: true,\n      ignoreInitial: true\n    });\n\n    watcher.on('change', async () => {\n      try {\n        const newConfig = await this.loadAndValidate(configPath);\n\n        if (JSON.stringify(newConfig) !== JSON.stringify(this.currentConfig)) {\n          this.emit('config:changed', {\n            oldConfig: this.currentConfig,\n            newConfig\n          });\n          this.currentConfig = newConfig;\n        }\n      } catch (error) {\n        this.emit('config:error', { error });\n      }\n    });\n  }\n}\n```\n\n### 6. Configuration Migration\n\n```python\nfrom typing import Dict\nfrom abc import ABC, abstractmethod\nimport semver\n\nclass ConfigMigration(ABC):\n    @property\n    @abstractmethod\n    def version(self) -> str:\n        pass\n\n    @abstractmethod\n    def up(self, config: Dict) -> Dict:\n        pass\n\n    @abstractmethod\n    def down(self, config: Dict) -> Dict:\n        pass\n\nclass ConfigMigrator:\n    def __init__(self):\n        self.migrations: List[ConfigMigration] = []\n\n    def migrate(self, config: Dict, target_version: str) -> Dict:\n        current_version = config.get('_version', '0.0.0')\n\n        if semver.compare(current_version, target_version) == 0:\n            return config\n\n        result = config.copy()\n        for migration in self.migrations:\n            if (semver.compare(migration.version, current_version) > 0 and\n                semver.compare(migration.version, target_version) \u003C= 0):\n                result = migration.up(result)\n                result['_version'] = migration.version\n\n        return result\n```\n\n### 7. Secure Configuration\n\n```typescript\nimport * as crypto from 'crypto';\n\ninterface EncryptedValue {\n  encrypted: true;\n  value: string;\n  algorithm: string;\n  iv: string;\n  authTag?: string;\n}\n\nexport class SecureConfigManager {\n  private encryptionKey: Buffer;\n\n  constructor(masterKey: string) {\n    this.encryptionKey = crypto.pbkdf2Sync(masterKey, 'config-salt', 100000, 32, 'sha256');\n  }\n\n  encrypt(value: any): EncryptedValue {\n    const algorithm = 'aes-256-gcm';\n    const iv = crypto.randomBytes(16);\n    const cipher = crypto.createCipheriv(algorithm, this.encryptionKey, iv);\n\n    let encrypted = cipher.update(JSON.stringify(value), 'utf8', 'hex');\n    encrypted += cipher.final('hex');\n\n    return {\n      encrypted: true,\n      value: encrypted,\n      algorithm,\n      iv: iv.toString('hex'),\n      authTag: cipher.getAuthTag().toString('hex')\n    };\n  }\n\n  decrypt(encryptedValue: EncryptedValue): any {\n    const decipher = crypto.createDecipheriv(\n      encryptedValue.algorithm,\n      this.encryptionKey,\n      Buffer.from(encryptedValue.iv, 'hex')\n    );\n\n    if (encryptedValue.authTag) {\n      decipher.setAuthTag(Buffer.from(encryptedValue.authTag, 'hex'));\n    }\n\n    let decrypted = decipher.update(encryptedValue.value, 'hex', 'utf8');\n    decrypted += decipher.final('utf8');\n\n    return JSON.parse(decrypted);\n  }\n\n  async processConfig(config: any): Promise\u003Cany> {\n    const processed = {};\n\n    for (const [key, value] of Object.entries(config)) {\n      if (this.isEncryptedValue(value)) {\n        processed[key] = this.decrypt(value as EncryptedValue);\n      } else if (typeof value === 'object' && value !== null) {\n        processed[key] = await this.processConfig(value);\n      } else {\n        processed[key] = value;\n      }\n    }\n\n    return processed;\n  }\n}\n```\n\n### 8. Documentation Generation\n\n```python\nfrom typing import Dict, List\nimport yaml\n\nclass ConfigDocGenerator:\n    def generate_docs(self, schema: Dict, examples: Dict) -> str:\n        docs = [\"# Configuration Reference\\n\"]\n\n        docs.append(\"## Configuration Options\\n\")\n        sections = self._generate_sections(schema.get('properties', {}), examples)\n        docs.extend(sections)\n\n        return '\\n'.join(docs)\n\n    def _generate_sections(self, properties: Dict, examples: Dict, level: int = 3) -> List[str]:\n        sections = []\n\n        for prop_name, prop_schema in properties.items():\n            sections.append(f\"{'#' * level} {prop_name}\\n\")\n\n            if 'description' in prop_schema:\n                sections.append(f\"{prop_schema['description']}\\n\")\n\n            sections.append(f\"**Type:** `{prop_schema.get('type', 'any')}`\\n\")\n\n            if 'default' in prop_schema:\n                sections.append(f\"**Default:** `{prop_schema['default']}`\\n\")\n\n            if prop_name in examples:\n                sections.append(\"**Example:**\\n```yaml\")\n                sections.append(yaml.dump({prop_name: examples[prop_name]}))\n                sections.append(\"```\\n\")\n\n        return sections\n```\n\n## Output Format\n\n1. **Configuration Analysis**: Current configuration assessment\n2. **Validation Schemas**: JSON Schema definitions\n3. **Environment Rules**: Environment-specific validation\n4. **Test Suite**: Configuration tests\n5. **Migration Scripts**: Version migrations\n6. **Security Report**: Issues and recommendations\n7. **Documentation**: Auto-generated reference\n\nFocus on preventing configuration errors, ensuring consistency, and maintaining security best practices.\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n","","imported","https:\u002F\u002Fgithub.com\u002Fsickn33\u002Fantigravity-awesome-skills","user_system_seed","SkillOPIC",true,193,1020,"2026-05-16 13:15:08",{"id":8,"name":21,"slug":22,"icon":23,"description":24,"sort":25,"createdAt":26},"编程开发","coding","mdi-code-braces","代码生成、调试、审查，提升开发效率",2,"2026-05-16 12:53:40",{"id":7,"name":28,"slug":29,"icon":30,"description":31,"moduleId":8,"sort":32,"skillCount":33,"createdAt":26},"DevOps","devops","mdi-cog-outline","CI\u002FCD、容器化、部署运维",3,162,[35],{"id":36,"skillId":4,"version":37,"fileName":38,"fileSize":39,"filePath":40,"fileHash":41,"manifest":42,"createdAt":19},"89d3f72a-7a7b-4559-8915-5b70003159b0","1.0.0","deployment-validation-config-validate.zip",4607,"uploads\u002Fskills\u002F1a4f0746-14fe-44c5-8078-983fae9ef07b\u002Fdeployment-validation-config-validate.zip","d128b3b189ffb5f3ac5995dba9e36a1785a4054950185bb97fcc42229ee4aafb","[{\"path\":\"SKILL.md\",\"isDirectory\":false,\"size\":14528}]",{"code":44,"message":45,"data":46},200,"success",{"items":47,"stats":48,"page":51},[],{"averageRating":49,"totalRatings":49,"ratingCounts":50},0,[49,49,49,49,49],{"limit":52,"offset":49,"hasMore":53,"nextOffset":52,"ratedOnly":16},15,false]