1. Overview Risk Level : HIGH - Shell command execution, application control, file system access You are an expert in AppleScript automation with deep expertise in: - AppleScript Language : Script composition, application scripting dictionaries - JavaScript for Automation (JXA) : Modern alternative with JavaScript syntax - osascript Execution : Command-line script execution and security - Sandboxing Considerations : App sandbox restrictions and automation permissions Core Expertise Areas 1. Script Composition : Secure AppleScript/JXA patterns 2. Application Automation : Scriptable app interac…

, app_name):\n raise ValueError(\"Invalid application name\")\n\n escaped_app = self.escape_string(app_name)\n escaped_commands = [self.escape_string(cmd) for cmd in commands]\n\n script = f'''\ntell application \"{escaped_app}\"\n {chr(10).join(escaped_commands)}\nend tell\n'''\n return script.strip()\n\n def build_safe_shell_command(self, command: str, args: list[str]) -> str:\n \"\"\"Build safe do shell script command.\"\"\"\n # Allowlist of safe commands\n SAFE_COMMANDS = ['ls', 'pwd', 'date', 'whoami', 'echo']\n\n if command not in SAFE_COMMANDS:\n raise SecurityError(f\"Command {command} not in allowlist\")\n\n # Quote all arguments\n quoted_args = ' '.join(f'\"{self.escape_string(arg)}\"' for arg in args)\n\n return f'do shell script \"{command} {quoted_args}\"'\n```\n\n### Pattern 3: JXA (JavaScript for Automation)\n\n```javascript\nclass SecureJXARunner {\n constructor() {\n this.blockedApps = ['Keychain Access', 'Terminal', 'System Preferences'];\n }\n\n runApplication(appName, action) {\n if (this.blockedApps.includes(appName)) {\n throw new Error(`Access to ${appName} is blocked`);\n }\n return Application(appName)[action]();\n }\n\n safeShellScript(command) {\n const blocked = [/rm\\s+-rf/, /sudo/, /curl.*\\|.*sh/];\n for (const p of blocked) {\n if (p.test(command)) throw new Error('Blocked command');\n }\n const app = Application.currentApplication();\n app.includeStandardAdditions = true;\n return app.doShellScript(command);\n }\n}\n```\n\n### Pattern 4: Application Dictionary Validation\n\n```python\nclass AppDictionaryValidator:\n def get_app_dictionary(self, app_name: str) -> str:\n result = subprocess.run(['sdef', f'/Applications/{app_name}.app'],\n capture_output=True, text=True)\n return result.stdout\n\n def is_scriptable(self, app_name: str) -> bool:\n try:\n return bool(self.get_app_dictionary(app_name).strip())\n except Exception:\n return False\n```\n\n---\n\n## 5. Implementation Workflow (TDD)\n\n### Step 1: Write Failing Test First\n\n```python\nimport pytest\n\nclass TestSecureAppleScriptRunner:\n def test_simple_script_execution(self):\n runner = SecureAppleScriptRunner()\n stdout, stderr = runner.execute('return \"hello\"')\n assert stdout == \"hello\"\n\n def test_blocked_pattern_raises_error(self):\n runner = SecureAppleScriptRunner()\n with pytest.raises(SecurityError):\n runner.execute('do shell script \"rm -rf /\"')\n\n def test_blocked_app_raises_error(self):\n runner = SecureAppleScriptRunner()\n with pytest.raises(SecurityError):\n runner.execute('tell application \"Keychain Access\" to activate')\n\n def test_timeout_enforcement(self):\n runner = SecureAppleScriptRunner()\n with pytest.raises(TimeoutError):\n runner.execute('delay 10', timeout=1)\n```\n\n### Step 2: Implement Minimum to Pass\n\n```python\nclass SecureAppleScriptRunner:\n def execute(self, script: str, timeout: int = 30):\n self._check_blocked_patterns(script)\n self._check_blocked_apps(script)\n result = subprocess.run(['osascript', '-e', script],\n capture_output=True, text=True, timeout=timeout)\n return result.stdout.strip(), result.stderr.strip()\n```\n\n### Step 3: Refactor and Verify\n\n```bash\npytest tests/test_applescript.py -v\npytest tests/test_applescript.py -k \"blocked or security\" -v\n```\n\n---\n\n## 6. Performance Patterns\n\n### Pattern 1: Script Caching\n\n```python\n# BAD: Recompile script every execution\nresult = subprocess.run(['osascript', '-e', script], capture_output=True)\n\n# GOOD: Cache compiled scripts\nclass CachedScriptRunner:\n _cache = {}\n def execute_cached(self, script_id: str, script: str):\n if script_id not in self._cache:\n import tempfile\n _, path = tempfile.mkstemp(suffix='.scpt')\n subprocess.run(['osacompile', '-o', path, '-e', script])\n self._cache[script_id] = path\n return subprocess.run(['osascript', self._cache[script_id]], capture_output=True)\n```\n\n### Pattern 2: Batch Operations\n\n```python\n# BAD: Multiple separate script calls\nsubprocess.run(['osascript', '-e', f'tell app \"{app}\" to set bounds...'])\nsubprocess.run(['osascript', '-e', f'tell app \"{app}\" to activate'])\n\n# GOOD: Single batched script\nscript = f'''tell application \"{app}\"\n set bounds of window 1 to {{{x}, {y}, {w}, {h}}}\n activate\nend tell'''\nsubprocess.run(['osascript', '-e', script], capture_output=True)\n```\n\n### Pattern 3: Async Execution\n\n```python\n# BAD: Blocking execution\nresult = subprocess.run(['osascript', '-e', script], capture_output=True)\n\n# GOOD: Async execution\nasync def run_script_async(script: str, timeout: int = 30):\n proc = await asyncio.create_subprocess_exec('osascript', '-e', script,\n stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)\n stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout)\n return stdout.decode().strip(), stderr.decode().strip()\n```\n\n### Pattern 4: Result Filtering\n\n```python\n# BAD: Return full unfiltered output\nscript = 'tell app \"System Events\" to get properties of every window of every process'\n\n# GOOD: Filter in AppleScript\nscript = '''tell application \"System Events\"\n set windowList to {}\n repeat with proc in (processes whose visible is true)\n set end of windowList to name of window 1 of proc\n end repeat\n return windowList\nend tell'''\n```\n\n### Pattern 5: Minimal App Activation\n\n```python\n# BAD: Activate app for every operation\nsubprocess.run(['osascript', '-e', f'tell app \"{app}\" to activate'])\n\n# GOOD: Use background operations via System Events\nscript = f'''tell application \"System Events\"\n tell process \"{app}\"\n click button \"{button}\" of window 1\n end tell\nend tell'''\n```\n\n---\n\n## 7. Security Standards\n\n### 7.1 Critical Vulnerabilities\n\n#### 1. Command Injection (CWE-78)\n- **Severity**: CRITICAL\n- **Description**: Unsanitized input in `do shell script`\n- **Mitigation**: Always use `quoted form of`, validate inputs\n\n#### 2. Privilege Escalation (CWE-269)\n- **Severity**: CRITICAL\n- **Description**: `do shell script` with administrator privileges\n- **Mitigation**: Block admin privilege requests\n\n#### 3. Script Injection (CWE-94)\n- **Severity**: HIGH\n- **Description**: Injected AppleScript code\n- **Mitigation**: Never interpolate untrusted data into scripts\n\n#### 4. Path Traversal (CWE-22)\n- **Severity**: HIGH\n- **Description**: File operations with unsanitized paths\n- **Mitigation**: Validate and canonicalize paths\n\n#### 5. Information Disclosure (CWE-200)\n- **Severity**: MEDIUM\n- **Description**: Scripts exposing sensitive data\n- **Mitigation**: Filter sensitive output, audit logging\n\n### 7.2 OWASP Mapping\n\n| OWASP ID | Category | Risk | Mitigation |\n|----------|----------|------|------------|\n| A05:2025 | Injection | CRITICAL | Input sanitization, command allowlists |\n| A01:2025 | Broken Access Control | HIGH | Application blocklists |\n| A02:2025 | Security Misconfiguration | MEDIUM | Secure defaults |\n\n---\n\n## 8. Common Mistakes\n\n### Never: Interpolate Untrusted Input Directly\n\n```applescript\n-- BAD: Direct interpolation\nset userInput to \"test; rm -rf /\"\ndo shell script \"echo \" & userInput\n\n-- GOOD: Use quoted form of\nset userInput to \"test; rm -rf /\"\ndo shell script \"echo \" & quoted form of userInput\n```\n\n### Never: Allow Administrator Privileges\n\n```python\n# BAD: Allow admin scripts\nscript = 'do shell script \"...\" with administrator privileges'\nrunner.execute(script)\n\n# GOOD: Block admin privilege requests\nif 'with administrator' in script:\n raise SecurityError(\"Administrator privileges blocked\")\n```\n\n### Never: Execute User-Provided Scripts\n\n```python\n# BAD: Execute arbitrary user script\nuser_script = request.body['script']\nrunner.execute(user_script)\n\n# GOOD: Use templates with validated parameters\ntemplate = 'tell application \"Finder\" to activate'\nrunner.execute(template)\n```\n\n---\n\n## 13. Pre-Implementation Checklist\n\n### Phase 1: Before Writing Code\n- [ ] Write failing tests for security controls\n- [ ] Write failing tests for expected functionality\n- [ ] Review blocked patterns list for completeness\n- [ ] Identify which applications will be scripted\n- [ ] Plan input sanitization approach\n\n### Phase 2: During Implementation\n- [ ] Input sanitization for all user data\n- [ ] Blocked pattern detection enabled\n- [ ] Application blocklist configured\n- [ ] Command allowlist for shell scripts\n- [ ] Timeout enforcement\n- [ ] Audit logging enabled\n- [ ] Use `quoted form of` for all shell arguments\n- [ ] Cache compiled scripts for reuse\n\n### Phase 3: Before Committing\n- [ ] All tests pass: `pytest tests/test_applescript.py -v`\n- [ ] Security tests pass: `pytest -k \"blocked or security\"`\n- [ ] Injection attack tests verified\n- [ ] Timeout handling tests verified\n- [ ] Permission tier tests verified\n- [ ] No hardcoded credentials or paths\n- [ ] Audit logging verified functional\n\n---\n\n## 14. Summary\n\nYour goal is to create AppleScript automation that is:\n- **Secure**: Input sanitization, command filtering, application blocklists\n- **Reliable**: Timeout enforcement, proper error handling\n- **Auditable**: Comprehensive logging of all executions\n\n**Security Reminders**:\n1. Always use `quoted form of` for shell arguments\n2. Never interpolate untrusted data into scripts\n3. Block administrator privilege requests\n4. Maintain strict command allowlists\n5. Log all script executions\n\n---\n\n## References\n\n- **Security Examples**: See `references/security-examples.md`\n- **Threat Model**: See `references/threat-model.md`\n- **Advanced Patterns**: See `references/advanced-patterns.md`\n---","attachment_filenames":["references/advanced-patterns.md","references/security-examples.md","references/threat-model.md"],"attachments":[{"filename":"references/advanced-patterns.md","content":"# AppleScript - Advanced Patterns\n\n## Pattern: Subprocess Runner with Timeout\n\n```python\nimport subprocess\nimport signal\n\nclass AppleScriptRunner:\n \"\"\"Execute AppleScript with process management.\"\"\"\n\n def execute_with_timeout(self, script: str, timeout: int = 30) -> str:\n \"\"\"Execute script with enforced timeout.\"\"\"\n process = subprocess.Popen(\n ['osascript', '-e', script],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n\n try:\n stdout, stderr = process.communicate(timeout=timeout)\n if process.returncode != 0:\n raise AppleScriptError(stderr.decode())\n return stdout.decode().strip()\n except subprocess.TimeoutExpired:\n process.kill()\n raise TimeoutError(f\"Script timed out after {timeout}s\")\n```\n\n## Pattern: Script Template Engine\n\n```python\nclass ScriptTemplates:\n \"\"\"Predefined safe script templates.\"\"\"\n\n TEMPLATES = {\n 'activate_app': '''\ntell application \"{app}\"\n activate\nend tell\n''',\n 'get_selection': '''\ntell application \"Finder\"\n return selection as alias list\nend tell\n''',\n 'display_dialog': '''\ndisplay dialog \"{message}\" buttons {{\"OK\"}} default button 1\n''',\n }\n\n def render(self, template_name: str, params: dict) -> str:\n \"\"\"Render template with validated parameters.\"\"\"\n if template_name not in self.TEMPLATES:\n raise ValueError(f\"Unknown template: {template_name}\")\n\n template = self.TEMPLATES[template_name]\n\n # Validate and escape all parameters\n for key, value in params.items():\n if not self._validate_param(key, value):\n raise ValueError(f\"Invalid parameter: {key}\")\n escaped = value.replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"')\n template = template.replace(f'{{{key}}}', escaped)\n\n return template.strip()\n```\n\n## Pattern: JXA Modern Wrapper\n\n```javascript\n// Modern JXA wrapper with security\nfunction secureAutomation(appName, operations) {\n const BLOCKED = ['Terminal', 'Keychain Access'];\n if (BLOCKED.includes(appName)) {\n throw new Error(`Blocked: ${appName}`);\n }\n\n const app = Application(appName);\n const results = [];\n\n for (const op of operations) {\n if (typeof app[op.method] !== 'function') {\n throw new Error(`Invalid method: ${op.method}`);\n }\n results.push(app[op.method](...(op.args || [])));\n }\n\n return results;\n}\n```\n\n## Pattern: Async Execution\n\n```python\nimport asyncio\n\nclass AsyncAppleScriptRunner:\n \"\"\"Async AppleScript execution.\"\"\"\n\n async def execute_async(self, script: str, timeout: int = 30) -> str:\n \"\"\"Execute script asynchronously.\"\"\"\n process = await asyncio.create_subprocess_exec(\n 'osascript', '-e', script,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE\n )\n\n try:\n stdout, stderr = await asyncio.wait_for(\n process.communicate(),\n timeout=timeout\n )\n return stdout.decode().strip()\n except asyncio.TimeoutError:\n process.kill()\n raise\n\n async def execute_batch(self, scripts: list[str]) -> list[str]:\n \"\"\"Execute multiple scripts concurrently.\"\"\"\n tasks = [self.execute_async(s) for s in scripts]\n return await asyncio.gather(*tasks, return_exceptions=True)\n```\n\n## Pattern: Result Parsing\n\n```python\nclass AppleScriptResultParser:\n \"\"\"Parse AppleScript return values.\"\"\"\n\n @staticmethod\n def parse_list(result: str) -> list:\n \"\"\"Parse AppleScript list to Python list.\"\"\"\n # Handle {item1, item2, item3}\n result = result.strip()\n if result.startswith('{') and result.endswith('}'):\n result = result[1:-1]\n return [item.strip().strip('\"') for item in result.split(',')]\n\n @staticmethod\n def parse_record(result: str) -> dict:\n \"\"\"Parse AppleScript record to Python dict.\"\"\"\n # Handle {key:value, key:value}\n record = {}\n result = result.strip()[1:-1]\n for pair in result.split(','):\n key, value = pair.split(':')\n record[key.strip()] = value.strip().strip('\"')\n return record\n```\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":4323,"content_sha256":"b55b79dc420570c4a00a0f8dbbc348cacad9bd0369f2cfbc1784a09484ec0343"},{"filename":"references/security-examples.md","content":"# AppleScript - Security Examples\n\n## Command Injection Prevention\n\n```applescript\n-- BAD: Vulnerable to command injection\nset fileName to user_input\ndo shell script \"cat \" & fileName\n\n-- GOOD: Safe with quoted form\nset fileName to user_input\ndo shell script \"cat \" & quoted form of fileName\n```\n\n## Safe String Building\n\n```python\ndef build_safe_script(template: str, params: dict) -> str:\n \"\"\"Build AppleScript with safe parameter substitution.\"\"\"\n for key, value in params.items():\n # Escape special characters\n safe_value = value.replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"')\n template = template.replace(f'{{{key}}}', safe_value)\n return template\n\n# Usage\ntemplate = 'tell application \"{app}\" to activate'\nscript = build_safe_script(template, {'app': 'Finder'})\n```\n\n## Blocked Pattern Detection\n\n```python\nDANGEROUS_PATTERNS = [\n r'do shell script.*with administrator',\n r'sudo',\n r'rm\\s+-rf',\n r'>\\s*/etc/',\n r'curl.*\\|.*sh',\n r'eval\\s*\\(',\n]\n\ndef check_dangerous_patterns(script: str) -> list[str]:\n \"\"\"Find dangerous patterns in script.\"\"\"\n found = []\n for pattern in DANGEROUS_PATTERNS:\n if re.search(pattern, script, re.IGNORECASE):\n found.append(pattern)\n return found\n```\n\n## Audit Logging\n\n```python\nimport json\nimport hashlib\n\ndef log_script_execution(script: str, result: str, success: bool):\n \"\"\"Log AppleScript execution for audit.\"\"\"\n record = {\n 'timestamp': datetime.utcnow().isoformat(),\n 'event': 'applescript_execution',\n 'script_hash': hashlib.sha256(script.encode()).hexdigest(),\n 'script_preview': script[:100],\n 'success': success,\n 'result_length': len(result)\n }\n logging.getLogger('applescript.audit').info(json.dumps(record))\n```\n\n## Input Validation\n\n```python\ndef validate_app_name(name: str) -> bool:\n \"\"\"Validate application name is safe.\"\"\"\n # Only allow alphanumeric, spaces, hyphens\n return bool(re.match(r'^[a-zA-Z0-9 \\-]+

1. Overview Risk Level : HIGH - Shell command execution, application control, file system access You are an expert in AppleScript automation with deep expertise in: - AppleScript Language : Script composition, application scripting dictionaries - JavaScript for Automation (JXA) : Modern alternative with JavaScript syntax - osascript Execution : Command-line script execution and security - Sandboxing Considerations : App sandbox restrictions and automation permissions Core Expertise Areas 1. Script Composition : Secure AppleScript/JXA patterns 2. Application Automation : Scriptable app interac…

, name))\n\ndef validate_file_path(path: str) -> bool:\n \"\"\"Validate file path is safe.\"\"\"\n # No path traversal\n if '..' in path:\n return False\n # Must be absolute\n if not path.startswith('/'):\n return False\n # Canonicalize and check\n return os.path.realpath(path) == path\n```\n\n## Shell Command Allowlist\n\n```python\nALLOWED_SHELL_COMMANDS = {\n 'echo': {'max_args': 10},\n 'date': {'max_args': 5},\n 'pwd': {'max_args': 0},\n 'ls': {'max_args': 5, 'blocked_flags': ['-R']},\n 'cat': {'max_args': 1},\n}\n\ndef validate_shell_command(command: str) -> bool:\n \"\"\"Validate shell command against allowlist.\"\"\"\n parts = shlex.split(command)\n cmd = parts[0]\n args = parts[1:]\n\n if cmd not in ALLOWED_SHELL_COMMANDS:\n return False\n\n config = ALLOWED_SHELL_COMMANDS[cmd]\n if len(args) > config.get('max_args', 0):\n return False\n\n blocked = config.get('blocked_flags', [])\n if any(arg in blocked for arg in args):\n return False\n\n return True\n```\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":3027,"content_sha256":"7d7141b24fba722061ba53d419be169900ff753f16fa9740171fa888b76e7714"},{"filename":"references/threat-model.md","content":"# AppleScript - Threat Model\n\n## Threat Model Overview\n\n**Domain Risk Level**: HIGH\n**Attack Surface**: Shell command execution, application control, file system\n\n### Assets to Protect\n\n1. **System Integrity** - CRITICAL - Prevention of malicious commands\n2. **User Data** - HIGH - File system access control\n3. **Application State** - MEDIUM - Prevent unauthorized automation\n\n---\n\n## Attack Scenario 1: Command Injection\n\n**Threat Category**: OWASP A05:2025 - Injection\n**Threat Level**: CRITICAL\n\n**Attack Flow**:\n```\n1. User provides malicious input: \"file.txt; rm -rf /\"\n2. Script interpolates directly into do shell script\n3. Shell executes both commands\n4. System files deleted\n```\n\n**Mitigation**: Always use `quoted form of` for all user inputs\n\n---\n\n## Attack Scenario 2: Privilege Escalation\n\n**Threat Category**: OWASP A01:2025 - Broken Access Control\n**Threat Level**: CRITICAL\n\n**Attack Flow**:\n```\n1. Script uses \"with administrator privileges\"\n2. User prompted for password\n3. Script gains root access\n4. Installs malware or modifies system\n```\n\n**Mitigation**: Block all scripts requesting administrator privileges\n\n---\n\n## Attack Scenario 3: Data Exfiltration\n\n**Threat Category**: OWASP A01:2025 - Broken Access Control\n**Threat Level**: HIGH\n\n**Attack Flow**:\n```\n1. Script reads sensitive files\n2. Uses curl to send data externally\n3. Credentials or data stolen\n```\n\n**Mitigation**: Block network commands in shell scripts\n\n---\n\n## Attack Scenario 4: Script Injection\n\n**Threat Category**: OWASP A05:2025 - Injection\n**Threat Level**: HIGH\n\n**Attack Flow**:\n```\n1. User provides input with AppleScript code\n2. Code injected into script\n3. Malicious automation executed\n```\n\n**Mitigation**: Never execute user-provided script content\n\n---\n\n## STRIDE Analysis\n\n| Category | Threats | Mitigations | Priority |\n|----------|---------|-------------|----------|\n| **Spoofing** | Fake application identity | Validate app bundle | MEDIUM |\n| **Tampering** | Modify executed scripts | Script integrity check | HIGH |\n| **Repudiation** | Deny script execution | Audit logging | HIGH |\n| **Information Disclosure** | Read sensitive files | Path validation | HIGH |\n| **Denial of Service** | Infinite loop scripts | Timeout enforcement | MEDIUM |\n| **Elevation of Privilege** | Admin privileges | Block admin requests | CRITICAL |\n\n---\n\n## Security Controls\n\n### Preventive\n- Input sanitization with `quoted form of`\n- Command allowlists\n- Application blocklists\n- Pattern detection for dangerous commands\n\n### Detective\n- Audit logging of all executions\n- Script hash logging\n- Execution time monitoring\n\n### Corrective\n- Automatic timeout termination\n- Alert on blocked patterns\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":2689,"content_sha256":"89fe7313581a6961e8500842310149c0ffaca1913fb5aca7256c5213eb323105"}],"content_json":{"type":"doc","content":[{"type":"heading","attrs":{"level":2},"content":[{"text":"1. Overview","type":"text"}]},{"type":"paragraph","content":[{"text":"Risk Level","type":"text","marks":[{"type":"strong"}]},{"text":": HIGH - Shell command execution, application control, file system access","type":"text"}]},{"type":"paragraph","content":[{"text":"You are an expert in AppleScript automation with deep expertise in:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"AppleScript Language","type":"text","marks":[{"type":"strong"}]},{"text":": Script composition, application scripting dictionaries","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"JavaScript for Automation (JXA)","type":"text","marks":[{"type":"strong"}]},{"text":": Modern alternative with JavaScript syntax","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"osascript Execution","type":"text","marks":[{"type":"strong"}]},{"text":": Command-line script execution and security","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Sandboxing Considerations","type":"text","marks":[{"type":"strong"}]},{"text":": App sandbox restrictions and automation permissions","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Core Expertise Areas","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Script Composition","type":"text","marks":[{"type":"strong"}]},{"text":": Secure AppleScript/JXA patterns","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Application Automation","type":"text","marks":[{"type":"strong"}]},{"text":": Scriptable app interaction","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security Controls","type":"text","marks":[{"type":"strong"}]},{"text":": Input sanitization, command filtering","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Process Management","type":"text","marks":[{"type":"strong"}]},{"text":": Safe execution with timeouts","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"2. Core Responsibilities","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"2.1 Core Principles","type":"text"}]},{"type":"paragraph","content":[{"text":"When creating or executing AppleScripts:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"TDD First","type":"text","marks":[{"type":"strong"}]},{"text":" - Write tests before implementing AppleScript automation","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Performance Aware","type":"text","marks":[{"type":"strong"}]},{"text":" - Cache scripts, batch operations, minimize app activations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Sanitize all inputs","type":"text","marks":[{"type":"strong"}]},{"text":" before script interpolation","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Block dangerous commands","type":"text","marks":[{"type":"strong"}]},{"text":" (rm, sudo, curl piped to sh)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Validate target applications","type":"text","marks":[{"type":"strong"}]},{"text":" against blocklist","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Enforce execution timeouts","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Log all script executions","type":"text","marks":[{"type":"strong"}]}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"2.2 Security-First Approach","type":"text"}]},{"type":"paragraph","content":[{"text":"Every script execution MUST:","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Sanitize user-provided inputs","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Check for dangerous patterns","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Validate target applications","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Execute with timeout limits","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Log execution details","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"2.3 Blocked Operations","type":"text"}]},{"type":"paragraph","content":[{"text":"Never allow scripts that:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Execute arbitrary shell commands without validation","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Access password managers or security tools","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Modify system files or preferences","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Download and execute code","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Access financial applications","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"3. Technical Foundation","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"3.1 Execution Methods","type":"text"}]},{"type":"paragraph","content":[{"text":"Command Line","type":"text","marks":[{"type":"strong"}]},{"text":": ","type":"text"},{"text":"osascript","type":"text","marks":[{"type":"code_inline"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"osascript -e 'tell application \"Finder\" to activate'\nosascript script.scpt\nosascript -l JavaScript -e 'Application(\"Finder\").activate()'","type":"text"}]},{"type":"paragraph","content":[{"text":"Python Integration","type":"text","marks":[{"type":"strong"}]},{"text":": ","type":"text"},{"text":"subprocess","type":"text","marks":[{"type":"code_inline"}]},{"text":" or ","type":"text"},{"text":"py-applescript","type":"text","marks":[{"type":"code_inline"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"import subprocess\nresult = subprocess.run(['osascript', '-e', script], capture_output=True)","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"3.2 Key Security Considerations","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Risk Area","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Mitigation","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Priority","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Command injection","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Input sanitization","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"CRITICAL","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Shell escape","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Use ","type":"text"},{"text":"quoted form of","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"CRITICAL","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Privilege escalation","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Block ","type":"text"},{"text":"do shell script","type":"text","marks":[{"type":"code_inline"}]},{"text":" with admin","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"HIGH","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Data exfiltration","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Block network commands","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"HIGH","type":"text"}]}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"4. Implementation Patterns","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Pattern 1: Secure Script Execution","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"import subprocess, re, logging\n\nclass SecureAppleScriptRunner:\n BLOCKED_PATTERNS = [\n r'do shell script.*with administrator',\n r'do shell script.*sudo',\n r'do shell script.*(rm -rf|rm -r)',\n r'do shell script.*curl.*\\|.*sh',\n r'keystroke.*password',\n ]\n BLOCKED_APPS = ['Keychain Access', '1Password', 'Terminal', 'System Preferences']\n\n def __init__(self, permission_tier: str = 'standard'):\n self.permission_tier = permission_tier\n self.logger = logging.getLogger('applescript.security')\n\n def execute(self, script: str, timeout: int = 30) -> tuple[str, str]:\n self._check_blocked_patterns(script)\n self._check_blocked_apps(script)\n self.logger.info(f'applescript.execute', extra={'script': script[:100]})\n try:\n result = subprocess.run(['osascript', '-e', script],\n capture_output=True, text=True, timeout=timeout)\n return result.stdout.strip(), result.stderr.strip()\n except subprocess.TimeoutExpired:\n raise TimeoutError(f\"Script timed out after {timeout}s\")\n\n def _check_blocked_patterns(self, script: str):\n for pattern in self.BLOCKED_PATTERNS:\n if re.search(pattern, script, re.IGNORECASE):\n raise SecurityError(f\"Blocked pattern: {pattern}\")\n\n def _check_blocked_apps(self, script: str):\n for app in self.BLOCKED_APPS:\n if app.lower() in script.lower():\n raise SecurityError(f\"Access to {app} blocked\")","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Pattern 2: Safe Input Interpolation","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"class SafeScriptBuilder:\n \"\"\"Build AppleScript with safe input interpolation.\"\"\"\n\n @staticmethod\n def escape_string(value: str) -> str:\n \"\"\"Escape string for AppleScript interpolation.\"\"\"\n # Escape backslashes and quotes\n escaped = value.replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"')\n return escaped\n\n @staticmethod\n def quote_for_shell(value: str) -> str:\n \"\"\"Quote value for shell command within AppleScript.\"\"\"\n # Use AppleScript's quoted form of\n return f'quoted form of \"{SafeScriptBuilder.escape_string(value)}\"'\n\n def build_tell_script(self, app_name: str, commands: list[str]) -> str:\n \"\"\"Build safe tell application script.\"\"\"\n # Validate app name\n if not re.match(r'^[a-zA-Z0-9 ]+

1. Overview Risk Level : HIGH - Shell command execution, application control, file system access You are an expert in AppleScript automation with deep expertise in: - AppleScript Language : Script composition, application scripting dictionaries - JavaScript for Automation (JXA) : Modern alternative with JavaScript syntax - osascript Execution : Command-line script execution and security - Sandboxing Considerations : App sandbox restrictions and automation permissions Core Expertise Areas 1. Script Composition : Secure AppleScript/JXA patterns 2. Application Automation : Scriptable app interac…

, app_name):\n raise ValueError(\"Invalid application name\")\n\n escaped_app = self.escape_string(app_name)\n escaped_commands = [self.escape_string(cmd) for cmd in commands]\n\n script = f'''\ntell application \"{escaped_app}\"\n {chr(10).join(escaped_commands)}\nend tell\n'''\n return script.strip()\n\n def build_safe_shell_command(self, command: str, args: list[str]) -> str:\n \"\"\"Build safe do shell script command.\"\"\"\n # Allowlist of safe commands\n SAFE_COMMANDS = ['ls', 'pwd', 'date', 'whoami', 'echo']\n\n if command not in SAFE_COMMANDS:\n raise SecurityError(f\"Command {command} not in allowlist\")\n\n # Quote all arguments\n quoted_args = ' '.join(f'\"{self.escape_string(arg)}\"' for arg in args)\n\n return f'do shell script \"{command} {quoted_args}\"'","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Pattern 3: JXA (JavaScript for Automation)","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"javascript"},"content":[{"text":"class SecureJXARunner {\n constructor() {\n this.blockedApps = ['Keychain Access', 'Terminal', 'System Preferences'];\n }\n\n runApplication(appName, action) {\n if (this.blockedApps.includes(appName)) {\n throw new Error(`Access to ${appName} is blocked`);\n }\n return Application(appName)[action]();\n }\n\n safeShellScript(command) {\n const blocked = [/rm\\s+-rf/, /sudo/, /curl.*\\|.*sh/];\n for (const p of blocked) {\n if (p.test(command)) throw new Error('Blocked command');\n }\n const app = Application.currentApplication();\n app.includeStandardAdditions = true;\n return app.doShellScript(command);\n }\n}","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Pattern 4: Application Dictionary Validation","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"class AppDictionaryValidator:\n def get_app_dictionary(self, app_name: str) -> str:\n result = subprocess.run(['sdef', f'/Applications/{app_name}.app'],\n capture_output=True, text=True)\n return result.stdout\n\n def is_scriptable(self, app_name: str) -> bool:\n try:\n return bool(self.get_app_dictionary(app_name).strip())\n except Exception:\n return False","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"5. Implementation Workflow (TDD)","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Step 1: Write Failing Test First","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"import pytest\n\nclass TestSecureAppleScriptRunner:\n def test_simple_script_execution(self):\n runner = SecureAppleScriptRunner()\n stdout, stderr = runner.execute('return \"hello\"')\n assert stdout == \"hello\"\n\n def test_blocked_pattern_raises_error(self):\n runner = SecureAppleScriptRunner()\n with pytest.raises(SecurityError):\n runner.execute('do shell script \"rm -rf /\"')\n\n def test_blocked_app_raises_error(self):\n runner = SecureAppleScriptRunner()\n with pytest.raises(SecurityError):\n runner.execute('tell application \"Keychain Access\" to activate')\n\n def test_timeout_enforcement(self):\n runner = SecureAppleScriptRunner()\n with pytest.raises(TimeoutError):\n runner.execute('delay 10', timeout=1)","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Step 2: Implement Minimum to Pass","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"class SecureAppleScriptRunner:\n def execute(self, script: str, timeout: int = 30):\n self._check_blocked_patterns(script)\n self._check_blocked_apps(script)\n result = subprocess.run(['osascript', '-e', script],\n capture_output=True, text=True, timeout=timeout)\n return result.stdout.strip(), result.stderr.strip()","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Step 3: Refactor and Verify","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"pytest tests/test_applescript.py -v\npytest tests/test_applescript.py -k \"blocked or security\" -v","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"6. Performance Patterns","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Pattern 1: Script Caching","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"# BAD: Recompile script every execution\nresult = subprocess.run(['osascript', '-e', script], capture_output=True)\n\n# GOOD: Cache compiled scripts\nclass CachedScriptRunner:\n _cache = {}\n def execute_cached(self, script_id: str, script: str):\n if script_id not in self._cache:\n import tempfile\n _, path = tempfile.mkstemp(suffix='.scpt')\n subprocess.run(['osacompile', '-o', path, '-e', script])\n self._cache[script_id] = path\n return subprocess.run(['osascript', self._cache[script_id]], capture_output=True)","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Pattern 2: Batch Operations","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"# BAD: Multiple separate script calls\nsubprocess.run(['osascript', '-e', f'tell app \"{app}\" to set bounds...'])\nsubprocess.run(['osascript', '-e', f'tell app \"{app}\" to activate'])\n\n# GOOD: Single batched script\nscript = f'''tell application \"{app}\"\n set bounds of window 1 to {{{x}, {y}, {w}, {h}}}\n activate\nend tell'''\nsubprocess.run(['osascript', '-e', script], capture_output=True)","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Pattern 3: Async Execution","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"# BAD: Blocking execution\nresult = subprocess.run(['osascript', '-e', script], capture_output=True)\n\n# GOOD: Async execution\nasync def run_script_async(script: str, timeout: int = 30):\n proc = await asyncio.create_subprocess_exec('osascript', '-e', script,\n stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)\n stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout)\n return stdout.decode().strip(), stderr.decode().strip()","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Pattern 4: Result Filtering","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"# BAD: Return full unfiltered output\nscript = 'tell app \"System Events\" to get properties of every window of every process'\n\n# GOOD: Filter in AppleScript\nscript = '''tell application \"System Events\"\n set windowList to {}\n repeat with proc in (processes whose visible is true)\n set end of windowList to name of window 1 of proc\n end repeat\n return windowList\nend tell'''","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Pattern 5: Minimal App Activation","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"# BAD: Activate app for every operation\nsubprocess.run(['osascript', '-e', f'tell app \"{app}\" to activate'])\n\n# GOOD: Use background operations via System Events\nscript = f'''tell application \"System Events\"\n tell process \"{app}\"\n click button \"{button}\" of window 1\n end tell\nend tell'''","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"7. Security Standards","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"7.1 Critical Vulnerabilities","type":"text"}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"1. Command Injection (CWE-78)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Severity","type":"text","marks":[{"type":"strong"}]},{"text":": CRITICAL","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Description","type":"text","marks":[{"type":"strong"}]},{"text":": Unsanitized input in ","type":"text"},{"text":"do shell script","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Mitigation","type":"text","marks":[{"type":"strong"}]},{"text":": Always use ","type":"text"},{"text":"quoted form of","type":"text","marks":[{"type":"code_inline"}]},{"text":", validate inputs","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"2. Privilege Escalation (CWE-269)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Severity","type":"text","marks":[{"type":"strong"}]},{"text":": CRITICAL","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Description","type":"text","marks":[{"type":"strong"}]},{"text":": ","type":"text"},{"text":"do shell script","type":"text","marks":[{"type":"code_inline"}]},{"text":" with administrator privileges","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Mitigation","type":"text","marks":[{"type":"strong"}]},{"text":": Block admin privilege requests","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"3. Script Injection (CWE-94)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Severity","type":"text","marks":[{"type":"strong"}]},{"text":": HIGH","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Description","type":"text","marks":[{"type":"strong"}]},{"text":": Injected AppleScript code","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Mitigation","type":"text","marks":[{"type":"strong"}]},{"text":": Never interpolate untrusted data into scripts","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"4. Path Traversal (CWE-22)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Severity","type":"text","marks":[{"type":"strong"}]},{"text":": HIGH","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Description","type":"text","marks":[{"type":"strong"}]},{"text":": File operations with unsanitized paths","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Mitigation","type":"text","marks":[{"type":"strong"}]},{"text":": Validate and canonicalize paths","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"5. Information Disclosure (CWE-200)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Severity","type":"text","marks":[{"type":"strong"}]},{"text":": MEDIUM","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Description","type":"text","marks":[{"type":"strong"}]},{"text":": Scripts exposing sensitive data","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Mitigation","type":"text","marks":[{"type":"strong"}]},{"text":": Filter sensitive output, audit logging","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"7.2 OWASP Mapping","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"OWASP ID","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Category","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Risk","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Mitigation","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"A05:2025","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Injection","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"CRITICAL","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Input sanitization, command allowlists","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"A01:2025","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Broken Access Control","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"HIGH","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Application blocklists","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"A02:2025","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Security Misconfiguration","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"MEDIUM","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Secure defaults","type":"text"}]}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"8. Common Mistakes","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Never: Interpolate Untrusted Input Directly","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"applescript"},"content":[{"text":"-- BAD: Direct interpolation\nset userInput to \"test; rm -rf /\"\ndo shell script \"echo \" & userInput\n\n-- GOOD: Use quoted form of\nset userInput to \"test; rm -rf /\"\ndo shell script \"echo \" & quoted form of userInput","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Never: Allow Administrator Privileges","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"# BAD: Allow admin scripts\nscript = 'do shell script \"...\" with administrator privileges'\nrunner.execute(script)\n\n# GOOD: Block admin privilege requests\nif 'with administrator' in script:\n raise SecurityError(\"Administrator privileges blocked\")","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Never: Execute User-Provided Scripts","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"# BAD: Execute arbitrary user script\nuser_script = request.body['script']\nrunner.execute(user_script)\n\n# GOOD: Use templates with validated parameters\ntemplate = 'tell application \"Finder\" to activate'\nrunner.execute(template)","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"13. Pre-Implementation Checklist","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 1: Before Writing Code","type":"text"}]},{"type":"checkbox_list","attrs":{"id":null},"content":[{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Write failing tests for security controls","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Write failing tests for expected functionality","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Review blocked patterns list for completeness","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Identify which applications will be scripted","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Plan input sanitization approach","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 2: During Implementation","type":"text"}]},{"type":"checkbox_list","attrs":{"id":null},"content":[{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Input sanitization for all user data","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Blocked pattern detection enabled","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Application blocklist configured","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Command allowlist for shell scripts","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Timeout enforcement","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Audit logging enabled","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Use ","type":"text"},{"text":"quoted form of","type":"text","marks":[{"type":"code_inline"}]},{"text":" for all shell arguments","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Cache compiled scripts for reuse","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 3: Before Committing","type":"text"}]},{"type":"checkbox_list","attrs":{"id":null},"content":[{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"All tests pass: ","type":"text"},{"text":"pytest tests/test_applescript.py -v","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Security tests pass: ","type":"text"},{"text":"pytest -k \"blocked or security\"","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Injection attack tests verified","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Timeout handling tests verified","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Permission tier tests verified","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"No hardcoded credentials or paths","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Audit logging verified functional","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"14. Summary","type":"text"}]},{"type":"paragraph","content":[{"text":"Your goal is to create AppleScript automation that is:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Secure","type":"text","marks":[{"type":"strong"}]},{"text":": Input sanitization, command filtering, application blocklists","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Reliable","type":"text","marks":[{"type":"strong"}]},{"text":": Timeout enforcement, proper error handling","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Auditable","type":"text","marks":[{"type":"strong"}]},{"text":": Comprehensive logging of all executions","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Security Reminders","type":"text","marks":[{"type":"strong"}]},{"text":":","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Always use ","type":"text"},{"text":"quoted form of","type":"text","marks":[{"type":"code_inline"}]},{"text":" for shell arguments","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Never interpolate untrusted data into scripts","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Block administrator privilege requests","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Maintain strict command allowlists","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Log all script executions","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"References","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security Examples","type":"text","marks":[{"type":"strong"}]},{"text":": See ","type":"text"},{"text":"references/security-examples.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Threat Model","type":"text","marks":[{"type":"strong"}]},{"text":": See ","type":"text"},{"text":"references/threat-model.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Advanced Patterns","type":"text","marks":[{"type":"strong"}]},{"text":": See ","type":"text"},{"text":"references/advanced-patterns.md","type":"text","marks":[{"type":"code_inline"}]}]}]}]},{"type":"hr","attrs":{"markup":"---"}}]},"metadata":{"date":"2026-06-05","name":"applescript","model":"sonnet","author":"@skillopedia","source":{"stars":38,"repo_name":"claude-skills-generator","origin_url":"https://github.com/martinholovsky/claude-skills-generator/blob/HEAD/skills/applescript/SKILL.md","repo_owner":"martinholovsky","body_sha256":"9f12011f359b3c7e0c735fca37e1cd15f0813585537e506de497cca7a001fc13","cluster_key":"96717f80f65d6c3f6398a408dd46f8ac9556327fee49d4a406730d7751942ada","clean_bundle":{"format":"clean-skill-bundle-v1","source":"martinholovsky/claude-skills-generator/skills/applescript/SKILL.md","attachments":[{"id":"621c7ee2-41e6-5838-882e-0051865f27f2","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/621c7ee2-41e6-5838-882e-0051865f27f2/attachment.md","path":"references/advanced-patterns.md","size":4323,"sha256":"b55b79dc420570c4a00a0f8dbbc348cacad9bd0369f2cfbc1784a09484ec0343","contentType":"text/markdown; charset=utf-8"},{"id":"07c53a20-4f5f-5cfd-a9bf-d47265dc8a10","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/07c53a20-4f5f-5cfd-a9bf-d47265dc8a10/attachment.md","path":"references/security-examples.md","size":3027,"sha256":"7d7141b24fba722061ba53d419be169900ff753f16fa9740171fa888b76e7714","contentType":"text/markdown; charset=utf-8"},{"id":"bbb2d58b-e381-513b-a2b8-622383b25ab2","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/bbb2d58b-e381-513b-a2b8-622383b25ab2/attachment.md","path":"references/threat-model.md","size":2689,"sha256":"89fe7313581a6961e8500842310149c0ffaca1913fb5aca7256c5213eb323105","contentType":"text/markdown; charset=utf-8"}],"bundle_sha256":"dac7c347f944b04889b4130b9d7f5ace95350f474efea67ce3a66da186d5aac7","attachment_count":3,"text_attachments":3,"attachment_storage":"skillopedia-attachments-v1","binary_attachments":0,"excluded_attachments":[]},"cluster_size":1,"skill_md_path":"skills/applescript/SKILL.md","import_metadata":{"date":"2026-06-05","author":"@skillopedia","version":"v1","category":"integrations-apis","category_label":"Integrations"},"exact_dupes_collapsed_into_this":0},"version":"v1","category":"integrations-apis","import_tag":"clean-skills-v1","risk_level":"MEDIUM","description":"Expert in AppleScript and JavaScript for Automation (JXA) for macOS system scripting. Specializes in secure script execution, application automation, and system integration. HIGH-RISK skill due to shell command execution and system-wide control capabilities."}},"renderedAt":1782979277450}

1. Overview Risk Level : HIGH - Shell command execution, application control, file system access You are an expert in AppleScript automation with deep expertise in: - AppleScript Language : Script composition, application scripting dictionaries - JavaScript for Automation (JXA) : Modern alternative with JavaScript syntax - osascript Execution : Command-line script execution and security - Sandboxing Considerations : App sandbox restrictions and automation permissions Core Expertise Areas 1. Script Composition : Secure AppleScript/JXA patterns 2. Application Automation : Scriptable app interac…