⛰️ LifeOS — The AI-powered Life Operating System that helps you hill climb to wherever you're going.
security: Restore pre-commit protection system
Daniel Miessler5adc3ed5913e
diff --git a/.pai-protected.json b/.pai-protected.jsonnew file mode 100644index 00000000..ff64fdc7--- /dev/null+++ b/.pai-protected.json@@ -0,0 +1,80 @@+{+ "$schema": "https://json-schema.org/draft-07/schema#",+ "description": "PAI Protected Files - Files that must NOT be overwritten with Kai content",+ "version": "2.0",+ "protected": {+ "core_documents": {+ "description": "Core PAI documentation that differs from Kai",+ "files": [+ "README.md",+ "INSTALL.md",+ "SECURITY.md"+ ],+ "validation": "Must contain 'PAI' or 'Personal AI Infrastructure' in content"+ },+ "pai_infrastructure": {+ "description": "PAI-specific infrastructure code",+ "files": [+ "Tools/validate-protected.ts",+ ".pai-protected.json"+ ],+ "validation": "Must not contain references to private Kai data"+ },+ "sanitized_config": {+ "description": "Configuration files that must remain sanitized",+ "files": [+ ".env.example"+ ],+ "validation": "Must not contain API keys, personal emails, or secrets"+ },+ "forbidden_directories": {+ "description": "Directories that should NEVER exist in public PAI",+ "patterns": [+ "^skills/",+ "^Deprecated/",+ "^.deprecated/",+ "^MEMORY/",+ "^History/",+ "^context/",+ "^progress/"+ ],+ "validation": "These directories contain private Kai data and must not be committed"+ },+ "protected_patterns": {+ "description": "String patterns that should never appear in PAI",+ "patterns": [+ "[email protected]",+ "[email protected]",+ "ANTHROPIC_API_KEY=sk-",+ "PERPLEXITY_API_KEY=[^E]",+ "ELEVENLABS_API_KEY=[^y]",+ "GOOGLE_API_KEY=[^y]",+ "/Users/daniel/.claude/skills/personal",+ "/Users/daniel/.claude/MEMORY",+ "/Users/daniel/.claude/History",+ "daemon.plist",+ "~/.claude/skills/CORE/USER"+ ],+ "exception_files": [+ "SECURITY.md",+ ".pai-protected.json",+ ".env.example",+ "Tools/validate-protected.ts"+ ]+ }+ },+ "kai_to_pai_workflow": {+ "description": "How to safely sync Kai improvements to PAI",+ "steps": [+ "1. Make changes in Kai (~/.claude/)",+ "2. Test thoroughly in Kai environment",+ "3. Identify which changes should go to public PAI",+ "4. Copy changes to PAI repo (~/Projects/PAI/)",+ "5. SKIP protected files (they stay PAI-specific)",+ "6. Sanitize any personal data or API keys",+ "7. Run: bun ~/Projects/PAI/Tools/validate-protected.ts",+ "8. If validation passes, commit to PAI",+ "9. If validation fails, check which protected files changed"+ ]+ }+}diff --git a/Tools/validate-protected.ts b/Tools/validate-protected.tsnew file mode 100644index 00000000..66609624--- /dev/null+++ b/Tools/validate-protected.ts@@ -0,0 +1,262 @@+#!/usr/bin/env bun+/**+ * PAI Protected Files Validator+ *+ * Ensures PAI-specific files haven't been overwritten with Kai content.+ * Run before committing changes to PAI repository.+ *+ * Usage:+ * bun ~/Projects/PAI/Tools/validate-protected.ts+ * bun ~/Projects/PAI/Tools/validate-protected.ts --staged (check only staged files)+ */++import { readFileSync, existsSync } from 'fs';+import { join } from 'path';+import { execSync } from 'child_process';++interface ProtectedManifest {+ version: string;+ protected: {+ [category: string]: {+ description: string;+ files?: string[];+ patterns?: string[];+ exception_files?: string[];+ validation?: string;+ };+ };+}++const PAI_ROOT = join(import.meta.dir, '..');+const MANIFEST_PATH = join(PAI_ROOT, '.pai-protected.json');++// Colors for terminal output+const RED = '\x1b[31m';+const GREEN = '\x1b[32m';+const YELLOW = '\x1b[33m';+const BLUE = '\x1b[34m';+const RESET = '\x1b[0m';++function loadManifest(): ProtectedManifest {+ if (!existsSync(MANIFEST_PATH)) {+ console.error(`${RED}❌ Protected files manifest not found: ${MANIFEST_PATH}${RESET}`);+ process.exit(1);+ }++ return JSON.parse(readFileSync(MANIFEST_PATH, 'utf-8'));+}++function getStagedFiles(): string[] {+ try {+ const output = execSync('git diff --cached --name-only', {+ cwd: PAI_ROOT,+ encoding: 'utf-8'+ });+ return output.trim().split('\n').filter(f => f.length > 0);+ } catch {+ return [];+ }+}++function checkForbiddenDirectories(stagedFiles: string[], manifest: ProtectedManifest): string[] {+ const violations: string[] = [];+ const forbiddenDirs = manifest.protected.forbidden_directories;++ if (!forbiddenDirs || !forbiddenDirs.patterns) {+ return violations;+ }++ for (const file of stagedFiles) {+ for (const pattern of forbiddenDirs.patterns) {+ const regex = new RegExp(pattern);+ if (regex.test(file)) {+ violations.push(`Forbidden directory file staged: ${file} (matches pattern: ${pattern})`);+ }+ }+ }++ return violations;+}++function getAllProtectedFiles(manifest: ProtectedManifest): string[] {+ const files: string[] = [];++ for (const category of Object.values(manifest.protected)) {+ if (category.files) {+ files.push(...category.files);+ }+ }++ return files;+}++function checkFileContent(filePath: string, manifest: ProtectedManifest): {+ valid: boolean;+ violations: string[];+} {+ const fullPath = join(PAI_ROOT, filePath);++ if (!existsSync(fullPath)) {+ return { valid: true, violations: [] };+ }++ const content = readFileSync(fullPath, 'utf-8');+ const violations: string[] = [];++ // Get exception files list (applies to ALL checks, not just patterns)+ const patternCategory = manifest.protected.protected_patterns;+ const exceptions = patternCategory?.exception_files || [];+ const isException = exceptions.includes(filePath);++ // Check for forbidden patterns (skip if exception)+ if (patternCategory && patternCategory.patterns && !isException) {+ for (const pattern of patternCategory.patterns) {+ const regex = new RegExp(pattern, 'g');+ const matches = content.match(regex);++ if (matches) {+ violations.push(`Found forbidden pattern: "${pattern}" (${matches.length} occurrence(s))`);+ }+ }+ }++ // Check category-specific validation+ for (const [categoryName, category] of Object.entries(manifest.protected)) {+ if (!category.files?.includes(filePath) || !category.validation) {+ continue;+ }++ // Core documents must reference PAI+ if (category.validation.includes('PAI')) {+ if (!content.includes('PAI') && !content.includes('Personal AI Infrastructure')) {+ violations.push(`Missing required reference to "PAI" or "Personal AI Infrastructure"`);+ }+ }++ // Must not contain private Kai data (skip if exception file)+ if (category.validation.includes('private Kai data') && !isException) {+ const privatePatterns = [+ /\/Users\/daniel\/\.claude\/skills\/personal/,+ /daemon\.plist/,+ /Kai \(Personal AI Infrastructure\)/,+ ];++ for (const pattern of privatePatterns) {+ if (pattern.test(content)) {+ violations.push(`Contains private Kai reference: ${pattern.source}`);+ }+ }+ }++ // Must not contain secrets (skip if exception file)+ if (category.validation.includes('secrets') && !isException) {+ const secretPatterns = [+ /ANTHROPIC_API_KEY=sk-/,+ /ELEVENLABS_API_KEY=(?!your_elevenlabs_api_key_here)/,+ /PERPLEXITY_API_KEY=(?!your_perplexity_api_key_here)/,+ /@danielmiessler\.com/,+ /@unsupervised-learning\.com/,+ ];++ for (const pattern of secretPatterns) {+ if (pattern.test(content)) {+ violations.push(`Contains secret or personal email: ${pattern.source}`);+ }+ }+ }+ }++ return { valid: violations.length === 0, violations };+}++async function main() {+ const args = process.argv.slice(2);+ const stagedOnly = args.includes('--staged');++ console.log(`\n${BLUE}🛡️ PAI Protected Files Validator${RESET}\n`);+ console.log('='.repeat(60));++ const manifest = loadManifest();+ const allProtectedFiles = getAllProtectedFiles(manifest);++ // Determine which files to check+ let filesToCheck: string[];++ if (stagedOnly) {+ const stagedFiles = getStagedFiles();++ // Check for forbidden directories FIRST+ const forbiddenViolations = checkForbiddenDirectories(stagedFiles, manifest);+ if (forbiddenViolations.length > 0) {+ console.log(`\n${RED}🚫 FORBIDDEN DIRECTORIES DETECTED${RESET}\n`);+ for (const violation of forbiddenViolations) {+ console.log(`${RED}❌${RESET} ${violation}`);+ }+ console.log('\n' + '='.repeat(60));+ console.log(`\n${RED}🚫 COMMIT BLOCKED${RESET}\n`);+ console.log('These directories contain private Kai data and must NOT be in public PAI.');+ console.log('\n' + YELLOW + 'To fix:' + RESET);+ console.log(' 1. git reset HEAD <file> to unstage');+ console.log(' 2. rm -rf <directory> to remove');+ console.log(' 3. Add to .gitignore if needed\n');+ process.exit(1);+ }++ filesToCheck = allProtectedFiles.filter(f => stagedFiles.includes(f));++ if (filesToCheck.length === 0) {+ console.log(`\n${GREEN}✅ No protected files staged for commit${RESET}\n`);+ process.exit(0);+ }++ console.log(`\n${YELLOW}Checking ${filesToCheck.length} staged protected file(s)...${RESET}\n`);+ } else {+ filesToCheck = allProtectedFiles;+ console.log(`\n${YELLOW}Checking all ${filesToCheck.length} protected files...${RESET}\n`);+ }++ let hasViolations = false;+ const results: { file: string; valid: boolean; violations: string[] }[] = [];++ // Check each file+ for (const file of filesToCheck) {+ const result = checkFileContent(file, manifest);+ results.push({ file, ...result });++ if (!result.valid) {+ hasViolations = true;+ }+ }++ // Print results+ for (const result of results) {+ if (result.valid) {+ console.log(`${GREEN}✅${RESET} ${result.file}`);+ } else {+ console.log(`${RED}❌${RESET} ${result.file}`);+ for (const violation of result.violations) {+ console.log(` ${RED}→${RESET} ${violation}`);+ }+ }+ }++ console.log('\n' + '='.repeat(60));++ if (hasViolations) {+ console.log(`\n${RED}🚫 VALIDATION FAILED${RESET}\n`);+ console.log('Protected files contain content that should not be in public PAI.');+ console.log('\n' + YELLOW + 'Common fixes:' + RESET);+ console.log(' 1. Remove API keys and secrets');+ console.log(' 2. Remove personal email addresses');+ console.log(' 3. Remove references to private Kai data');+ console.log(' 4. Ensure PAI-specific files reference "PAI" not "Kai"');+ console.log('\n📖 See .pai-protected.json for details\n');+ process.exit(1);+ } else {+ console.log(`\n${GREEN}✅ All protected files validated successfully!${RESET}\n`);+ console.log('Safe to commit to PAI repository.\n');+ process.exit(0);+ }+}++main();