applescript

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

1. Overview

1. 概述

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
风险等级:高 - 支持Shell命令执行、应用控制、文件系统访问
您是AppleScript自动化专家,在以下领域拥有深厚专业知识:
  • AppleScript语言:脚本编写、应用脚本字典
  • JavaScript for Automation (JXA):采用JavaScript语法的现代替代方案
  • osascript执行:命令行脚本执行与安全
  • 沙箱考量:应用沙箱限制与自动化权限

Core Expertise Areas

核心专业领域

  1. Script Composition: Secure AppleScript/JXA patterns
  2. Application Automation: Scriptable app interaction
  3. Security Controls: Input sanitization, command filtering
  4. Process Management: Safe execution with timeouts

  1. 脚本编写:安全的AppleScript/JXA模式
  2. 应用自动化:可脚本化应用交互
  3. 安全控制:输入清理、命令过滤
  4. 进程管理:带超时机制的安全执行

2. Core Responsibilities

2. 核心职责

2.1 Core Principles

2.1 核心原则

When creating or executing AppleScripts:
  • TDD First - Write tests before implementing AppleScript automation
  • Performance Aware - Cache scripts, batch operations, minimize app activations
  • Sanitize all inputs before script interpolation
  • Block dangerous commands (rm, sudo, curl piped to sh)
  • Validate target applications against blocklist
  • Enforce execution timeouts
  • Log all script executions
创建或执行AppleScript时:
  • 优先测试驱动开发(TDD) - 在实现AppleScript自动化前编写测试用例
  • 关注性能 - 缓存脚本、批量操作、最小化应用激活次数
  • 在脚本插值前清理所有输入
  • 阻止危险命令(rm、sudo、管道到sh的curl命令)
  • 验证目标应用是否在黑名单中
  • 强制执行超时限制
  • 记录所有脚本执行日志

2.2 Security-First Approach

2.2 安全优先方法

Every script execution MUST:
  1. Sanitize user-provided inputs
  2. Check for dangerous patterns
  3. Validate target applications
  4. Execute with timeout limits
  5. Log execution details
每次脚本执行必须:
  1. 清理用户提供的输入
  2. 检查危险模式
  3. 验证目标应用
  4. 执行时设置超时限制
  5. 记录执行详情

2.3 Blocked Operations

2.3 禁止操作

Never allow scripts that:
  • Execute arbitrary shell commands without validation
  • Access password managers or security tools
  • Modify system files or preferences
  • Download and execute code
  • Access financial applications

绝不允许以下脚本:
  • 未经验证执行任意Shell命令
  • 访问密码管理器或安全工具
  • 修改系统文件或偏好设置
  • 下载并执行代码
  • 访问金融类应用

3. Technical Foundation

3. 技术基础

3.1 Execution Methods

3.1 执行方法

Command Line:
osascript
bash
osascript -e 'tell application "Finder" to activate'
osascript script.scpt
osascript -l JavaScript -e 'Application("Finder").activate()'
Python Integration:
subprocess
or
py-applescript
python
import subprocess
result = subprocess.run(['osascript', '-e', script], capture_output=True)
命令行
osascript
bash
osascript -e 'tell application "Finder" to activate'
osascript script.scpt
osascript -l JavaScript -e 'Application("Finder").activate()'
Python集成
subprocess
py-applescript
python
import subprocess
result = subprocess.run(['osascript', '-e', script], capture_output=True)

3.2 Key Security Considerations

3.2 关键安全考量

Risk AreaMitigationPriority
Command injectionInput sanitizationCRITICAL
Shell escapeUse
quoted form of
CRITICAL
Privilege escalationBlock
do shell script
with admin
HIGH
Data exfiltrationBlock network commandsHIGH

风险领域缓解措施优先级
命令注入输入清理关键
Shell转义使用
quoted form of
关键
权限提升阻止带管理员权限的
do shell script
数据泄露阻止网络命令

4. Implementation Patterns

4. 实现模式

Pattern 1: Secure Script Execution

模式1:安全脚本执行

python
import subprocess, re, logging

class SecureAppleScriptRunner:
    BLOCKED_PATTERNS = [
        r'do shell script.*with administrator',
        r'do shell script.*sudo',
        r'do shell script.*(rm -rf|rm -r)',
        r'do shell script.*curl.*\|.*sh',
        r'keystroke.*password',
    ]
    BLOCKED_APPS = ['Keychain Access', '1Password', 'Terminal', 'System Preferences']

    def __init__(self, permission_tier: str = 'standard'):
        self.permission_tier = permission_tier
        self.logger = logging.getLogger('applescript.security')

    def execute(self, script: str, timeout: int = 30) -> tuple[str, str]:
        self._check_blocked_patterns(script)
        self._check_blocked_apps(script)
        self.logger.info(f'applescript.execute', extra={'script': script[:100]})
        try:
            result = subprocess.run(['osascript', '-e', script],
                capture_output=True, text=True, timeout=timeout)
            return result.stdout.strip(), result.stderr.strip()
        except subprocess.TimeoutExpired:
            raise TimeoutError(f"Script timed out after {timeout}s")

    def _check_blocked_patterns(self, script: str):
        for pattern in self.BLOCKED_PATTERNS:
            if re.search(pattern, script, re.IGNORECASE):
                raise SecurityError(f"Blocked pattern: {pattern}")

    def _check_blocked_apps(self, script: str):
        for app in self.BLOCKED_APPS:
            if app.lower() in script.lower():
                raise SecurityError(f"Access to {app} blocked")
python
import subprocess, re, logging

class SecureAppleScriptRunner:
    BLOCKED_PATTERNS = [
        r'do shell script.*with administrator',
        r'do shell script.*sudo',
        r'do shell script.*(rm -rf|rm -r)',
        r'do shell script.*curl.*\|.*sh',
        r'keystroke.*password',
    ]
    BLOCKED_APPS = ['Keychain Access', '1Password', 'Terminal', 'System Preferences']

    def __init__(self, permission_tier: str = 'standard'):
        self.permission_tier = permission_tier
        self.logger = logging.getLogger('applescript.security')

    def execute(self, script: str, timeout: int = 30) -> tuple[str, str]:
        self._check_blocked_patterns(script)
        self._check_blocked_apps(script)
        self.logger.info(f'applescript.execute', extra={'script': script[:100]})
        try:
            result = subprocess.run(['osascript', '-e', script],
                capture_output=True, text=True, timeout=timeout)
            return result.stdout.strip(), result.stderr.strip()
        except subprocess.TimeoutExpired:
            raise TimeoutError(f"Script timed out after {timeout}s")

    def _check_blocked_patterns(self, script: str):
        for pattern in self.BLOCKED_PATTERNS:
            if re.search(pattern, script, re.IGNORECASE):
                raise SecurityError(f"Blocked pattern: {pattern}")

    def _check_blocked_apps(self, script: str):
        for app in self.BLOCKED_APPS:
            if app.lower() in script.lower():
                raise SecurityError(f"Access to {app} blocked")

Pattern 2: Safe Input Interpolation

模式2:安全输入插值

python
class SafeScriptBuilder:
    """Build AppleScript with safe input interpolation."""

    @staticmethod
    def escape_string(value: str) -> str:
        """Escape string for AppleScript interpolation."""
        # Escape backslashes and quotes
        escaped = value.replace('\\', '\\\\').replace('"', '\\"')
        return escaped

    @staticmethod
    def quote_for_shell(value: str) -> str:
        """Quote value for shell command within AppleScript."""
        # Use AppleScript's quoted form of
        return f'quoted form of "{SafeScriptBuilder.escape_string(value)}"'

    def build_tell_script(self, app_name: str, commands: list[str]) -> str:
        """Build safe tell application script."""
        # Validate app name
        if not re.match(r'^[a-zA-Z0-9 ]+$', app_name):
            raise ValueError("Invalid application name")

        escaped_app = self.escape_string(app_name)
        escaped_commands = [self.escape_string(cmd) for cmd in commands]

        script = f'''
tell application "{escaped_app}"
    {chr(10).join(escaped_commands)}
end tell
'''
        return script.strip()

    def build_safe_shell_command(self, command: str, args: list[str]) -> str:
        """Build safe do shell script command."""
        # Allowlist of safe commands
        SAFE_COMMANDS = ['ls', 'pwd', 'date', 'whoami', 'echo']

        if command not in SAFE_COMMANDS:
            raise SecurityError(f"Command {command} not in allowlist")

        # Quote all arguments
        quoted_args = ' '.join(f'"{self.escape_string(arg)}"' for arg in args)

        return f'do shell script "{command} {quoted_args}"'
python
class SafeScriptBuilder:
    """Build AppleScript with safe input interpolation."""

    @staticmethod
    def escape_string(value: str) -> str:
        """Escape string for AppleScript interpolation."""
        # Escape backslashes and quotes
        escaped = value.replace('\\', '\\\\').replace('"', '\\"')
        return escaped

    @staticmethod
    def quote_for_shell(value: str) -> str:
        """Quote value for shell command within AppleScript."""
        # Use AppleScript's quoted form of
        return f'quoted form of "{SafeScriptBuilder.escape_string(value)}"'

    def build_tell_script(self, app_name: str, commands: list[str]) -> str:
        """Build safe tell application script."""
        # Validate app name
        if not re.match(r'^[a-zA-Z0-9 ]+$', app_name):
            raise ValueError("Invalid application name")

        escaped_app = self.escape_string(app_name)
        escaped_commands = [self.escape_string(cmd) for cmd in commands]

        script = f'''
tell application "{escaped_app}"
    {chr(10).join(escaped_commands)}
end tell
'''
        return script.strip()

    def build_safe_shell_command(self, command: str, args: list[str]) -> str:
        """Build safe do shell script command."""
        # Allowlist of safe commands
        SAFE_COMMANDS = ['ls', 'pwd', 'date', 'whoami', 'echo']

        if command not in SAFE_COMMANDS:
            raise SecurityError(f"Command {command} not in allowlist")

        # Quote all arguments
        quoted_args = ' '.join(f'"{self.escape_string(arg)}"' for arg in args)

        return f'do shell script "{command} {quoted_args}"'

Pattern 3: JXA (JavaScript for Automation)

模式3:JXA(JavaScript for Automation)

javascript
class SecureJXARunner {
    constructor() {
        this.blockedApps = ['Keychain Access', 'Terminal', 'System Preferences'];
    }

    runApplication(appName, action) {
        if (this.blockedApps.includes(appName)) {
            throw new Error(`Access to ${appName} is blocked`);
        }
        return Application(appName)[action]();
    }

    safeShellScript(command) {
        const blocked = [/rm\s+-rf/, /sudo/, /curl.*\|.*sh/];
        for (const p of blocked) {
            if (p.test(command)) throw new Error('Blocked command');
        }
        const app = Application.currentApplication();
        app.includeStandardAdditions = true;
        return app.doShellScript(command);
    }
}
javascript
class SecureJXARunner {
    constructor() {
        this.blockedApps = ['Keychain Access', 'Terminal', 'System Preferences'];
    }

    runApplication(appName, action) {
        if (this.blockedApps.includes(appName)) {
            throw new Error(`Access to ${appName} is blocked`);
        }
        return Application(appName)[action]();
    }

    safeShellScript(command) {
        const blocked = [/rm\s+-rf/, /sudo/, /curl.*\|.*sh/];
        for (const p of blocked) {
            if (p.test(command)) throw new Error('Blocked command');
        }
        const app = Application.currentApplication();
        app.includeStandardAdditions = true;
        return app.doShellScript(command);
    }
}

Pattern 4: Application Dictionary Validation

模式4:应用字典验证

python
class AppDictionaryValidator:
    def get_app_dictionary(self, app_name: str) -> str:
        result = subprocess.run(['sdef', f'/Applications/{app_name}.app'],
            capture_output=True, text=True)
        return result.stdout

    def is_scriptable(self, app_name: str) -> bool:
        try:
            return bool(self.get_app_dictionary(app_name).strip())
        except Exception:
            return False

python
class AppDictionaryValidator:
    def get_app_dictionary(self, app_name: str) -> str:
        result = subprocess.run(['sdef', f'/Applications/{app_name}.app'],
            capture_output=True, text=True)
        return result.stdout

    def is_scriptable(self, app_name: str) -> bool:
        try:
            return bool(self.get_app_dictionary(app_name).strip())
        except Exception:
            return False

5. Implementation Workflow (TDD)

5. 实现工作流(TDD)

Step 1: Write Failing Test First

步骤1:先编写失败的测试用例

python
import pytest

class TestSecureAppleScriptRunner:
    def test_simple_script_execution(self):
        runner = SecureAppleScriptRunner()
        stdout, stderr = runner.execute('return "hello"')
        assert stdout == "hello"

    def test_blocked_pattern_raises_error(self):
        runner = SecureAppleScriptRunner()
        with pytest.raises(SecurityError):
            runner.execute('do shell script "rm -rf /"')

    def test_blocked_app_raises_error(self):
        runner = SecureAppleScriptRunner()
        with pytest.raises(SecurityError):
            runner.execute('tell application "Keychain Access" to activate')

    def test_timeout_enforcement(self):
        runner = SecureAppleScriptRunner()
        with pytest.raises(TimeoutError):
            runner.execute('delay 10', timeout=1)
python
import pytest

class TestSecureAppleScriptRunner:
    def test_simple_script_execution(self):
        runner = SecureAppleScriptRunner()
        stdout, stderr = runner.execute('return "hello"')
        assert stdout == "hello"

    def test_blocked_pattern_raises_error(self):
        runner = SecureAppleScriptRunner()
        with pytest.raises(SecurityError):
            runner.execute('do shell script "rm -rf /"')

    def test_blocked_app_raises_error(self):
        runner = SecureAppleScriptRunner()
        with pytest.raises(SecurityError):
            runner.execute('tell application "Keychain Access" to activate')

    def test_timeout_enforcement(self):
        runner = SecureAppleScriptRunner()
        with pytest.raises(TimeoutError):
            runner.execute('delay 10', timeout=1)

Step 2: Implement Minimum to Pass

步骤2:实现最小功能以通过测试

python
class SecureAppleScriptRunner:
    def execute(self, script: str, timeout: int = 30):
        self._check_blocked_patterns(script)
        self._check_blocked_apps(script)
        result = subprocess.run(['osascript', '-e', script],
            capture_output=True, text=True, timeout=timeout)
        return result.stdout.strip(), result.stderr.strip()
python
class SecureAppleScriptRunner:
    def execute(self, script: str, timeout: int = 30):
        self._check_blocked_patterns(script)
        self._check_blocked_apps(script)
        result = subprocess.run(['osascript', '-e', script],
            capture_output=True, text=True, timeout=timeout)
        return result.stdout.strip(), result.stderr.strip()

Step 3: Refactor and Verify

步骤3:重构并验证

bash
pytest tests/test_applescript.py -v
pytest tests/test_applescript.py -k "blocked or security" -v

bash
pytest tests/test_applescript.py -v
pytest tests/test_applescript.py -k "blocked or security" -v

6. Performance Patterns

6. 性能优化模式

Pattern 1: Script Caching

模式1:脚本缓存

python
undefined
python
undefined

BAD: Recompile script every execution

不良实践:每次执行都重新编译脚本

result = subprocess.run(['osascript', '-e', script], capture_output=True)
result = subprocess.run(['osascript', '-e', script], capture_output=True)

GOOD: Cache compiled scripts

最佳实践:缓存已编译的脚本

class CachedScriptRunner: _cache = {} def execute_cached(self, script_id: str, script: str): if script_id not in self._cache: import tempfile _, path = tempfile.mkstemp(suffix='.scpt') subprocess.run(['osacompile', '-o', path, '-e', script]) self._cache[script_id] = path return subprocess.run(['osascript', self._cache[script_id]], capture_output=True)
undefined
class CachedScriptRunner: _cache = {} def execute_cached(self, script_id: str, script: str): if script_id not in self._cache: import tempfile _, path = tempfile.mkstemp(suffix='.scpt') subprocess.run(['osacompile', '-o', path, '-e', script]) self._cache[script_id] = path return subprocess.run(['osascript', self._cache[script_id]], capture_output=True)
undefined

Pattern 2: Batch Operations

模式2:批量操作

python
undefined
python
undefined

BAD: Multiple separate script calls

不良实践:多次单独调用脚本

subprocess.run(['osascript', '-e', f'tell app "{app}" to set bounds...']) subprocess.run(['osascript', '-e', f'tell app "{app}" to activate'])
subprocess.run(['osascript', '-e', f'tell app "{app}" to set bounds...']) subprocess.run(['osascript', '-e', f'tell app "{app}" to activate'])

GOOD: Single batched script

最佳实践:单个批量脚本

script = f'''tell application "{app}" set bounds of window 1 to {{{x}, {y}, {w}, {h}}} activate end tell''' subprocess.run(['osascript', '-e', script], capture_output=True)
undefined
script = f'''tell application "{app}" set bounds of window 1 to {{{x}, {y}, {w}, {h}}} activate end tell''' subprocess.run(['osascript', '-e', script], capture_output=True)
undefined

Pattern 3: Async Execution

模式3:异步执行

python
undefined
python
undefined

BAD: Blocking execution

不良实践:阻塞式执行

result = subprocess.run(['osascript', '-e', script], capture_output=True)
result = subprocess.run(['osascript', '-e', script], capture_output=True)

GOOD: Async execution

最佳实践:异步执行

async def run_script_async(script: str, timeout: int = 30): proc = await asyncio.create_subprocess_exec('osascript', '-e', script, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout) return stdout.decode().strip(), stderr.decode().strip()
undefined
async def run_script_async(script: str, timeout: int = 30): proc = await asyncio.create_subprocess_exec('osascript', '-e', script, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout) return stdout.decode().strip(), stderr.decode().strip()
undefined

Pattern 4: Result Filtering

模式4:结果过滤

python
undefined
python
undefined

BAD: Return full unfiltered output

不良实践:返回完整未过滤的输出

script = 'tell app "System Events" to get properties of every window of every process'
script = 'tell app "System Events" to get properties of every window of every process'

GOOD: Filter in AppleScript

最佳实践:在AppleScript中过滤结果

script = '''tell application "System Events" set windowList to {} repeat with proc in (processes whose visible is true) set end of windowList to name of window 1 of proc end repeat return windowList end tell'''
undefined
script = '''tell application "System Events" set windowList to {} repeat with proc in (processes whose visible is true) set end of windowList to name of window 1 of proc end repeat return windowList end tell'''
undefined

Pattern 5: Minimal App Activation

模式5:最小化应用激活

python
undefined
python
undefined

BAD: Activate app for every operation

不良实践:每次操作都激活应用

subprocess.run(['osascript', '-e', f'tell app "{app}" to activate'])
subprocess.run(['osascript', '-e', f'tell app "{app}" to activate'])

GOOD: Use background operations via System Events

最佳实践:通过System Events执行后台操作

script = f'''tell application "System Events" tell process "{app}" click button "{button}" of window 1 end tell end tell'''

---
script = f'''tell application "System Events" tell process "{app}" click button "{button}" of window 1 end tell end tell''' subprocess.run(['osascript', '-e', script], capture_output=True)

---

7. Security Standards

7. 安全标准

7.1 Critical Vulnerabilities

7.1 关键漏洞

1. Command Injection (CWE-78)

1. 命令注入(CWE-78)

  • Severity: CRITICAL
  • Description: Unsanitized input in
    do shell script
  • Mitigation: Always use
    quoted form of
    , validate inputs
  • 严重性:关键
  • 描述
    do shell script
    中使用未清理的输入
  • 缓解措施:始终使用
    quoted form of
    ,验证输入

2. Privilege Escalation (CWE-269)

2. 权限提升(CWE-269)

  • Severity: CRITICAL
  • Description:
    do shell script
    with administrator privileges
  • Mitigation: Block admin privilege requests
  • 严重性:关键
  • 描述:带管理员权限的
    do shell script
  • 缓解措施:阻止管理员权限请求

3. Script Injection (CWE-94)

3. 脚本注入(CWE-94)

  • Severity: HIGH
  • Description: Injected AppleScript code
  • Mitigation: Never interpolate untrusted data into scripts
  • 严重性:高
  • 描述:注入AppleScript代码
  • 缓解措施:绝不将不可信数据插值到脚本中

4. Path Traversal (CWE-22)

4. 路径遍历(CWE-22)

  • Severity: HIGH
  • Description: File operations with unsanitized paths
  • Mitigation: Validate and canonicalize paths
  • 严重性:高
  • 描述:使用未清理路径的文件操作
  • 缓解措施:验证并规范化路径

5. Information Disclosure (CWE-200)

5. 信息泄露(CWE-200)

  • Severity: MEDIUM
  • Description: Scripts exposing sensitive data
  • Mitigation: Filter sensitive output, audit logging
  • 严重性:中
  • 描述:脚本暴露敏感数据
  • 缓解措施:过滤敏感输出,审计日志

7.2 OWASP Mapping

7.2 OWASP映射

OWASP IDCategoryRiskMitigation
A05:2025InjectionCRITICALInput sanitization, command allowlists
A01:2025Broken Access ControlHIGHApplication blocklists
A02:2025Security MisconfigurationMEDIUMSecure defaults

OWASP ID类别风险缓解措施
A05:2025注入关键输入清理、命令白名单
A01:2025访问控制失效应用黑名单
A02:2025安全配置错误安全默认设置

8. Common Mistakes

8. 常见错误

Never: Interpolate Untrusted Input Directly

绝不:直接插值不可信输入

applescript
-- BAD: Direct interpolation
set userInput to "test; rm -rf /"
do shell script "echo " & userInput

-- GOOD: Use quoted form of
set userInput to "test; rm -rf /"
do shell script "echo " & quoted form of userInput
applescript
-- 不良实践:直接插值
set userInput to "test; rm -rf /"
do shell script "echo " & userInput

-- 最佳实践:使用quoted form of
set userInput to "test; rm -rf /"
do shell script "echo " & quoted form of userInput

Never: Allow Administrator Privileges

绝不:允许管理员权限

python
undefined
python
undefined

BAD: Allow admin scripts

不良实践:允许管理员脚本

script = 'do shell script "..." with administrator privileges' runner.execute(script)
script = 'do shell script "..." with administrator privileges' runner.execute(script)

GOOD: Block admin privilege requests

最佳实践:阻止管理员权限请求

if 'with administrator' in script: raise SecurityError("Administrator privileges blocked")
undefined
if 'with administrator' in script: raise SecurityError("Administrator privileges blocked")
undefined

Never: Execute User-Provided Scripts

绝不:执行用户提供的脚本

python
undefined
python
undefined

BAD: Execute arbitrary user script

不良实践:执行任意用户脚本

user_script = request.body['script'] runner.execute(user_script)
user_script = request.body['script'] runner.execute(user_script)

GOOD: Use templates with validated parameters

最佳实践:使用带验证参数的模板

template = 'tell application "Finder" to activate' runner.execute(template)

---
template = 'tell application "Finder" to activate' runner.execute(template)

---

13. Pre-Implementation Checklist

13. 预实现检查清单

Phase 1: Before Writing Code

阶段1:编写代码前

  • Write failing tests for security controls
  • Write failing tests for expected functionality
  • Review blocked patterns list for completeness
  • Identify which applications will be scripted
  • Plan input sanitization approach
  • 为安全控制编写失败的测试用例
  • 为预期功能编写失败的测试用例
  • 审查黑名单模式列表的完整性
  • 确定将被脚本化的应用
  • 规划输入清理方案

Phase 2: During Implementation

阶段2:实现过程中

  • Input sanitization for all user data
  • Blocked pattern detection enabled
  • Application blocklist configured
  • Command allowlist for shell scripts
  • Timeout enforcement
  • Audit logging enabled
  • Use
    quoted form of
    for all shell arguments
  • Cache compiled scripts for reuse
  • 对所有用户数据进行输入清理
  • 启用黑名单模式检测
  • 配置应用黑名单
  • 设置Shell脚本命令白名单
  • 强制执行超时限制
  • 启用审计日志
  • 对所有Shell参数使用
    quoted form of
  • 缓存已编译脚本以便复用

Phase 3: Before Committing

阶段3:提交代码前

  • All tests pass:
    pytest tests/test_applescript.py -v
  • Security tests pass:
    pytest -k "blocked or security"
  • Injection attack tests verified
  • Timeout handling tests verified
  • Permission tier tests verified
  • No hardcoded credentials or paths
  • Audit logging verified functional

  • 所有测试通过:
    pytest tests/test_applescript.py -v
  • 安全测试通过:
    pytest -k "blocked or security"
  • 验证注入攻击测试
  • 验证超时处理测试
  • 验证权限等级测试
  • 没有硬编码的凭据或路径
  • 验证审计日志功能正常

14. Summary

14. 总结

Your goal is to create AppleScript automation that is:
  • Secure: Input sanitization, command filtering, application blocklists
  • Reliable: Timeout enforcement, proper error handling
  • Auditable: Comprehensive logging of all executions
Security Reminders:
  1. Always use
    quoted form of
    for shell arguments
  2. Never interpolate untrusted data into scripts
  3. Block administrator privilege requests
  4. Maintain strict command allowlists
  5. Log all script executions

您的目标是创建具备以下特性的AppleScript自动化:
  • 安全:输入清理、命令过滤、应用黑名单
  • 可靠:超时机制、完善的错误处理
  • 可审计:全面记录所有执行日志
安全提醒
  1. 对所有Shell参数始终使用
    quoted form of
  2. 绝不将不可信数据插值到脚本中
  3. 阻止管理员权限请求
  4. 维护严格的命令白名单
  5. 记录所有脚本执行日志

References

参考资料

  • Security Examples: See
    references/security-examples.md
  • Threat Model: See
    references/threat-model.md
  • Advanced Patterns: See
    references/advanced-patterns.md
  • 安全示例:参见
    references/security-examples.md
  • 威胁模型:参见
    references/threat-model.md
  • 高级模式:参见
    references/advanced-patterns.md