Skip to content

⛰️ LifeOS — The AI-powered Life Operating System that helps you hill climb to wherever you're going.

feat: Add optional security and UX hooks to settings.json

Daniel Miessler47ebcf00a7ba
diff --git a/.claude/hooks/security-validator.ts b/.claude/hooks/security-validator.ts
new file mode 100755
index 00000000..e720bcc5
--- /dev/null
+++ b/.claude/hooks/security-validator.ts
@@ -0,0 +1,235 @@
+#!/usr/bin/env bun
+
+/**
+ * security-validator.ts - PreToolUse Security Validation Hook
+ *
+ * Fast pattern-based security validation for Bash commands.
+ * Blocks commands matching known attack patterns before execution.
+ *
+ * Design Principles:
+ * - Fast path: Most commands allowed with minimal processing
+ * - Pre-compiled regex patterns at module load
+ * - Only log/block on high-confidence attack detection
+ * - Fail open on errors (don't break legitimate work)
+ *
+ * CUSTOMIZATION REQUIRED:
+ * This template includes basic examples. Add your own security patterns
+ * based on your threat model and environment.
+ */
+
+// ============================================================================
+// ATTACK PATTERNS - CUSTOMIZE THESE FOR YOUR ENVIRONMENT
+// ============================================================================
+
+// Example: Reverse Shell Patterns (BLOCK - rarely legitimate)
+const REVERSE_SHELL_PATTERNS: RegExp[] = [
+ /\/dev\/(tcp|udp)\/[0-9]/, // Bash TCP/UDP device
+ /bash\s+-i\s+>&?\s*\/dev\//, // Interactive bash redirect
+ // Add your own reverse shell patterns here
+];
+
+// Example: Instruction Override (BLOCK - prompt injection)
+const INSTRUCTION_OVERRIDE_PATTERNS: RegExp[] = [
+ /ignore\s+(all\s+)?previous\s+instructions?/i,
+ /disregard\s+(all\s+)?(prior|previous)\s+(instructions?|rules?)/i,
+ // Add your own prompt injection patterns here
+];
+
+// Example: Catastrophic Deletion Patterns (BLOCK - filesystem destruction)
+const CATASTROPHIC_DELETION_PATTERNS: RegExp[] = [
+ // Trailing tilde bypass
+ /\s+~\/?(\s*$|\s+)/, // Space then ~/ at end
+ /\brm\s+(-[rfivd]+\s+)*\S+\s+~\/?/, // rm something ~/
+
+ // Relative path recursive deletion
+ /\brm\s+(-[rfivd]+\s+)*\.\/\s*$/, // rm -rf ./
+ /\brm\s+(-[rfivd]+\s+)*\.\.\/\s*$/, // rm -rf ../
+
+ // Add your own dangerous deletion patterns here
+];
+
+// Example: Dangerous File Operations (BLOCK - data destruction)
+const DANGEROUS_FILE_OPS_PATTERNS: RegExp[] = [
+ /\bchmod\s+(-R\s+)?0{3,}/, // chmod 000
+ // Add your own dangerous file operation patterns here
+];
+
+// OPTIONAL: Operations that require confirmation instead of blocking
+const DANGEROUS_GIT_PATTERNS: RegExp[] = [
+ /\bgit\s+push\s+.*(-f\b|--force)/i, // git push --force
+ /\bgit\s+reset\s+--hard/i, // git reset --hard
+ // Add your own git safety patterns here
+];
+
+// Combined patterns for fast iteration
+const ALL_BLOCK_PATTERNS: { category: string; patterns: RegExp[] }[] = [
+ { category: 'reverse_shell', patterns: REVERSE_SHELL_PATTERNS },
+ { category: 'instruction_override', patterns: INSTRUCTION_OVERRIDE_PATTERNS },
+ { category: 'catastrophic_deletion', patterns: CATASTROPHIC_DELETION_PATTERNS },
+ { category: 'dangerous_file_ops', patterns: DANGEROUS_FILE_OPS_PATTERNS },
+];
+
+const CONFIRM_PATTERNS: { category: string; patterns: RegExp[] }[] = [
+ { category: 'dangerous_git', patterns: DANGEROUS_GIT_PATTERNS },
+];
+
+// ============================================================================
+// TYPES
+// ============================================================================
+
+interface HookInput {
+ session_id: string;
+ tool_name: string;
+ tool_input: Record<string, unknown> | string;
+}
+
+interface HookOutput {
+ permissionDecision: 'allow' | 'deny';
+ additionalContext?: string;
+ feedback?: string;
+}
+
+// ============================================================================
+// DETECTION LOGIC
+// ============================================================================
+
+interface DetectionResult {
+ blocked: boolean;
+ requiresConfirmation?: boolean;
+ category?: string;
+ pattern?: string;
+}
+
+function detectAttack(content: string): DetectionResult {
+ // First check for hard blocks
+ for (const { category, patterns } of ALL_BLOCK_PATTERNS) {
+ for (const pattern of patterns) {
+ if (pattern.test(content)) {
+ return { blocked: true, category, pattern: pattern.source };
+ }
+ }
+ }
+
+ // Then check for confirmation-required patterns
+ for (const { category, patterns } of CONFIRM_PATTERNS) {
+ for (const pattern of patterns) {
+ if (pattern.test(content)) {
+ return { blocked: false, requiresConfirmation: true, category, pattern: pattern.source };
+ }
+ }
+ }
+
+ return { blocked: false };
+}
+
+// ============================================================================
+// ASYNC LOGGING (fire-and-forget on block only)
+// ============================================================================
+
+function logSecurityEvent(event: Record<string, unknown>): void {
+ // Fire-and-forget - don't await, don't block
+ const logPath = `${process.env.PAI_DIR || '~/.claude'}/history/security/security-events.jsonl`;
+ const entry = JSON.stringify({ timestamp: new Date().toISOString(), ...event }) + '\n';
+
+ Bun.write(logPath, entry, { createPath: true }).catch(() => {
+ // Silently fail - logging should never break the hook
+ });
+}
+
+// ============================================================================
+// MAIN HOOK LOGIC
+// ============================================================================
+
+async function main(): Promise<void> {
+ let input: HookInput;
+
+ try {
+ // Fast stdin read with short timeout
+ const text = await Promise.race([
+ Bun.stdin.text(),
+ new Promise<string>((_, reject) => setTimeout(() => reject(new Error('timeout')), 100))
+ ]);
+
+ if (!text.trim()) {
+ console.log(JSON.stringify({ permissionDecision: 'allow' }));
+ return;
+ }
+
+ input = JSON.parse(text);
+ } catch {
+ // Parse error or timeout - fail open
+ console.log(JSON.stringify({ permissionDecision: 'allow' }));
+ return;
+ }
+
+ // Only validate Bash commands
+ if (input.tool_name !== 'Bash') {
+ console.log(JSON.stringify({ permissionDecision: 'allow' }));
+ return;
+ }
+
+ // Extract command string
+ const command = typeof input.tool_input === 'string'
+ ? input.tool_input
+ : (input.tool_input?.command as string) || '';
+
+ if (!command) {
+ console.log(JSON.stringify({ permissionDecision: 'allow' }));
+ return;
+ }
+
+ // Check all patterns
+ const result = detectAttack(command);
+
+ if (result.blocked) {
+ // Log and block
+ logSecurityEvent({
+ type: 'attack_blocked',
+ category: result.category,
+ pattern: result.pattern,
+ command: command.slice(0, 200), // Truncate for log
+ session_id: input.session_id,
+ });
+
+ const output: HookOutput = {
+ permissionDecision: 'deny',
+ additionalContext: `🚨 SECURITY: Blocked ${result.category} pattern`,
+ feedback: `This command matched a security pattern (${result.category}). If this is legitimate, please rephrase the command.`,
+ };
+
+ console.log(JSON.stringify(output));
+ process.exit(2); // Exit 2 = blocking error
+ }
+
+ if (result.requiresConfirmation) {
+ // Log warning and require confirmation
+ logSecurityEvent({
+ type: 'confirmation_required',
+ category: result.category,
+ pattern: result.pattern,
+ command: command.slice(0, 200),
+ session_id: input.session_id,
+ });
+
+ const output: HookOutput = {
+ permissionDecision: 'deny',
+ additionalContext: `⚠️ DANGEROUS: ${result.category} operation requires confirmation`,
+ feedback: `This is a dangerous operation (${command.slice(0, 50)}...). This can cause data loss. If you're sure, explicitly confirm this command.`,
+ };
+
+ console.log(JSON.stringify(output));
+ process.exit(2); // Exit 2 = requires user confirmation
+ }
+
+ // Allow - no logging, immediate exit
+ console.log(JSON.stringify({ permissionDecision: 'allow' }));
+}
+
+// ============================================================================
+// RUN
+// ============================================================================
+
+main().catch(() => {
+ // On any error, fail open
+ console.log(JSON.stringify({ permissionDecision: 'allow' }));
+});
diff --git a/.claude/hooks/update-tab-on-action.ts b/.claude/hooks/update-tab-on-action.ts
new file mode 100755
index 00000000..07734f99
--- /dev/null
+++ b/.claude/hooks/update-tab-on-action.ts
@@ -0,0 +1,145 @@
+#!/usr/bin/env bun
+/**
+ * Tab Title Update on Action Tools
+ * Updates Kitty tab title when action tools complete (Edit, Write, Bash, Task)
+ * Uses the tool's description directly - no AI call needed
+ *
+ * PAI-safe: No sensitive data, just tool descriptions
+ */
+
+import { execSync } from 'child_process';
+
+// Action tools that warrant a tab title update
+const ACTION_TOOLS = new Set([
+ 'Edit',
+ 'Write',
+ 'Bash',
+ 'Task',
+ 'NotebookEdit',
+ 'MultiEdit'
+]);
+
+interface HookInput {
+ session_id: string;
+ tool_name: string;
+ tool_input: {
+ description?: string;
+ command?: string;
+ file_path?: string;
+ prompt?: string;
+ subagent_type?: string;
+ };
+ tool_response?: unknown;
+ hook_event_name: string;
+}
+
+/**
+ * Read stdin with timeout
+ */
+async function readStdinWithTimeout(timeout: number = 3000): Promise<string> {
+ return new Promise((resolve, reject) => {
+ let data = '';
+ const timer = setTimeout(() => {
+ reject(new Error('Timeout'));
+ }, timeout);
+
+ process.stdin.on('data', (chunk) => {
+ data += chunk.toString();
+ });
+
+ process.stdin.on('end', () => {
+ clearTimeout(timer);
+ resolve(data);
+ });
+
+ process.stdin.on('error', (err) => {
+ clearTimeout(timer);
+ reject(err);
+ });
+ });
+}
+
+/**
+ * Update Kitty tab title using escape codes
+ */
+function setTabTitle(title: string): void {
+ try {
+ // Truncate to reasonable length
+ const truncated = title.length > 50 ? title.slice(0, 47) + '...' : title;
+ const escaped = truncated.replace(/'/g, "'\\''");
+
+ // Multiple escape sequences for compatibility
+ execSync(`printf '\\033]0;${escaped}\\007' >&2`, { stdio: ['pipe', 'pipe', 'inherit'] });
+ execSync(`printf '\\033]2;${escaped}\\007' >&2`, { stdio: ['pipe', 'pipe', 'inherit'] });
+ execSync(`printf '\\033]30;${escaped}\\007' >&2`, { stdio: ['pipe', 'pipe', 'inherit'] });
+ } catch {
+ // Silently fail - don't interrupt Claude's work
+ }
+}
+
+/**
+ * Generate a human-readable title from tool input
+ */
+function generateTitle(toolName: string, input: HookInput['tool_input']): string {
+ // Use explicit description if provided
+ if (input.description) {
+ return input.description;
+ }
+
+ // Generate based on tool type
+ switch (toolName) {
+ case 'Edit':
+ case 'Write':
+ case 'MultiEdit':
+ case 'NotebookEdit':
+ if (input.file_path) {
+ const filename = input.file_path.split('/').pop() || input.file_path;
+ return `Editing ${filename}`;
+ }
+ return `Editing file`;
+
+ case 'Bash':
+ if (input.command) {
+ // Extract first command word
+ const cmd = input.command.split(/\s+/)[0].split('/').pop() || 'command';
+ return `Running ${cmd}`;
+ }
+ return 'Running command';
+
+ case 'Task':
+ if (input.subagent_type) {
+ return `Agent: ${input.subagent_type}`;
+ }
+ if (input.prompt) {
+ const words = input.prompt.slice(0, 30).split(/\s+/).slice(0, 3).join(' ');
+ return `Task: ${words}...`;
+ }
+ return 'Spawning agent';
+
+ default:
+ return `${toolName}...`;
+ }
+}
+
+async function main() {
+ try {
+ const input = await readStdinWithTimeout();
+ const data: HookInput = JSON.parse(input);
+
+ // Only process action tools
+ if (!ACTION_TOOLS.has(data.tool_name)) {
+ process.exit(0);
+ }
+
+ // Generate and set title
+ const title = generateTitle(data.tool_name, data.tool_input);
+ setTabTitle(title);
+
+ process.exit(0);
+ } catch {
+ // Silently exit - don't interrupt Claude's flow
+ process.exit(0);
+ }
+}
+
+main();
diff --git a/.claude/settings.json b/.claude/settings.json
index bb6045f4..5c437ddb 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -69,6 +69,15 @@
"enabledMcpjsonServers": [],
"hooks": {
"PreToolUse": [
+ {
+ "matcher": "Bash",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "${PAI_DIR}/hooks/security-validator.ts"
+ }
+ ]
+ },
{
"matcher": "*",
"hooks": [
@@ -85,11 +94,11 @@
"hooks": [
{
"type": "command",
- "command": "${PAI_DIR}/hooks/capture-tool-output.ts"
+ "command": "${PAI_DIR}/hooks/capture-all-events.ts --event-type PostToolUse"
},
{
"type": "command",
- "command": "${PAI_DIR}/hooks/capture-all-events.ts --event-type PostToolUse"
+ "command": "${PAI_DIR}/hooks/update-tab-on-action.ts"
}
]
}