👾 Open Computer Use – Open-Source Alternative to Codex Computer Use
Swift accessibilityai-agentai-agentsclaude-codecodexcodex-computer-usecomputer-usecomputer-use-agentcross-platformcuadesktop-automationgemini-cligui-automationmacosmcpmodel-context-protocolopen-computer-useopen-computer-use-mcpopenai-codexopencode
fix(macos): validate Locked Use host and reduce broker overhead
ifurystf3b73c1e443c
diff --git a/apps/OpenComputerUse/Sources/OpenComputerUse/LockedUseSettings.swift b/apps/OpenComputerUse/Sources/OpenComputerUse/LockedUseSettings.swiftindex 0291ae6..a1c3546 100644--- a/apps/OpenComputerUse/Sources/OpenComputerUse/LockedUseSettings.swift+++ b/apps/OpenComputerUse/Sources/OpenComputerUse/LockedUseSettings.swift@@ -117,6 +117,32 @@ enum LockedUseSettings {}private static func installedAction(_ action: String) throws {let team = try LockedUseSigningIdentity.current().teamIdentifier!+ let bundled = Bundle.main.bundleURL.appendingPathComponent("Contents/Resources/LockedUse/OCULockInstaller")+ if action == "uninstall", FileManager.default.fileExists(atPath: bundled.path) {+ // Upgrade/removal must run the current fix, not an older installed+ // installer that may fail while deleting the OS-managed cache.+ let parent = "/Library/Application Support/OpenComputerUseLockedUseStaging"+ let stage = parent + "/" + UUID().uuidString+ let requirement = "=identifier \"dev.opencomputeruse.locked-use.installer\" and anchor apple generic and certificate leaf[subject.OU] = \"\(team)\""+ let commands = "set -eu\numask 077\n" ++ "/bin/test ! -L " + quote(parent) + "\n" ++ "/bin/mkdir -p " + quote(parent) + "\n" ++ "/usr/sbin/chown root:wheel " + quote(parent) + "\n" ++ "/bin/chmod -N " + quote(parent) + "\n" ++ "/bin/chmod 700 " + quote(parent) + "\n" ++ "/bin/mkdir " + quote(stage) + "\n" ++ "trap " + quote("/bin/rm -rf " + quote(stage)) + " EXIT\n" ++ "/usr/bin/ditto " + quote(bundled.path) + " " + quote(stage + "/OCULockInstaller") + "\n" ++ "/bin/test ! -L " + quote(stage + "/OCULockInstaller") + "\n" ++ "/bin/test -f " + quote(stage + "/OCULockInstaller") + "\n" ++ "/usr/sbin/chown root:wheel " + quote(stage + "/OCULockInstaller") + "\n" ++ "/bin/chmod -N " + quote(stage + "/OCULockInstaller") + "\n" ++ "/bin/chmod 700 " + quote(stage + "/OCULockInstaller") + "\n" ++ "/usr/bin/codesign --verify --strict -R " + quote(requirement) + " " + quote(stage + "/OCULockInstaller") + "\n" ++ quote(stage + "/OCULockInstaller") + " uninstall"+ try elevate(commands)+ return+ }let base = "/Library/Application Support/OpenComputerUse/LockedUse/"let current = base + "OCULockInstaller"let legacy = base + "OpenComputerUseLockedUseInstaller"diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 17eac7b..85ee038 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -193,3 +193,7 @@ macOS 在原有 9 个工具之外新增 `query`,按文字或角色查找目标## 结构化权限查询macOS `doctor --json` 在 CLI 和 app-agent proxy 路径复用 `PermissionDiagnostics`,只输出一份 JSON 快照,不打开 onboarding。字段为 `platform: "macos"`、`accessibilityTrusted`、`screenCaptureGranted`、`allGranted` 和 `missingPermissions`(`accessibility` / `screenRecording`)。缺权限仍退出 0,宿主应读取 `allGranted` 并重新查询授权变化。此状态延续系统 API/TCC 合并诊断语义,并非操作成功证明;Linux/Windows 明确拒绝该权限查询模式。普通 `doctor` 保留文本输出与权限引导。++Locked Use’s non-UI authorization mechanism is registered with `,privileged` and restricted to Apple's root authorizationhosthelper peers. A separate load-check right must return a fixed extractable context marker before the installer attaches the remote branch to system.login.screensaver; signature checks and a denied AuthorizationCopyRights result alone do not prove host compatibility. The original native fallback is preserved.++The load-check grants only its isolated right, with `shared=false` and a fresh AuthorizationRef that is destroyed afterwards. authd does not export context on a denied result. It reads/writes no credentials and never evaluates system.login.screensaver; successful marker export is required before installation changes that policy.diff --git a/docs/RELIABILITY.md b/docs/RELIABILITY.mdindex b6969f9..d2bd90e 100644--- a/docs/RELIABILITY.md+++ b/docs/RELIABILITY.md@@ -70,3 +70,9 @@ CI/CD 流程结构和 release 自动化的默认方案,统一写在 `docs/CICD- `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。++Locked Use Broker uses a one-second timer only when idle or awaiting manual unlock with both guards fully released. Any active / incomplete recovery state retains the 100 ms watchdog cadence; incoming state transitions restore it immediately. Policy observations remain once per second with the existing two-second freshness gate. This reduces idle wakeups without extending guard / permit deadlines.++Known-peer heartbeat/message revalidation on macOS 14.4+ uses kernel code-hash requirements instead of repeated certificate/disk assessment on the control queue. Forwarded SCM_RIGHTS clients also enter through the signature worker pool with an eight-second deadline; cancellation releases only the borrowed descriptor after in-flight verification finishes, preventing descriptor reuse races without shutting down the caller’s live transport.++Installer removal leaves StagedPlugins to authd. Installation waits only for an existing mismatched cache to disappear or match the expected signature hash, for at most 15 seconds. The smoke controller retains its verified demo after relock/dual release even if manual-unlock observation times out; that timeout remains a failed manual check.diff --git a/docs/SECURITY.md b/docs/SECURITY.mdindex 5dd924a..4232464 100644--- a/docs/SECURITY.md+++ b/docs/SECURITY.md@@ -69,3 +69,13 @@受保护 Return 验证实验不开放通用 keyboard exemption。与 click 不同的随机 tag 只经继承管道交给独立 watchdog;两套 gate 对原锁定 session、来源、目标、固定 keyCode 36、无 modifiers / autorepeat、5 秒有效期及 250ms down/up 进行独立一次性检查。真实硬件输入监控继续生效,停止 / 接管同时撤销 mouse 与 Return gate。只有管理员 validation profile 创建 Return 能力,生产等待完整实测。++### Authorization host loading++The non-UI remote mechanism uses Apple's documented `,privileged` host. Broker only accepts root peers signed by Apple with the two fixed authorizationhosthelper identifiers; audit-session matching and single-use guard-bound permits remain required. Installation first runs a separate load-check right in the same host. Success requires the plug-in's extractable fixed context marker, not merely errAuthorizationDenied, before modifying system.login.screensaver. Legacy nonprivileged rules are accepted only for conservative uninstall/recovery.++A third-party plug-in cannot solve a platform host's Library Validation failure by re-signing the Apple host or adding private entitlements. A valid bundle signature alone is not proof of successful host loading. Reference: [Apple authorization plug-ins](https://developer.apple.com/documentation/security/extending-authorization-services-with-plug-ins).++After full peer admission, macOS 14.4+ revalidation pins the kernel audit token, signing identifier, exact CodeDirectoryHash and live valid/signed flags. Static entitlements and the original administrator requirement remain bound to that exact admitted code; neither a supplied identifier nor a disk-path replacement can authorize a different task. A modern kernel failure does not fall back. Older systems keep full SecCode verification. Forwarded client admission uses the bounded signature worker pool, retains fd ownership until completion, and cannot grant actions while pending.++The load-check grants only its isolated right, with `shared=false` and a fresh AuthorizationRef that is destroyed afterwards. authd does not export context on a denied result. It reads/writes no credentials and never evaluates system.login.screensaver; successful marker export is required before installation changes that policy.diff --git a/docs/exec-plans/active/20261014-locked-use-unlock-latency.md b/docs/exec-plans/active/20261014-locked-use-unlock-latency.mdnew file mode 100644index 0000000..509c390--- /dev/null+++ b/docs/exec-plans/active/20261014-locked-use-unlock-latency.md@@ -0,0 +1,16 @@+# Locked Use unlock latency++## Goal++Fix the authorization plug-in load failure seen during manual unlock, check related idle / IPC costs, and submit a reviewed PR.++## Constraints++Preserve native password fallback and peer / permit validation. Do not disable SIP, alter Apple signatures, or grant private entitlements. Keep diagnostics bounded and avoid automatic lock tests until a short recovery path is ready.++## Progress++- [x] Read the referenced diagnosis and reproduce the installed metadata / host boundary read-only.+- [x] Confirm delayed system assessment, subsequent successful loading, real marker export and privileged host session binding.+- [x] Fix relevant polling / admission costs with regression coverage.+- [ ] Validate build and authorization behavior; document limits and submit PR.diff --git a/docs/histories/2026-10/20261014-2200-locked-use-unlock-latency.md b/docs/histories/2026-10/20261014-2200-locked-use-unlock-latency.mdnew file mode 100644index 0000000..c9f7dc2--- /dev/null+++ b/docs/histories/2026-10/20261014-2200-locked-use-unlock-latency.md@@ -0,0 +1,29 @@+# Locked Use unlock latency and cleanup++## 用户诉求++结合另一个会话的系统卡顿诊断,修复 Locked Use 问题、检查类似路径并提交 PR。++## 定位结果++本机保留的是旧开发组件。原始解锁日志中,系统评估插件约耗时六秒,并报公证与 Library Validation 错误;但插件随后确实进入 MechanismInvoke,Broker 在约 12 ms 内拒绝空闲请求。因此加载错误不能单独作为最终加载失败的证据。++独立授权测试中,公开 1.1.0 插件约 449 ms 进入机制。修正版导出的标记证明普通宿主与 privileged 宿主都能加载;当前普通用户 CLI 发起的测试里,后者的内核 audit session 与调用方一致。完整受保护 GUI 测试进一步确认了新宿主的许可绑定。++## 修正++- 非 UI 机制使用 Apple 文档支持的 privileged host。Broker 固定验证 Apple 签名、helper identifier、root UID、原 audit session 与一次性许可,不放宽保护条件。+- 安装前运行独立 load-check right。只有实际插件返回成功并导出固定标记后,才接入系统锁屏规则。该检查只授予独立检查权,shared=false,使用全新且随后销毁的 AuthorizationRef;不请求锁屏权、不读取或写入凭据。真实测试发现拒绝结果不会导出 context,因此不能用 deny 作为加载成功证据。+- macOS 14.4+ 的已批准 peer 复核绑定内核 audit token、精确 CodeDirectoryHash、identifier 与动态有效/已签名标志,避免在 heartbeat/message 控制队列上重复执行完整签名评估。首次批准仍保留原管理员 requirement;现代失败不回退。+- 转交的 SCM_RIGHTS 客户端同样进入有界工作队列。副本通过 borrowed-socket 生命周期管理保留在途验证,取消只释放本地 fd,不 shutdown 调用方仍在使用的原连接。+- 空闲且两套保护完全释放后,轮询降为一秒;活动/未完成恢复仍为 100 ms,入站状态切换立即恢复频率,许可和策略新鲜度不变。+- 不再删除 OS 保护的 StagedPlugins 缓存,交给 authd 清理。安装只在旧缓存与新签名哈希不同的情况下等待刷新,最多 15 秒,失败不挂接锁屏规则。+- 停用优先使用当前 App 内的签名安装器,修复旧安装器无法卸载缓存的问题。status 显示已安装/内置插件版本差异与明确重装步骤。+- 测试控制器在已重锁且确认双保护释放后保留 Counter,即使人工解锁观察超时;未观察到解锁仍如实报未完成。++## 验证++- Swift 334 项,8 项跳过、0 失败;额外跳过项要求正常解锁的 console session,其余为 opt-in live 测试。内核 hash/token/无效 fd 反例、borrowed fd 在途释放与原连接可用性、版本提示和轮询边界通过。+- 签名 native App 与四组件、remote ABI/重放/取消/load-check 失败反例、kernel verifier 正负例通过。+- 本机旧组件正常卸载,修正版普通 enable 成功,权限和认证规则完整,status available=true。没有改变 SIP 或 Apple 签名。+- 受保护 normal MCP 实测:自动解锁并捕获,AX Counter 0→1、截图变化、保持五秒、重锁与双保护释放 ACK 均通过;连接在 turn-ended 后继续可用。人工解锁观察等待超时,物理遮蔽/无桌面闪现和最终人工解锁确认仍待用户回复。未进行完整故障矩阵、Intel 实机或系统凭据保持验收。diff --git a/docs/locked-use.en.md b/docs/locked-use.en.mdindex c9fcf16..0f58bb4 100644--- a/docs/locked-use.en.md+++ b/docs/locked-use.en.md@@ -14,7 +14,7 @@ Unlock your Mac normally, then run this command and complete the administrator pocu locked-use enable```-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.+This installs the components, checks that macOS can load the authorization plug-in, and requests permissions for the main app and Guardian. If the load check fails, the plug-in is not attached to system lock-screen authentication. No manual configuration is needed. OCU's regular permission setup does not enable Locked Use automatically.```bash# Check installation and permissions@@ -24,6 +24,8 @@ ocu locked-use statusocu locked-use disable```+Updating OCU does not replace the system components installed by `enable`. If `status` reports different installed and bundled plug-in versions, finish any recovery, run `ocu locked-use disable`, then `ocu locked-use enable` from the updated signed app.+## Required permissionsAllow these under **System Settings → Privacy & Security**:@@ -64,4 +66,4 @@ Guardian also has a separate watchdog process that uses the same app. It provide-In the diagram, OCU Locked Use Broker is `OCULockService`, and Authz Plugin is `OCULockAuth.bundle`. `loginwindow`, `SecurityAgentHelper`, and `launchd` are macOS components. The watchdog is not shown separately.+In the diagram, OCU Locked Use Broker is `OCULockService`, and Authz Plugin is `OCULockAuth.bundle`. `loginwindow` and `launchd` are macOS components. The diagram’s `SecurityAgentHelper` label shows the previous path; the non-UI mechanism now uses the system `authorizationhosthelper` (privileged host). The watchdog is not shown separately.diff --git a/docs/locked-use.zh-CN.md b/docs/locked-use.zh-CN.mdindex 471ab35..b84304e 100644--- a/docs/locked-use.zh-CN.md+++ b/docs/locked-use.zh-CN.md@@ -14,7 +14,7 @@ Locked Use 可以让 Agent 在 Mac 锁屏时继续操作 GUI。期间所有屏ocu locked-use enable```-这个命令会安装所需组件,并请求主 App 和 Guardian 的权限,不需要手动修改配置。Locked Use 不会随 OCU 的普通权限引导自动开启。+这个命令会安装所需组件,先确认授权插件能被 macOS 加载,再请求主 App 和 Guardian 的权限。加载检查失败时,不会把插件接入系统锁屏认证。不需要手动修改配置。Locked Use 不会随 OCU 的普通权限引导自动开启。```bash# 查看安装和权限状态@@ -24,6 +24,8 @@ ocu locked-use statusocu locked-use disable```+更新 OCU 不会自动替换 `enable` 安装的系统组件。如果 `status` 显示已安装和 App 内置的插件版本不同,先完成未结束的恢复,再执行 `ocu locked-use disable`、`ocu locked-use enable`,重新安装。+## 需要什么权限在「系统设置 → 隐私与安全性」中允许:@@ -64,4 +66,4 @@ Guardian 还有一个独立的 watchdog 进程,使用同一个 App,负责主-图中的 OCU Locked Use Broker 对应 `OCULockService`,Authz Plugin 对应 `OCULockAuth.bundle`;`loginwindow`、`SecurityAgentHelper` 和 `launchd` 都是 macOS 自带组件。图中未单独画出 watchdog。+图中的 OCU Locked Use Broker 对应 `OCULockService`,Authz Plugin 对应 `OCULockAuth.bundle`;`loginwindow` 和 `launchd` 都是 macOS 自带组件。图中的 `SecurityAgentHelper` 是旧路径标注;无 UI 授权机制现在使用系统的 `authorizationhosthelper`(privileged host)。图中未单独画出 watchdog。diff --git a/docs/releases/feature-release-notes.md b/docs/releases/feature-release-notes.mdindex 2982f7b..3c8a168 100644--- a/docs/releases/feature-release-notes.md+++ b/docs/releases/feature-release-notes.md@@ -4,6 +4,7 @@| 日期 | 功能域 | 用户价值 | 变更摘要 || --- | --- | --- | --- |+| 2026-10-15 | Locked Use 安装与性能修复 | 减少认证和 IPC 开销,旧系统组件也能正常移除并重装。 | 非 UI 插件使用 privileged host,安装前验证真实加载;修复系统缓存卸载与转交 socket 的生命周期,降低空闲唤醒,status 提示组件版本差异。 || 2026-10-14 | 1.1.0 正式发布 | 用户可直接安装 Locked Use,在锁屏遮罩期间继续 GUI 操作,也可用定向查询和持久截图配置减少工具开销。 | 统一版本为 1.1.0;签名 universal macOS App 内嵌服务、Guardian、安装器和授权插件,普通 enable 请求权限,补齐冷启动握手隔离和发布制品检查;新增 app.query()、doctor --json 与 ocu config。 || 2026-10-10 | macOS Locked Use 验证版 | 可在已登录 Mac 锁屏时,通过全屏遮罩继续 GUI 自动化,并在结束或本地接管后安全重锁。 | 正式组件采用 OCU Guardian / OCULockService / OCULockInstaller / OCULockAuth 短名称,开发 App 保留 Dev 区分;新增签名 Broker / 授权插件、双进程显示器保护、一次性许可、租约排空 / 恢复及构建和实机验证脚本;管理员显式启用 validation profile,生产 backend 在完整验证前保持关闭。 || 2026-10-10 | macOS 定向 AX 查询 | 知道控件文案时,可以直接查询并操作,不必先获取截图和完整 AX tree。 | 新增 native `query` 和 JS `app.query()`,按文字、角色和窗口查找元素,返回完整性元数据;查询索引仅在同一会话内有效,操作前重新验证目标和位置。 |diff --git a/experiments/LockedUse/AuthorizationPlugin/RemotePlugin.m b/experiments/LockedUse/AuthorizationPlugin/RemotePlugin.mindex 2cabfe5..2fe84c8 100644--- a/experiments/LockedUse/AuthorizationPlugin/RemotePlugin.m+++ b/experiments/LockedUse/AuthorizationPlugin/RemotePlugin.m@@ -12,6 +12,7 @@#include <time.h>#include <unistd.h>#include <os/log.h>+#include <bsm/libbsm.h>#ifndef OCU_SIGNING_TEAM#error "Remote mechanism requires a fixed Developer ID signing team"@@ -129,6 +130,7 @@ static NSDictionary *exchange(int fd, NSString *operation, NSDictionary *extra,@property(nonatomic, assign) int descriptor;@property(nonatomic, assign) BOOL cancelled;@property(nonatomic, assign) BOOL invoked;+@property(nonatomic, assign) BOOL loadCheck;@end@implementation OCUMechanism@end@@ -144,12 +146,13 @@ static OSStatus mechanismCreate(AuthorizationPluginRef pluginRef, AuthorizationEif (!out) return errAuthorizationInvalidPointer;*out = NULL;if (!pluginRef || !engine || !name) return errAuthorizationInvalidRef;- if (strcmp(name, "remote") != 0) return errAuthorizationInternal;+ if (strcmp(name, "remote") != 0 && strcmp(name, "load-check") != 0) return errAuthorizationInternal;OCUMechanism *mechanism = [OCUMechanism new];mechanism.plugin = (__bridge OCUPlugin *)pluginRef;mechanism.mutex = [NSRecursiveLock new];mechanism.engine = engine;mechanism.descriptor = -1;+ mechanism.loadCheck = strcmp(name, "load-check") == 0;*out = (AuthorizationMechanismRef)CFBridgingRetain(mechanism);return errAuthorizationSuccess;}@@ -165,6 +168,30 @@ static OSStatus mechanismInvoke(AuthorizationMechanismRef ref) {[mechanism.mutex unlock]; return errAuthorizationInternal;}mechanism.invoked = YES;+ if (mechanism.loadCheck) {+ // Installer-only, separate right. Context is exported by authd+ // only on success: grant this load-check right, never a session+ // unlock right or reusable credential. Remote still requires a+ // guard-bound Broker permit; this mechanism is not its fallback.+ const char marker[] = "OCULockAuth-loaded-v1";+ AuthorizationValue value = {.length = sizeof(marker), .data = (void *)marker};+ OSStatus markerStatus = mechanism.plugin.callbacks->SetContextValue+ ? mechanism.plugin.callbacks->SetContextValue(mechanism.engine,+ "dev.opencomputeruse.locked-use.load-check", kAuthorizationContextFlagExtractable, &value)+ : errAuthorizationInternal;+ auditinfo_addr_t audit = {0};+ if (markerStatus == errAuthorizationSuccess && getaudit_addr(&audit, sizeof(audit)) == 0) {+ uint32_t session = (uint32_t)audit.ai_asid;+ AuthorizationValue sessionValue = {.length = sizeof(session), .data = &session};+ (void)mechanism.plugin.callbacks->SetContextValue(mechanism.engine,+ "dev.opencomputeruse.locked-use.load-check.audit-session", kAuthorizationContextFlagExtractable, &sessionValue);+ }+ OSStatus result = mechanism.plugin.callbacks->SetResult(mechanism.engine,+ markerStatus == errAuthorizationSuccess ? kAuthorizationResultAllow : kAuthorizationResultDeny);+ os_log_with_type(logger, OS_LOG_TYPE_DEFAULT, "loadCheck markerStatus=%{public}d resultStatus=%{public}d", (int)markerStatus, (int)result);+ [mechanism.mutex unlock];+ return result;+ }int fd = socket(AF_UNIX, SOCK_STREAM, 0);mechanism.descriptor = fd;[mechanism.mutex unlock];diff --git a/experiments/LockedUse/AuthorizationPlugin/RemotePluginTests.c b/experiments/LockedUse/AuthorizationPlugin/RemotePluginTests.cindex 4a42618..c87b7fe 100644--- a/experiments/LockedUse/AuthorizationPlugin/RemotePluginTests.c+++ b/experiments/LockedUse/AuthorizationPlugin/RemotePluginTests.c@@ -2,10 +2,27 @@#include <assert.h>#include <dlfcn.h>#include <stdio.h>+#include <string.h>+#include <stdint.h>-static unsigned results, deactivations;+static unsigned results, deactivations, markers;+static AuthorizationResult expectedResult = kAuthorizationResultDeny;+static OSStatus setContext(AuthorizationEngineRef engine, AuthorizationString key,+ AuthorizationContextFlags flags, const AuthorizationValue *value) {+ const char marker[] = "OCULockAuth-loaded-v1";+ assert(engine);+ if (strcmp(key, "dev.opencomputeruse.locked-use.load-check.audit-session") == 0) {+ assert(flags == kAuthorizationContextFlagExtractable && value && value->length == sizeof(uint32_t));+ return errAuthorizationSuccess;+ }+ assert(strcmp(key, "dev.opencomputeruse.locked-use.load-check") == 0);+ assert(flags == kAuthorizationContextFlagExtractable);+ assert(value && value->length == sizeof(marker) && memcmp(value->data, marker, sizeof(marker)) == 0);+ markers++;+ return errAuthorizationSuccess;+}static OSStatus setResult(AuthorizationEngineRef engine, AuthorizationResult result) {- assert(engine && result == kAuthorizationResultDeny);+ assert(engine && result == expectedResult);results++;return errAuthorizationSuccess;}@@ -21,7 +38,7 @@ int main(int argc, char **argv) {typedef OSStatus (*Create)(const AuthorizationCallbacks *, AuthorizationPluginRef *, const AuthorizationPluginInterface **);Create create = (Create)dlsym(handle, "AuthorizationPluginCreate");assert(create);- AuthorizationCallbacks callbacks = {.version = 1, .SetResult = setResult, .DidDeactivate = deactivate};+ AuthorizationCallbacks callbacks = {.version = 1, .SetResult = setResult, .DidDeactivate = deactivate, .SetContextValue = setContext};AuthorizationPluginRef plugin = NULL;const AuthorizationPluginInterface *interface = NULL;assert(create(NULL, &plugin, &interface) != errAuthorizationSuccess);@@ -30,7 +47,7 @@ int main(int argc, char **argv) {assert(interface->MechanismCreate(plugin, (AuthorizationEngineRef)&callbacks, "allow", &mechanism) != errAuthorizationSuccess);assert(!mechanism);assert(interface->MechanismCreate(plugin, (AuthorizationEngineRef)&callbacks, "remote", &mechanism) == errAuthorizationSuccess);- // This test process is never an approved Apple SecurityAgentHelper peer.+ // This test process is never an approved Apple authorizationhosthelper peer.// Even if a Broker is installed it must not grant this caller a permit.assert(interface->MechanismInvoke(mechanism) == errAuthorizationSuccess);assert(results == 1);@@ -45,6 +62,20 @@ int main(int argc, char **argv) {assert(interface->MechanismInvoke(mechanism) != errAuthorizationSuccess);assert(results == 1);assert(interface->MechanismDestroy(mechanism) == errAuthorizationSuccess);+ expectedResult = kAuthorizationResultAllow; // Only the independent load-check right.+ assert(interface->MechanismCreate(plugin, (AuthorizationEngineRef)&callbacks, "load-check", &mechanism) == errAuthorizationSuccess);+ assert(interface->MechanismInvoke(mechanism) == errAuthorizationSuccess);+ assert(results == 2 && markers == 1); // Grant proves load-check only, not a screensaver permission.+ assert(interface->MechanismInvoke(mechanism) != errAuthorizationSuccess);+ assert(results == 2 && markers == 1);+ assert(interface->MechanismDestroy(mechanism) == errAuthorizationSuccess);+ // A failed/missing context callback cannot grant even the load-check right.+ expectedResult = kAuthorizationResultDeny;+ callbacks.SetContextValue = NULL;+ assert(interface->MechanismCreate(plugin, (AuthorizationEngineRef)&callbacks, "load-check", &mechanism) == errAuthorizationSuccess);+ assert(interface->MechanismInvoke(mechanism) == errAuthorizationSuccess);+ assert(results == 3 && markers == 1);+ assert(interface->MechanismDestroy(mechanism) == errAuthorizationSuccess);assert(interface->PluginDestroy(plugin) == errAuthorizationSuccess);assert(dlclose(handle) == 0);puts("Remote mechanism offline ABI: deny without approved Broker permit, replay/cancellation rejected; no rights evaluated.");diff --git a/experiments/LockedUse/Sources/Broker/BrokerMain.swift b/experiments/LockedUse/Sources/Broker/BrokerMain.swiftindex 49cd93b..2b634a9 100644--- a/experiments/LockedUse/Sources/Broker/BrokerMain.swift+++ b/experiments/LockedUse/Sources/Broker/BrokerMain.swift@@ -46,7 +46,9 @@ private final class BrokerServer: @unchecked Sendable {private let peerAuthenticator = LockedUsePeerAuthenticator()private var pendingAdmissions: [UUID: Int32] = [:]private var cancelledAdmissions: Set<UUID> = []+ private var forwardedAdmissions: Set<UUID> = []private var timer: DispatchSourceTimer?+ private var timerInterval: TimeInterval?private var lastPolicyCheck: TimeInterval = 0private var policyInvalidated = falseprivate let policyMonitor = LockedUsePolicyMonitor {@@ -111,12 +113,13 @@ private final class BrokerServer: @unchecked Sendable {} catch { Darwin.close(fd); throw error }}let timer = DispatchSource.makeTimerSource(queue: queue)- timer.schedule(deadline: .now(), repeating: .milliseconds(100), leeway: .milliseconds(10))+ // Cadence is selected after the source is assigned below.timer.setEventHandler { [weak self] inguard let self else { return }do {let previousPhase = self.coordinator.phasedefer {+ self.updateTimerCadence()if previousPhase != self.coordinator.phase {self.logger.notice("phase=\(self.coordinator.phase.rawValue, privacy: .public) stopReason=\(self.coordinator.stopReason?.rawValue ?? "none", privacy: .public)")self.logProtectionLoss()@@ -132,7 +135,7 @@ private final class BrokerServer: @unchecked Sendable {self.close(connection)}if let owner = self.coordinator.owner,- let connection = self.connections[owner.connectionID], !connection.clientInvalidated {+ let connection = self.connections[owner.connectionID], !connection.clientInvalidated, connection.clientDescriptor >= 0, !connection.clientAdmissionPending {do { try self.verifyOriginalClient(connection) }catch {connection.clientInvalidated = true@@ -152,9 +155,19 @@ private final class BrokerServer: @unchecked Sendable {catch { self.stopAll() }}self.timer = timer+ updateTimerCadence()timer.resume()}+ private func updateTimerCadence() {+ let interval = LockedUseBrokerPolling.interval(phase: coordinator.phase, fullyReleased: coordinator.isFullyReleased)+ guard interval != timerInterval, let timer else { return }+ timerInterval = interval+ // An incoming begin must restore watchdog cadence immediately, rather+ // than waiting for the next idle tick.+ timer.schedule(deadline: .now(), repeating: .milliseconds(Int(interval * 1000)), leeway: .milliseconds(10))+ }+private func accept(fd: Int32, endpoint: LockedUseIPCEndpoint) {for _ in 0..<16 {let client = Darwin.accept(fd, nil, nil)@@ -228,11 +241,11 @@ private final class BrokerServer: @unchecked Sendable {guard peer.userID == 0, peer.hardenedRuntime, !peer.permitsCodeInjection else { throw BrokerError.message("untrusted installer") }return peercase .plugin:- // SecurityAgent is Apple signed, not signed by the application's+ // The privileged authorization host is Apple signed, not signed by our// Developer ID team. Never substitute a user-provided requirement.- let requirement = "anchor apple and (identifier \"com.apple.SecurityAgentHelper.arm64\" or identifier \"com.apple.SecurityAgentHelper.x86_64\")"+ let requirement = "anchor apple and (identifier \"com.apple.authorizationhosthelper.arm64\" or identifier \"com.apple.authorizationhosthelper.x86_64\")"let peer = try LockedUsePeerIdentity.verified(socket: fd, requirement: requirement)- guard peer.auditSessionID > 0, !peer.permitsCodeInjection else { throw BrokerError.message("untrusted authorization helper") }+ guard peer.userID == 0, peer.auditSessionID > 0, !peer.permitsCodeInjection else { throw BrokerError.message("untrusted authorization helper") }return peer}}@@ -247,11 +260,41 @@ private final class BrokerServer: @unchecked Sendable {guard ocu_copy_peer_identity(fd, &native) == 0, native.effective_user_id == connection.identity.userID,native.audit_session_id == connection.identity.auditSessionID else { throw BrokerError.message("client session mismatch") }let token = withUnsafeBytes(of: native.audit_token) { Data($0) }- let client = try? approvals.verifiedPeer(socket: fd, role: .client)- guard client != nil || coordinator.recordedOwner?.auditToken == connection.identity.auditToken && ownerClientToken == token else {- throw BrokerError.message("client not approved for this epoch")+ let borrowed = LockedUseBorrowedSocket(descriptor: fd)+ connection.clientSocket = borrowed+ connection.clientAdmissionPending = true+ connection.readSource?.suspend()+ let admission = UUID()+ let deadline = ProcessInfo.processInfo.systemUptime + 8+ pendingAdmissions[admission] = fd+ forwardedAdmissions.insert(admission)+ queue.asyncAfter(deadline: .now() + 8) { [self, connection] in+ guard pendingAdmissions[admission] == fd else { return }+ cancelledAdmissions.insert(admission)+ close(connection) // Retain borrowed fd until the worker returns.+ }+ peerAuthenticator.verify({ [self] in+ try borrowed.withDescriptor { try? approvals.verifiedPeer(socket: $0, role: .client) }+ }) { [self, connection] result in+ queue.async { [self, connection] in+ pendingAdmissions.removeValue(forKey: admission)+ forwardedAdmissions.remove(admission)+ let cancelled = cancelledAdmissions.remove(admission) != nil+ connection.clientAdmissionPending = false+ if connection.closed {+ connection.clientSocket = nil+ return+ }+ connection.readSource?.resume()+ guard !cancelled, ProcessInfo.processInfo.systemUptime < deadline,+ case let .success(client) = result,+ client != nil || coordinator.recordedOwner?.auditToken == connection.identity.auditToken && ownerClientToken == token else {+ close(connection); return+ }+ connection.clientIdentity = client+ connection.clientAuditToken = token+ }}- connection.clientDescriptor = fd; connection.clientIdentity = client; connection.clientAuditToken = token} catch { Darwin.close(fd); close(connection) }return}@@ -261,7 +304,7 @@ private final class BrokerServer: @unchecked Sendable {guard count > 0 else { close(connection); return }do {if connection.endpoint == .observer { logger.notice("observerStage=readStarted") }- let current = try authenticate(fd: connection.fd, endpoint: connection.endpoint)+ let current = try connection.identity.revalidated(socket: connection.fd)if connection.endpoint == .observer { logger.notice("observerStage=verified") }guard current.auditToken == connection.identity.auditToken,current.codeDirectoryHash == connection.identity.codeDirectoryHash else { throw BrokerError.message("peer changed") }@@ -290,6 +333,7 @@ private final class BrokerServer: @unchecked Sendable {reply = .init(id: request.id, result: .denied, phase: coordinator.phase,detail: "Request denied by Broker policy")}+ updateTimerCadence()if previousPhase != coordinator.phase {logger.notice("phase=\(self.coordinator.phase.rawValue, privacy: .public) stopReason=\(self.coordinator.stopReason?.rawValue ?? "none", privacy: .public)")logProtectionLoss()@@ -400,7 +444,7 @@ private final class BrokerServer: @unchecked Sendable {guard peeked > 0 || (peeked < 0 && [EAGAIN, EWOULDBLOCK, EINTR].contains(errno)) else {throw BrokerError.message("client disconnected")}- let client = try approvals.verifiedPeer(socket: connection.clientDescriptor, role: .client)+ let client = try previous.revalidated(socket: connection.clientDescriptor)guard client.auditToken == previous.auditToken,client.codeDirectoryHash == previous.codeDirectoryHash else { throw BrokerError.message("client changed") }}@@ -434,7 +478,9 @@ private final class BrokerServer: @unchecked Sendable {private func close(_ connection: BrokerConnection) {guard !connection.closed else { return }connection.closed = true- if connection.clientDescriptor >= 0 { Darwin.close(connection.clientDescriptor); connection.clientDescriptor = -1 }+ if connection.clientAdmissionPending { connection.readSource?.resume() }+ connection.clientSocket?.close()+ connection.clientSocket = niltry? coordinator.disconnected(connection.context)try? persistRecovery()connection.readSource?.cancel(); connection.writeSource?.cancel()@@ -445,7 +491,7 @@ private final class BrokerServer: @unchecked Sendable {for connection in Array(connections.values) { close(connection) }for (admission, fd) in pendingAdmissions {cancelledAdmissions.insert(admission)- shutdown(fd, SHUT_RDWR)+ if !forwardedAdmissions.contains(admission) { shutdown(fd, SHUT_RDWR) }}}@@ -511,7 +557,9 @@ private final class BrokerConnection: @unchecked Sendable {let created = ProcessInfo.processInfo.systemUptimevar clientAuditToken: Data?var clientInvalidated = false- var clientDescriptor: Int32 = -1+ var clientAdmissionPending = false+ var clientSocket: LockedUseBorrowedSocket?+ var clientDescriptor: Int32 { clientSocket?.descriptor ?? -1 }var clientIdentity: LockedUsePeerIdentity?init(fd: Int32, endpoint: LockedUseIPCEndpoint, identity: LockedUsePeerIdentity,context: LockedUseBrokerCoordinator.Context) {diff --git a/experiments/LockedUse/Sources/Installer/InstallerMain.swift b/experiments/LockedUse/Sources/Installer/InstallerMain.swiftindex f41ab53..5a62320 100644--- a/experiments/LockedUse/Sources/Installer/InstallerMain.swift+++ b/experiments/LockedUse/Sources/Installer/InstallerMain.swift@@ -12,7 +12,7 @@ private let daemon = URL(fileURLWithPath: "/Library/LaunchDaemons/dev.opencomputprivate let plugin = URL(fileURLWithPath: "/Library/Security/SecurityAgentPlugins/" + pluginName)private let screensaver = "system.login.screensaver"-private enum InstallError: Error { case invalidArguments, untrusted, existingInstallation, authentication(OSStatus), changedPolicy, process(Int32) }+private enum InstallError: Error { case stalePluginCache, pluginLoadFailed(OSStatus), invalidArguments, untrusted, existingInstallation, authentication(OSStatus), changedPolicy, process(Int32) }@mainstruct InstallerMain {@@ -138,9 +138,60 @@ struct InstallerMain {}private static func remoteDefinition() throws -> Data {try PropertyListSerialization.data(fromPropertyList: ["class": "evaluate-mechanisms",- "mechanisms": ["OCULockAuth:remote"], "shared": false,+ "mechanisms": [LockedUseAuthorizationRules.remoteMechanism], "shared": false,"timeout": 0, "tries": 1, "comment": "Open Computer Use single-use protected-session authorization"], format: .xml, options: 0)}+ private static func waitForStagedPlugin(team: String) throws {+ let staged = plugin.deletingLastPathComponent().appendingPathComponent("StagedPlugins/" + pluginName)+ guard let expected = try verify(plugin, id: "dev.opencomputeruse.locked-use.authorization", team: team)[kSecCodeInfoUnique as String] as? Data else { throw InstallError.untrusted }+ let deadline = ProcessInfo.processInfo.systemUptime + 15+ // Only wait when an old OS-managed copy actually exists. authd may+ // remove or refresh it after source replacement; never mutate its cache.+ while FileManager.default.fileExists(atPath: staged.path) {+ if let info = try? verify(staged, id: "dev.opencomputeruse.locked-use.authorization", team: team),+ info[kSecCodeInfoUnique as String] as? Data == expected { return }+ guard ProcessInfo.processInfo.systemUptime < deadline else { throw InstallError.stalePluginCache }+ Thread.sleep(forTimeInterval: 0.1)+ }+ }++ private static func verifyPluginLoads(authorization: AuthorizationRef) throws {+ let right = LockedUseAuthorizationRules.loadCheckRight+ var existing: CFDictionary?+ guard AuthorizationRightGet(right, &existing) == errAuthorizationDenied else { throw InstallError.existingInstallation }+ let definition = try PropertyListSerialization.data(fromPropertyList: [+ "class": "evaluate-mechanisms", "mechanisms": [LockedUseAuthorizationRules.loadCheckMechanism],+ "shared": false, "tries": 1, "timeout": 0+ ], format: .xml, options: 0)+ try setRight(right, data: definition, authorization: authorization)+ var removed = false+ defer { if !removed { _ = AuthorizationRightRemove(authorization, right) } }+ var probe: AuthorizationRef?+ let created = AuthorizationCreate(nil, nil, [], &probe)+ guard created == errSecSuccess, let probe else { throw InstallError.authentication(created) }+ defer { AuthorizationFree(probe, [.destroyRights]) }+ let result = right.withCString { name in+ var item = AuthorizationItem(name: name, valueLength: 0, value: nil, flags: 0)+ return withUnsafeMutablePointer(to: &item) { pointer in+ var rights = AuthorizationRights(count: 1, items: pointer)+ return AuthorizationCopyRights(probe, &rights, nil, [.extendRights], nil)+ }+ }+ var info: UnsafeMutablePointer<AuthorizationItemSet>?+ let copied = right.withCString { AuthorizationCopyInfo(probe, $0, &info) }+ defer { if let info { AuthorizationFreeItemSet(info) } }+ let expected = Data("OCULockAuth-loaded-v1\0".utf8)+ let removal = AuthorizationRightRemove(authorization, right)+ guard removal == errSecSuccess else { throw InstallError.authentication(removal) }+ removed = true+ guard result == errSecSuccess, copied == errSecSuccess, let info,+ info.pointee.count == 1, let item = info.pointee.items, let value = item.pointee.value,+ item.pointee.valueLength == expected.count,+ Data(bytes: value, count: expected.count) == expected else {+ throw InstallError.pluginLoadFailed(result)+ }+ }+private static func install(source: URL, uid: UInt32, team: String, validation: Bool) throws {try trustedTree(source)let broker = source.appendingPathComponent("OCULockService")@@ -181,6 +232,9 @@ struct InstallerMain {// Preserve a recoverable plan before writes; never blindly repair a// concurrently modified authentication policy in a failure handler.do {+ // Never attach an unloadable plug-in to every manual unlock.+ try waitForStagedPlugin(team: team)+ try verifyPluginLoads(authorization: reference)try setRight(LockedUseAuthorizationRules.remoteRight, data: remoteDefinition(), authorization: reference)guard try LockedUseAuthorizationRules.installationStillApplicable(current: readRight(screensaver), plan: plan) else { throw InstallError.changedPolicy }try setRight(screensaver, data: plan.installed, authorization: reference)@@ -340,16 +394,25 @@ struct InstallerMain {var existing: CFDictionary?let found = AuthorizationRightGet(LockedUseAuthorizationRules.remoteRight, &existing)if found == errSecSuccess {- guard let right = existing as? [String: Any], right["class"] as? String == "evaluate-mechanisms",- right["mechanisms"] as? [String] == ["OCULockAuth:remote"] else { throw InstallError.changedPolicy }+ guard let right = existing as? [String: Any],+ LockedUseAuthorizationRules.isOwnedRemoteRule(right, allowLegacy: true) else { throw InstallError.changedPolicy }let result = AuthorizationRightRemove(authorization, LockedUseAuthorizationRules.remoteRight)guard result == errSecSuccess else { throw InstallError.authentication(result) }} else if found != errAuthorizationDenied { throw InstallError.authentication(found) }- for candidate in [plugin, plugin.deletingLastPathComponent().appendingPathComponent("StagedPlugins/" + pluginName)] {- if FileManager.default.fileExists(atPath: candidate.path) {- _ = try verify(candidate, id: "dev.opencomputeruse.locked-use.authorization", team: team)- try FileManager.default.removeItem(at: candidate)- }+ var check: CFDictionary?+ let checkFound = AuthorizationRightGet(LockedUseAuthorizationRules.loadCheckRight, &check)+ if checkFound == errSecSuccess {+ guard let rule = check as? [String: Any], rule["class"] as? String == "evaluate-mechanisms",+ rule["mechanisms"] as? [String] == [LockedUseAuthorizationRules.loadCheckMechanism],+ (rule["shared"] as? NSNumber)?.boolValue == false else { throw InstallError.changedPolicy }+ let result = AuthorizationRightRemove(authorization, LockedUseAuthorizationRules.loadCheckRight)+ guard result == errSecSuccess else { throw InstallError.authentication(result) }+ } else if checkFound != errAuthorizationDenied { throw InstallError.authentication(checkFound) }+ // StagedPlugins is OS-managed and protected even from administrator+ // removal. authd watches the source and removes its own staged copy.+ if FileManager.default.fileExists(atPath: plugin.path) {+ _ = try verify(plugin, id: "dev.opencomputeruse.locked-use.authorization", team: team)+ try FileManager.default.removeItem(at: plugin)}if FileManager.default.fileExists(atPath: daemon.path) { try FileManager.default.removeItem(at: daemon) }try trustedTreeShallow(root)diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseAuthorizationRules.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseAuthorizationRules.swiftindex ba99b3e..2745b36 100644--- a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseAuthorizationRules.swift+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseAuthorizationRules.swift@@ -6,6 +6,16 @@ import Security/// or system writes occur here. The installer must retain the original plan in/// root-owned storage and re-read immediately before and after each mutation.public enum LockedUseAuthorizationRules {+ // Non-UI mechanism uses Apple's documented privileged authorization host.+ public static let remoteMechanism = "OCULockAuth:remote,privileged"+ public static let loadCheckRight = "dev.opencomputeruse.locked-use.load-check"+ public static let loadCheckMechanism = "OCULockAuth:load-check,privileged"+ public static func isOwnedRemoteRule(_ rule: [String: Any], allowLegacy: Bool = false) -> Bool {+ guard rule["class"] as? String == "evaluate-mechanisms",+ (rule["shared"] as? NSNumber)?.boolValue == false,+ let mechanisms = rule["mechanisms"] as? [String] else { return false }+ return mechanisms == [remoteMechanism] || (allowLegacy && mechanisms == ["OCULockAuth:remote"])+ }public static let remoteRight = "dev.opencomputeruse.locked-use.remote"public enum Failure: Error { case malformed, unsupported, alreadyPresent, changedSincePlanning }@@ -62,9 +72,7 @@ public enum LockedUseAuthorizationRules {var remote: CFDictionary?guard AuthorizationRightGet(remoteRight, &remote) == errAuthorizationSuccess,let rule = remote as? [String: Any] else { return false }- return rule["class"] as? String == "evaluate-mechanisms"- && rule["mechanisms"] as? [String] == ["OCULockAuth:remote"]- && (rule["shared"] as? NSNumber)?.boolValue == false+ return isOwnedRemoteRule(rule)}private static func validate(_ plan: Plan) throws {diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseBorrowedSocket.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseBorrowedSocket.swiftnew file mode 100644index 0000000..6522076--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseBorrowedSocket.swift@@ -0,0 +1,45 @@+import Darwin+import Foundation++/// An SCM_RIGHTS duplicate shares the caller's transport. Release only this fd;+/// shutdown would also break the caller. In-flight verification pins its lifetime.+public final class LockedUseBorrowedSocket: @unchecked Sendable {+ public enum Failure: Error { case closed }+ private let lock = NSLock()+ private var fd: Int32+ private var readers = 0+ private var closing = false++ public init(descriptor: Int32) { fd = descriptor }+ public var descriptor: Int32 {+ lock.lock(); defer { lock.unlock() }+ return closing ? -1 : fd+ }++ public func withDescriptor<T>(_ body: (Int32) throws -> T) throws -> T {+ lock.lock()+ guard !closing, fd >= 0 else { lock.unlock(); throw Failure.closed }+ readers += 1+ let current = fd+ lock.unlock()+ defer {+ lock.lock()+ readers -= 1+ let released = closing && readers == 0 ? fd : -1+ if released >= 0 { fd = -1 }+ lock.unlock()+ if released >= 0 { Darwin.close(released) }+ }+ return try body(current)+ }++ public func close() {+ lock.lock()+ closing = true+ let released = readers == 0 ? fd : -1+ if released >= 0 { fd = -1 }+ lock.unlock()+ if released >= 0 { Darwin.close(released) }+ }+ deinit { close() }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseBrokerPolling.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseBrokerPolling.swiftnew file mode 100644index 0000000..92ce423--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseBrokerPolling.swift@@ -0,0 +1,9 @@+import Foundation++/// Idle services need policy observation, but no 100 ms lease watchdog.+/// Incomplete guard release always retains the recovery cadence.+public enum LockedUseBrokerPolling {+ public static func interval(phase: LockedUseStateMachine.Phase, fullyReleased: Bool) -> TimeInterval {+ fullyReleased && (phase == .idle || phase == .awaitingManualUnlock) ? 1 : 0.1+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseDiagnostics.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseDiagnostics.swiftindex fb10aca..6c43039 100644--- a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseDiagnostics.swift+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseDiagnostics.swift@@ -80,6 +80,8 @@ public struct LockedUseDiagnostics: Codable, Sendable {public let accessibility: Boolpublic let screenRecording: Boolpublic let inputMonitoring: Bool+ public let installedPluginVersion: String?+ public let bundledPluginVersion: String?public let pluginInstalled: Boolpublic let brokerInstalled: Boolpublic let guardianAccessibility: Bool?@@ -118,6 +120,8 @@ public struct LockedUseDiagnostics: Codable, Sendable {clientApproved: approved, authenticationPolicyIntact: policyIntact,session: .current(), accessibility: AXIsProcessTrusted(),screenRecording: CGPreflightScreenCaptureAccess(), inputMonitoring: CGPreflightListenEventAccess(),+ installedPluginVersion: Bundle(url: URL(fileURLWithPath: pluginsPath + "/" + ownPlugin))?.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String,+ bundledPluginVersion: Bundle(url: Bundle.main.bundleURL.appendingPathComponent("Contents/Resources/LockedUse/OCULockAuth.bundle"))?.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String,pluginInstalled: entries.contains(ownPlugin),brokerInstalled: FileManager.default.fileExists(atPath: "/Library/Application Support/OpenComputerUse/LockedUse/OCULockService"),guardianAccessibility: guardianPermissions["accessibility"],@@ -154,11 +158,18 @@ public struct LockedUseDiagnostics: Codable, Sendable {} catch { return [:] }}+ public static func versionAdvice(installed: String?, bundled: String?) -> String? {+ guard let installed, let bundled, !installed.isEmpty, !bundled.isEmpty, installed != bundled else { return nil }+ return "Installed Locked Use components differ from this OCU app. Updating OCU does not update system components. Run ocu locked-use disable, then ocu locked-use enable to reinstall; incomplete tasks must finish recovery first."+ }+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"+ "Open Computer Use: Accessibility=\(accessibility), Screen Recording=\(screenRecording)\n"+ "Guardian: Accessibility=\(guardianAccessibility.map(String.init) ?? "unknown"), Input Monitoring=\(guardianInputMonitoring.map(String.init) ?? "unknown")\n"+ + "Authorization plugin: installed=\(installedPluginVersion ?? "unknown"), bundled=\(bundledPluginVersion ?? "unknown")\n"+ + (Self.versionAdvice(installed: installedPluginVersion, bundled: bundledPluginVersion).map { $0 + "\n" } ?? "")+ "Other authorization plugins: \(otherAuthorizationPlugins.isEmpty ? "none detected" : otherAuthorizationPlugins.joined(separator: ", "))\n"+ blockers.joined(separator: "\n")}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUsePeerIdentity.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUsePeerIdentity.swiftindex 313a6cd..bc500b6 100644--- a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUsePeerIdentity.swift+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUsePeerIdentity.swift@@ -2,6 +2,7 @@ import Darwinimport Foundationimport LockedUseNativeimport Security+import LightweightCodeRequirements/// Identity extracted from the connected socket, validated against a designated/// signing requirement. Same UID, a PID, or a claimed bundle ID is insufficient.@@ -20,6 +21,37 @@ public struct LockedUsePeerIdentity: Sendable {public enum Failure: Error { case peerUnavailable(Int32), signingUnavailable(OSStatus), invalidSignature(OSStatus), malformedIdentity }+ /// Revalidate an already admitted peer against its exact kernel code hash.+ /// The first admission still evaluates the full administrator requirement.+ /// Modern rechecks avoid network/disk assessment on the heartbeat queue.+ public func revalidated(socket descriptor: Int32) throws -> LockedUsePeerIdentity {+ var native = OCUPeerIdentity()+ guard ocu_copy_peer_identity(descriptor, &native) == 0 else { throw Failure.peerUnavailable(errno) }+ let token = withUnsafeBytes(of: native.audit_token) { Data($0) }+ guard token == auditToken else { throw Failure.malformedIdentity }+ if #available(macOS 14.4, *) {+ var audit = audit_token_t()+ _ = withUnsafeMutableBytes(of: &audit) { token.copyBytes(to: $0) }+ guard let task = SecTaskCreateWithAuditToken(nil, audit) else { throw Failure.malformedIdentity }+ let requirement = try ProcessCodeRequirement.allOf {+ CodeDirectoryHash(codeDirectoryHash)+ SigningIdentifier(signingIdentifier)+ ProcessCodeSigningFlags.isSuperset(of: [.isDynamicallyValid, .isSigned])+ }+ guard try SecTaskValidateForRequirement(task: task, requirement: requirement) else {+ throw Failure.invalidSignature(errSecCSReqFailed)+ }+ return self+ }+ // Legacy systems keep the original full verification; modern failures+ // never fall back to disk-only or identifier-only checks.+ let current = try Self.verified(socket: descriptor, requirement: designatedRequirement)+ guard current.auditToken == auditToken, current.codeDirectoryHash == codeDirectoryHash else {+ throw Failure.malformedIdentity+ }+ return current+ }+/// The requirement must come from administrator-owned installation config/// or an explicit client approval. Never accept it in the peer's payload.public static func verified(socket descriptor: Int32, requirement: String) throws -> LockedUsePeerIdentity {diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUsePermitRegistry.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUsePermitRegistry.swiftindex 4b07d38..2eb26e0 100644--- a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUsePermitRegistry.swift+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUsePermitRegistry.swift@@ -46,7 +46,7 @@ public struct LockedUsePermitRegistry: Sendable {return permit}- /// Authentication of the plugin's Apple SecurityAgent identity must precede+ /// Authentication of the plugin's Apple authorization-host identity must precede/// this operation. A consumed/expired/revoked attempt is never reusable.public mutating func consume(attemptID: UUID, session: Session, nonce: Data,guardsHealthy: Bool, now: TimeInterval) throws -> Permit {diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseAuthorizationRulesTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseAuthorizationRulesTests.swiftindex ae2a081..d1afeef 100644--- a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseAuthorizationRulesTests.swift+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseAuthorizationRulesTests.swift@@ -10,6 +10,22 @@ final class LockedUseAuthorizationRulesTests: XCTestCase {try XCTUnwrap(PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any])}+ func testOnlyPrivilegedNonUIRuleIsAcceptedForRuntimeButLegacyCanBeRemoved() {+ let current: [String: Any] = ["class": "evaluate-mechanisms", "shared": false,+ "mechanisms": [LockedUseAuthorizationRules.remoteMechanism]]+ XCTAssertTrue(LockedUseAuthorizationRules.isOwnedRemoteRule(current))+ var old = current+ old["mechanisms"] = ["OCULockAuth:remote"]+ XCTAssertFalse(LockedUseAuthorizationRules.isOwnedRemoteRule(old))+ XCTAssertTrue(LockedUseAuthorizationRules.isOwnedRemoteRule(old, allowLegacy: true))+ old["mechanisms"] = ["OCULockAuth:load-check,privileged"]+ XCTAssertFalse(LockedUseAuthorizationRules.isOwnedRemoteRule(old, allowLegacy: true))+ old["mechanisms"] = [LockedUseAuthorizationRules.remoteMechanism, "other:allow"]+ XCTAssertFalse(LockedUseAuthorizationRules.isOwnedRemoteRule(old, allowLegacy: true))+ old = current; old["shared"] = true+ XCTAssertFalse(LockedUseAuthorizationRules.isOwnedRemoteRule(old, allowLegacy: true))+ }+func testDefaultFallbackAndUnrelatedFieldsSurviveRoundTrip() throws {let before = try data(["class": "rule", "rule": ["use-login-window-ui"], "version": 1,"comment": "existing comment", "shared": false, "created": 10.5, "modified": 20.5])diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseBrokerPollingTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseBrokerPollingTests.swiftnew file mode 100644index 0000000..7d9c364--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseBrokerPollingTests.swift@@ -0,0 +1,18 @@+import XCTest+@testable import OpenComputerUseKit++final class LockedUseBrokerPollingTests: XCTestCase {+ func testIdleOnlySlowsWhenGuardsAreFullyReleased() {+ for phase in [LockedUseStateMachine.Phase.idle, .awaitingManualUnlock] {+ XCTAssertEqual(LockedUseBrokerPolling.interval(phase: phase, fullyReleased: true), 1)+ XCTAssertEqual(LockedUseBrokerPolling.interval(phase: phase, fullyReleased: false), 0.1)+ }+ }++ func testActiveAndRecoveryPhasesRetainWatchdogCadence() {+ for phase in [LockedUseStateMachine.Phase.preparing, .authorizing, .unlocking, .active, .relocking] {+ XCTAssertEqual(LockedUseBrokerPolling.interval(phase: phase, fullyReleased: true), 0.1)+ XCTAssertEqual(LockedUseBrokerPolling.interval(phase: phase, fullyReleased: false), 0.1)+ }+ }+}diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseComponentVersionTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseComponentVersionTests.swiftnew file mode 100644index 0000000..51e6543--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseComponentVersionTests.swift@@ -0,0 +1,15 @@+import XCTest+@testable import OpenComputerUseKit++final class LockedUseComponentVersionTests: XCTestCase {+ func testOldDevelopmentInstallationSuggestsExplicitReinstall() {+ let advice = LockedUseDiagnostics.versionAdvice(installed: "0.0.1", bundled: "1.1.0")+ XCTAssertTrue(advice?.contains("ocu locked-use disable") == true)+ XCTAssertTrue(advice?.contains("ocu locked-use enable") == true)+ }+ func testMatchingOrUnknownVersionsDoNotSuggestReplacingComponents() {+ XCTAssertNil(LockedUseDiagnostics.versionAdvice(installed: "1.1.0", bundled: "1.1.0"))+ XCTAssertNil(LockedUseDiagnostics.versionAdvice(installed: nil, bundled: "1.1.0"))+ XCTAssertNil(LockedUseDiagnostics.versionAdvice(installed: "0.0.1", bundled: nil))+ }+}diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseIPCTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseIPCTests.swiftindex cdeccda..c6262ee 100644--- a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseIPCTests.swift+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseIPCTests.swift@@ -5,6 +5,31 @@ import LockedUseNativeimport XCTestfinal class LockedUseIPCTests: XCTestCase {+ func testReleasingForwardedDescriptorKeepsOriginalTransportUsable() throws {+ var channel: [Int32] = [-1, -1]+ var original: [Int32] = [-1, -1]+ XCTAssertEqual(socketpair(AF_UNIX, SOCK_STREAM, 0, &channel), 0)+ XCTAssertEqual(socketpair(AF_UNIX, SOCK_STREAM, 0, &original), 0)+ defer { channel.forEach { Darwin.close($0) }; original.forEach { Darwin.close($0) } }+ XCTAssertEqual(ocu_send_peer_socket(channel[0], original[0]), 0)+ let borrowed = ocu_receive_peer_socket(channel[1])+ XCTAssertGreaterThanOrEqual(borrowed, 0)+ let socket = LockedUseBorrowedSocket(descriptor: borrowed)+ try socket.withDescriptor { descriptor in+ socket.close() // Closing during verification keeps its fd pinned.+ var identity = OCUPeerIdentity()+ XCTAssertEqual(ocu_copy_peer_identity(descriptor, &identity), 0)+ }+ XCTAssertEqual(socket.descriptor, -1)+ socket.close() // Idempotent; must not close a subsequently reused fd.+ XCTAssertThrowsError(try socket.withDescriptor { _ in XCTFail("Closed socket reused") })+ var sent: UInt8 = 42+ var received: UInt8 = 0+ XCTAssertEqual(Darwin.write(original[0], &sent, 1), 1)+ XCTAssertEqual(Darwin.read(original[1], &received, 1), 1)+ XCTAssertEqual(received, sent)+ }+func testTransferredSocketRetainsKernelPeerAndIsCloseOnExec() throws {var channel: [Int32] = [-1, -1], peer: [Int32] = [-1, -1]XCTAssertEqual(socketpair(AF_UNIX, SOCK_STREAM, 0, &channel), 0)diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUsePeerRevalidationTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUsePeerRevalidationTests.swiftnew file mode 100644index 0000000..4052640--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUsePeerRevalidationTests.swift@@ -0,0 +1,28 @@+import Darwin+import XCTest+@testable import OpenComputerUseKit++final class LockedUsePeerRevalidationTests: XCTestCase {+ func testKernelRecheckAcceptsSameLivePeerAndRejectsForgedHashOrToken() throws {+ guard #available(macOS 14.4, *) else { throw XCTSkip("Kernel requirements need macOS 14.4") }+ var sockets: [Int32] = [-1, -1]+ XCTAssertEqual(socketpair(AF_UNIX, SOCK_STREAM, 0, &sockets), 0)+ defer { Darwin.close(sockets[0]); Darwin.close(sockets[1]) }+ // Test executable can be ad hoc signed; production admission retains+ // its administrator-supplied Apple/Developer ID requirement.+ let peer = try LockedUsePeerIdentity.verified(socket: sockets[0], requirement: "true")+ XCTAssertEqual(try peer.revalidated(socket: sockets[0]).auditToken, peer.auditToken)+ func changed(hash: Data, token: Data) -> LockedUsePeerIdentity {+ .init(auditToken: token, userID: peer.userID, auditUserID: peer.auditUserID,+ auditSessionID: peer.auditSessionID, processID: peer.processID,+ signingIdentifier: peer.signingIdentifier, teamIdentifier: peer.teamIdentifier,+ codeDirectoryHash: hash, designatedRequirement: peer.designatedRequirement,+ hardenedRuntime: peer.hardenedRuntime, permitsCodeInjection: peer.permitsCodeInjection)+ }+ XCTAssertThrowsError(try changed(hash: Data(repeating: 0, count: peer.codeDirectoryHash.count),+ token: peer.auditToken).revalidated(socket: sockets[0]))+ XCTAssertThrowsError(try changed(hash: peer.codeDirectoryHash,+ token: Data(repeating: 0, count: peer.auditToken.count)).revalidated(socket: sockets[0]))+ XCTAssertThrowsError(try peer.revalidated(socket: -1))+ }+}diff --git a/scripts/run-locked-use-smoke.py b/scripts/run-locked-use-smoke.pyindex 4315b77..d0f33c7 100644--- a/scripts/run-locked-use-smoke.py+++ b/scripts/run-locked-use-smoke.py@@ -45,6 +45,7 @@ def main():fixture = Nonelocked = Falsecompleted = False+ protection_released = Falsestarted = time.time()events = []trace = runner.LiveAuthenticationTrace(started)@@ -92,6 +93,7 @@ def main():rpc.notify("notifications/turn-ended")runner.wait_for(args.guardian, "locked", timeout=5)runner.wait_for_release(rpc)+ protection_released = Truerecord("relockedAndBothGuardsReleased")print("Unlock normally. The Counter: 1 window will remain open.", flush=True)runner.wait_for(args.guardian, "unlocked", timeout=120)@@ -101,7 +103,7 @@ def main():completed = Truerecord("manualUnlockAndCounterPassed", counter=final)finally:- if locked and not completed:+ if locked and not completed and not protection_released:try:rpc.notify("notifications/turn-ended")runner.wait_for_release(rpc)@@ -109,7 +111,9 @@ def main():except Exception:record("failureRecoveryPending")rpc.close()- if fixture and (not completed or not args.confirm_lock_test):+ # A manual-unlock observation timeout must not discard the already+ # verified counter. This retains only the demo, never a lease/guard.+ if fixture and (not protection_released 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,diff --git a/scripts/tests/locked-use-smoke.test.py b/scripts/tests/locked-use-smoke.test.pyindex ce516f0..9c98c85 100644--- a/scripts/tests/locked-use-smoke.test.py+++ b/scripts/tests/locked-use-smoke.test.py@@ -3,6 +3,8 @@ import importlib.utilimport pathlibimport sysimport unittest+from unittest.mock import Mock, patch+from contextlib import ExitStackroot = pathlib.Path(__file__).resolve().parents[1]sys.path.insert(0, str(root))@@ -12,6 +14,33 @@ spec.loader.exec_module(smoke)class SmokeReadbackTests(unittest.TestCase):+ def test_manual_unlock_timeout_retains_counter_after_guard_release(self):+ def state(count):+ return {"content": [{"type": "text", "text": f"Counter: {count}\n3 button Increment Counter locked-use-validation-increment"},+ {"type": "image", "data": f"image-{count}"}]}+ rpc, fixture, trace = Mock(), Mock(), Mock()+ rpc.call.side_effect = [{"passed": True}, state(0), state(0), {}, state(1)]+ trace.finish.return_value = ([], "ended")+ def wait_for(_guardian, state, **_kwargs):+ if state == "unlocked": raise TimeoutError("Manual unlock not observed")+ with ExitStack() as stack:+ stack.enter_context(patch.object(sys, "argv", ["smoke", "--app", "/tmp/app", "--guardian", "/tmp/guardian", "--fixture", "/tmp/fixture", "--confirm-lock-test"]))+ stack.enter_context(patch.object(smoke.runner, "session", return_value="unlocked"))+ stack.enter_context(patch.object(smoke.runner, "RPC", return_value=rpc))+ stack.enter_context(patch.object(smoke.runner, "LiveAuthenticationTrace", return_value=trace))+ stack.enter_context(patch.object(smoke.runner, "wait_for", side_effect=wait_for))+ released = stack.enter_context(patch.object(smoke.runner, "wait_for_release"))+ stack.enter_context(patch.object(smoke.runner, "write_report", return_value=pathlib.Path("report.json")))+ stack.enter_context(patch.object(smoke.subprocess, "Popen", return_value=fixture))+ stack.enter_context(patch.object(smoke.subprocess, "run"))+ stack.enter_context(patch.object(smoke.time, "sleep"))+ stack.enter_context(patch("builtins.print"))+ with self.assertRaises(TimeoutError): smoke.main()+ fixture.terminate.assert_not_called()+ released.assert_called_once_with(rpc)+ rpc.close.assert_called_once()+ rpc.notify.assert_called_once_with("notifications/turn-ended")+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):