audit-env-variables
暂无简介
- License 许可
- MIT
- 最近更新
- 2026-05-18
- Stars
- ★ 0
- Forks
- 0
02 资源文件 2
- 参考文档references/service-patterns.md7.4 KB
- 参考文档templates/env-audit-report.md3.2 KB
03 SKILL.md 正文
---name: audit-env-variablesdescription: Analyze environment variables in JavaScript/TypeScript projects. Identifies unused variables, infers permission scopes, detects specific services (Stripe, AWS, Supabase), and documents code paths. Includes optional cleanup of unused variables with regression detection. Use when auditing .env files, reviewing security, or documenting project configuration.argument-hint: "[output-path] [--cleanup]"allowed-tools: [Read, Grep, Glob, Bash, Write, Edit, AskUserQuestion]---<objective>Perform a comprehensive audit of environment variables in a JS/TS project:1. Discovery - Find all env files and code references2. Usage Analysis - Identify which variables are used vs unused3. Service Detection - Recognize services (Stripe, AWS, Supabase, etc.) and their permission implications4. Code Path Mapping - Document where each variable is used in the codebase5. Report Generation - Output a structured markdown document6. Cleanup (optional) - Safely remove unused variables with user confirmation7. Regression Prevention - Validate no regressions via build/test validation with automatic rollback</objective><quick_start>Audit only (default):1. Scan for .env* files in project root2. Grep codebase for process.env., import.meta.env., and destructured env patterns3. Cross-reference declared vs used variables4. Identify services by naming patterns and categorize permissions5. Generate markdown report using the templateWith cleanup (--cleanup flag):6. Check for dynamic access patterns that might hide usage7. Present unused variables and get user confirmation8. Create backups, remove confirmed variables9. Run build/tests to detect regressions10. Auto-rollback if regressions detected</quick_start><process>## Step 1: Discover Environment FilesFind all env-related files:bashfind . -maxdepth 2 -name ".env*" -o -name "env.d.ts" | grep -v node_modulesCommon files:- .env - Local development- .env.local - Local overrides- .env.development / .env.production - Environment-specific- .env.example - Template for required variables## Step 2: Extract Declared VariablesParse each env file for variable declarations:Grep pattern: ^[A-Z][A-Z0-9_]+=Build a list of all declared variables with their source file.## Step 3: Find Code ReferencesSearch for environment variable usage patterns:Direct access:process.env.VARIABLE_NAMEimport.meta.env.VARIABLE_NAMEprocess.env["VARIABLE_NAME"]Destructured patterns:javascriptconst { API_KEY, DATABASE_URL } = process.envFramework-specific:javascript// Next.js public varsNEXT_PUBLIC_*// ViteVITE_*Use Grep tool with patterns:process\.env\.([A-Z][A-Z0-9_]+)import\.meta\.env\.([A-Z][A-Z0-9_]+)## Step 4: Cross-Reference UsageFor each declared variable:- Used: Found in code references- Unused: Declared but no code references found- Undeclared: Referenced in code but not in any env fileFlag potential issues:- Unused variables (cleanup candidates)- Undeclared variables (missing from .env.example)- Variables only in .env but not .env.example (documentation gap)## Step 5: Detect Services and Infer PermissionsMatch variable names against known service patterns. See references/service-patterns.md for the complete list.Categories:- Database - Connection strings, credentials- Authentication - JWT secrets, OAuth credentials- Payment - Stripe, payment processor keys- Cloud Services - AWS, GCP, Azure credentials- Third-party APIs - Various service integrations- Feature Flags - Toggle configurations- Application Config - URLs, ports, modesPermission levels:- Critical - Full account access, billing, admin operations- High - Read/write access to user data- Medium - Limited API access, specific operations- Low - Public keys, non-sensitive configuration## Step 6: Map Code PathsFor each used variable, document:- File path where it's used- Function/component context- Purpose (inferred from surrounding code)Example:STRIPE_SECRET_KEYÔö£ÔöÇÔöÇ src/lib/stripe.ts:15 - Stripe client initializationÔö£ÔöÇÔöÇ src/api/webhooks/stripe.ts:8 - Webhook signature verificationÔööÔöÇÔöÇ src/api/checkout/route.ts:23 - Create checkout session## Step 7: Generate ReportUse the template in templates/env-audit-report.md to generate the final document.Output to: ENV_AUDIT.md in project root (or user-specified location)## Step 8: Cleanup Unused Variables (Optional)Trigger: User passes --cleanup flag or explicitly requests cleanup after reviewing the audit report.### 8.1 Present Cleanup CandidatesDisplay unused variables with context:UNUSED VARIABLES (candidates for removal):1. OLD_API_KEY (.env, .env.local) - Last modified: [file date] - No code references found2. DEPRECATED_SERVICE_URL (.env) - Last modified: [file date] - No code references found### 8.2 Dynamic Access CheckBefore confirming removal, search for dynamic access patterns that grep may have missed:javascript// These patterns indicate variables might be used dynamically:process.env[variableName] // Dynamic key accessprocess.env[`${prefix}_KEY`] // Template literal accessObject.keys(process.env) // Iteration over all env vars{ ...process.env } // Spread operatorUse Grep with patterns:process\.env\[Object\.keys\(process\.env\)Object\.entries\(process\.env\)\.\.\.process\.envIf dynamic access patterns found: Flag affected variables for manual review and warn user.### 8.3 User ConfirmationUse AskUserQuestion to confirm each removal:The following variables appear unused. Select which to remove:[ ] OLD_API_KEY - Remove from .env, .env.local[ ] DEPRECATED_SERVICE_URL - Remove from .env[ ] Skip cleanupÔÜá´©Å Variables will be backed up before removal.Safety rules:- NEVER auto-delete without explicit user confirmation- NEVER remove variables from .env.example (it serves as documentation)- Create backup before any modifications### 8.4 Create BackupsBefore modifying any file:bash# Create timestamped backup directorymkdir -p .env-backups/$(date +%Y%m%d_%H%M%S)# Backup each env file being modifiedcp .env .env-backups/$(date +%Y%m%d_%H%M%S)/.env.backupcp .env.local .env-backups/$(date +%Y%m%d_%H%M%S)/.env.local.backup### 8.5 Remove Confirmed VariablesFor each confirmed variable:1. Use Edit tool to remove the line from each env file2. Preserve comments associated with the variable (line immediately above if it starts with #)3. Log the removal### 8.6 Document CleanupAppend cleanup summary to ENV_AUDIT.md:markdown## Cleanup Log**Date:** [timestamp]**Backup Location:** .env-backups/[timestamp]/### Removed Variables| Variable | Removed From | Reason ||----------|--------------|--------|| OLD_API_KEY | .env, .env.local | Unused - no code references |### Preserved (Manual Review Required)| Variable | Reason ||----------|--------|| DYNAMIC_VAR | Dynamic access pattern detected |## Step 9: Regression PreventionPurpose: Validate that removing unused variables doesn't break the application.### 9.1 Pre-Cleanup BaselineBefore removing any variables, capture baseline state:bash# Check if project builds successfullynpm run build 2>&1 | tee .env-backups/pre-cleanup-build.logecho $? > .env-backups/pre-cleanup-build-status# Run tests if availablenpm test 2>&1 | tee .env-backups/pre-cleanup-test.logecho $? > .env-backups/pre-cleanup-test-statusStore exit codes:- 0 = Success (baseline is green)- Non-zero = Already failing (warn user but proceed if they confirm)### 9.2 Dynamic Access DetectionSearch for patterns that indicate runtime env var access:High-risk patterns (require manual review):javascript// Config objects that spread envconst config = { ...process.env }// Dynamic key constructionconst key = `${SERVICE}_API_KEY`process.env[key]// Iteration patternsObject.entries(process.env).filter(([k]) => k.startsWith('FEATURE_'))// External config loadersrequire('dotenv').config({ path: customPath })Detection commands:Grep: process\.env\[(?!['"][A-Z])Grep: Object\.(keys|values|entries)\(process\.env\)Grep: \.\.\.process\.envGrep: dotenv.*configIf detected: List affected files and require explicit user acknowledgment before proceeding.### 9.3 Post-Cleanup ValidationAfter removing variables, run validation:bash# Verify build still succeedsnpm run build 2>&1 | tee .env-backups/post-cleanup-build.logPOST_BUILD_STATUS=$?# Verify tests still passnpm test 2>&1 | tee .env-backups/post-cleanup-test.logPOST_TEST_STATUS=$?### 9.4 Regression DetectionCompare pre and post states:| Check | Pre-Cleanup | Post-Cleanup | Status ||-------|-------------|--------------|--------|| Build | Ô£à Pass | Ô£à Pass | OK || Tests | Ô£à Pass | Ô£à Pass | OK |If regression detected:1. Immediately alert user2. Offer automatic rollback: ÔÜá´©Å REGRESSION DETECTED Build/tests failed after removing variables. Options: 1. Rollback all changes (restore from backup) 2. Rollback specific variables 3. Investigate failure (show diff) 4. Proceed anyway (not recommended) ### 9.5 Automatic RollbackIf user requests rollback:bash# Restore from backupcp .env-backups/[timestamp]/.env.backup .envcp .env-backups/[timestamp]/.env.local.backup .env.local# Verify restorationnpm run build && npm test### 9.6 Git Integration (Optional)If in a git repository, offer branch-based cleanup:bash# Create cleanup branchgit checkout -b env-cleanup/$(date +%Y%m%d)# After cleanup, changes can be reviewed via PRgit add .env .env.localgit commit -m "chore: remove unused environment variablesRemoved:- OLD_API_KEY (unused)- DEPRECATED_SERVICE_URL (unused)Backup: .env-backups/[timestamp]/"Benefits:- Easy rollback via git checkout -- Changes visible in PR review- CI/CD will validate before merge</process><reference_index>Service Patterns: references/service-patterns.md - Known services and their variable naming conventions</reference_index><success_criteria>Audit is complete when:- [ ] All .env files discovered and parsed- [ ] All code references found- [ ] Variables categorized as used/unused/undeclared- [ ] Services detected and permission levels assigned- [ ] Code paths documented for each variable- [ ] Markdown report generated with all sections- [ ] Report saved to specified locationCleanup is complete when (if --cleanup requested):- [ ] Dynamic access patterns checked- [ ] User confirmed variables to remove- [ ] Backups created in .env-backups/- [ ] Variables removed from env files (not .env.example)- [ ] Cleanup log appended to reportRegression prevention is complete when:- [ ] Pre-cleanup build/test baseline captured- [ ] Post-cleanup validation run- [ ] No regressions detected OR rollback performed- [ ] Git branch created (if opted in)</success_criteria>
04 同仓库更多 Skills
webapp-testing
Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.
web-design-guidelines
Review UI code for Web Interface Guidelines compliance. Use when asked to "review my UI", "check accessibility", "audit design", "review UX", or "check my site against best practices".
vercel-react-view-transitions
Guide for implementing smooth, native-feeling animations using React's View Transition API (`<ViewTransition>` component, `addTransitionType`, and CSS view transition pseudo-elements). Use this skill whenever the user wants to add page transitions, animate route changes, create shared element animations, animate enter/exit of components, animate list reorder, implement directional (forward/back) navigation animations, or integrate view transitions in Next.js. Also use when the user mentions view transitions, `startViewTransition`, `ViewTransition`, transition types, or asks about animating between UI states in React without third-party animation libraries.
vercel-react-best-practices
React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.
vercel-composition-patterns
React composition patterns that scale. Use when refactoring components with boolean prop proliferation, building flexible component libraries, or designing reusable APIs. Triggers on tasks involving compound components, render props, context providers, or component architecture. Includes React 19 API changes.
vercel-cli-with-tokens
Deploy and manage projects on Vercel using token-based authentication. Use when working with Vercel CLI using access tokens rather than interactive login — e.g. "deploy to vercel", "set up vercel", "add environment variables to vercel".