Skip to content

👾 Open Computer Use – Open-Source Alternative to Codex Computer Use

feat(macos): simplify Locked Use enable and isolate cold peer verification

ifuryst89c5b64addf8
diff --git a/apps/OpenComputerUse/Sources/OpenComputerUse/LockedUseSettings.swift b/apps/OpenComputerUse/Sources/OpenComputerUse/LockedUseSettings.swift
index 5ee2a9b..0291ae6 100644
--- a/apps/OpenComputerUse/Sources/OpenComputerUse/LockedUseSettings.swift
+++ b/apps/OpenComputerUse/Sources/OpenComputerUse/LockedUseSettings.swift
@@ -1,4 +1,6 @@
import AppKit
+@preconcurrency import ApplicationServices
+import CoreGraphics
import Darwin
import Foundation
import OpenComputerUseKit
@@ -11,8 +13,8 @@ enum LockedUseSettings {
static func handle(arguments: [String]) throws -> Bool {
guard arguments.first == "locked-use", arguments.count > 1,
["enable", "disable", "recover", "certify", "settings"].contains(arguments[1]) else { return false }
- guard arguments.count == 2 || arguments == ["locked-use", "enable", "--validation"] else {
- throw OpenComputerUseCLIError(message: "Usage: ocu locked-use enable [--validation] | disable | recover | certify | settings")
+ guard arguments.count == 2 else {
+ throw OpenComputerUseCLIError(message: "Usage: ocu locked-use enable | disable | recover | certify | settings")
}
let action = arguments[1]
if action == "settings" {
@@ -20,18 +22,18 @@ enum LockedUseSettings {
app.setActivationPolicy(.accessory)
let alert = NSAlert()
alert.messageText = "Locked Use"
- alert.informativeText = "在锁屏时继续使用已登录的 Mac。所有显示器会被遮蔽;移动鼠标或按键立即返回锁屏。启用需要管理员授权和已验证的解锁组件。"
+ alert.informativeText = "在锁屏时继续使用已登录的 Mac。所有显示器会被遮蔽;移动鼠标或按键立即返回锁屏。启用需要管理员授权、辅助功能、屏幕录制和输入监控权限。"
alert.addButton(withTitle: "启用")
alert.addButton(withTitle: "停用并移除")
alert.addButton(withTitle: "取消")
switch alert.runModal() {
- case .alertFirstButtonReturn: try enable(validation: false)
+ case .alertFirstButtonReturn: try enable()
case .alertSecondButtonReturn: try disable()
default: break
}
- } else if action == "enable" { try enable(validation: arguments.last == "--validation") }
+ } else if action == "enable" { try enable() }
else if action == "certify" { try certify() }
- else if action == "recover" { try enable(validation: false, recovering: true) }
+ else if action == "recover" { try enable(recovering: true) }
else { try disable() }
return true
}
@@ -51,7 +53,7 @@ enum LockedUseSettings {
guard process.terminationStatus == 0 else { throw OpenComputerUseCLIError(message: "Locked Use administrator installation did not complete. Existing recovery records were retained.") }
print(text, terminator: "")
}
- private static func enable(validation: Bool, recovering: Bool = false) throws {
+ private static func enable(recovering: Bool = false) throws {
guard LockedUseSession.current().state == .unlocked else { throw OpenComputerUseCLIError(message: "Unlock the Mac normally before administrator installation or recovery.") }
let identity = try LockedUseSigningIdentity.current()
guard identity.userID > 0, ["com.ifuryst.opencomputeruse", "com.ifuryst.opencomputeruse.dev"].contains(identity.signingIdentifier),
@@ -80,8 +82,26 @@ enum LockedUseSettings {
"/bin/chmod -RN " + quote(stage) + "\n" +
"/bin/chmod -R go-w " + quote(stage) + "\n" +
"/usr/bin/codesign --verify --strict -R " + quote(requirement) + " " + quote(stage + "/OCULockInstaller") + "\n" +
- quote(stage + "/OCULockInstaller") + (recovering ? " recover" : " install " + quote(stage) + " " + String(identity.userID) + " " + (validation ? "validation" : "production"))
+ quote(stage + "/OCULockInstaller") + (recovering ? " recover" : " install " + quote(stage) + " " + String(identity.userID) + " " + "production")
try elevate(shell)
+ if !recovering { try requestPermissions() }
+ }
+
+ private static func requestPermissions() throws {
+ let team = try LockedUseSigningIdentity.current().teamIdentifier!
+ // Verify the administrator-installed components before launching Guardian.
+ _ = try LockedUseComponentValidation.current(team: team)
+ let guardian = Process()
+ guardian.executableURL = URL(fileURLWithPath: "/Library/Application Support/OpenComputerUse/LockedUse/OCU Guardian.app/Contents/MacOS/OCUGuardian")
+ guardian.arguments = ["--request-permissions"]
+ try guardian.run()
+ guardian.waitUntilExit()
+ guard guardian.terminationStatus == 0 else {
+ throw OpenComputerUseCLIError(message: "Locked Use is installed, but Guardian permission setup failed. Run locked-use status before using it.")
+ }
+ _ = AXIsProcessTrustedWithOptions([kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary)
+ if !CGPreflightScreenCaptureAccess() { _ = CGRequestScreenCaptureAccess() }
+ print("Locked Use installed. Complete Open Computer Use and OCU Guardian permissions in System Settings, then run ocu locked-use status.")
}
private static func certify() throws {
guard LockedUseSession.current().state == .unlocked else {
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index cfa4d9c..17eac7b 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -143,9 +143,9 @@
- `locked-use status [--json]` 和 `doctor` 增加只读 session / Input Monitoring / 插件诊断,由 app agent 提供真实 runtime 权限状态。 `doctor --json` 保持纯权限 JSON,不弹权限引导;定向 AX `query` 在读取前和返回结果前检查会话与当前租约。
- 真实窗口 snapshot、缓存复用与事件投递检查当前控制台 session;锁屏或未知 / 切换用户状态明确拒绝。fixture 不属于真实桌面,继续支持 headless 测试。
-- `LockedUseStateMachine` 是由独立 Broker 串行驱动的纯保护策略,覆盖一次性许可、租约、guardian heartbeat、接管和重锁确认;已接入受管理员验证 profile 限定的 unlock 事务,受保护 legacy 闭环已实测,完整生产证据仍待完成。
-- `experiments/LockedUse` 与独立脚本提供 deny-only Authorization 插件 ABI / 系统加载探针(仅独立 right),完整管理员验证组件另在 screensaver 授权链登记自定义分支并保留系统认证 fallback。独立 `OCUGuardian` 测试 app 先用共享的 `DisplayShieldSurface` 做不锁屏 / 不操作的 15 秒品牌遮罩 preview(倒计时仅记录到日志),再用 child watchdog rehearsal 验证输入接管、重锁、遮挡窗口 AX / ScreenCaptureKit 及只读 loginwindow 结构。新增签名 Broker、remote 机制、锁屏 Guardian 和安装入口仍处于验证阶段,生产 profile 缺少实测证据时拒绝自动解锁。
-- `LockedUseNative` 读取 Unix socket 的内核 audit token;`LockedUsePeerIdentity` 验证动态进程签名;`LockedUseClientApprovals` 从 root 所有、不可由普通用户写入的目录加载批准记录;`LockedUsePermitRegistry` 管理绑定会话的一次性 32-byte 许可。Broker IPC 通过 SCM_RIGHTS 验证原生 CLI client 并隔离 agent / guardian / Apple helper / observer / admin 角色;app agent 按连接管理租约与排空。安装入口保留认证 fallback 并登记当前用户的同团队组件。真实 loginwindow / Keychain / 故障验证仍待完成,生产 backend 默认关闭。详细边界见 [Locked Use](locked-use.md)。
+- `LockedUseStateMachine` 是由独立 Broker 串行驱动的纯保护策略,覆盖一次性许可、租约、guardian heartbeat、接管和重锁确认;已接入管理员显式启用的 unlock 事务,受保护 legacy 闭环已实测,完整生产证据仍待完成。
+- `experiments/LockedUse` 与独立脚本提供 deny-only Authorization 插件 ABI / 系统加载探针(仅独立 right),完整管理员验证组件另在 screensaver 授权链登记自定义分支并保留系统认证 fallback。独立 `OCUGuardian` 测试 app 先用共享的 `DisplayShieldSurface` 做不锁屏 / 不操作的 15 秒品牌遮罩 preview(倒计时仅记录到日志),再用 child watchdog rehearsal 验证输入接管、重锁、遮挡窗口 AX / ScreenCaptureKit 及只读 loginwindow 结构。新增签名 Broker、remote 机制、锁屏 Guardian 和安装入口仍处于验证阶段,普通 enable 安装服务并申请权限,服务启动仍严格验证同团队组件签名。
+- `LockedUseNative` 读取 Unix socket 的内核 audit token;`LockedUsePeerIdentity` 验证动态进程签名;`LockedUseClientApprovals` 从 root 所有、不可由普通用户写入的目录加载批准记录;`LockedUsePermitRegistry` 管理绑定会话的一次性 32-byte 许可。Broker IPC 通过 SCM_RIGHTS 验证原生 CLI client 并隔离 agent / guardian / Apple helper / observer / admin 角色;app agent 按连接管理租约与排空。安装入口保留认证 fallback 并登记当前用户的同团队组件。历史验证报告保留为研发证据,正常启用不以报告为门槛;完整故障矩阵仍需继续实测。详细边界见 [Locked Use](locked-use.md)。
## 关键边界
diff --git a/docs/QUALITY_SCORE.md b/docs/QUALITY_SCORE.md
index 7656a7b..e680e7e 100644
--- a/docs/QUALITY_SCORE.md
+++ b/docs/QUALITY_SCORE.md
@@ -14,7 +14,7 @@
| 产品面 | B | 已经有 Swift 本地 `computer-use` MCP server、默认 app 模式权限引导,以及一轮按官方 surface / result 行为收敛过的 9 个 tools。 | 继续收敛复杂 AX 场景下的 state rendering 细节、权限 UI 和更清晰的用户错误提示。 |
| Windows runtime | C | 已新增独立 Go `.exe`,通过 Windows UI Automation + Win32 window message 暴露同样 9 个 tools、MCP server 和 `call --calls`;默认不再自动启动 app、执行 `SetFocus`,或让 `type_text` 走可能抢前台的 UIA text fallback;截图会过滤隐藏、最小化、cloaked、离屏和退化窗口,并在 Go 层复核 PNG,但整体仍是功能性第一版。 | 把当前实机 screenshot 边界用例收敛成仓库内 Windows fixture / 交互式 smoke,再补 installer/signing,以及更原生的 Go UIA 实现或更稳定的 bridge。 |
| Linux runtime | C | 已新增独立 Go binary,通过 Python GI / AT-SPI2 暴露同样 9 个 tools、MCP server 和 `call --calls`;Ubuntu GNOME VM 已跑通 `list_apps`、MCP tools list 和 Text Editor 8-tool sequence,并已接入 npm bundled artifact 分发,但截图在 GNOME Wayland 下仍只能 best-effort,coordinate input 也不是通用后台模型。 | 补 Linux fixture、可重复 smoke runner、portal/compositor screenshot 路径,以及更原生的 Go D-Bus/libatspi bridge。 |
-| macOS Locked Use | D | 已有签名 Broker / 插件、双进程保护、原生租约与恢复入口,离线和遮罩 rehearsal 有回归;安装恢复和无许可双保护释放已实测,独立无遮罩 Return 解锁 / 重锁已实测,受保护自动解锁 / AX / SCK / 重锁及隔离 legacy Keychain 已有一轮实测通过,完整会话认证状态 / 故障链路尚未通过实测,生产关闭。 | 物理覆盖已确认,完成 Data Protection Keychain / 会话认证状态和 Secure Input / 崩溃 / 显示器故障实测后开放生产。 |
+| macOS Locked Use | D | 已有签名 Broker / 插件、双进程保护、原生租约与恢复入口,离线和遮罩 rehearsal 有回归;安装恢复和无许可双保护释放已实测,独立无遮罩 Return 解锁 / 重锁已实测,受保护自动解锁 / AX / SCK / 重锁及隔离 legacy Keychain 已有一轮实测通过,完整会话认证状态 / 故障链路尚未通过实测;正常启用改为管理员 enable 与签名校验,普通 enable / 正常 MCP 的完整 GUI 闭环已实测。 | 物理覆盖已确认,继续完成 Data Protection / 会话认证状态、Secure Input / 崩溃 / 显示器故障回归及正式发布制品检查。 |
| 架构文档 | B | 顶层结构、fixture bridge、app 模式和验证路径已经落文档。 | 后续补 release artifact、code signing / notarization 和 host 集成方式。 |
| 测试 | B | `swift test` + smoke suite 已覆盖 9 个 tools 的回归,并新增了针对“前台焦点是否被抢占”的手工对比样本沉淀。 | 增加更多普通 app 的录制回归,减少只依赖 fixture 和一次性手工检查。 |
| 可观测性 | C | 已有 `doctor`、`snapshot`、smoke 输出,以及一组仓库内留档的官方 `computer-use` / 本仓库实现对比样本。 | 补统一日志级别、失败上下文和 release artifact 里的诊断信息,把一次性样本收敛成可重复采集流程。 |
diff --git a/docs/RELIABILITY.md b/docs/RELIABILITY.md
index 5987f88..b6969f9 100644
--- a/docs/RELIABILITY.md
+++ b/docs/RELIABILITY.md
@@ -59,7 +59,7 @@ CI/CD 流程结构和 release 自动化的默认方案,统一写在 `docs/CICD
## macOS Locked Use 预检
-- `ocu locked-use status --json`:只读检查当前会话 / runtime 权限 / 安装组件;缺少完整实测证据时生产自动解锁不可用,显式验证 profile 与生产状态分开报告。
+- `ocu locked-use status --json`:只读检查当前会话 / runtime 权限 / 安装组件;普通 enable 安装并请求权限,status 检查签名、客户端批准与认证规则;开发诊断 profile 不属于普通开启流程。
- `swift test --filter LockedUseTests`:许可、租约、超时、显示器变化、本地接管和重锁确认策略回归。
- `./scripts/build-locked-use-plugin.sh`:构建 deny-only ABI probe 并在普通进程内测试;通过不代表 SecurityAgent 加载成功。
- `./scripts/build-locked-use-guardian.sh`:构建独立 Guardian / child watchdog;`--diagnose` 与签名构建后的 `--peer-self-test` 为非锁屏诊断。先运行 `python3 scripts/run-locked-use-rehearsal.py --shield-preview` 观察 15 秒倒计时与所有物理屏幕;用户准备好后才运行 `--confirm-lock-test`,验证窗口 AX / SCK 与重锁结果;人工 GUI 测试不进入自动 CI。`python3 scripts/tests/locked-use-rehearsal.test.py` 不启动 GUI / 锁屏,回归 controller 的恢复顺序和 preview 不锁屏边界。
@@ -67,3 +67,6 @@ CI/CD 流程结构和 release 自动化的默认方案,统一写在 `docs/CICD
- Root 的认证策略读取使用独立队列;策略待定 / 过期 / 失败时停止新许可,协调队列继续处理恢复。独立 agent deadline 限制准备 / 停止时间,仍须验证真正撤罩和正常手动解锁的耗时。
- `python3 scripts/run-locked-use-native-validation.py --confirm-recovery-test` 是验证 profile 的人工故障收束入口,不签发解锁许可。必须同时证明两个保护确曾就绪、原会话锁定、动作排空与双方释放 ACK,才报告通过。
+
+- `python3 scripts/run-locked-use-smoke.py --app <signed-app> --guardian <guardian-binary> --fixture <demo-app> --confirm-lock-test` 通过正常 MCP 读取 / 点击 / 截图验证普通 enable 的闭环,不使用测试解锁 RPC 或 Keychain。成功后保留 Counter 窗口,失败先结束租约并等待双方保护释放。
+- 首次原生连接握手的响应预算为 8 秒,冷签名校验由独立的有界工作队列完成;动作、保护和插件 RPC 仍为 2 秒。策略观察过期停止当前工作并等待新观察,不永久禁用安装;确认认证策略变化才永久禁用当前服务 epoch。
diff --git a/docs/SECURITY.md b/docs/SECURITY.md
index 3b34e86..5dd924a 100644
--- a/docs/SECURITY.md
+++ b/docs/SECURITY.md
@@ -50,7 +50,7 @@
## macOS Locked Use 实验边界
-- 生产 backend 在完整实测证据缺失时关闭;只有管理员显式安装的验证 profile 能运行实验事务。用户环境和请求 metadata 不能开启生产自动解锁。
+- 正常 backend 由管理员 enable 安装启用,启动时验证同团队组件签名;历史验证报告不作为用户启用门槛。用户环境和请求 metadata 不能开启管理员未安装的服务;无遮罩与 recovery probe 等诊断仍只对内部验证 profile 开放。
- 签名 Root Broker 从内核 audit token 认证原生 CLI / app agent / Guardian / Apple helper,批准绑定 UID、角色、signer 和 Team ID。SCM_RIGHTS 原客户端端点也要验证;许可绑定会话、连接与一次性 attempt,不能从请求指定任意 requirement。
- 安装器只添加自己的 OR branch,保留原密码 fallback;备份完整语义规则并在回滚前检查当前策略没有第三方变更。独立 deny-only probe 与实际验证 profile 分离。
- 解锁入口仅在双保护准备后做一次公开电源活动声明,并在 3 秒内等待完整 AX 发布。只按 Apple 签名 loginwindow 的 AXIdentifier 匹配(深度 ≤8),唯一候选写空字符串,不读取密码。验证版本随后尝试一次窗口限定点击:要求有限 AX 几何、唯一同 PID 的 on-screen 窗口包含目标点,使用 NSEvent.windowNumber、目标 PID / 窗口字段、与现有 sky_click 复用的 CGEventSetWindowLocation 私有编码及 subtype 3,在 session stage 投递鼠标 down/up,不合成全局 Return。验证 profile 可在真实 UserPasswordTextField 空写成功、字段声明支持 AXConfirm 时尝试一次 AXConfirm;是否生效独立记录,不视作解锁证据。两个会话过滤器只接受继承私有管道传递的随机一次性标记、正确 Guardian 来源、无 Shift / Control / Option / Command 点击修饰键、同目标 / 窗口 / 坐标且相隔小于 250ms 的一对点击;能力最多 5 秒,重复、接管、停止或重锁后不可恢复,不增加 PID-only 豁免。随机标记不进入 argv/env、日志或报告。硬件活动检测始终独立工作并撤销能力。此路由实际投递 / 认证效果尚待实测,queued 不是成功证据。取消禁止迟到写入,在途事件必须排空。SetResult 与真实同会话 unlocked 观察缺一不可。
diff --git a/docs/exec-plans/completed/20261013-locked-use-enable.md b/docs/exec-plans/completed/20261013-locked-use-enable.md
new file mode 100644
index 0000000..24d6cb0
--- /dev/null
+++ b/docs/exec-plans/completed/20261013-locked-use-enable.md
@@ -0,0 +1,40 @@
+# Locked Use 单一启用入口
+
+## 目标
+
+用户只需 enable / status / disable 即可安装、授权并使用 Locked Use;验证模式不再是正常解锁的前提。在当前 PR 分支完成签名构建和实机闭环,验收后再合并。
+
+## 范围
+
+- 正常服务由管理员安装与签名检查决定可用性,保留双保护、许可、身份校验和重锁屏障。
+- enable 完成安装后请求主 App 和 Guardian 权限;状态区分安装与权限就绪。
+- 开发诊断入口不因正式启用而开放;旧验证记录只用于测试报告。
+- 同步中英文使用指南及架构、安全、可靠性说明。
+- 不发布版本、不自动合并 PR、不访问现有用户凭据。
+
+## 验证方式
+
+- Swift / Node / Python 回归,签名组件 ABI 与严格嵌套签名检查。
+- 正式 App 的普通 enable 安装,权限检查,短时双屏遮罩、自动解锁、真实 AX 点击 / SCK、重锁与正常手动解锁。
+- 任一失败先结束租约并确认保护释放,避免重复锁回用户会话。
+
+## 进度
+
+- [x] 确认普通 enable 目前仍被旧验证记录门槛阻塞,Return 确认能力也只在验证 profile 下下发。
+- [x] 收敛 CLI、安装与服务启动行为,接入权限引导。
+- [x] 离线验证与正式构建。
+ - Swift 327 项(7 跳过)、Node 36 项、Python 30 项均通过;Developer ID 正式 App 与组件构建及严格签名检查通过。
+- [x] 普通 enable 与短时实机闭环。
+- [x] 更新文档与 history,提交后 rebase main 并更新 PR。
+
+## 实机迭代
+
+- 普通 enable 安装成功,launchd 使用 --serve,主 App 和 Guardian 的实际权限检查均通过。
+- 初次只读 observer 遇到冷签名校验 3.14 秒,超过 2 秒响应预算。只读响应预算调整为 6 秒,其他 RPC 与许可时限不变。
+- 该延迟还触发旧服务将策略观察过期永久判为安装失效。改为过期停止当前工作但允许新观察恢复;真实策略失效仍禁用当前 epoch,新增两项回归通过。
+- 本轮失败在解锁与显示遮罩前结束,双方保护释放,用户正常恢复桌面。正在正常卸载 / 重装修正版,再验证完整闭环。
+
+- 普通 --serve 已通过一次完整的正常 MCP 解锁 / AX 点击 / 截图变化 / 5 秒保持 / 重锁和双保护释放闭环,用户正常解锁后看到 Counter: 1。
+- 再测遇到 Agent 首次连接冷签名校验约 3 秒,旧 2 秒请求预算在遮罩启动前失败。改为首次握手 8 秒、动作与保护 2 秒;首次签名校验移到 4 个并发 worker 的独立队列,未认证 socket 与已认证连接总数最多 64,超时先 shutdown 并保留 fd 所有权至校验完成,避免复用竞态。新增独立控制队列回归通过。
+
+- 异步首次校验后的实机闭环通过:锁屏后正常 MCP 自动解锁 / 捕获约 3.48 秒,AX 计数 0→1、截图变化、遮罩保持 5 秒、重锁、双方释放 ACK、正常手动解锁后同一窗口仍为 Counter: 1。用户确认可以并要求 rebase main 后推送。该闭环不代表完整系统凭据与故障矩阵全部验收。
diff --git a/docs/histories/2026-10/20261005-1109-macos-locked-use-preflight.md b/docs/histories/2026-10/20261005-1109-macos-locked-use-preflight.md
index 0f748e1..8fa775b 100644
--- a/docs/histories/2026-10/20261005-1109-macos-locked-use-preflight.md
+++ b/docs/histories/2026-10/20261005-1109-macos-locked-use-preflight.md
@@ -380,3 +380,11 @@ Swift 301 项(7 跳过、0 失败)、Node 25 项、Python 29 项和文档检
合并 main 的只读 doctor --json 和定向 AX query,解决 CLI 枚举 / 解析、主 App 与代理诊断输出、JS 回归和发布记录冲突。JSON 模式保留纯权限 JSON 与不弹引导的行为;文本 doctor 继续输出 Locked Use 诊断,两边命令和测试均保留。新 query 入口在读取前与返回结果前加入当前会话 / 租约检查,扩展无输入投递的失效租约回归,防止新读取路径绕过既有 Locked Use 限制。
Swift 323 项(7 跳过、0 失败)、Node 36 项、Locked Use Python 27 项、文档与格式检查通过;直接运行新构建 doctor --json,确认可作为单个 JSON 对象解析。本轮未安装组件、锁屏或更改系统认证策略。
+
+### 收敛正常 enable 与冷启动稳定性(2026-10-14)
+
+用户要求正常启用不再依赖开发验证参数。公共 enable 移除该参数,安装正常 --serve 服务并请求主 App / Guardian 的权限。启动仍校验同团队签名、root 安装记录、批准与原认证规则;双保护、一次性许可、会话身份和重锁屏障保留。受保护的空值 / 点击 / Return 提交能力向正常 Guardian 开放;无遮罩等开发诊断仍隔离。status 增加安装 Guardian 的实际权限检查,available 包含主 App 与 Guardian 权限,不再以历史测试报告为开启门槛。中英文使用指南与架构 / 安全 / 可靠性文档同步。
+
+新增正常 MCP smoke:不使用测试解锁 RPC 或 Keychain,实际读取目标、AX 点击、确认计数与截图变化,保持 5 秒并重锁,等待双方保护释放和手动解锁,保留原 Counter 窗口。实机遇到冷签名校验约 3 秒:首次签名校验移到独立 4-worker 队列,最多 64 个已认证 / 待认证连接,首次原生握手 8 秒、动作 / 心跳 / 插件许可 2 秒;待验证 fd 超时先 shutdown,完成前不关闭复用。策略观察过期停止当前工作但不永久禁用安装,真实策略变化仍禁用 epoch。新增超时分层、独立控制队列和过期恢复回归。
+
+Swift 327 项(7 跳过、0 失败)、Node 36 项、Python 30 项与文档 / 格式检查通过;签名正式 App、组件 ABI 和严格签名检查通过。普通 enable 安装及 --serve / 权限就绪确认通过,正常 MCP 闭环已实测;最终异步校验版锁屏到捕获约 3.48 秒,计数 0→1、截图变化、保持 5 秒、重锁、双方释放 ACK、手动解锁与计数保留均通过,用户确认可以并要求补充推送。完整系统凭据 / 故障矩阵及 universal 发布制品仍需继续验证,本轮不 bump / tag / 发布。
diff --git a/docs/locked-use.en.md b/docs/locked-use.en.md
index e7f67f2..8cf02ef 100644
--- a/docs/locked-use.en.md
+++ b/docs/locked-use.en.md
@@ -11,12 +11,10 @@ You need macOS 14 or later and a signed OCU app that includes the Locked Use com
Unlock your Mac normally, then run this command and complete the administrator prompt:
```bash
-ocu locked-use enable --validation
+ocu locked-use enable
```
-This installs the components and enables validation mode. No manual configuration is needed. OCU's regular permission setup does not enable Locked Use automatically.
-
-Use validation mode for testing for now. Full production validation is still incomplete. Running `ocu locked-use enable` without `--validation` does not allow automatic unlock unless valid validation records are present.
+This installs the components and requests permissions for the main app and Guardian. No manual configuration is needed. OCU's regular permission setup does not enable Locked Use automatically.
```bash
# Check installation and permissions
@@ -37,7 +35,7 @@ Allow these under **System Settings → Privacy & Security**:
Installation and removal also require administrator authorization. Broker and the authorization plug-in do not need separate grants for these permissions. Development app names include `(Dev)`.
-After installation, run this command to request Guardian's permissions, then follow the system prompts:
+`enable` requests these permissions. To request Guardian's permissions again, run:
```bash
"/Library/Application Support/OpenComputerUse/LockedUse/OCU Guardian.app/Contents/MacOS/OCUGuardian" --request-permissions
diff --git a/docs/locked-use.md b/docs/locked-use.md
index 2b14d84..88b3489 100644
--- a/docs/locked-use.md
+++ b/docs/locked-use.md
@@ -1,4 +1,19 @@
-# macOS Locked Use(实验阶段)
+# macOS Locked Use
+
+正常使用只需要三个命令:
+
+```sh
+ocu locked-use enable
+ocu locked-use status
+ocu locked-use disable
+```
+
+`enable` 安装签名组件、保留系统密码认证方式,并请求主 App 和 Guardian 的权限。正常启用不需要开发验证参数或历史验证报告。完整安装位置和权限说明见[中文使用指南](locked-use.zh-CN.md) / [English](locked-use.en.md)。
+
+## 研发记录(历史行为)
+
+以下保留研发过程与测试边界,包含旧版本的 profile、验证门槛及未完成的测试。这些记录不代表当前 enable 的开启要求;实际使用以上面的使用指南为准。
+
目标是在已登录用户的屏幕锁定后,允许已授权客户端临时解锁 GUI 会话,同时遮蔽所有物理显示器,继续通过 AX / ScreenCaptureKit / 输入执行任务,最后重锁。
@@ -166,7 +181,7 @@ OPEN_COMPUTER_USE_INCLUDE_LOCKED_USE=1 scripts/build-open-computer-use-app.sh de
安装 UI 将 artifacts 复制到 root 保护的 staging,验证签名 Installer 后才执行它。Installer 再验证全部组件、签名团队、hardened runtime、无注入 entitlement 和 root 目录 / ACL;登记当前用户的原生 CLI client、app agent 与 Guardian。当前登记范围是本 app 的原生客户端,不能将其描述为已认证 Node / Codex 父进程。原生客户端 socket 通过 SCM_RIGHTS 转交,Broker 仅检验内核 peer,不读该 socket 的业务数据;UID / audit session 必须与 agent 一致。规则备份先写入 root 目录;只为现有 OR policy 增加独立 remote branch,保留原生 / 第三方 fallback。Installer 并发操作用独立 flock 排斥。
-`locked-use enable` 安装生产 profile,缺少匹配实测证据时不能自动解锁。仅开发实测显式使用 `locked-use enable --validation`;它通过管理员安装的 launchd profile 开放验证事务,不等于生产验证通过。`locked-use disable` 先冻结 Broker 的新租约,只有 idle / awaitingManualUnlock 时恢复匹配的原规则、停止服务并移除自身插件及 staged 副本;第三方策略改变时拒绝覆盖。安装失败会保留 recovery plan,`locked-use recover` 可恢复部分安装,但只有实例锁和 root journal 证明旧保护已释放时才移除组件;未排空的崩溃事务必须先恢复 Broker。此路径仍待系统验证。
+`locked-use enable` 安装生产 profile,缺少匹配实测证据时不能自动解锁。仅开发实测显式使用 `locked-use enable`;它通过管理员安装的 launchd profile 开放验证事务,不等于生产验证通过。`locked-use disable` 先冻结 Broker 的新租约,只有 idle / awaitingManualUnlock 时恢复匹配的原规则、停止服务并移除自身插件及 staged 副本;第三方策略改变时拒绝覆盖。安装失败会保留 recovery plan,`locked-use recover` 可恢复部分安装,但只有实例锁和 root journal 证明旧保护已释放时才移除组件;未排空的崩溃事务必须先恢复 Broker。此路径仍待系统验证。
普通 app-agent GUI 调用在完成登录的锁定 console session 请求租约;库存 / 协议查询不触发解锁。Guardian 从锁屏启动,通过私有 inherited pipe 接收 challenge;准备覆盖、tap、硬件活动 monitor 与独立 watchdog 后,收到 root 的一次 requestUnlock,调用公开 IOPMAssertionDeclareUserActivity 唤醒显示器。随后等待系统发起 screensaver 认证事务,remote 插件显式 SetResult 放行已消费的一次性许可。唤醒成功不证明事务已开始或会话已解锁;3 秒预算内重试完整 AX 发布,然后在已验证 Apple 签名的 loginwindow 上遍历 AXChildren(深度 ≤8、最多 300 节点、0.75 秒扫描预算),优先匹配 `UserPasswordTextField`,回退 `FocusedUser`。完整扫描且候选唯一时空字符串写入,不读取字段内容。仅 fallback 使用一次窗口限定、双过滤器能力验证的点击;点击后重新查找真正的密码框。管理员验证 profile 才允许在密码框空写成功、明确声明支持 AXConfirm 时执行一次确认,采用 Root hello 的实验开关;生产及旧协议缺少开关时不执行。没有全局键盘合成。空写、点击、AXConfirm 返回均不能替代许可消费与真实同会话解锁证据。两套保护分别持有有界 display-sleep assertion,退出 / 最大租约期限时由 powerd 释放。原生会话真实 unlocked 且根服务确认全部保护健康后,才启用 GUI dispatch。各输入 / AX mutation / snapshot session gate 再向根服务核验当前连接。其他连接用只读 observer endpoint 检查租约,不能借用临时解锁的桌面。Secure Event Input 下 IOHID 活动交付尚待实机验证。参考方案的核对与尚未证实的系统行为见 [解锁入口复核](references/macos-locked-use-solution-review.md)。
diff --git a/docs/locked-use.zh-CN.md b/docs/locked-use.zh-CN.md
index 25a22e1..5a0d128 100644
--- a/docs/locked-use.zh-CN.md
+++ b/docs/locked-use.zh-CN.md
@@ -11,12 +11,10 @@ Locked Use 可以让 Agent 在 Mac 锁屏时继续操作 GUI。期间所有屏
先正常解锁 Mac,然后运行下面的命令,完成管理员授权:
```bash
-ocu locked-use enable --validation
+ocu locked-use enable
```
-这个命令会安装所需组件并开启验证模式,不需要手动修改配置。Locked Use 不会随 OCU 的普通权限引导自动开启。
-
-目前先用验证模式测试。正式模式的完整验证尚未完成;`ocu locked-use enable` 不带 `--validation` 时,缺少有效验证记录就不会自动解锁。
+这个命令会安装所需组件,并请求主 App 和 Guardian 的权限,不需要手动修改配置。Locked Use 不会随 OCU 的普通权限引导自动开启。
```bash
# 查看安装和权限状态
@@ -37,7 +35,7 @@ ocu locked-use disable
安装、卸载还需要管理员授权。Broker 和授权插件不需要单独申请上述权限。开发版的 App 名称会带 `(Dev)`。
-安装后运行下面的命令,弹出 Guardian 的权限申请,再按系统提示授权:
+`enable` 会发起权限申请。若需要再次申请 Guardian 权限,可以运行:
```bash
"/Library/Application Support/OpenComputerUse/LockedUse/OCU Guardian.app/Contents/MacOS/OCUGuardian" --request-permissions
diff --git a/experiments/LockedUse/Sources/Broker/BrokerMain.swift b/experiments/LockedUse/Sources/Broker/BrokerMain.swift
index 4418e21..49cd93b 100644
--- a/experiments/LockedUse/Sources/Broker/BrokerMain.swift
+++ b/experiments/LockedUse/Sources/Broker/BrokerMain.swift
@@ -18,11 +18,11 @@ enum BrokerMain {
let configuration = try LockedUseBrokerConfiguration.loadInstalled()
let validation = CommandLine.arguments[1] == "--serve-validation"
let team = try LockedUseSigningIdentity.current().teamIdentifier!
- let evidence = try LockedUseComponentValidation.current(team: team)
- let matched = configuration.matchesValidation(osBuild: evidence.osBuild,
- brokerHash: evidence.brokerHash, guardianHash: evidence.guardianHash, pluginHash: evidence.pluginHash)
+ // Administrator enrollment enables the backend; all installed code
+ // still has to pass the same-team strict signature verification.
+ _ = try LockedUseComponentValidation.current(team: team)
let server = try BrokerServer(approvals: approvals, enabled: configuration.enabled,
- backendValidated: validation || matched, validationMode: validation)
+ backendValidated: true, validationMode: validation)
try server.start()
withExtendedLifetime(server) { dispatchMain() }
} catch {
@@ -43,6 +43,9 @@ private final class BrokerServer: @unchecked Sendable {
private var coordinator: LockedUseBrokerCoordinator
private var listeners: [DispatchSourceRead] = []
private var connections: [UUID: BrokerConnection] = [:]
+ private let peerAuthenticator = LockedUsePeerAuthenticator()
+ private var pendingAdmissions: [UUID: Int32] = [:]
+ private var cancelledAdmissions: Set<UUID> = []
private var timer: DispatchSourceTimer?
private var lastPolicyCheck: TimeInterval = 0
private var policyInvalidated = false
@@ -156,33 +159,56 @@ private final class BrokerServer: @unchecked Sendable {
for _ in 0..<16 {
let client = Darwin.accept(fd, nil, nil)
if client < 0 { return }
- guard connections.count < 64 else { Darwin.close(client); continue }
+ guard connections.count + pendingAdmissions.count < 64 else { Darwin.close(client); continue }
do {
try LockedUseIPCSocket.configure(client)
guard fcntl(client, F_SETFL, O_NONBLOCK) == 0 else { throw BrokerError.message("client socket unavailable") }
- if endpoint == .observer { logger.notice("observerStage=accepting") }
- let identity = try authenticate(fd: client, endpoint: endpoint)
- if endpoint == .observer { logger.notice("observerStage=authenticated") }
- let role: LockedUseBrokerCoordinator.Role = endpoint == .agent ? .agent : endpoint == .guardian ? .guardian : (endpoint == .observer || endpoint == .admin) ? .observer : .plugin
- let old = [coordinator.recordedOwner, coordinator.recordedGuardian, coordinator.recordedWatchdog]
- .compactMap { $0 }.first { $0.role == role && $0.auditToken == identity.auditToken && $0.codeHash == identity.codeDirectoryHash }
- let context = LockedUseBrokerCoordinator.Context(id: old?.id ?? UUID(), role: role,
- userID: identity.userID, auditSessionID: identity.auditSessionID, auditToken: identity.auditToken,
- processID: identity.processID, codeHash: identity.codeDirectoryHash)
- if let previous = connections[context.id] { close(previous) }
- let connection = BrokerConnection(fd: client, endpoint: endpoint, identity: identity, context: context)
- connections[context.id] = connection
- let source = DispatchSource.makeReadSource(fileDescriptor: client, queue: queue)
- source.setEventHandler { [weak self, weak connection] in
- guard let connection, !connection.closed else { return }
- self?.read(connection)
+ } catch { Darwin.close(client); continue }
+ let admission = UUID()
+ let deadline = ProcessInfo.processInfo.systemUptime + 8
+ pendingAdmissions[admission] = client
+ queue.asyncAfter(deadline: .now() + 8) { [self] in
+ guard pendingAdmissions[admission] == client else { return }
+ cancelledAdmissions.insert(admission)
+ // Keep descriptor ownership until the worker returns. Closing
+ // now could reuse the fd while the verifier is inspecting it.
+ shutdown(client, SHUT_RDWR)
+ }
+ peerAuthenticator.verify({ [self] in try authenticate(fd: client, endpoint: endpoint) }) { [self] result in
+ queue.async { [self] in
+ pendingAdmissions.removeValue(forKey: admission)
+ let cancelled = cancelledAdmissions.remove(admission) != nil
+ guard !cancelled, ProcessInfo.processInfo.systemUptime < deadline,
+ case let .success(identity) = result else {
+ logger.notice("peerRejected endpoint=\(endpoint.rawValue, privacy: .public)")
+ Darwin.close(client)
+ return
+ }
+ admit(fd: client, endpoint: endpoint, identity: identity)
}
- connection.readSource = source
- source.resume()
- } catch { logger.notice("peerRejected endpoint=\(endpoint.rawValue, privacy: .public)"); Darwin.close(client) }
+ }
}
}
+ private func admit(fd: Int32, endpoint: LockedUseIPCEndpoint, identity: LockedUsePeerIdentity) {
+ let role: LockedUseBrokerCoordinator.Role = endpoint == .agent ? .agent : endpoint == .guardian ? .guardian : (endpoint == .observer || endpoint == .admin) ? .observer : .plugin
+ let old = [coordinator.recordedOwner, coordinator.recordedGuardian, coordinator.recordedWatchdog]
+ .compactMap { $0 }.first { $0.role == role && $0.auditToken == identity.auditToken && $0.codeHash == identity.codeDirectoryHash }
+ let context = LockedUseBrokerCoordinator.Context(id: old?.id ?? UUID(), role: role,
+ userID: identity.userID, auditSessionID: identity.auditSessionID, auditToken: identity.auditToken,
+ processID: identity.processID, codeHash: identity.codeDirectoryHash)
+ if let previous = connections[context.id] { close(previous) }
+ let connection = BrokerConnection(fd: fd, endpoint: endpoint, identity: identity, context: context)
+ connections[context.id] = connection
+ let source = DispatchSource.makeReadSource(fileDescriptor: fd, queue: queue)
+ source.setEventHandler { [weak self, weak connection] in
+ guard let connection, !connection.closed else { return }
+ self?.read(connection)
+ }
+ connection.readSource = source
+ source.resume()
+ }
+
private func authenticate(fd: Int32, endpoint: LockedUseIPCEndpoint) throws -> LockedUsePeerIdentity {
let began = ProcessInfo.processInfo.systemUptime
defer {
@@ -346,10 +372,12 @@ private final class BrokerServer: @unchecked Sendable {
return
}
let observation = policyMonitor.status()
- if observation == .invalid || observation == .stale {
+ if observation == .invalid {
try coordinator.invalidateInstallation()
policyInvalidated = true
logger.error("installationPolicyInvalidated")
+ } else if observation == .stale {
+ try coordinator.suspendForPolicyObservation()
}
if requireFresh, observation != .valid {
throw BrokerError.message("authentication policy observation unavailable")
@@ -413,7 +441,13 @@ private final class BrokerServer: @unchecked Sendable {
shutdown(connection.fd, SHUT_RDWR); Darwin.close(connection.fd)
connections.removeValue(forKey: connection.context.id)
}
- private func stopAll() { for connection in Array(connections.values) { close(connection) } }
+ private func stopAll() {
+ for connection in Array(connections.values) { close(connection) }
+ for (admission, fd) in pendingAdmissions {
+ cancelledAdmissions.insert(admission)
+ shutdown(fd, SHUT_RDWR)
+ }
+ }
private static func validateRunDirectory() throws {
var fd = open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC)
diff --git a/experiments/LockedUse/Sources/Guardian/GuardianMain.swift b/experiments/LockedUse/Sources/Guardian/GuardianMain.swift
index c416410..0cbad6a 100644
--- a/experiments/LockedUse/Sources/Guardian/GuardianMain.swift
+++ b/experiments/LockedUse/Sources/Guardian/GuardianMain.swift
@@ -129,6 +129,9 @@ struct GuardianMain {
emit("peerSelfTest", details: ["verified": true, "wrongSignerRejected": denied,
"identifier": identity.signingIdentifier, "auditSessionMatches": true,
"approvedRoleVerified": true, "wrongRoleRejected": wrongRoleDenied])
+ case ["--permission-status"]:
+ emit("permissionStatus", details: ["accessibility": AXIsProcessTrusted(),
+ "inputMonitoring": CGPreflightListenEventAccess()])
case ["--request-permissions"]:
_ = AXIsProcessTrustedWithOptions([kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary)
_ = CGRequestListenEventAccess()
diff --git a/experiments/LockedUse/Sources/Installer/InstallerMain.swift b/experiments/LockedUse/Sources/Installer/InstallerMain.swift
index 2d2d8c3..f41ab53 100644
--- a/experiments/LockedUse/Sources/Installer/InstallerMain.swift
+++ b/experiments/LockedUse/Sources/Installer/InstallerMain.swift
@@ -192,7 +192,7 @@ struct InstallerMain {
try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0).write(to: daemon, options: [.withoutOverwriting])
guard chmod(daemon.path, 0o644) == 0 else { throw InstallError.untrusted }
try run("/bin/launchctl", ["bootstrap", "system", daemon.path])
- print("Installed Locked Use with preserved native fallback. Profile: \(validation ? "explicit validation" : "production; backend remains unvalidated").")
+ print("Installed Locked Use with preserved native fallback. Profile: \(validation ? "explicit validation" : "enabled").")
} catch {
if let current = try? readRight(screensaver), let original = try? LockedUseAuthorizationRules.planUninstallation(current: current, plan: plan) {
try? setRight(screensaver, data: original, authorization: reference)
diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseBrokerCoordinator.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseBrokerCoordinator.swift
index 6082c66..8645a0f 100644
--- a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseBrokerCoordinator.swift
+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseBrokerCoordinator.swift
@@ -297,6 +297,12 @@ public struct LockedUseBrokerCoordinator: Sendable {
/// cleanup channels alive so old queued unlock work can safely drain.
public mutating func invalidateInstallation() throws {
accepting = false
+ try suspendForPolicyObservation()
+ }
+
+ /// A slow observation stops current work without permanently invalidating
+ /// an unchanged installation. New permits still require a fresh check.
+ public mutating func suspendForPolicyObservation() throws {
unshieldedDiagnostic?.cancel()
if let owner, ![.idle, .relocking, .awaitingManualUnlock].contains(phase) {
try apply(machine.end(owner: owner, reason: .operationFailed))
@@ -405,7 +411,7 @@ public struct LockedUseBrokerCoordinator: Sendable {
leaseID: isOwner(context) || isGuardian(context) || isWatchdog(context) || context.id == pluginID ? leaseID : nil,
token: token, effects: effects, guardsReleased: isFullyReleased,
recoveryProbePrepared: recoveryProbe ? recoveryProbePrepared : nil, startupDeadline: machine.startupDeadline,
- validationConfirmation: validationMode && isGuardian(context))
+ validationConfirmation: isGuardian(context))
}
private func randomToken() throws -> Data {
var bytes = [UInt8](repeating: 0, count: 32)
diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseDiagnostics.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseDiagnostics.swift
index 729e69d..fb10aca 100644
--- a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseDiagnostics.swift
+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseDiagnostics.swift
@@ -82,6 +82,8 @@ public struct LockedUseDiagnostics: Codable, Sendable {
public let inputMonitoring: Bool
public let pluginInstalled: Bool
public let brokerInstalled: Bool
+ public let guardianAccessibility: Bool?
+ public let guardianInputMonitoring: Bool?
public let otherAuthorizationPlugins: [String]
public let blockers: [String]
@@ -102,30 +104,61 @@ public struct LockedUseDiagnostics: Codable, Sendable {
&& record.teamIdentifier == identity?.teamIdentifier
} ?? false
var available = false
+ var guardianPermissions: [String: Bool] = [:]
if let configuration, let team = try? LockedUseSigningIdentity.current().teamIdentifier,
let evidence = try? LockedUseComponentValidation.current(team: team) {
- available = policyIntact && approved && configuration.matchesValidation(osBuild: evidence.osBuild, brokerHash: evidence.brokerHash,
- guardianHash: evidence.guardianHash, pluginHash: evidence.pluginHash)
+ _ = evidence
+ guardianPermissions = installedGuardianPermissions()
+ available = configuration.enabled && policyIntact && approved
+ && AXIsProcessTrusted() && CGPreflightScreenCaptureAccess()
+ && guardianPermissions["accessibility"] == true && guardianPermissions["inputMonitoring"] == true
}
return .init(
- schemaVersion: 1, stage: available ? "validated" : configuration == nil ? "experimental-preflight" : "installed-awaiting-validation", enabled: configuration?.enabled ?? false, available: available,
+ schemaVersion: 1, stage: available ? "enabled" : configuration == nil ? "not-installed" : "unavailable", enabled: configuration?.enabled ?? false, available: available,
clientApproved: approved, authenticationPolicyIntact: policyIntact,
session: .current(), accessibility: AXIsProcessTrusted(),
screenRecording: CGPreflightScreenCaptureAccess(), inputMonitoring: CGPreflightListenEventAccess(),
pluginInstalled: entries.contains(ownPlugin),
brokerInstalled: FileManager.default.fileExists(atPath: "/Library/Application Support/OpenComputerUse/LockedUse/OCULockService"),
+ guardianAccessibility: guardianPermissions["accessibility"],
+ guardianInputMonitoring: guardianPermissions["inputMonitoring"],
otherAuthorizationPlugins: others,
blockers: available ? [] : [
- "The loginwindow unlock backend and Keychain preservation require live validation for these components and this macOS build. Production automatic unlock is unavailable.",
- "An explicitly administrator-installed validation profile can exercise the protected unlock transaction; installation alone does not validate it."
+ "Run ocu locked-use enable and complete permissions for Open Computer Use and OCU Guardian. Installation, client approval, signed components and authentication policy must be intact."
]
)
}
+ private static func installedGuardianPermissions() -> [String: Bool] {
+ // Called only after strict installed-component signature verification.
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/Library/Application Support/OpenComputerUse/LockedUse/OCU Guardian.app/Contents/MacOS/OCUGuardian")
+ process.arguments = ["--permission-status"]
+ let pipe = Pipe()
+ process.standardOutput = pipe
+ process.standardError = FileHandle.nullDevice
+ do {
+ try process.run()
+ let deadline = Date().addingTimeInterval(2)
+ while process.isRunning && Date() < deadline { Thread.sleep(forTimeInterval: 0.01) }
+ guard !process.isRunning, process.terminationStatus == 0 else {
+ if process.isRunning { process.terminate() }
+ return [:]
+ }
+ let data = pipe.fileHandleForReading.readDataToEndOfFile()
+ guard data.count < 8192, let value = try JSONSerialization.jsonObject(with: data) as? [String: Any],
+ value["event"] as? String == "permissionStatus",
+ let accessibility = value["accessibility"] as? Bool,
+ let input = value["inputMonitoring"] as? Bool else { return [:] }
+ return ["accessibility": accessibility, "inputMonitoring": input]
+ } catch { return [:] }
+ }
+
public var summary: String {
"Locked Use: stage=\(stage), enabled=\(enabled), available=\(available), session=\(session.state.rawValue)\n"
+ "Client approved: \(clientApproved), authentication policy intact: \(authenticationPolicyIntact)\n"
- + "Input Monitoring: \(inputMonitoring ? "granted" : "missing")\n"
+ + "Open Computer Use: Accessibility=\(accessibility), Screen Recording=\(screenRecording)\n"
+ + "Guardian: Accessibility=\(guardianAccessibility.map(String.init) ?? "unknown"), Input Monitoring=\(guardianInputMonitoring.map(String.init) ?? "unknown")\n"
+ "Other authorization plugins: \(otherAuthorizationPlugins.isEmpty ? "none detected" : otherAuthorizationPlugins.joined(separator: ", "))\n"
+ blockers.joined(separator: "\n")
}
diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseIPCSocket.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseIPCSocket.swift
index a39c918..8c894dd 100644
--- a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseIPCSocket.swift
+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseIPCSocket.swift
@@ -4,6 +4,14 @@ import LockedUseNative
public enum LockedUseIPCEndpoint: String, Sendable {
case agent, guardian, plugin, observer, admin
+ var responseTimeout: TimeInterval { 2 }
+ func timeout(operation: LockedUseIPCMessage.Operation, firstReply: Bool) -> TimeInterval {
+ if firstReply, self != .plugin,
+ [.status, .begin, .beginRecoveryProbe, .guardianHello, .guardianRecoveryHello,
+ .watchdogHello, .watchdogRecoveryHello, .ownerRecoveryHello, .disable,
+ .beginUnshieldedDiagnostic].contains(operation) { return 8 }
+ return responseTimeout
+ }
public var path: String {
"/Library/Application Support/OpenComputerUse/LockedUse/run/\(rawValue).sock"
}
@@ -17,6 +25,8 @@ public final class LockedUseIPCClient: @unchecked Sendable {
private var descriptor: Int32
private var decoder = LockedUseIPCFrame()
private let brokerRequirement: String
+ private let endpoint: LockedUseIPCEndpoint
+ private var receivedReply = false
public let broker: LockedUsePeerIdentity
public init(endpoint: LockedUseIPCEndpoint, brokerRequirement: String, clientSocket: Int32? = nil) throws {
@@ -35,6 +45,7 @@ public final class LockedUseIPCClient: @unchecked Sendable {
}
broker = peer
self.brokerRequirement = brokerRequirement
+ self.endpoint = endpoint
descriptor = fd
} catch { Darwin.close(fd); throw error }
}
@@ -50,7 +61,7 @@ public final class LockedUseIPCClient: @unchecked Sendable {
throw LockedUseClientApprovals.Failure.unapproved
}
_ = try message.validated()
- let deadline = ProcessInfo.processInfo.systemUptime + 2
+ let deadline = ProcessInfo.processInfo.systemUptime + endpoint.timeout(operation: message.operation, firstReply: !receivedReply)
try LockedUseIPCSocket.writeAll(try LockedUseIPCFrame.encode(message), descriptor: descriptor, deadline: deadline)
var bytes = [UInt8](repeating: 0, count: 4096)
while true {
@@ -67,6 +78,7 @@ public final class LockedUseIPCClient: @unchecked Sendable {
let reply = try JSONDecoder().decode(LockedUseIPCReply.self, from: frame)
guard reply.version == 1, reply.id == message.id,
reply.token == nil || reply.token?.count == 32 else { throw LockedUseIPCFrame.Failure.malformed }
+ receivedReply = true
return reply
}
}
diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUsePeerAuthenticator.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUsePeerAuthenticator.swift
new file mode 100644
index 0000000..89c86b0
--- /dev/null
+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUsePeerAuthenticator.swift
@@ -0,0 +1,22 @@
+import Foundation
+
+/// Expensive first-peer signature checks must not run on the Broker queue that
+/// handles guard heartbeats, revocation and recovery. Admission stays with the
+/// caller, which must keep the socket alive until verification completes.
+public final class LockedUsePeerAuthenticator: @unchecked Sendable {
+ private let workers: OperationQueue
+
+ public init() {
+ workers = OperationQueue()
+ workers.name = "ocu.locked-use.peer-verification"
+ workers.maxConcurrentOperationCount = 4
+ workers.qualityOfService = .userInitiated
+ }
+
+ public func verify<T: Sendable>(
+ _ check: @escaping @Sendable () throws -> T,
+ completion: @escaping @Sendable (Result<T, Error>) -> Void
+ ) {
+ workers.addOperation { completion(Result { try check() }) }
+ }
+}
diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/OpenComputerUseCLI.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/OpenComputerUseCLI.swift
index f8c83db..0eeb6fa 100644
--- a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/OpenComputerUseCLI.swift
+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/OpenComputerUseCLI.swift
@@ -154,15 +154,15 @@ public func openComputerUseHelpText(command: String? = nil) -> String {
open-computer-use locked-use status [--json]
Read-only macOS session, permission, and system-component diagnostics.
- open-computer-use locked-use enable [--validation]
+ open-computer-use locked-use enable
open-computer-use locked-use disable
open-computer-use locked-use recover
open-computer-use locked-use certify
open-computer-use locked-use settings
Installation and removal require macOS administrator authentication.
- --validation installs an experimental profile for supervised testing.
- Production unlock requires evidence matching this OS and component build.
+ enable installs signed components and requests macOS permissions.
+ Automatic unlock requires an approved client and both display guards.
recover restores an interrupted installation only after safe drainage.
"""
case "list-apps":
@@ -502,7 +502,6 @@ private func parseLockedUse(arguments: [String]) throws -> OpenComputerUseCLICom
}
if arguments == ["status"] { return .lockedUseStatus(json: false) }
if arguments == ["status", "--json"] { return .lockedUseStatus(json: true) }
- if arguments == ["enable", "--validation"] { return .lockedUseManagement(action: "enable", validation: true) }
if arguments.count == 1, let action = arguments.first,
["enable", "disable", "recover", "certify", "settings"].contains(action) {
return .lockedUseManagement(action: action, validation: false)
diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseBrokerCoordinatorTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseBrokerCoordinatorTests.swift
index 36d269a..8df511b 100644
--- a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseBrokerCoordinatorTests.swift
+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseBrokerCoordinatorTests.swift
@@ -28,6 +28,28 @@ final class LockedUseBrokerCoordinatorTests: XCTestCase {
XCTAssertThrowsError(try broker.handle(.init(operation: .pluginConsume, leaseID: lease, token: claim.token), context: plugin, now: 1.4))
}
+ func testStaleIdleObservationDoesNotPermanentlyDisableLeases() throws {
+ var broker = LockedUseBrokerCoordinator(enabled: true, backendValidated: true)
+ try broker.suspendForPolicyObservation()
+ let begin = try broker.handle(.init(operation: .begin, session: locked), context: agent, now: 1)
+ XCTAssertEqual(begin.phase, .preparing)
+ }
+
+ func testStaleObservationStopsActionsAndAllowsRecoveryBeforeAnotherLease() throws {
+ var broker = LockedUseBrokerCoordinator(enabled: true, backendValidated: true)
+ let lease = try prepare(&broker)
+ try grant(&broker, lease: lease)
+ _ = try broker.handle(.init(operation: .guardianReport, leaseID: lease, session: unlocked, guards: healthy, unlockWorkPending: false), context: guardian, now: 1.5)
+ try broker.suspendForPolicyObservation()
+ XCTAssertEqual(broker.phase, .relocking)
+ XCTAssertThrowsError(try broker.handle(.init(operation: .action, leaseID: lease, session: unlocked), context: agent, now: 1.6))
+ _ = try broker.handle(.init(operation: .quiesced, leaseID: lease), context: agent, now: 1.7)
+ _ = try broker.handle(.init(operation: .guardianReport, leaseID: lease, session: locked, guards: healthy, unlockWorkPending: false), context: guardian, now: 1.8)
+ _ = try broker.handle(.init(operation: .guardianReleased, leaseID: lease), context: guardian, now: 1.9)
+ _ = try broker.handle(.init(operation: .status, session: unlocked), context: agent, now: 2)
+ XCTAssertNoThrow(try broker.handle(.init(operation: .begin, session: locked), context: agent, now: 2.1))
+ }
+
func testPermitConsumptionDoesNotAuthorizeGUIUntilObservedUnlock() throws {
var broker = LockedUseBrokerCoordinator(enabled: true, backendValidated: true)
let lease = try prepare(&broker)
@@ -43,13 +65,13 @@ final class LockedUseBrokerCoordinatorTests: XCTestCase {
XCTAssertNil(status.leaseID)
}
- func testConfirmationExperimentRequiresValidationProfileAndGuardianIdentity() throws {
+ func testProtectedReturnRequiresGuardianIdentityInBothProfiles() throws {
for validation in [false, true] {
var broker = LockedUseBrokerCoordinator(enabled: true, backendValidated: true, validationMode: validation)
let begin = try broker.handle(.init(operation: .begin, session: locked), context: agent, now: 1)
XCTAssertEqual(begin.validationConfirmation, false)
let hello = try broker.handle(.init(operation: .guardianHello, leaseID: begin.leaseID, token: begin.token), context: guardian, now: 1.1)
- XCTAssertEqual(hello.validationConfirmation, validation)
+ XCTAssertEqual(hello.validationConfirmation, true)
let status = try broker.handle(.init(operation: .status), context: agent, now: 1.2)
XCTAssertEqual(status.validationConfirmation, false)
}
diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseDispatchTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseDispatchTests.swift
index 11a8daf..57421c5 100644
--- a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseDispatchTests.swift
+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseDispatchTests.swift
@@ -5,6 +5,19 @@ import XCTest
final class LockedUseDispatchTests: XCTestCase {
private enum Revoked: Error { case lease }
+ func testColdHandshakeBudgetDoesNotExtendActionOrGuardDeadlines() {
+ XCTAssertEqual(LockedUseIPCEndpoint.agent.timeout(operation: .begin, firstReply: true), 8)
+ XCTAssertEqual(LockedUseIPCEndpoint.observer.timeout(operation: .status, firstReply: true), 8)
+ XCTAssertEqual(LockedUseIPCEndpoint.guardian.timeout(operation: .guardianHello, firstReply: true), 8)
+ for endpoint in [LockedUseIPCEndpoint.agent, .guardian, .plugin, .admin] {
+ for operation in [LockedUseIPCMessage.Operation.action, .guardianReport, .watchdogReport, .pluginConsume] {
+ XCTAssertEqual(endpoint.timeout(operation: operation, firstReply: true), 2)
+ }
+ }
+ XCTAssertEqual(LockedUseIPCEndpoint.agent.timeout(operation: .begin, firstReply: false), 2)
+ XCTAssertEqual(LockedUseIPCEndpoint.plugin.timeout(operation: .pluginClaim, firstReply: true), 2)
+ }
+
func testLeasedCapturePolicyIsClearedOnThrow() {
XCTAssertFalse(LockedUseActionScope.requiresScreenCaptureKit)
XCTAssertThrowsError(try LockedUseActionScope.withValidator({}, body: {
diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUsePeerAuthenticatorTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUsePeerAuthenticatorTests.swift
new file mode 100644
index 0000000..0209b4d
--- /dev/null
+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUsePeerAuthenticatorTests.swift
@@ -0,0 +1,26 @@
+import Dispatch
+import XCTest
+@testable import OpenComputerUseKit
+
+final class LockedUsePeerAuthenticatorTests: XCTestCase {
+ func testSlowSignatureCheckDoesNotBlockControlQueue() {
+ let entered = expectation(description: "signature check started")
+ let controlRan = expectation(description: "control queue still handles recovery")
+ let completed = expectation(description: "verification completed")
+ let release = DispatchSemaphore(value: 0)
+ let authenticator = LockedUsePeerAuthenticator()
+ authenticator.verify({ () -> Int in
+ entered.fulfill()
+ release.wait()
+ return 42
+ }, completion: { result in
+ XCTAssertEqual(try? result.get(), 42)
+ completed.fulfill()
+ })
+ wait(for: [entered], timeout: 1)
+ DispatchQueue(label: "test.broker.control").async { controlRan.fulfill() }
+ wait(for: [controlRan], timeout: 1)
+ release.signal()
+ wait(for: [completed], timeout: 1)
+ }
+}
diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseTests.swift
index a8e0d8b..2ea557a 100644
--- a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseTests.swift
+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseTests.swift
@@ -277,7 +277,7 @@ final class LockedUseTests: XCTestCase {
XCTAssertEqual(try parseOpenComputerUseCLI(arguments: ["locked-use", action]), command)
XCTAssertFalse(shouldUseMacOSAppAgentProxy(command: command, proxyDisabled: false, appBundleAvailable: true, runningFromLaunchServicesAppInstance: false))
}
- XCTAssertEqual(try parseOpenComputerUseCLI(arguments: ["locked-use", "enable", "--validation"]), .lockedUseManagement(action: "enable", validation: true))
+ XCTAssertThrowsError(try parseOpenComputerUseCLI(arguments: ["locked-use", "enable", "--validation"]))
for arguments in [["status", "--json", "--json"], ["disable", "--validation"], ["enable", "--validation", "extra"], ["authorize-client", "test"], ["uninstall"], ["unknown"], []] {
XCTAssertThrowsError(try parseOpenComputerUseCLI(arguments: ["locked-use"] + arguments))
}
diff --git a/scripts/run-locked-use-smoke.py b/scripts/run-locked-use-smoke.py
new file mode 100644
index 0000000..4315b77
--- /dev/null
+++ b/scripts/run-locked-use-smoke.py
@@ -0,0 +1,121 @@
+#!/usr/bin/env python3
+"""Exercise normal MCP tools through the installed Locked Use service.
+
+No credential access or test-only unlock RPC. The signed demo stays open after
+success so the user can inspect Counter: 1 after normal manual unlock.
+"""
+import argparse
+import hashlib
+import importlib.util
+import json
+import pathlib
+import re
+import subprocess
+import time
+
+spec = importlib.util.spec_from_file_location("locked_use_runner", pathlib.Path(__file__).with_name("run-locked-use-native-validation.py"))
+runner = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(runner)
+
+
+def read_state(result):
+ if result.get("isError"):
+ raise RuntimeError("GUI tool failed")
+ content = result.get("content", [])
+ text = "\n".join(item.get("text", "") for item in content if item.get("type") == "text")
+ counts = re.findall(r"Counter: ([0-9]+)", text)
+ buttons = [line.split()[0] for line in text.splitlines()
+ if "Increment Counter" in line and "locked-use-validation-increment" in line]
+ images = [item.get("data", "") for item in content if item.get("type") == "image"]
+ if len(counts) != 1 or len(buttons) != 1 or not buttons[0].isdigit() or not images or not images[0]:
+ raise RuntimeError("Demo counter, button, or capture missing")
+ return int(counts[0]), buttons[0], hashlib.sha256(images[0].encode()).hexdigest()
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--app", type=pathlib.Path, required=True)
+ parser.add_argument("--guardian", type=pathlib.Path, required=True)
+ parser.add_argument("--fixture", type=pathlib.Path, required=True)
+ parser.add_argument("--confirm-lock-test", action="store_true")
+ args = parser.parse_args()
+ if runner.session(args.guardian, timeout=15) != "unlocked":
+ raise RuntimeError("Unlock normally before testing")
+ rpc = runner.RPC(args.app / "Contents/MacOS/OpenComputerUse")
+ fixture = None
+ locked = False
+ completed = False
+ started = time.time()
+ events = []
+ trace = runner.LiveAuthenticationTrace(started)
+ trace.start()
+
+ def record(event, **details):
+ value = {"event": event, "elapsedSeconds": round(time.time() - started, 3), **details}
+ events.append(value)
+ print(json.dumps(value), flush=True)
+
+ def snapshot():
+ return read_state(rpc.call("tools/call", {"name": "get_app_state", "arguments": {"app": "dev.opencomputeruse.locked-use.fixture.dev"}}, timeout=28))
+
+ try:
+ if not rpc.call("ocu/locked-use/ready", timeout=5)["passed"]:
+ raise RuntimeError("Broker not ready; no lock requested")
+ fixture = subprocess.Popen([str(args.fixture / "Contents/MacOS/OCUGuardian"), "--external-fixture"],
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL, start_new_session=True)
+ time.sleep(1)
+ initial, _, _ = snapshot()
+ if initial != 0:
+ raise RuntimeError("Expected a fresh demo counter")
+ record("demoReady", counter=initial, credentialAccess=False)
+ if not args.confirm_lock_test:
+ completed = True
+ record("unlockedPreflightPassed")
+ return
+ print("Locking in 5 seconds. Keep the mouse and keyboard still until relock.", flush=True)
+ time.sleep(5)
+ subprocess.run([str(args.guardian), "--request-lock"], check=True, stdout=subprocess.DEVNULL, timeout=3)
+ locked = True
+ runner.wait_for(args.guardian, "locked", timeout=5)
+ record("lockedObserved")
+ before, index, image = snapshot()
+ record("normalMCPUnlockedAndCaptured", counter=before)
+ click = rpc.call("tools/call", {"name": "click", "arguments": {"app": "dev.opencomputeruse.locked-use.fixture.dev", "element_index": index, "click_method": "accessibility"}}, timeout=10)
+ if click.get("isError"):
+ raise RuntimeError("Click failed")
+ after, _, after_image = snapshot()
+ if after != before + 1 or image == after_image:
+ raise RuntimeError("Counter or screenshot did not change")
+ record("realAXAndCapturePassed", counter=after, imageChanged=True)
+ time.sleep(5)
+ rpc.notify("notifications/turn-ended")
+ runner.wait_for(args.guardian, "locked", timeout=5)
+ runner.wait_for_release(rpc)
+ record("relockedAndBothGuardsReleased")
+ print("Unlock normally. The Counter: 1 window will remain open.", flush=True)
+ runner.wait_for(args.guardian, "unlocked", timeout=120)
+ final, _, _ = snapshot()
+ if final != after:
+ raise RuntimeError("Counter changed after manual unlock")
+ completed = True
+ record("manualUnlockAndCounterPassed", counter=final)
+ finally:
+ if locked and not completed:
+ try:
+ rpc.notify("notifications/turn-ended")
+ runner.wait_for_release(rpc)
+ record("failureGuardsReleased")
+ except Exception:
+ record("failureRecoveryPending")
+ rpc.close()
+ if fixture and (not completed or not args.confirm_lock_test):
+ fixture.terminate()
+ live_events, trace_status = trace.finish()
+ path = runner.write_report(pathlib.Path(__file__).resolve().parent.parent, started, events,
+ live_events=live_events, trace_status=trace_status)
+ print(json.dumps({"event": "reportSaved", "path": str(path)}), flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/tests/locked-use-smoke.test.py b/scripts/tests/locked-use-smoke.test.py
new file mode 100644
index 0000000..ce516f0
--- /dev/null
+++ b/scripts/tests/locked-use-smoke.test.py
@@ -0,0 +1,32 @@
+#!/usr/bin/env python3
+import importlib.util
+import pathlib
+import sys
+import unittest
+
+root = pathlib.Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(root))
+spec = importlib.util.spec_from_file_location("smoke", root / "run-locked-use-smoke.py")
+smoke = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(smoke)
+
+
+class SmokeReadbackTests(unittest.TestCase):
+ def test_missing_capture_cannot_pass_counter_verification(self):
+ result = {"content": [{"type": "text", "text": "Counter: 1\n3 button Increment Counter locked-use-validation-increment"}]}
+ with self.assertRaises(RuntimeError):
+ smoke.read_state(result)
+
+ def test_tool_error_cannot_be_used_as_a_successful_readback(self):
+ result = {"isError": True, "content": [{"type": "text", "text": "Counter: 1"}, {"type": "image", "data": "image"}]}
+ with self.assertRaises(RuntimeError):
+ smoke.read_state(result)
+
+ def test_ambiguous_counter_is_rejected(self):
+ result = {"content": [{"type": "text", "text": "Counter: 0\nCounter: 1\n3 button Increment Counter locked-use-validation-increment"}, {"type": "image", "data": "image"}]}
+ with self.assertRaises(RuntimeError):
+ smoke.read_state(result)
+
+
+if __name__ == "__main__":
+ unittest.main()