👾 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
feat(macos): add Locked Use
ifurystd5b23ed87716
diff --git a/Package.swift b/Package.swiftindex a70eca5..39f5351 100644--- a/Package.swift+++ b/Package.swift@@ -8,6 +8,9 @@ let package = Package(.macOS(.v14),],products: [+ .executable(name: "OCULockInstaller", targets: ["OCULockInstaller"]),+ .executable(name: "OCULockService", targets: ["OCULockService"]),+ .executable(name: "OCUGuardian", targets: ["OCUGuardian"]),.library(name: "OpenComputerUseKit",targets: ["OpenComputerUseKit"]@@ -45,9 +48,30 @@ let package = Package(.linkedFramework("CoreGraphics"),]),+ .target(+ name: "LockedUseNative",+ path: "packages/LockedUseNative",+ publicHeadersPath: "include",+ linkerSettings: [.linkedLibrary("bsm")]+ ),+ .executableTarget(+ name: "OCULockInstaller",+ dependencies: ["OpenComputerUseKit", "LockedUseNative"],+ path: "experiments/LockedUse/Sources/Installer"+ ),+ .executableTarget(+ name: "OCULockService",+ dependencies: ["OpenComputerUseKit", "LockedUseNative"],+ path: "experiments/LockedUse/Sources/Broker"+ ),+ .executableTarget(+ name: "OCUGuardian",+ dependencies: ["OpenComputerUseKit"],+ path: "experiments/LockedUse/Sources/Guardian"+ ),.target(name: "OpenComputerUseKit",- dependencies: ["OpenComputerUseVirtualDisplayShim", .product(name: "libwebp", package: "libwebp-Xcode")],+ dependencies: ["OpenComputerUseVirtualDisplayShim", "LockedUseNative", .product(name: "libwebp", package: "libwebp-Xcode")],path: "packages/OpenComputerUseKit/Sources/OpenComputerUseKit"),.executableTarget(diff --git a/README.md b/README.mdindex d8b764a..137451d 100644--- a/README.md+++ b/README.md@@ -103,6 +103,8 @@ You can also manually download and install the## More+See the [Locked Use guide](docs/locked-use.en.md) for setup, installed components, and permissions.+Besides the MCP JSON config above, you can also use the built-in commands:```bashdiff --git a/README.zh-CN.md b/README.zh-CN.mdindex b2d60a7..97d1524 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -101,6 +101,8 @@ npx skills update open-computer-use -g -y## 更多+Locked Use 的开启方式、安装组件和权限见[文档](docs/locked-use.zh-CN.md)。+除了直接用上面的 MCP JSON 配置,你也可以用一些内置子命令:```bashdiff --git a/apps/OpenComputerUse/Sources/OpenComputerUse/LockedUseConnection.swift b/apps/OpenComputerUse/Sources/OpenComputerUse/LockedUseConnection.swiftnew file mode 100644index 0000000..88b2fe7--- /dev/null+++ b/apps/OpenComputerUse/Sources/OpenComputerUse/LockedUseConnection.swift@@ -0,0 +1,263 @@+import Darwin+import Foundation+import OpenComputerUseKit+import os++/// One authenticated Broker connection per app-agent client. Only GUI requests+/// acquire a lease; inventory, diagnostics and protocol discovery do not unlock.+final class LockedUseConnection: @unchecked Sendable {+ private let mutex = NSLock()+ private let logger = Logger(subsystem: "dev.opencomputeruse.locked-use", category: "AgentRecovery")+ private let clientSocket: Int32+ private var broker: LockedUseIPCClient?+ private var lease: UUID?+ private var guardian: Process?+ private var timer: DispatchSourceTimer?+ private var stopped = false+ private var clientDisconnected = false+ private var inFlight = false+ private var validationLease: UUID?+ private var recoveryProbeStarted = false+ private let recoveryDeadline = LockedUseRecoveryDeadline {+ // Exit our own automation agent, not the Guardian/watchdog or a user+ // application. Root still requires observed lock and unlock-work drain+ // before either shield can be released.+ fputs("Locked Use recovery deadline expired; stopping automation agent.\n", stderr)+ _exit(70)+ }++ init(clientSocket: Int32) {+ self.clientSocket = dup(clientSocket)+ if self.clientSocket >= 0 { _ = fcntl(self.clientSocket, F_SETFD, FD_CLOEXEC) }+ }+ deinit { if clientSocket >= 0 { Darwin.close(clientSocket) } }++ func perform<T>(_ body: () throws -> T) throws -> T {+ let session = LockedUseSession.current()+ mutex.lock(); let needsRecovery = stopped && lease == nil; mutex.unlock()+ if session.state == .unlocked, needsRecovery || FileManager.default.fileExists(atPath: LockedUseIPCEndpoint.observer.path) {+ _ = try observeManualUnlock()+ }+ if session.state == .locked { try acquire(session: session) }+ mutex.lock()+ guard !stopped && !clientDisconnected else { mutex.unlock(); throw ComputerUseError.stateUnavailable("Locked Use stopped. Unlock the Mac normally before starting another session.") }+ let scoped = lease != nil+ inFlight = true+ mutex.unlock()+ defer {+ mutex.lock(); inFlight = false; let drain = stopped; mutex.unlock()+ if drain { acknowledgeDrain() }+ }+ if scoped {+ return try LockedUseActionScope.withValidator({ [self] in try validateAction() }, body: body)+ }+ return try body()+ }++ private func acquire(session: LockedUseSession, recoveryProbe: Bool = false) throws {+ mutex.lock(); let existing = lease; let denied = stopped || clientDisconnected; mutex.unlock()+ if existing != nil || denied { try validateAction(); return }+ let connection = try LockedUseIPCClient(endpoint: .agent,+ brokerRequirement: LockedUseSigningIdentity.brokerRequirement(), clientSocket: clientSocket)+ let reply = try connection.request(.init(operation: recoveryProbe ? .beginRecoveryProbe : .begin, session: session))+ let now = ProcessInfo.processInfo.systemUptime+ let startupDeadline = reply.startupDeadline ?? now + LockedUseStateMachine.unlockTimeout+ guard reply.result != .denied, reply.phase == .preparing,+ startupDeadline.isFinite, startupDeadline > now,+ startupDeadline <= now + LockedUseStateMachine.validationUnlockTimeout,+ let lease = reply.leaseID, let token = reply.token else {+ connection.close()+ throw ComputerUseError.stateUnavailable("Locked Use is unavailable. Enable and validate it in Open Computer Use settings.")+ }+ mutex.lock(); broker = connection; self.lease = lease; let disconnected = clientDisconnected; mutex.unlock()+ if recoveryProbe { mutex.lock(); recoveryProbeStarted = true; mutex.unlock() }+ // Follow the authenticated root's bounded deadline, plus its existing+ // two-second RPC budget for stop/drain. The client cannot extend it.+ recoveryDeadline.arm(after: startupDeadline - now + 2)+ do {+ guard !disconnected else { throw ComputerUseError.stateUnavailable("Computer Use client disconnected during lease acquisition.") }+ let child = Process()+ // The installer fixes this location; caller arguments cannot select+ // another guardian or executable while holding a capability.+ child.executableURL = URL(fileURLWithPath: "/Library/Application Support/OpenComputerUse/LockedUse/OCU Guardian.app/Contents/MacOS/OCUGuardian")+ child.arguments = ["--broker-guardian"]+ let input = Pipe()+ child.standardInput = input+ let directory = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask)[0].appendingPathComponent("Logs/OpenComputerUse/LockedUse", isDirectory: true)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])+ let logURL = directory.appendingPathComponent(UUID().uuidString + ".jsonl")+ let logFD = open(logURL.path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600)+ guard logFD >= 0 else { throw POSIXError(.init(rawValue: errno) ?? .EIO) }+ let log = FileHandle(fileDescriptor: logFD, closeOnDealloc: true)+ defer { try? log.close() }+ child.standardOutput = log+ child.standardError = FileHandle.nullDevice+ try child.run()+ guardian = child+ try input.fileHandleForWriting.write(contentsOf: LockedUseIPCFrame.encode(LockedUseGuardianBootstrap(leaseID: lease, token: token, startupDeadline: startupDeadline)))+ try input.fileHandleForWriting.close()+ startPolling()+ let deadline = startupDeadline+ while ProcessInfo.processInfo.systemUptime < deadline {+ let status = try connection.request(.init(operation: .status, leaseID: lease, session: .current()))+ receive(status)+ if status.result == .active { recoveryDeadline.cancel(); return }+ if status.result == .denied || status.phase == .relocking || status.phase == .awaitingManualUnlock || !child.isRunning { break }+ Thread.sleep(forTimeInterval: 0.1)+ }+ throw ComputerUseError.stateUnavailable("Locked Use could not observe a protected GUI session becoming unlocked.")+ } catch { end(); throw error }+ }++ private func validateAction() throws {+ mutex.lock(); let connection = broker; let lease = lease; let denied = stopped || clientDisconnected; mutex.unlock()+ guard !denied, let connection, let lease else {+ throw ComputerUseError.stateUnavailable("Locked Use lease is no longer active.")+ }+ let reply = try connection.request(.init(operation: .action, leaseID: lease, session: .current()))+ receive(reply)+ guard reply.result == .active else { throw ComputerUseError.stateUnavailable("Locked Use stopped before this GUI action.") }+ }++ /// Exercise real dual-guard cleanup without allowing a single unlock. The+ /// installed validation Broker rejects this mode in a production profile.+ func validateRecovery() throws -> Bool {+ let session = LockedUseSession.current()+ guard session.state == .locked else { throw ComputerUseError.stateUnavailable("Recovery probe requires a locked session") }+ mutex.lock(); recoveryProbeStarted = false; mutex.unlock()+ do { try acquire(session: session, recoveryProbe: true) }+ catch { logger.notice("recoveryProbeAcquireEnded") }+ mutex.lock(); let started = recoveryProbeStarted; mutex.unlock()+ guard started else { throw ComputerUseError.stateUnavailable("Recovery probe was not admitted") }+ let observer = try LockedUseIPCClient(endpoint: .observer, brokerRequirement: LockedUseSigningIdentity.brokerRequirement())+ defer { observer.close() }+ let deadline = ProcessInfo.processInfo.systemUptime + 5+ while ProcessInfo.processInfo.systemUptime < deadline {+ let reply = try observer.request(.init(operation: .status, session: .current()))+ if reply.phase == .awaitingManualUnlock, reply.guardsReleased == true,+ reply.recoveryProbePrepared == true,+ LockedUseSession.current() == session { return true }+ if reply.phase == .awaitingManualUnlock, reply.guardsReleased == true {+ throw ComputerUseError.stateUnavailable("Recovery probe stopped before both guards became ready")+ }+ Thread.sleep(forTimeInterval: 0.1)+ }+ throw ComputerUseError.stateUnavailable("Recovery probe did not observe both guards released")+ }++ /// A fresh CLI connection still has to report an actual normal unlock.+ /// Wall-clock waiting or merely creating a new client cannot reset the+ /// Broker's failed locked episode.+ func observeManualUnlock() throws -> Bool {+ let session = LockedUseSession.current()+ guard session.state == .unlocked else { return false }+ let observer = try LockedUseIPCClient(endpoint: .observer, brokerRequirement: LockedUseSigningIdentity.brokerRequirement())+ defer { observer.close() }+ let reply = try observer.request(.init(operation: .status, session: session))+ if reply.phase == .idle {+ mutex.lock(); if lease == nil { stopped = false }; mutex.unlock()+ }+ return reply.phase == .idle && reply.guardsReleased == true+ }++ func protectionReleased() throws -> Bool {+ let observer = try LockedUseIPCClient(endpoint: .observer, brokerRequirement: LockedUseSigningIdentity.brokerRequirement())+ defer { observer.close() }+ let reply = try observer.request(.init(operation: .status, session: .current()))+ return reply.guardsReleased == true && (reply.phase == .idle || reply.phase == .awaitingManualUnlock)+ }++ func recordValidation(manual: Bool = false) throws {+ mutex.lock(); let lease = manual ? validationLease : lease; mutex.unlock()+ guard let lease else { throw ComputerUseError.stateUnavailable("No native validation lease.") }+ if manual {+ let connection = try LockedUseIPCClient(endpoint: .agent, brokerRequirement: LockedUseSigningIdentity.brokerRequirement(), clientSocket: clientSocket)+ defer { connection.close() }+ let reply = try connection.request(.init(operation: .validationManual, leaseID: lease, session: .current()))+ guard reply.result != .denied else { throw ComputerUseError.stateUnavailable("Validation manual-unlock confirmation denied.") }+ } else {+ try validateAction()+ mutex.lock(); let connection = broker; mutex.unlock()+ let reply = try connection?.request(.init(operation: .validationPassed, leaseID: lease))+ guard reply?.result != .denied, reply != nil else { throw ComputerUseError.stateUnavailable("Validation evidence denied.") }+ mutex.lock(); validationLease = lease; mutex.unlock()+ }+ }++ func end(disconnecting: Bool = false) {+ mutex.lock()+ stopped = lease != nil+ clientDisconnected = clientDisconnected || disconnecting+ let connection = broker; let lease = lease; let drain = !inFlight+ mutex.unlock()+ if lease != nil { recoveryDeadline.arm(after: 5) }+ if let connection, let lease {+ if let reply = try? connection.request(.init(operation: .end, leaseID: lease, stopReason: disconnecting ? .disconnected : .turnEnded)) { receive(reply) }+ if drain { acknowledgeDrain() }+ }+ }++ private func startPolling() {+ let timer = DispatchSource.makeTimerSource(queue: DispatchQueue(label: "ocu.locked-use.connection"))+ timer.schedule(deadline: .now(), repeating: .milliseconds(200))+ timer.setEventHandler { [self] in+ mutex.lock(); let connection = broker; let lease = lease; mutex.unlock()+ guard let lease else { return }+ do {+ let active: LockedUseIPCClient+ if let connection { active = connection }+ else {+ let candidate = try LockedUseIPCClient(endpoint: .agent, brokerRequirement: LockedUseSigningIdentity.brokerRequirement(), clientSocket: clientSocket)+ let hello = try candidate.request(.init(operation: .ownerRecoveryHello, leaseID: lease, session: .current()))+ guard hello.result != .denied else { candidate.close(); throw ComputerUseError.stateUnavailable("Broker recovery denied") }+ mutex.lock(); broker = candidate; mutex.unlock()+ active = candidate+ }+ let reply = try active.request(.init(operation: .status, leaseID: lease, session: .current()))+ receive(reply)+ mutex.lock(); let drain = stopped && !inFlight; mutex.unlock()+ if drain { acknowledgeDrain() }+ } catch {+ logger.error("brokerPollingFailed recoveryDeadlineArmed=true")+ recoveryDeadline.arm(after: 5)+ mutex.lock(); stopped = true; let failed = broker; broker = nil; mutex.unlock()+ failed?.close()+ // Guardian independently observes Broker failure and relocks.+ // Do not kill it, its watchdog, or its shields on IPC failure.+ }+ }+ self.timer = timer; timer.resume()+ }++ private func receive(_ reply: LockedUseIPCReply) {+ mutex.lock(); defer { mutex.unlock() }+ if reply.effects.contains("stopActions") || reply.phase == .relocking {+ stopped = true+ recoveryDeadline.arm(after: 5)+ }+ if reply.phase == .idle || reply.phase == .awaitingManualUnlock {+ recoveryDeadline.cancel()+ timer?.cancel(); timer = nil+ // This acknowledgment follows Guardian's lock observation and drain.+ lease = nil+ if reply.phase == .idle { stopped = false }+ broker?.close(); broker = nil+ }+ }++ private func acknowledgeDrain() {+ mutex.lock(); let connection = broker; let lease = lease; mutex.unlock()+ guard let connection, let lease else {+ logger.notice("actionDrainDeferred brokerAvailable=\(connection != nil, privacy: .public) leaseAvailable=\(lease != nil, privacy: .public)")+ return+ }+ logger.notice("actionDrainSubmitting")+ do {+ let reply = try connection.request(.init(operation: .quiesced, leaseID: lease))+ logger.notice("actionDrainReply phase=\(reply.phase.rawValue, privacy: .public) denied=\(reply.result == .denied, privacy: .public)")+ receive(reply)+ } catch {+ logger.error("actionDrainRPCFailed recoveryDeadlinePending=true")+ }+ }+}diff --git a/apps/OpenComputerUse/Sources/OpenComputerUse/LockedUseDeferredCleanup.swift b/apps/OpenComputerUse/Sources/OpenComputerUse/LockedUseDeferredCleanup.swiftnew file mode 100644index 0000000..2a4e1b4--- /dev/null+++ b/apps/OpenComputerUse/Sources/OpenComputerUse/LockedUseDeferredCleanup.swift@@ -0,0 +1,34 @@+import Dispatch+import OpenComputerUseKit++/// A disconnected test client may leave the OS refusing Keychain deletion until+/// a normal unlock. Retain only this process's isolated probe objects and retry;+/// never enumerate existing Keychain items to discover cleanup targets.+final class LockedUseDeferredCleanup: @unchecked Sendable {+ private final class Item: @unchecked Sendable {+ let probe: LockedUseKeychainProbe+ init(_ probe: LockedUseKeychainProbe) { self.probe = probe }+ }+ static let shared = LockedUseDeferredCleanup()+ private let queue = DispatchQueue(label: "ocu.locked-use.keychain-cleanup")+ private var items: [Item] = []+ private var timer: DispatchSourceTimer?++ func retainIfNeeded(_ probe: LockedUseKeychainProbe) {+ guard !probe.cleanup() else { return }+ let item = Item(probe)+ queue.async { [self, item] in+ items.append(item)+ if timer == nil {+ let source = DispatchSource.makeTimerSource(queue: queue)+ source.schedule(deadline: .now() + 1, repeating: .seconds(1))+ source.setEventHandler { [self] in+ guard LockedUseSession.current().state == .unlocked else { return }+ items.removeAll { $0.probe.cleanup() }+ if items.isEmpty { timer?.cancel(); timer = nil }+ }+ timer = source; source.resume()+ }+ }+ }+}diff --git a/apps/OpenComputerUse/Sources/OpenComputerUse/LockedUseNativeValidation.swift b/apps/OpenComputerUse/Sources/OpenComputerUse/LockedUseNativeValidation.swiftnew file mode 100644index 0000000..2a3b6f1--- /dev/null+++ b/apps/OpenComputerUse/Sources/OpenComputerUse/LockedUseNativeValidation.swift@@ -0,0 +1,64 @@+import AppKit+import CryptoKit+import Foundation+import OpenComputerUseKit+import Security+import os++/// Fixed real GUI target; no host-supplied app, index, image or "passed" flag.+enum LockedUseNativeValidation {+ static func run(probe: LockedUseKeychainProbe) throws {+ let logger = Logger(subsystem: "dev.opencomputeruse.locked-use", category: "NativeValidation")+ logger.notice("fixtureValidationStarted")+ let identifier = "dev.opencomputeruse.locked-use.fixture.dev"+ let apps = NSRunningApplication.runningApplications(withBundleIdentifier: identifier)+ guard apps.count == 1, let path = apps.first?.bundleURL,+ let team = try LockedUseSigningIdentity.current().teamIdentifier else {+ throw ComputerUseError.stateUnavailable("Launch the signed OCU Lock Demo first.")+ }+ var code: SecStaticCode?+ var requirement: SecRequirement?+ let expression = "identifier \"\(identifier)\" and anchor apple generic and certificate leaf[subject.OU] = \"\(team)\""+ guard SecStaticCodeCreateWithPath(path as CFURL, [], &code) == errSecSuccess,+ SecRequirementCreateWithString(expression as CFString, [], &requirement) == errSecSuccess,+ let code, SecStaticCodeCheckValidity(code, SecCSFlags(rawValue: kSecCSStrictValidate), requirement) == errSecSuccess else {+ throw ComputerUseError.stateUnavailable("Native validation fixture signer is not approved.")+ }+ let service = ComputerUseService()+ let before = try service.getAppState(app: identifier)+ guard let text = before.primaryText else { throw LockedUseKeychainProbe.Failure.verification }+ let buttons = text.split(separator: "\n").filter {+ $0.contains("Increment Counter") && $0.contains("locked-use-validation-increment")+ }+ guard buttons.count == 1, let index = buttons[0].split(whereSeparator: { $0.isWhitespace }).first,+ Int(index) != nil else { throw LockedUseKeychainProbe.Failure.verification }+ let counter = try counterValue(text)+ logger.notice("fixtureBeforeCaptured counter=\(counter, privacy: .public)")+ _ = try service.click(app: identifier, elementIndex: String(index), x: nil, y: nil,+ clickCount: 1, mouseButton: "left", clickMethod: .accessibility)+ let after = try service.getAppState(app: identifier)+ let afterCounter = try counterValue(after.primaryText ?? "")+ let imageChanged = try imageHash(before) != imageHash(after)+ logger.notice("fixtureReadBack counter=\(afterCounter, privacy: .public) imageChanged=\(imageChanged, privacy: .public)")+ guard afterCounter == counter + 1, imageChanged else { throw LockedUseKeychainProbe.Failure.verification }+ logger.notice("fixtureChanged counterIncremented=true imageChanged=true")+ try probe.verify()+ logger.notice("isolatedKeychainVerified dataProtectionIncluded=\(probe.includesDataProtection, privacy: .public)")+ }++ private static func counterValue(_ text: String) throws -> Int {+ let regex = try NSRegularExpression(pattern: #"Counter: ([0-9]+)"#)+ let matches = regex.matches(in: text, range: NSRange(text.startIndex..., in: text))+ guard matches.count == 1, let range = Range(matches[0].range(at: 1), in: text),+ let value = Int(text[range]), value < Int.max else { throw LockedUseKeychainProbe.Failure.verification }+ return value+ }+ private static func imageHash(_ result: ToolCallResult) throws -> Data {+ guard let content = result.asDictionary["content"] as? [[String: Any]],+ let base64 = content.first(where: { $0["type"] as? String == "image" })?["data"] as? String,+ let image = Data(base64Encoded: base64), !image.isEmpty else {+ throw ComputerUseError.stateUnavailable("Real ScreenCaptureKit validation image missing.")+ }+ return Data(SHA256.hash(data: image))+ }+}diff --git a/apps/OpenComputerUse/Sources/OpenComputerUse/LockedUseSettings.swift b/apps/OpenComputerUse/Sources/OpenComputerUse/LockedUseSettings.swiftnew file mode 100644index 0000000..5ee2a9b--- /dev/null+++ b/apps/OpenComputerUse/Sources/OpenComputerUse/LockedUseSettings.swift@@ -0,0 +1,112 @@+import AppKit+import Darwin+import Foundation+import OpenComputerUseKit++/// Explicit local enrollment. The elevated shell only stages signed artifacts+/// into a protected directory and verifies the installer before executing it.+/// It never executes a repository script with administrator privileges.+@MainActor+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")+ }+ let action = arguments[1]+ if action == "settings" {+ let app = NSApplication.shared+ app.setActivationPolicy(.accessory)+ let alert = NSAlert()+ alert.messageText = "Locked Use"+ alert.informativeText = "在锁屏时继续使用已登录的 Mac。所有显示器会被遮蔽;移动鼠标或按键立即返回锁屏。启用需要管理员授权和已验证的解锁组件。"+ alert.addButton(withTitle: "启用")+ alert.addButton(withTitle: "停用并移除")+ alert.addButton(withTitle: "取消")+ switch alert.runModal() {+ case .alertFirstButtonReturn: try enable(validation: false)+ case .alertSecondButtonReturn: try disable()+ default: break+ }+ } else if action == "enable" { try enable(validation: arguments.last == "--validation") }+ else if action == "certify" { try certify() }+ else if action == "recover" { try enable(validation: false, recovering: true) }+ else { try disable() }+ return true+ }++ private static func quote(_ text: String) -> String { "'" + text.replacingOccurrences(of: "'", with: "'\\''") + "'" }+ private static func elevate(_ commands: String) throws {+ // AppleScript receives one data string through an argument, avoiding+ // interpolation into AppleScript syntax or shell command substitution.+ let script = "on run argv\nreturn do shell script (item 1 of argv) with administrator privileges\nend run"+ let process = Process()+ process.executableURL = URL(fileURLWithPath: "/usr/bin/osascript")+ process.arguments = ["-e", script, commands]+ let output = Pipe(); process.standardOutput = output+ try process.run()+ let text = String(decoding: output.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)+ process.waitUntilExit()+ 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 {+ 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),+ let team = identity.teamIdentifier else { throw OpenComputerUseCLIError(message: "Use the signed Open Computer Use app to enable Locked Use.") }+ let source = Bundle.main.bundleURL.appendingPathComponent("Contents/Resources/LockedUse")+ guard FileManager.default.fileExists(atPath: source.appendingPathComponent("OCULockInstaller").path) else {+ throw OpenComputerUseCLIError(message: "Signed Locked Use components are missing from this app. Build with OPEN_COMPUTER_USE_INCLUDE_LOCKED_USE=1.")+ }+ // Administrator staging has a protected parent; /tmp ancestry would+ // permit path replacement even when a leaf happens to be root owned.+ let requirement = "=identifier \"dev.opencomputeruse.locked-use.installer\" and anchor apple generic and certificate leaf[subject.OU] = \"\(team)\""+ let stageParent = "/Library/Application Support/OpenComputerUseLockedUseStaging"+ let stage = stageParent + "/" + UUID().uuidString+ let shell = "set -eu\numask 077\n" ++ "/bin/test ! -L " + quote(stageParent) + "\n" ++ "/bin/mkdir -p " + quote(stageParent) + "\n" ++ "/usr/sbin/chown root:wheel " + quote(stageParent) + "\n" ++ "/bin/chmod -N " + quote(stageParent) + "\n" ++ "/bin/chmod 700 " + quote(stageParent) + "\n" ++ "/bin/mkdir " + quote(stage) + "\n" ++ "trap " + quote("/bin/rm -rf " + quote(stage)) + " EXIT\n" ++ "/usr/bin/ditto " + quote(source.path) + " " + quote(stage) + "\n" ++ "/usr/bin/ditto " + quote(Bundle.main.bundleURL.path) + " " + quote(stage + "/Client.app") + "\n" ++ "/usr/bin/find " + quote(stage) + " -type l -print -quit | /usr/bin/awk 'END { exit(NR != 0) }'\n" ++ "/usr/sbin/chown -hR -P root:wheel " + quote(stage) + "\n" ++ "/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"))+ try elevate(shell)+ }+ private static func certify() throws {+ guard LockedUseSession.current().state == .unlocked else {+ throw OpenComputerUseCLIError(message: "Unlock normally before reviewing production validation.")+ }+ let alert = NSAlert()+ alert.messageText = "确认 Locked Use 实机验证"+ alert.informativeText = "请仅在这些测试均通过后继续:所有物理屏幕持续遮蔽;Secure Input 下键盘和鼠标立即接管;Guardian、watchdog、app agent、Broker 故障及显示器变化安全重锁;正常密码及 Touch ID 解锁。专用窗口 AX / ScreenCaptureKit 与两类 Keychain 测试证据还会由安装器独立检查。升级 macOS 或保护组件后须重新验证。"+ alert.addButton(withTitle: "全部通过,启用")+ alert.addButton(withTitle: "取消")+ guard alert.runModal() == .alertFirstButtonReturn else { return }+ try installedAction("promote")+ }+ private static func installedAction(_ action: String) throws {+ let team = try LockedUseSigningIdentity.current().teamIdentifier!+ let base = "/Library/Application Support/OpenComputerUse/LockedUse/"+ let current = base + "OCULockInstaller"+ let legacy = base + "OpenComputerUseLockedUseInstaller"+ let path = FileManager.default.fileExists(atPath: current) ? current : legacy+ let requirement = "=identifier \"dev.opencomputeruse.locked-use.installer\" and anchor apple generic and certificate leaf[subject.OU] = \"\(team)\""+ try elevate("set -eu\n/usr/bin/codesign --verify --strict -R " + quote(requirement) + " " + quote(path) + "\n" + quote(path) + " " + quote(action))+ }++ private static func disable() throws {+ guard LockedUseSession.current().state == .unlocked else { throw OpenComputerUseCLIError(message: "Unlock the Mac normally before administrator removal.") }+ try installedAction("uninstall")+ }+}diff --git a/apps/OpenComputerUse/Sources/OpenComputerUse/MacOSAppAgentProxy.swift b/apps/OpenComputerUse/Sources/OpenComputerUse/MacOSAppAgentProxy.swiftindex 6e6060b..9c7deb7 100644--- a/apps/OpenComputerUse/Sources/OpenComputerUse/MacOSAppAgentProxy.swift+++ b/apps/OpenComputerUse/Sources/OpenComputerUse/MacOSAppAgentProxy.swift@@ -6,6 +6,7 @@ import OpenComputerUseKitprivate let appAgentCommand = "__open-computer-use-app-agent"private let appAgentDisableEnvironmentKey = "OPEN_COMPUTER_USE_DISABLE_APP_AGENT_PROXY"private let appAgentProcessStartDate = Date()+private let appAgentBuildIdentifier = Bundle.main.object(forInfoDictionaryKey: "OpenComputerUseBuildIdentifier") as? String ?? ""enum MacOSAppAgentProxy {static func isAgentInvocation(arguments: [String]) -> Bool {@@ -18,6 +19,10 @@ enum MacOSAppAgentProxy {throw OpenComputerUseCLIError(message: "\(appAgentCommand) requires a socket path")}+ // Swift globals initialize lazily. Capture both before the first request+ // so a later agentInfo call cannot mistake an old process for a rebuild.+ _ = appAgentProcessStartDate+ _ = appAgentBuildIdentifiertry MacOSAppAgentRuntime.run(socketPath: arguments[1])}@@ -88,6 +93,9 @@ enum MacOSAppAgentProxy {}_ = try? client.request(["kind": "terminate"])+ guard client.waitForDisconnect() else {+ throw OpenComputerUseCLIError(message: "Previous app agent has not exited. Retry after its current work stops.")+ }unlink(socketPath)} else {unlink(socketPath)@@ -303,9 +311,12 @@ private final class AppAgentSocketListener: @unchecked Sendable {private final class AppAgentConnection: @unchecked Sendable {private let fileDescriptor: Int32private let server = StdioMCPServer()+ private let lockedUse: LockedUseConnection+ private var keychainProbe: LockedUseKeychainProbe?init(fileDescriptor: Int32) {self.fileDescriptor = fileDescriptor+ lockedUse = LockedUseConnection(clientSocket: fileDescriptor)}func run() {@@ -313,7 +324,22 @@ private final class AppAgentConnection: @unchecked Sendable {close(fileDescriptor)return}+ let monitorQueue = DispatchQueue(label: "ocu.client-disconnect")+ let monitor = DispatchSource.makeTimerSource(queue: monitorQueue)+ monitor.schedule(deadline: .now(), repeating: .milliseconds(100))+ monitor.setEventHandler { [self] in+ var byte: UInt8 = 0+ let count = recv(fileDescriptor, &byte, 1, MSG_PEEK | MSG_DONTWAIT)+ if count == 0 || count < 0 && ![EAGAIN, EWOULDBLOCK, EINTR].contains(errno) {+ lockedUse.end(disconnecting: true)+ monitor.cancel()+ }+ }+ monitor.resume()defer {+ monitor.cancel(); monitorQueue.sync {}+ lockedUse.end(disconnecting: true)+ if let probe = keychainProbe { keychainProbe = nil; LockedUseDeferredCleanup.shared.retainIfNeeded(probe) }server.endSession()fclose(file)}@@ -339,6 +365,7 @@ private final class AppAgentConnection: @unchecked Sendable {"bundleURL": Bundle.main.bundleURL.standardizedFileURL.path,"executableURL": Bundle.main.executableURL?.standardizedFileURL.path ?? "","processStartTime": appAgentProcessStartDate.timeIntervalSince1970,+ "buildIdentifier": appAgentBuildIdentifier,]case "terminate":Task { @MainActor in@@ -348,8 +375,74 @@ private final class AppAgentConnection: @unchecked Sendable {case "mcp":let line = request["line"] as? String ?? ""let environment = request["environment"] as? [String: String] ?? [:]- let response = AppAgentEnvironment.withOverrides(environment) {- server.handle(line: line)+ let response: String? = try AppAgentEnvironment.withOverrides(environment) {+ let payload = try JSONSerialization.jsonObject(with: Data(line.utf8)) as? [String: Any]+ if payload?["method"] as? String == "notifications/turn-ended" { lockedUse.end() }+ if let method = payload?["method"] as? String, method.hasPrefix("ocu/locked-use/keychain/") || ["ocu/locked-use/validate", "ocu/locked-use/validate-unlocked", "ocu/locked-use/validate-recovery", "ocu/locked-use/validate-unlock", "ocu/locked-use/ready", "ocu/locked-use/protection-released"].contains(method) {+ var passed = false+ switch method {+ case "ocu/locked-use/ready":+ passed = try lockedUse.observeManualUnlock()+ case "ocu/locked-use/protection-released":+ passed = try lockedUse.protectionReleased()+ case "ocu/locked-use/validate-recovery":+ passed = try lockedUse.validateRecovery()+ case "ocu/locked-use/validate-unlock":+ guard LockedUseSession.current().state == .locked else {+ throw ComputerUseError.stateUnavailable("Begin unlock validation in a locked session")+ }+ // acquire() returns only after Root has observed+ // the original session unlocked with fresh guards.+ // No application, input, capture or Keychain access.+ try lockedUse.perform {+ guard LockedUseSession.current().state == .unlocked else {+ throw ComputerUseError.stateUnavailable("Protected session did not remain unlocked")+ }+ }+ passed = true+ case "ocu/locked-use/keychain/prepare", "ocu/locked-use/keychain/prepare-legacy":+ guard LockedUseSession.current().state == .unlocked, keychainProbe == nil else { throw ComputerUseError.stateUnavailable("Prepare validation items in a normally unlocked session.") }+ keychainProbe = try LockedUseKeychainProbe(includeDataProtection: method != "ocu/locked-use/keychain/prepare-legacy"); passed = true+ case "ocu/locked-use/keychain/verify":+ guard let probe = keychainProbe else { throw ComputerUseError.stateUnavailable("Prepare validation items first.") }+ try lockedUse.perform { try probe.verify() }; passed = true+ case "ocu/locked-use/validate-unlocked":+ guard LockedUseSession.current().state == .unlocked, let probe = keychainProbe else {+ throw ComputerUseError.stateUnavailable("Unshielded native fixture preflight requires a normally unlocked session.")+ }+ try lockedUse.perform { try LockedUseNativeValidation.run(probe: probe) }+ passed = true+ case "ocu/locked-use/validate":+ guard LockedUseSession.current().state == .locked, let probe = keychainProbe else {+ throw ComputerUseError.stateUnavailable("Begin fixed native validation from a locked session with prepared isolated Keychain items.")+ }+ try lockedUse.perform {+ try LockedUseNativeValidation.run(probe: probe)+ if probe.includesDataProtection { try lockedUse.recordValidation() }+ }+ passed = true+ case "ocu/locked-use/keychain/verify-manual":+ guard LockedUseSession.current().state == .unlocked, let probe = keychainProbe else {+ throw ComputerUseError.stateUnavailable("Unlock normally before the final isolated Keychain check.")+ }+ try probe.verify()+ if probe.includesDataProtection { try lockedUse.recordValidation(manual: true) }+ passed = true+ case "ocu/locked-use/keychain/cleanup":+ passed = keychainProbe?.cleanup() ?? true+ if passed { keychainProbe = nil }+ default: throw ComputerUseError.message("Unknown Keychain validation operation.")+ }+ let result: [String: Any] = ["jsonrpc": "2.0", "id": payload?["id"] ?? NSNull(), "result": ["passed": passed, "existingItemsRead": false, "dataProtectionIncluded": keychainProbe?.includesDataProtection ?? false]]+ return String(decoding: try JSONSerialization.data(withJSONObject: result), as: UTF8.self)+ }+ let parameters = payload?["params"] as? [String: Any]+ if payload?["method"] as? String == "tools/call",+ let name = parameters?["name"] as? String,+ name != "list_apps", ToolDefinitions.all.contains(where: { $0.name == name }) {+ return try lockedUse.perform { server.handle(line: line) }+ }+ return server.handle(line: line)}if let response {return ["response": response]@@ -358,8 +451,13 @@ private final class AppAgentConnection: @unchecked Sendable {case "cli":let arguments = request["arguments"] as? [String] ?? []let environment = request["environment"] as? [String: String] ?? [:]- let response = AppAgentEnvironment.withOverrides(environment) {- runCLI(arguments: arguments)+ let response = try AppAgentEnvironment.withOverrides(environment) {+ let command = try parseOpenComputerUseCLI(arguments: arguments)+ switch command {+ case .snapshot, .call:+ return try lockedUse.perform { runCLI(arguments: arguments) }+ default: return runCLI(arguments: arguments)+ }}return ["stdout": response.stdout,@@ -371,6 +469,24 @@ private final class AppAgentConnection: @unchecked Sendable {}} catch {let message = (error as? LocalizedError)?.errorDescription ?? String(describing: error)+ // Preserve the native RPC id even when lease acquisition fails+ // before the MCP server runs. The stdio proxy forwards responses,+ // not the app-agent envelope's error field.+ if let envelope = try? JSONSerialization.jsonObject(with: Data(requestLine.utf8)) as? [String: Any] {+ if envelope["kind"] as? String == "mcp",+ let line = envelope["line"] as? String,+ let rpc = try? JSONSerialization.jsonObject(with: Data(line.utf8)) as? [String: Any],+ let id = rpc["id"] {+ let failure: [String: Any] = ["jsonrpc": "2.0", "id": id,+ "error": ["code": -32000, "message": message]]+ if let data = try? JSONSerialization.data(withJSONObject: failure) {+ return ["response": String(decoding: data, as: UTF8.self)]+ }+ }+ if envelope["kind"] as? String == "cli" {+ return ["stdout": "", "stderr": message + "\n", "exitCode": Int(EXIT_FAILURE)]+ }+ }return ["error": message]}}@@ -396,7 +512,12 @@ private final class AppAgentConnection: @unchecked Sendable {PermissionOnboardingApp.present()}}- return CLIProxyResponse(stdout: (try json ? permissions.jsonText() : permissions.summary) + "\n", stderr: "", exitCode: EXIT_SUCCESS)+ let text = try json ? permissions.jsonText() : permissions.summary + "\n" + LockedUseDiagnostics.current().summary+ return CLIProxyResponse(stdout: text + "\n", stderr: "", exitCode: EXIT_SUCCESS)++ case let .lockedUseStatus(json):+ let diagnostics = LockedUseDiagnostics.current()+ return CLIProxyResponse(stdout: (try json ? diagnostics.jsonText() : diagnostics.summary) + "\n", stderr: "", exitCode: EXIT_SUCCESS)case .listApps:let service = ComputerUseService()@@ -528,6 +649,18 @@ private final class AppAgentSocketClient: @unchecked Sendable {return response}+ func waitForDisconnect() -> Bool {+ let deadline = ProcessInfo.processInfo.systemUptime + 3+ var byte: UInt8 = 0+ while ProcessInfo.processInfo.systemUptime < deadline {+ let count = recv(fileno(file), &byte, 1, MSG_PEEK | MSG_DONTWAIT)+ if count == 0 { return true }+ if count < 0, ![EAGAIN, EWOULDBLOCK, EINTR].contains(errno) { return true }+ Thread.sleep(forTimeInterval: 0.05)+ }+ return false+ }+func isCurrentAgent(for appURL: URL) throws -> Bool {let response = try request(["kind": "agentInfo"])let expectedBundleURL = appURL.standardizedFileURL@@ -536,6 +669,9 @@ private final class AppAgentSocketClient: @unchecked Sendable {return false}+ if let expectedBuild = Bundle(url: expectedBundleURL)?.object(forInfoDictionaryKey: "OpenComputerUseBuildIdentifier") as? String,+ !expectedBuild.isEmpty, response["buildIdentifier"] as? String != expectedBuild { return false }+guard let processStartTime = response["processStartTime"] as? TimeInterval else {return false}diff --git a/apps/OpenComputerUse/Sources/OpenComputerUse/OpenComputerUseMain.swift b/apps/OpenComputerUse/Sources/OpenComputerUse/OpenComputerUseMain.swiftindex 60f0129..fef1c19 100644--- a/apps/OpenComputerUse/Sources/OpenComputerUse/OpenComputerUseMain.swift+++ b/apps/OpenComputerUse/Sources/OpenComputerUse/OpenComputerUseMain.swift@@ -38,6 +38,8 @@ enum OpenComputerUseMain {}switch command {+ case .lockedUseManagement:+ _ = try LockedUseSettings.handle(arguments: arguments)case .mcp:let service = ComputerUseService()let server = StdioMCPServer(service: service)@@ -51,9 +53,15 @@ enum OpenComputerUseMain {case let .doctor(json):let permissions = PermissionDiagnostics.current()print(try json ? permissions.jsonText() : permissions.summary)+ if !json {+ print(LockedUseDiagnostics.current().summary)+ }if !json && !permissions.missingPermissions.isEmpty {PermissionOnboardingApp.launch()}+ case let .lockedUseStatus(json):+ let diagnostics = LockedUseDiagnostics.current()+ print(try json ? diagnostics.jsonText() : diagnostics.summary)case .listApps:let service = ComputerUseService()print(service.listApps().primaryText ?? "")diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 65603a4..cfa4d9c 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -139,6 +139,14 @@- Linux `click_method=accessibility` 映射到 AT-SPI action,`global` 映射到 AT-SPI mouse synthesis 并要求全局指针环境变量;AT-SPI 没有等价的进程定向 mouse dispatch,因此 `app_post` 和 macOS-only 的 `sky_click` 会在 snapshot lookup 前明确返回 unsupported,`key_method=sky_key` 也一样。`auto` 仍保持 AT-SPI action 优先、mouse synthesis fallback 的现有行为。- 当前 Linux 侧仍是功能性第一版:没有 visual cursor overlay、没有 installer/desktop entry,也没有独立 Linux fixture。后续 TODO 记录在 `docs/exec-plans/active/20260422-linux-computer-use-runtime.md`。+## macOS Locked Use 实验++- `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)。+## 关键边界- 开源版当前不复刻官方闭源实现里的 caller signing、私有 IPC、完整 overlay choreography 和 plugin 自安装逻辑。diff --git a/docs/QUALITY_SCORE.md b/docs/QUALITY_SCORE.mdindex f0548fc..7656a7b 100644--- a/docs/QUALITY_SCORE.md+++ b/docs/QUALITY_SCORE.md@@ -14,6 +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 / 崩溃 / 显示器故障实测后开放生产。 || 架构文档 | 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.mdindex b0c3c6c..5987f88 100644--- a/docs/RELIABILITY.md+++ b/docs/RELIABILITY.md@@ -56,3 +56,14 @@- 增加普通 app 回归样本,而不是只覆盖 fixture。CI/CD 流程结构和 release 自动化的默认方案,统一写在 `docs/CICD.md`。++## macOS Locked Use 预检++- `ocu locked-use status --json`:只读检查当前会话 / runtime 权限 / 安装组件;缺少完整实测证据时生产自动解锁不可用,显式验证 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 不锁屏边界。+- 系统插件加载实验和后续真实锁屏测试是独立的人工门槛,不进入常规 CI / smoke,也不在日常账户自动运行。步骤和恢复路径见 [Locked Use](locked-use.md)。++- Root 的认证策略读取使用独立队列;策略待定 / 过期 / 失败时停止新许可,协调队列继续处理恢复。独立 agent deadline 限制准备 / 停止时间,仍须验证真正撤罩和正常手动解锁的耗时。+- `python3 scripts/run-locked-use-native-validation.py --confirm-recovery-test` 是验证 profile 的人工故障收束入口,不签发解锁许可。必须同时证明两个保护确曾就绪、原会话锁定、动作排空与双方释放 ACK,才报告通过。diff --git a/docs/SECURITY.md b/docs/SECURITY.mdindex c461497..3b34e86 100644--- a/docs/SECURITY.md+++ b/docs/SECURITY.md@@ -47,3 +47,25 @@- 任何面向真实 app 的能力新增,都不应该复用这条测试专用通道。仓库级的依赖、SBOM 和 provenance 默认能力,统一写在 `docs/SUPPLY_CHAIN_SECURITY.md`。++## macOS Locked Use 实验边界++- 生产 backend 在完整实测证据缺失时关闭;只有管理员显式安装的验证 profile 能运行实验事务。用户环境和请求 metadata 不能开启生产自动解锁。+- 签名 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 观察缺一不可。+- 认证策略观察在独立队列完成。双保护就绪后保持有界 authorizing 待命,不预先签发许可;仅在已验证插件首次 claim、原会话仍锁定、策略和双保护新鲜时签发。许可最多 5 秒且不得超过本轮启动截止(默认 8 秒,显式验证 profile 总待命 20 秒;准备双保护仍最多 8 秒);取消 / 过期等待不能重启。恢复协议不能被同步 authd 查询堵塞。策略最大 2 秒新鲜度不是每条消息都做同步读取,也不覆盖第三方新规则。+- 两个保护进程各持有遮罩、输入过滤和硬件活动检测;只有撤销许可、排空动作 / 解锁事务并观测同会话锁定后才释放。停止 deadline 只结束自身 automation agent,不能提前杀保护或按时间撤罩。+- 人工 recovery-only 入口只对验证 profile 开放,在准备双保护后、签发许可前结束事务。准备失败的快速收束不能冒充双保护完整通过。+- 当前自动解锁、完整 Keychain、Secure Input、进程 / 服务故障和显示器变化仍未全部通过。两个物理屏幕 preview 和已解锁遮罩下 AX / SCK 的结果不能替代这些门槛。详见 [实验与恢复说明](locked-use.md)。++- macOS 14.4+ 的授权插件用 public LightweightCodeRequirements 对 socket audit token 建立 SecTask 验证:固定 signing ID / 团队、Developer ID validation category、动态签名有效、已签名、hardened runtime 和 Library Validation。逐项拒绝危险 entitlement,并重校验运行中的任务;现代验证失败不回退到字符串或磁盘检查。旧系统保留原 SecCode 路径。独立签名测试验证合法身份通过、错误 ID / 团队 / ad hoc / get-task-allow 被拒绝;实机锁屏表现仍须单独记录。++认证诊断采集是只读、限时、限量的辅助观察;原始 OS 字段不持久化,只保存白名单枚举,缺失日志不能作为认证 / 撤罩依据。上游报告记录插件介入后的会话级 Keychain 不可访问,未证明空输入导致重设;隔离环境是开发建议,不是 API 要求。新认证路径仍需验证系统的 Keychain 可用状态,不能从固定 AX 探针结果推出安全性。++验证 profile 的 HID 对比实验只改变鼠标投递层,继续经过同样的双会话过滤器和一次性能力校验;HID 注入不等于真实硬件活动或认证授权。生产与旧协议保持 session 层。++- 用户明确选择的无遮罩诊断是独立验证 profile 分支:只接受 Root 已批准签名探针的原锁定 session,不声明 guardsReady,不接受应用 action / 生产验证 / promotion,不恢复诊断许可。许可仍为首次同 audit session 插件 claim 后最多 5 秒且不超过 20 秒诊断截止;断开 / 策略失效 / 过期撤销不可重启。结果明确不含生产证据。正常生产保护规则不变。+++受保护 Return 验证实验不开放通用 keyboard exemption。与 click 不同的随机 tag 只经继承管道交给独立 watchdog;两套 gate 对原锁定 session、来源、目标、固定 keyCode 36、无 modifiers / autorepeat、5 秒有效期及 250ms down/up 进行独立一次性检查。真实硬件输入监控继续生效,停止 / 接管同时撤销 mouse 与 Return gate。只有管理员 validation profile 创建 Return 能力,生产等待完整实测。diff --git a/docs/assets/locked-use-architecture.png b/docs/assets/locked-use-architecture.pngnew file mode 100644index 0000000..a1bac80Binary files /dev/null and b/docs/assets/locked-use-architecture.png differdiff --git a/docs/exec-plans/active/20261005-macos-locked-use.md b/docs/exec-plans/active/20261005-macos-locked-use.mdnew file mode 100644index 0000000..9900c16--- /dev/null+++ b/docs/exec-plans/active/20261005-macos-locked-use.md@@ -0,0 +1,310 @@+# macOS Locked Use++## 目标与边界++用户显式安装并授权客户端后,普通 OCU GUI 调用在已登录会话锁定时自动进入临时解锁、全显示器遮蔽、AX / ScreenCaptureKit / 输入控制模式。turn-ended、断开、30 秒空闲或本地输入触发撤销许可和重锁。仅 macOS;首次启动 / FileVault / 用户切换不在范围。++## 实施门槛++1. 在可恢复测试环境验证真实 SecurityAgent 插件加载和 loginwindow 解锁事务。+2. 证明先建立显示器、输入和独立 watchdog 保护,再允许解锁;组件死亡和显示器重配置不得继续动作。+3. 验证正常密码 / Touch ID 解锁与 login / Data Protection Keychain 不受影响。+4. 可以先开发 Broker、guardian 和客户端登记等组件;生产启用必须等以上实测通过。未验证的 backend 必须 fail closed;不能以 AuthorizationCopyRights 返回成功伪装桌面已解锁。++## 当前实现切片++- [x] 只读原生会话、权限、安装及兼容性诊断,CLI / doctor 入口。+- [x] 可注入的保护状态机和回归测试:一次性许可、确认解锁、所有者、超时、接管、重锁确认。+- [x] 独立 Authorization 插件实验源码与无安装构建;仅支持 preflight 机制,始终拒绝授权。+- [x] 默认 GUI 边界对锁定 / 未知控制台状态明确拒绝,避免旧 snapshot 继续输入。+- [x] Swift / JS / GUI smoke / 插件构建验证与文档同步。+- [x] 独立 deny-only right 的管理员实机加载 / 调用 / 卸载探针。+- [x] 独立 Shield Guardian / watchdog rehearsal、受控 AX / SCK capture fixture、只读 loginwindow 结构探针和交互式恢复 controller。+- [x] 独立 15 秒遮罩倒计时 preview;两块物理显示器覆盖、倒计时和退出由用户确认,WindowServer 检查持续通过。+- [x] 遮罩期间受控 fixture 的 AX / SCK 实机闭环与 15 秒租约重锁日志验证。+- [x] 动作测试的两块物理屏幕持续遮蔽及正常手动解锁确认。+- [x] 本地鼠标输入接管专项验证:立即停止、确认锁定后撤罩,用户正常解锁。+- [x] 独立 watchdog 主线程卡死故障恢复软件专项验证。+- [x] watchdog 测试的物理屏幕持续遮蔽 / 正常解锁确认。+- [ ] 组件死亡与显示器变化故障验证。+- [x] 内核 audit-token / 动态签名认证、root 批准记录读取与短期一次性 permit registry;签名 / 角色实机自检与离线策略回归。+- [x] 保留现有认证 fallback 的离线安装规划;拒绝不同阈值、规则变化与篡改备份,未执行系统写入。+- [ ] 真正 loginwindow 解锁、独立保护与 Keychain 保持实验(阻塞生产 backend 开放)。+- [x] 签名 Broker 控制面、限定角色 IPC、remote 插件一次性放行与锁屏 Guardian 接入;离线验证通过,已安装验证 profile,真实许可消费与 SetResult(Allow) 已通过,解锁切换被严格遮罩尺寸检查中止;完整 GUI 闭环仍未通过。+- [x] 管理员安装 / 卸载入口、同团队原生客户端登记与 OCU 自动租约接入;已编译,系统验证 profile 安装与卸载已通过。+- [x] JS reset / timeout / EOF 停止通道与独立 Keychain 自有测试项 API。+- [x] 安装失败恢复入口、Broker 崩溃 journal / 双 Guardian release ACK、同团队原生客户端登记和验证转生产入口;离线通过,系统效果待实测。+- [ ] 真实安装 / 恢复、故障注入、升级失效与生产 promotion 验证。+- [ ] 真实自动解锁、Secure Input 硬件输入与 Keychain 保持验证。++## 环境观测++当前只读观测为 Apple Silicon / macOS 26.5.1。初始系统已有 Codex 的 screensaver remote rule / Authorization 插件,用户关闭后已确认移除。开发在独立 worktree;用户完成 Codex 插件清理后,通过系统管理员授权窗口运行了独立 deny-only right 的安装 / 卸载实验;不触碰 screensaver 链路,没有触发锁屏或读取凭据。不保存用户名、证书身份、本地绝对路径或原始日志。++## 验证++- swift test(保护状态机 / CLI / session gate)+- swift build+- node --test scripts/node-repl/*.test.mjs+- ./scripts/run-tool-smoke-tests.sh+- ./scripts/build-locked-use-plugin.sh(仅输出隔离构建产物)+- open-computer-use locked-use status --json(不授权、不安装、不解锁)++## 已知风险与来源++Apple DTS 确认过 screensaver authorization plugin 的 Data Protection Keychain 问题 FB13128730;当前系统上的已知症状不能当作本实现已安全的依据。保留 use-login-window-ui,不改旧式认证 UI,不伪造密码上下文,不关闭 SIP / Library Validation。++- https://developer.apple.com/documentation/security/extending-authorization-services-with-plug-ins+- https://developer.apple.com/documentation/security/authorizationcopyrights(_:_:_:_:_:)+- https://developer.apple.com/library/archive/samplecode/NullAuthPlugin/Introduction/Intro.html+- https://developer.apple.com/forums/thread/796487+- https://github.com/VenusOne-Lee/DispatchShield+- https://github.com/trycua/cua/issues/1744 (方案讨论,非完整可复用实现)++## 合并++2026-10-05 用户明确要求先保留开发 commit,所有实现与验证完成后才一次性合并到 awesome-extension;不提前合并任何实现切片。++基于本地 awesome-extension 的已提交状态。另一个会话有未提交的虚拟显示器工作;不 stash / reset 该会话。合并前再次检查目标工作区,只有不覆盖其改动时才在本地合并;不推远端。++## 进度记录++- 2026-10-05:继续下一阶段的安装边界,新增 LockedUseAuthorizationRules 与 7 项离线回归;保留原生 / Platform SSO rule 名称及顺序,只对现有 OR policy 插入本项目 branch,恢复前拒绝第三方语义变化与篡改计划。重新核对 Apple GetSessionId 为 opaque 认证事务 ID,不能冒充内核 audit session。当前系统 rules 仅只读检查,未安装生产 Broker 或自动解锁机制。++- 2026-10-05:watchdog 第二次实机测试软件通过:受控 AX / SCK 成功后 Guardian 主线程实际卡死约 5 秒;恢复时系统已锁定,privately inherited pipe 收到 watchdog 的重锁请求回报,再由原 session 锁定策略释放遮罩。不是 Guardian 在恢复后才完成锁定;用户确认没有露出桌面、手动解锁正常。没有自动解锁。卡死与进程死亡是不同故障;后者尚未验证。++- 2026-10-05:首次 watchdog 注入测试在启动约 0.4 秒时先发生 guardianFailure,未执行卡死注入;结果明确失败,controller 恢复路径观测系统锁定。补充 coverage 失败细项、tap disable 原因、Secure Input、watchdog pipe / heartbeat age 埋点后再定位,不能将这次提前重锁当作 watchdog 故障验证成功。++- 2026-10-05:输入接管专项测试:用户在倒计时约剩 10 秒时轻微移动鼠标,global mouseMoved 触发 localInput,约 90 毫秒后观测原会话锁定,再释放遮罩。用户确认接管与正常手动解锁。新增独立 watchdog 主线程 5 秒卡死注入入口;必须看到 watchdog 私有管道重锁请求回报且 Guardian 恢复前已锁定才能通过。++- 2026-10-05:多次人工 rehearsal 观测到真实系统锁屏并由用户正常解锁;其中一次同进程后台 AX 调用触发 MainActor 断言退出,已改为 MainActor AXPress 并通过独立自检。controller 异常路径先保留 watchdog / 请求确认重锁,再清理测试进程组。其他短暂遮罩测试有 mouseMoved 接管事件,不能直接归因于真实鼠标移动或宣称持续遮蔽通过。+- 2026-10-05:按用户要求拆出不锁屏、不执行动作的独立 preview,复用相同遮罩实现,增加倒计时、单调时间、每秒 coverage / 输入类型汇总。两块显示器持续约 15 秒软件覆盖检查通过,无输入事件;用户确认两块物理屏幕完整遮住、倒计时正常、结束恢复桌面。此结果仅覆盖遮罩预览,不证明锁屏解锁或动作闭环。修改后完整 Swift 206 项、1 项跳过、0 失败。+- 2026-10-05:用户保持输入静止后的受控动作 rehearsal 日志通过:同进程 AXPress counter 0→1,SCK 捕获被遮挡窗口预期蓝色内容并验证动作前后图像不同;guardian / watchdog 心跳持续健康,约 15 秒 leaseExpired 后观测同会话锁定再释放遮罩。用户确认两块物理屏幕始终遮蔽、未露出桌面或 fixture、手动解锁正常。没有执行自动解锁。新增 4 项离线 controller 回归验证异常 / 超时恢复顺序、preview 不请求锁屏与锁定会话不启动。++- 2026-10-05:创建隔离 worktree,基于本地 awesome-extension 已提交状态;未复制另一个会话的未提交代码。+- 2026-10-05:用户已在应用关闭 Codex Locked Use;只读检查证实其 bundle 和 screensaver remote rule 已清理,screensaver 保留 use-login-window-ui。+- 2026-10-05:20 项保护策略测试、完整 Swift 188 项测试(1 项 gated live test 跳过)、Node 21 项测试和 fixture / cursor smoke 通过。系统 Node 动态库损坏,Node 测试使用应用提供的 bundled runtime,不修改系统安装。+- 2026-10-05:插件离线 ABI probe 通过。新增只注册独立 deny-only right 的可审阅管理员实验脚本;终端 sudo -n 显示需要密码,尚未执行系统安装或真实解锁。+- 2026-10-05:macOS 26.5.1 的 CGSession dictionary 不提供 console-set key,改用公开 SessionGetInfo 的 audit-session identity,并校验当前 on-console、login-done 与 UID;新增缺字段和 session mismatch 回归。+- 2026-10-05:补充取消 / 排空 barrier。原锁屏仍可见不能提前解除遮蔽;Broker 确认许可撤销、解锁与动作排空后,再确认锁定。+- 2026-10-05:通过 macOS 管理员授权窗口安装独立签名 probe,修正 codesign inline requirement 必须使用 `=` 前缀的校验格式。4 次 AuthorizationCopyRights 返回预期 denied;SecurityAgentHelper 的固定日志确认实际机制调用。首次出现 Library Validation 错误后同一 helper 仍执行机制,记录这一行为,不将单条加载错误或 denied 返回当作唯一判据。+- 2026-10-05:实验完成后卸载独立 right、原 bundle 和自身 staged 副本;核对 screensaver right 与实验前一致。真实解锁 / Keychain 与生产 Broker / guardian 仍未完成。+- 2026-10-05:用户要求继续完成并同意配合锁屏测试。新增独立 Guardian 与独立 child watchdog;只在显式 rehearsal 中拦截输入和请求重锁,不解锁、不改系统认证规则。实际 desktop / Secure Input / 显示器覆盖仍待物理观察。测试 controller 可从工具侧结束自身进程组恢复操作,该恢复只用于开发,不能视为生产遮蔽保证。+- 2026-10-05:待用户确认首次 15 秒测试时间;测试同时验证遮挡的专用窗口经 AX 改变并经 SCK 捕获,重锁后只读检查 loginwindow 结构。真实 unlock trigger 不能根据猜测的 AX 控件或授权返回值实现。+- 2026-10-05:完整 Swift 206 项(1 项 gated live test 跳过)、fixture / cursor smoke 通过。签名 Guardian 的内核身份、批准角色、错误 signer / role 及 debug-injectable 副本拒绝均验证;批准文件拒绝 extended ACL 写授权。没有触发真实锁屏;生产 Broker IPC、客户端登记与实际 unlock backend 仍待完成。++- 2026-10-05:新增有界 framing / 绝对 RPC 超时、动态 audit token 与签名重校验的 Broker 服务和 remote 插件;授权放行与实际 GUI 可用状态分离,取消后等待解锁事务和动作排空才释放。Guardian 增加锁屏 AXConfirm 与只观察活动的 IOHID 输入保护;Secure Input 下的硬件事件交付仍需实机确认。完整 Swift 222 项、1 项跳过、0 失败;签名插件 ABI 拒绝 / 重复 / 取消回归通过。未安装生产服务、未更改 screensaver right。++- 2026-10-05:补齐固定已安装位置的签名 native Installer、原客户端 socket 的 SCM_RIGHTS 内核验证、连接级动作 / 排空、JS reset / timeout / EOF 终止旧 native epoch;新增 root boot-bound crash journal、严格旧 peer 重连及主 / watchdog 保护释放 ACK。Broker 策略被更改后撤销新许可但保留恢复通道。+- 2026-10-05:独立 watchdog 增加备用遮罩、tap 和硬件活动观察;准备阶段必须收到 child 的独立健康回报。新增固定真实 GUI / 自有 Keychain 验证、root 验证记录及管理员认证的 promotion 入口。缺少匹配 OCU 的 provisioning profile,Data Protection Keychain 尚未测试;构建已支持受限自有 group。+- 2026-10-05:Swift 234 项、1 项跳过、0 失败,Node 24 项通过,fixture / cursor smoke 和签名 remote ABI 通过。未锁屏的 legacy Keychain 自有项目 prepare / read / cleanup 通过;真实 native AX / SCK preflight 因新隔离 app 权限缺失被拒绝,不能报告通过。发现并修复懒初始化启动时间导致复用旧 agent 的问题,构建增加唯一标识。已打开权限引导,等待用户配合;尚未安装自动解锁 profile。++- 用户完成隔离 app 授权并重启验证实例后,固定独立 native fixture 的真实 AXPress、计数器变化、前后 SCK 图像变化及 legacy 自有测试项通过;没有执行锁屏或自动解锁,测试项已清理。++- 首次系统验证 profile 安装与安全卸载成功,screensaver 的原 fallback 保留并恢复。发现管理员 staging 的 umask 077 使系统 namespace 不可供用户遍历,已修正为明确的系统目录权限;锁屏测试在启动前退出,没有尝试解锁。恢复 / 验证记录改为从创建起 0600、清除继承 ACL、原子替换和 fsync,不先公开再 chmod;增加继承读取 ACL 和不可信目录回归。修正版已完成管理员认证和重新安装。++- 修正版系统目录可遍历、客户端批准及认证策略完整性诊断通过。第一次真实锁屏事务在 preparing 阶段因独立 watchdog 未完成健康注册中止,未发出解锁许可;用户正常解锁。补充 watchdog 停止原因及 Broker 注册诊断。会话门单测以受控 validator 隔离系统安装状态;完整 Swift 236 项、1 项跳过、0 失败。++- 真实锁屏复测定位独立 watchdog 的 `shieldNotInWindowServer`,Broker 注册本身成功;未放行解锁。主 / 备用遮罩增加公开 AppKit `canBecomeVisibleWithoutLogin`;主遮罩锁屏覆盖检查通过,备用进程补齐 `finishLaunching` 与首帧 RunLoop 绘制后待实测。++- watchdog 首帧健康检查新增独立、不锁屏的 surface self-test。实测缩放后的窗口矩形与完整显示器不同;禁用 NSWindow 出现动画后自检通过。全屏窗口禁用 AppKit frame constraint,并增加真实矩形诊断。控制器支持观察正常手动解锁替代 stdin 确认,遵循用户固定解锁节奏;不以等待时间当作解锁证据。++- 双保护真实锁屏准备检查已通过,Broker 进入 authorizing;解锁触发未找到可提交 AX secure field,实际会话保持锁定,保护正常收束。加入有界 AX publication 等待与仅结构的诊断,尚未证明自动解锁。++- 后续固定 Return 提交实验没有证明自动解锁,Broker RPC 超时后未收到 agent 排空 ACK,导致双保护反复请求锁定并阻碍用户登录数分钟。已停止真实锁屏实验、卸载组件并恢复原认证规则。新增停止重复锁屏、独立 agent 准备 / 清理 deadline 与排空日志;先验证无锁屏故障链路和恢复时延,再恢复实机测试。准备期限 8 秒、停止期限 5 秒只约束 agent 退出,不代表全系统恢复期限已经验证。++- 参考用户提供的锁屏方案后,移除主动账户选择、AXConfirm 与固定 Return,改为双保护准备后的单次公开显示器唤醒,随后等待系统认证与实际解锁证据。新增独立 display-sleep assertion;不把唤醒等同于授权成功。资料中的返回码、Keychain 保证、AX 树绝对断言和提前撤罩顺序不能直接采用。+- 将 AuthorizationRightGet 移出 Broker 协调队列;签发 / 消费只接受有界新鲜策略观察,超时拒绝新许可而保留清理通信。新增只限验证 profile 的 recovery-only 事务,准备双保护后在签发任何许可前主动停止并检查双方释放 ACK;下一步先实测此链路,再验证自动解锁。++- 第一轮恢复专项约 3.1 秒清理,两个保护进程均退出,随后观测正常手动解锁;但备用进程注册前准备计时已到期,不算完整双保护通过。修正准备期与运行期心跳计时边界;准备总期限仍为 8 秒,Guardian 等待独立子进程就绪最多 3.5 秒。新增 root recoveryProbePrepared 证据和启动失败不能假报成功的回归。++- 修正版 recovery-only 实机通过:备用进程完成 root 注册,主保护报告 shieldReady,Root 记录双方就绪后主动停止;约 2.0 秒收到动作排空、实际锁定与双保护释放证据。检查保护进程已退出,并观测用户正常手动解锁。没有签发任何解锁许可,未执行 GUI / Keychain 动作;下一轮仅测单次唤醒和立即重锁。++- 2026-10-05:按更新参考实现 identifier-only、有界固定 AXValue 可写性探测;不读密码、不发送认证动作。新增取消 / 在途写入排空回归;完整 Swift 249 项,跳过 1 项,0 失败。快速控制器在真实 GUI 验证后立即重锁、等待双方释放,并保存不含原始日志 / 字段 / 图像的私有诊断时间线。自动解锁与完整生产验证仍待实测,尚未合并。++- 2026-10-05:首轮快速真实流程找到 14 节点、唯一 FocusedUser,但预查询不可写而未执行固定值探测,未触发机制 / 自动解锁;失败后进入 awaitingManualUnlock、双方保护退出。移除将可写性预查询作为写入前置条件的差异,保持其仅作诊断;实际写入仍仅限固定 AXValue、取消与同会话检查。++- 2026-10-05:第二轮固定 AXValue 实际写入返回成功,但未触发认证机制 / 自动解锁;约 6.6 秒保护事务失败结束,控制器确认双保护释放。正常手动登录中的 Broker 校验出现 -67061;另一个不锁屏、无租约的 remote-only 探测中全部签名校验成功,Broker 正确拒绝无许可 claim。暂不能归因于签名材料本身,需继续核对认证宿主环境与认证发起时序。新增独立不锁屏诊断入口,Python 报告过滤 4 项通过。尚未完成 / 合并。++- 2026-10-05:核对两级认证规则、4-byte length + JSON 协议与显式 SetResult;独立 remote 分支在真实 SecurityAgent 已可达。新增 macOS 14.4+ public SecTask / ProcessCodeRequirement 验证,签名类别 + 固定 ID / Team + 动态有效 / runtime / LV + 注入 entitlement 检查,不做 identifier-only 放宽。独立签名合法 / 错误 ID / ad hoc / get-task-allow 正反检查与原 ABI 通过;Python 白名单报告 6 项通过。+- 2026-10-05:实机裁决链第一次通过:同 audit session claim 成功、consume 返回 authorized、SetResult(Allow) 返回成功;约 1 秒后因遮罩尺寸缩为 90% 而 guardLost,中止重锁并确认双保护退出。正常手动解锁与自有 Keychain 清理通过。仍不能记作完整 GUI 闭环通过;遮罩改为 nonactivating NSPanel,等待切换复测。++- 2026-10-05:nonactivating NSPanel + 主屏蔽层级 +1 的不锁屏 surface 自检通过;完整 Swift 249 项、1 跳过、0 失败。下一轮真实切换仍待系统管理员完成旧验证版卸载认证后安装新版,不将尺寸自检记为解锁切换覆盖证明。++- 待查:独立诊断中的合成 PID-version 实验发生进程退出未完成,已撤销该注入用例;生产前仍必须覆盖真实 Broker 死亡 / socket token 过期时 verifier 和认证宿主的有界恢复。合法 / 错误身份 / ad hoc / debug 的实际签名测试通过。++- 2026-10-05:新版 NSPanel 的真实快速闭环复测未自动解锁。双保护准备成功;单次显示器唤醒与固定 AXValue 写入成功,但整个 5 秒 authorizing 窗口没有机制调用,随后 unlockTimeout。锁定观测后约 7.1 秒确认双方释放。正常手动登录时机制调用、现代签名验证成功,过期 claim 被拒绝,原系统 fallback 成功;自有 legacy 测试项验证与清理通过。这轮没有进入 active / native AX-SCK,不能证明 NSPanel 在自动解锁切换时的覆盖修复。下一步定位系统认证事务启动时机差异,不能靠延长许可或重复锁屏宣称修复;生产仍关闭,尚未合并。++- 2026-10-05:复核新认证时序资料与本机 Guardian build 1001365,发现参考路径实际写空字符串、AXValue 是属性名,并调用 SynthesizedEvent.click / send;未确认 Return 或真实认证效果,未照搬到日常账户。历史 SetResult(Allow) 不排除人工认证重叠,不能算自动唤醒成功。新增锁屏前只读实时白名单采集、schema 2 许可 / 手动恢复分窗和不锁屏被动入口,缺失日志不证明缺失事务。遮罩使用 Quartz 全局坐标完整包含,仍拒绝任何未覆盖边缘和 90% 缩小。Swift 251 项(1 跳过、0 失败)、Python 报告 10 项 / rehearsal 5 项、签名组件 / ABI / 内核签名正反例、不锁屏 surface 自检通过;被动采集完成。本轮没有安装 / 真实解锁;新认证路径的 Keychain 可用状态尚待验证(后续复核纠正了重设归因)。生产关闭,未合并。++- 2026-10-05:用户要求按官方 API 复核 Keychain 风险。纠正此前错误归因:上游 #40226 是插件介入后的会话级访问失败,明确排除文件损坏并称重启恢复,没有空输入或重设证据。SetResult 只定义授权结果;Apple 公开 Security 源码区分登录处理与显式重设,不能当作当前 loginwindow 完整调用链。同步修正文档,将隔离环境明确为开发建议而非 API 要求;本轮无代码或系统认证变更。++- 2026-10-05:用户批准当前账户短测试,重新打包 / 管理员安装后运行 wake-only 基线,未加入空输入 / 点击 / Return,不创建 Keychain 测试项、不执行 GUI 动作。双保护成功准备;5 秒 authorizing 窗口内未观察到 screensaver right 求值或机制调用,AX 扫描只有根节点且不完整,未写固定值;unlockTimeout 后锁屏观测至双方释放约 7.9 秒。后续 Touch ID 人工登录出现 right 求值、签名验证通过、过期 claim 拒绝 / SetResult(Deny) 成功、原系统 right 成功。约 27 秒确认会话正常解锁;并无自动解锁成功证据。测试后成功卸载 / 恢复原策略,保护和 Broker 退出。采集过程中实时 / 历史日志重复阶段,修复 authorizing 重复开窗并新增回归;Python 报告 11 项、rehearsal 5 项通过。后续仍需定位 AX 发布时序并验证真正的认证入口,生产关闭,未合并。++- 2026-10-06:用户要求在当前账户持续实测迭代,不再重复未修改基线。验证入口改为 3 秒内重试完整 AXIdentifier 扫描,找到唯一候选后写空字符串,再尝试一次 FocusedUser AXPress;保留签名、同会话、取消 / 在途排空和 5 秒许可,不读取字段、不发送 Return。首轮在 preparing 因 physicalInput 收束,锁定观测后约 1.6 秒确认双保护释放;认证动作尚未执行,正常手动解锁通过。复测 readiness 在锁屏前因 Broker RPC 超时拒绝,未再次锁屏。补充原客户端死亡 / socket EOF 检查,先拒绝失效 SCM_RIGHTS 连接再签名重验;原因尚待重装实测确认。签名组件 / app 构建与 ABI / 内核身份正反例通过,Swift 251 项(1 跳过、0 失败)、Python 报告 11 项通过。正在等待系统管理员卸载认证;不得将本轮计为自动解锁或新认证入口验证成功。++- 2026-10-06:重装后实测完整 AX 树 14 节点、唯一 FocusedUser,空字符串写入成功;AXPress 返回 actionUnsupported(-25206),5 秒许可窗没有认证求值 / 插件调用,双方保护释放和正常手动解锁通过。恢复后的 readiness 仍超时,原客户端断开检查没有证明已解决该问题。下一版实测 public CGEvent 目标进程点击已发送,但仍未观察到认证;未将 queued 当作投递成功或自动解锁。继续加入一次目标进程 Return(不含密码)及 Broker observer 各阶段固定日志,待验证。组件 / app 签名构建及 ABI / 内核身份正反例通过,Python 报告 12 项通过。生产保持关闭,尚未合并。++- 2026-10-06:保护待命与许可签发分离:首次已认证插件 claim 才签发,许可 deadline 不超过原 8 秒启动上限。原等待版本实测没有机制,agent 的同刻 8 秒退出造成报告失败;修正为 8 秒启动 + 2 秒 RPC 排空余量,控制器容忍已退出 stdin 的 BrokenPipeError。Swift 253 项(1 跳过、0 失败),Python 报告 13 / controller 1 / rehearsal 5 项通过,签名组件 / ABI / 内核身份正反例与 app 构建通过。+- 短实测确认失败结果约启动 8.1 秒返回,约 0.3 秒后双保护退出 ACK,正常手动解锁和报告保存通过;没有机制 / 许可 / 自动解锁。一次 annotated-stage 点击因同 PID 几何包含目标不唯一而未发出,改为先匹配 AXWindow 完整几何再确定唯一 CGWindow,拒绝模糊目标。原 postToPid 点击 / Return 实验无认证证据,已撤回。参考 build 动态 CGEventAPI.post 路径支持会话级点击,不能再用零导入证明纯观察;实际认证效果仍未证明。生产关闭,未合并。++- 2026-10-06 后续:AXWindow 完整几何匹配后唯一目标和 annotated-stage queued 已实测,仍无机制;NSEvent.windowNumber 版本也未自动解锁,并出现一次 native RPC 超时,独立只读检查确认会话已解锁、保护已退出,但未取得该轮退出 ACK,不能算恢复验证通过。补齐 timer phase 与慢签名检查日志。+- 新增会话入口的一次性点击能力:独立随机标记经继承管道共享,双过滤器验证 Guardian 来源、有序同窗口 / 坐标点击、5 秒能力 / 250ms 配对;硬件接管与停止撤销,不使用 PID-only 豁免,标记不落日志。离线 Swift 257 项(1 跳过、0 失败)、报告 14 项、controller 1 项 / rehearsal 5 项通过,签名 / ABI / 内核身份正反例通过。第一轮点击被 watchdog 拒绝,约启动 2 秒收束并确认双保护退出 / 手动解锁,未证明跨过滤器投递;补充固定拒绝枚举并为 NSEvent 的 CGEvent 显式指定私有 source,待复测。生产关闭,未合并。++- 事件 source 复测仍由 watchdog 在 flags 检查处拒绝,未观察到一次放行。双保护退出 ACK 与正常手动解锁通过。将过严的所有 flags 为零检查收敛到四个会改变左键语义的键盘修饰键,保留能力 / 来源 / 几何 / 顺序 / 时限,并只记录整数 flags 与固定拒绝枚举,待投递复测。++- 2026-10-06:会话点击经过双过滤器放行已实测(down/up 均有 main / watchdog 记录),flags=0x20000000,四个点击修饰键为零;仍未见机制,约 8.6 秒后双保护退出 ACK / 正常手动解锁通过。参考进一步静态复核定位 CGEventSetWindowLocation 与 mouse subtype=3;本项目补齐编码,并在原 3 秒唤醒预算内有界重新扫描点击后出现的密码字段,不二次点击。+- 结合用户的待命建议,显式验证 profile 改为 20 秒总等待,双保护准备仍限于 8 秒;插件首次 claim 才签发最多 5 秒许可,截止裁剪到本轮起始 deadline。Root 的绝对 uptime 截止经 IPC 与继承管道传给 agent 和双遮罩,统一倒计时,agent 只增加既有 2 秒 RPC 排空余量。默认 profile 不变。新增晚到 claim、20 秒过期不可重启、待命时本地输入撤销回归;Swift 260 项(1 跳过、0 失败)、报告 14 / controller 1 项通过,签名组件 / ABI / 内核身份正反例与 app 构建通过。系统安装等待管理员认证;新的 20 秒 / 编码路径尚未实测,生产关闭,未合并。++- 2026-10-06:20 秒窗口 / 私有窗口坐标编码实测:双过滤器放行 down/up,点击约 200ms 后重新扫描出现唯一 UserPasswordTextField,可写且空写成功;启动约 20 秒后 unlockTimeout,未观察到机制 / 许可。双方释放 ACK 约失败后 0.15 秒,随后 Touch ID 手动解锁触发真正的 right 求值与 remote 机制;此时 Broker 已 awaitingManualUnlock 并正确拒绝,不算自动解锁。修复测试控制器复用旧常驻 agent 的问题,每轮采用新独立 namespace。当前瓶颈是可交互密码 UI 到授权链之间,非 5 秒许可提前过期或 guardLost。+- 下一验证版仅管理员验证 profile 在唯一真实密码字段支持 AXConfirm 且空写成功时尝试一次确认;Root hello 显式传递开关,默认与旧协议关闭,未知动作不盲试,不合成全局 Return。新增固定布尔 / OSStatus 日志;同时修复报告 PATTERNS 重复 Watchdog 键覆盖导致部分退出原因丢失。待签名构建与实际测试,不作为成功证据。++- 确认实验离线验证:原完整 Swift 260 项(1 跳过、0 失败)通过;新增验证 profile / Guardian 身份 / 旧协议开关回归后 coordinator 10 项通过。报告 15 项与控制器 1 项通过,签名组件、插件 ABI、内核身份正反例和 app 构建通过。旧系统验证版已卸载并恢复原规则,新版正在安装;实际 AXConfirm 结果仍待验证。++- 确认实验实测:点击后约 200ms 唯一真实密码框出现;空写成功,字段明确支持 AXConfirm,单次 AXConfirm 返回 success。仍等满原 20 秒截止,没有观察到 right 求值 / 机制 / 许可;失败后约 0.17 秒确认双保护释放,随后用户 Touch ID 解锁才出现 right 求值与 remote 机制。Root 此时正确拒绝过期 claim,普通解锁成功。不可把本轮算作自动解锁;后续关键未知是无用户凭据条件下 loginwindow 如何进入 screensaver right 求值,不再仅延长等待或重复等价 UI 动作。只读检查参考 InstallerTool / service 未找到 screenUnlockMode 字符串(不证明完整实现不存在间接路径),本机该偏好未设置。实验结束已卸载并恢复原认证策略;生产关闭、尚未合并。++- HID 单变量实验:用户授权尝试仅将受控 down/up 投递从 session 改到 HID;复用已认证 Root 的验证 profile 开关,生产 / 旧协议保持 session。事件字段、双会话过滤的一次性能力、硬件活动接管、空写 + 单次支持确认、20 秒截止不变。新增固定 clickTap 枚举日志;此改动不保证被系统视作真实硬件或启动认证,待实测。++- HID 实测已完成:明确 clickTap=hid,双 session 过滤器放行同一对 down/up;点击后先短暂 AX 发布不完整,再出现唯一真实密码框,空写成功且声明支持 AXConfirm,但单次确认返回 cannotComplete (-25204)。20 秒截止内无观察到的 right 求值 / 机制 / 许可 / 自动解锁;失败后约 0.22 秒收到双保护释放 ACK,用户随后正常手动解锁才触发 remote 机制。不能宣布 HID 活动假设成立,或仅凭此轮失败排除所有 HID 路径。完整 Swift 261 项(1 跳过、0 失败)、报告 15 项通过;签名 / ABI / 内核身份正反例和 app 构建通过。未合并,生产关闭。++- 本轮 HID 实验卸载完成,只读复核 screensaver 原认证规则已恢复。++- 确认超时修正:扫描给候选 AX 对象设置的 50ms 消息超时会被后续 action 沿用。Apple AXUIElementPerformAction 文档明确 cannotComplete 可能源自超时 / 模态处理,但不能仅据错误码确认因果或动作未执行。session 轮先前已执行同一确认并返回成功,不是 HID 轮首次加入。验证版为单次确认独立设置最多 2 秒、裁剪到原 3 秒 UI 请求截止的超时,结束恢复扫描超时;记录配置结果、实际调用开始、调用耗时与结果。不自动重试,避免无法确认是否执行时重复提交。Root 总 20 秒截止、取消 / 排空与双保护不变。待实测比较。++- 超时分离首次实测:2 秒动作超时配置成功,AXConfirm 实际 37ms 返回 success;之后仍未观察到 right 求值 / 机制 / 许可。因此不能确认上一轮 -25204 唯一源自 50ms,也不能以确认返回成功推出认证已提交。本轮总起始约 18.9 秒出现 guardLost,主 Guardian 私有状态持续报告遮罩 / tap / watchdog 健康,收到 root stopRequested 后退出;失败后约 0.25 秒确认双保护释放、正常手动解锁。新增 Broker 两类报告 age / watchdogProtected 固定诊断,进一步区分 IPC 陈旧与真实遮罩不健康;新增只读按钮 enabled 计数与密码框焦点布尔,明确没有收集标题、标识字符串或值。修正等待期间每秒常规 300 秒 active 标签覆盖 20 秒启动倒计时的问题,只有观察到解锁后显示 active 标签。确认只有一次,无模糊结果重试。系统验证版已卸载并恢复原规则,下一诊断版待复测。++- 第二轮 2 秒确认实测:真实密码框 focused=true,扫描按钮 enabled=2 / disabled=0 / unknown=0;AXConfirm 34ms 返回 success,无观察到的认证求值 / 许可。约启动 14 秒 guardLost 的 Broker 固定证据显示 guardian report age≈1570ms / watchdog report age≈1577ms,watchdogProtected=true;本地 Guardian 仍持续健康。不能将本轮归因为动作超时或 UI 未聚焦,Root 失联新鲜度仍待定位。双保护释放与正常手动解锁完成,卸载恢复原认证规则。按用户新要求,暂停受保护复测,下一步独立无遮罩 / 无 watchdog 解锁诊断;不得假造生产 guardsReady、不得执行 GUI 应用动作或签发生产验证记录。++## 无遮罩解锁诊断(仅管理员验证 profile)++用户明确要求拆开解锁与保护问题后,新增独立 `LockedUseUnshieldedDiagnostic`,不复用生产 guardsReady 或 GUI action 状态机。Root 只接受管理员验证 profile 下、已批准签名 UI 探针的原锁定 UID / audit session;诊断总期限 20 秒,插件首次同会话 claim 才签发最多 5 秒且裁剪到原截止的一次性许可。无守护健康 / 心跳条件,也不伪造覆盖证据。断开、认证策略失效、期限到达或许可过期撤销后不能恢复。所有应用 action、生产验证 / promotion 与正常租约入口在诊断活跃时拒绝;重启不恢复任何诊断许可。++签名工具的独立 `--unshielded-unlock-diagnostic --confirm-visible-desktop-test` 入口复用 `LockScreenInteractor`,没有构造 DisplayGuardian、遮罩、输入 tap、硬件 monitor 或 child watchdog。因此桌面若被解锁会实际可见,不能视为生产 Locked Use。它只观察原会话解锁并立即请求 / 确认重锁,最后向 Root 结束诊断;结果与私有报告始终 productionEvidenceEligible=false,不访问应用窗口 / ScreenCaptureKit / Keychain。外部控制器入口为:++```sh+python3 scripts/run-locked-use-unshielded-diagnostic.py --confirm-visible-desktop-test+```++该入口针对人为配合的单次故障定位,没有完整保护路径的进程崩溃与遮蔽保证。实现回归覆盖生产 profile 拒绝、原 session / role 绑定、跨 audit session / 重复 claim / 许可重放、晚到许可裁剪、5 秒过期 / 20 秒过期 / 取消不可重启、非原会话结束与 GUI / 生产验证拒绝。当前 Swift 266 项(1 跳过、0 失败)通过,真实诊断待安装运行。+++### 无遮罩实测归因与报告修正++首轮诊断观察到原会话解锁、插件消费许可和重锁,但系统时间线先出现 Touch ID match,约 0.67 秒后才出现 remote mechanism。因此它证明手动认证与待命许可重叠时插件链可完成,不能证明自动解锁;测试后的再次解锁也由用户完成。++修正控制器将原生 stdout 缓冲到进程退出才记录的时间偏差:改为有界逐行读取,以原生 uptime 对齐本轮时间线;修正 trace 清理调用为 finish,确保保存报告。报告增加 authorizing 窗口内 Touch ID 介入标记,拒绝将这类结果当作自动解锁证据;没有该标记也不自动认定为成功。新增 3 项归因回归测试,覆盖窗内 / 窗外 Touch ID 与单独 evaluatePolicy 不能证明人工操作。++第二轮明确不操作鼠标、密码或 Touch ID,无遮罩、无输入过滤、无 watchdog 等满原 20 秒:唯一真实密码框已聚焦,空写成功,单次 AXConfirm 88ms 返回 success,但未观察到认证 right 求值、mechanism、许可消费或原会话解锁。结束后确认原会话锁定、Root 返回 idle。这说明撤掉保护逻辑本身没有解决认证入口;AXConfirm success 不能替代实际解锁证据。生产保持关闭,尚未合并。+++### Return 单变量诊断(待实测)++用户提供成功时间线中 secure textfield Return → loginPressed → authBegan → authCopyRights → 插件的链路,作为新的待验证假设。Apple 文档仍将 AXConfirm 定义为模拟 Return,不能据该样本断言所有实现中它只聚焦或按钮永远不能提交;当前系统上的 AXConfirm 实测未产生同样授权链。++仅独立无遮罩诊断改为固定 keyCode 36 的单对 HID down/up,替代 AXConfirm,未加入保护路径。要求同一原锁定会话、完整扫描唯一密码框、空写成功且可写 / focused、Apple loginwindow 签名有效、无 Shift / Control / Option / Command,签名检查后再校验焦点与会话 / 请求截止。私有事件源,无修饰键、重复或文字载荷,派发按下后立即释放,即使期间取消也释放;不重试。Root 20 秒诊断窗口及首次 claim 才发一次性许可不变,观察实际解锁后立即重锁。受保护输入过滤器没有键盘许可,不能直接推广该实验。++新增固定枚举日志 secureReturnObserved / localAuthenticationBegan / loginwindowRightsRequested 与 Return dispatch / queued 标记,不保存 surrounding 账户 / 认证上下文。Swift 编译通过,报告回归 17 项、诊断归因 3 项通过。Developer ID 签名两次返回 errSecInternalComponent,新制品未部署 / 未实测;等待用户恢复系统构建签名私钥访问。旧已签名 components 未替换,生产关闭,尚未合并。+++- 签名阻塞追踪:Return 代码已提交 b444978,旧 components 保持原已签名版本。重试默认身份、显式 login 钥匙串与无 timestamp 均失败;只读默认钥匙串状态 flags=7,不能归因为普通锁定。securityd 固定错误码含 errSecAuthFailed / CSSMERR_CSP_OPERATION_AUTH_DENIED;不能据此确定凭据损坏。没有修改私钥 ACL、信任设置、钥匙串文件或生产签名策略,也未发送 Return / 启动锁屏。GUI Terminal 重试被 Computer Use 工具安全限制拒绝,准备私有本机构建签名脚本供用户在 GUI 终端完成;随后再运行真实测试。+++### 签名与已安装机制回溯++主 checkout 仅只读核对:Dev App 严格 deep 校验通过、Hardened Runtime、既有签名时间为本地 12:19;不是新的签名成功证据。worktree 最后成功组件签名约 12:42,新 Guardian 首次观察到签名失败约 16:55,中间没有连续签名探测,不能断言故障发生于某一次解锁。隔离 /usr/bin/true 副本(未执行)同一 Developer ID 签名也失败,最新重试仍失败,因此不局限于 Guardian 构建内容或一次偶发错误。++当前 system.login.screensaver OR 首分支和 remote evaluate-mechanisms 仍指向 OCU;安装插件 strict 签名有效、SHA256 与本 worktree 制品一致,安装 Broker 二进制与本地制品一致且运行,未观察到当前被替换。历史 authd 日志本地 15:18 调用了 OCU mechanism,15:30 / 15:31 则调用 CodexComputerUseAuthorizationPlugin;15:31 后 loginwindow SecKeychainLogin 返回 -25293。这证明历史机制确有差异,不证明当前仍被顶掉,也不能仅据日志确定何人或何时改过 policy。钥匙串状态 flags=7 与签名认证失败并存,未更改权限、信任、搜索链或钥匙串数据。需分开验证图形会话认证状态与签名环境,禁止把空值认证导致的普通 keychain login 失败直接判为钥匙串损坏。+++### 密码解锁恢复签名与 Return 首轮通过++用户用账户密码正常解锁后,同一 Developer ID 签名命令立即通过严格校验,未修改证书、私钥 ACL、信任、钥匙串搜索链或数据。这支持先前签名认证拒绝与会话认证状态有关,但仍不能将变化唯一归因到 OCU / Codex 某个插件。签名通过的新 UI 探针替换本地 components,未替换系统安装插件。++首次新探针诊断在 beginUnshieldedDiagnostic 被 Root 拒绝、未发 Return。只读回溯证实本地 15:30:12 installationPolicyInvalidated;Broker 对认证策略变化永久关闭该 service epoch 的 accepting,恢复相同规则不能自动重新授权。校验当前规则、安装插件 / Broker 与本地制品一致、无活跃保护后,经 macOS 管理员认证仅 kickstart 验证 Broker,未改规则或削弱策略失效时的关闭行为。++随后无遮罩复测出现完整自动链:FocusedUser 空写 → 单次 HID 点击 → 唯一密码框空写、focused=true → Return 单对派发 → loginPressed / authBegan / loginwindow rights request → OCU mechanism claim / 一次性 permit consume / SetResult allowed → 原会话实际 unlocked → 立即请求且确认 locked → Root idle。原生诊断起始约 8.358s,观察解锁约 9.692s,结束 / 重锁确认约 10.137s(相对控制器开始,含 5 秒初始提示)。报告内无 Touch ID match;未访问应用 GUI、SCK 或 Keychain。不能视为完整生产验收,报告仍 productionEvidenceEligible=false,自动归因没有因缺失 Touch ID 就签发证书。用户现场观察仍待补充。++下一步是为受保护主 / watchdog 过滤器增加严格的一次性 Return 能力,保留硬件接管 / 重锁、原会话及焦点校验,再验证遮罩期间应用操作和故障恢复。本轮 Return 尚未启用到受保护路径;生产关闭,未合并 awesome-extension。+++### 受保护 Return 接入(待真实完整复测)++用户确认无遮罩通过后要求提交并恢复 Guardian。此前实现与证据已分别提交 b444978 / 48d918f。新增 LockedUseReturnAllowance,通过 Guardian → watchdog 私有继承管道传递独立随机 returnTag,只在 Root 管理员 validation profile 下创建,不与鼠标 clickTag 混用。两套 session tap 分别验证同一原锁定 UID / audit session、Guardian 来源 PID、能力 tag、有效目标 PID、固定 keyCode 36、无重复 / 修饰键、5 秒总有效期和 250ms 匹配 down/up;重放、错序、取消和真实硬件接管均不能重开。watchdog / 主 Guardian 停止会撤销两类输入能力。++LockScreenInteractor 在完整扫描唯一密码框、空写成功、可写且焦点确认、Apple loginwindow 签名 / 会话再次检查后才提交 Return;受保护事件写入来源 / 目标和独立 tag。没有通用键盘放行、没有 PID-only 绕过。无 Return 能力的旧 bootstrap 不获得键盘权限。生产 profile 暂不启用。新增 6 项策略回归覆盖两独立 gate、nonce / 来源错误、其他按键 / 修饰 / repeat、跨会话 / 过期、顺序 / 目标 / 间隔 / 重放、取消与旧 bootstrap。Swift 272 项(1 跳过、0 失败)、Python 报告 17 项与归因 3 项通过;签名组件、ABI、内核身份检查与 Dev app 构建通过。真实受保护完整链待安装复测,未合并。+++### 受保护首轮:Return / 插件通过,遮罩过渡失败++新验证版安装和普通已解锁真实 AX / SCK preflight 通过。完整 fast / legacy-only 轮两套过滤器均放行鼠标 down/up,Return 派发后 OCU 插件 claim / consume / SetResult 成功。还未确认 active GUI 就遇 watchdog shieldBoundsMismatch:实际 Quartz bounds 在系统解锁动画缩至 2404×1352 且偏移 78,44,未覆盖原 2560×1440。watchdog 正确请求 guardLost 重锁;约 9.594 秒(含 5 秒提示)Root 确认双保护释放,没有循环遮罩。不得把此轮算完整成功,也没有观察到 returnAdmitted 日志,Secure Input 时事件是否经过 session tap 仍须谨慎描述。++修正使用居中 1.5× 实际不透明窗口,使系统 zoom 缩放后仍覆盖屏幕;不是放宽 coverage 判定。保留对 WindowServer 实际 bounds 完整包含 CGDisplayBounds、alpha=1、owner / layer / active topology 的严格要求。新增负坐标 / 不同比例缩放下 overscan 实际覆盖测试及不足覆盖拒绝,Swift 273 项(1 跳过、0 失败)通过。仅更新经 Developer ID 签名的 staged Guardian,保持 root 所有与普通用户不可写,Broker / auth rules 不变,待复测。++用户提供 Native Fixture “not open anymore” 提示。控制器在失败恢复后会关闭 RPC 并终止固定测试 fixture,当前没有发现其相关新 crash report,无法仅凭截图判定为崩溃;Finder 最新状态未见该弹窗。将其作为测试窗口生命周期诊断,未改私钥或认证策略。+++### 受保护完整流程首次通过(overscan 修正版)++更新 staged Guardian 后,同一 fast / legacy-only 真实测试通过:约 11.532s 派发单对 Return,11.534s loginwindow 观察 secure Return,11.539s authBegan,12.555s 首次 claim 签发许可,12.560s consume,12.561s SetResult allowed,12.564s 系统报告解锁,12.815s Root 在双保护健康下进入 active。固定签名 Native Fixture 在 13.421s 捕获 counter=0,14.198s AX 操作验证 counter 增加且 SCK 图像改变;14.560s 确认重锁,14.825s 确认双保护释放。用户随后正常手动解锁,30.859s 自有隔离 legacy Keychain 项验证 / 清理通过。报告无 failureType,没有本轮 guardLost / shieldBoundsMismatch。时间均相对控制器开始,含初始 5 秒提示;实时 / 历史副本不代表重复派发。++本轮首次证明受保护自动解锁 → GUI / SCK 变化 → 重锁 → 双保护释放的实际闭环。没有观察到 returnAdmitted 日志,不能宣称 Secure Input 下两个 session tap 实际接收了该按键;需要继续验证硬件接管。现场两块物理显示器的持续覆盖仍待用户补充。legacy-only 报告 productionEvidenceEligible=false,不覆盖 Data Protection Keychain、崩溃 / 拓扑变化或生产 promotion;默认生产 profile 仍关闭 Return。未合并 awesome-extension。+++### 5 秒受保护停留复测通过++用户指出首轮遮罩不足 5 秒。核对首轮 --fast 将 hold_seconds 设为 0:authorizing 到双方释放约 3.683 秒,active 到观察重锁约 1.745 秒,结束原因 turnEnded,非遮罩失效。为控制器补充 protectedHoldStarted / protectedHoldEnded,实际等待采用 monotonic 计时;没有更改 Root 截止、遮罩或输入策略。++随后不使用 --fast、指定 --hold-seconds 5 的同账号 legacy-only 复测通过:12.659s active,13.799s AX counter 增加且 SCK 图像变化;13.815s 开始停留,18.817s 结束,实际 5.002 秒;18.834s turnEnded 重锁,19.108s 确认锁定,19.203s 双保护释放,22.703s 普通手动解锁后自有隔离项验证 / 清理通过。authorizing 至双方释放约 7.780 秒,无报告覆盖故障 / guardLost。两轮完整流程均通过,但仍不能替代生产验收;物理显示器持续覆盖及剩余故障 / Data Protection Keychain 等验证需继续,生产关闭,未合并。+++### 遮罩文字跳变修正++用户现场观察认证倒计时 / 使用倒计时反复跳变。代码确认主 Guardian 的 startup 倒计时在 hasObservedUnlock 后仍每秒更新,与 active 标签互相覆盖;watchdog 又未离开 startup 标签。新增两套遮罩共用的纯显示状态 LockedUseShieldStatus:等待认证(同一 Root startup deadline)→ 正在操作 → 正在锁屏,阶段只前进,只有文字改变时绘制。操作阶段显示稳定提示,不再展示与固定 5 秒测试停留无关的 300 秒上限。此显示状态不授予 GUI 权限、不改变 Broker / 输入 / coverage 策略。新增两项回归覆盖解锁后旧 locked 样本 / 认证截止不能覆盖 active 文案、停止后不回退和主 / watchdog 同输入一致,均通过;真实部署复测待完成。+++显示状态修正版 e25dd37 已签名部署。相同 5 秒停留实测的 AX / SCK 闭环通过,实际停留 5.005 秒,约 19.625s 确认重锁、19.679s 双保护释放;没有以显示文案变化代替认证 / coverage / 释放证据。现场文字稳定性与正常手动解锁清理待反馈。+++用户因上一轮离开要求重新现场观察。上一轮双保护约 19.679s 已释放,之后仅等手动解锁,最终 120 秒手动验证等待超时;不应描述为完整验收或遮罩保留数分钟。此次相同显示状态修正版、legacy-only / hold=5 复测通过:10.647s 固定 AX / SCK 验证通过,实际停留 5.005 秒,16.260s 确认重锁,16.445s 双保护释放,20.439s 正常手动解锁后隔离项验证 / 清理通过。现场文字稳定性待用户反馈,报告 productionEvidenceEligible=false,未合并。+++### 退出前文字重排修正++用户确认整体遮罩和主要文字状态正常,但消失前文字仍轻微跳动。退出状态原先立即替换为“正在锁屏”,触发一次新文字布局;两个窗口的释放时刻不同,可能放大视觉切换。改为停止时冻结最后呈现帧,不再更新标签或倒计时,直到已确认锁定 / 排空后关闭窗口。没有增加延迟、关闭动画或绕过双保护释放屏障。回归验证停止后包括晚到 unlocked 样本都不会触发绘制。现场修正版尚待观察,不将已知文字布局机制当作所有末帧视觉变化的唯一原因。+++退出帧冻结修正版 714c020 真实复测的软件闭环通过:10.138s 固定 AX / SCK 验证完成,再停留 5.000 秒;15.764s 确认重锁、16.228s 双保护释放,23.080s 正常手动解锁后自有隔离 legacy 项验证 / 清理通过。现场退出文字是否稳定待用户反馈,不由软件流程成功推断;productionEvidenceEligible=false,未合并。+++### 撤罩后桌面闪现:锁屏呈现屏障++用户确认退出字体稳定,但撤罩后桌面闪现再进入锁屏;该反馈推翻了此前“软件锁定 / 覆盖检查即可证明整个视觉交接无泄露”的假设。原 main policy 和 watchdog 都仅根据原会话 locked / 排空决定释放,缺少系统锁屏界面的呈现稳定检查。普通锁屏的只读元数据采样看到 Apple loginwindow 的全局背景层从 alpha=0 到 alpha=1 的过渡,不采集像素、标题或密码。++新增两进程各自执行的 LockScreenPresentation:验证 Apple loginwindow 动态签名,原 UID / audit session locked、所有活动显示器均由屏蔽层级及以上的 loginwindow alpha=1 窗口完整覆盖,显示器与背景几何指纹连续稳定至少 1 秒、采样间隔不超过 0.5 秒,才允许本进程释放。主 policy 默认缺少呈现证据不释放;watchdog 保留独立观察和 root / 主进程排空信号。窗口变化、覆盖缺失、跨会话、解锁、时钟异常均重置,不以固定睡眠、客户端标记或新一轮 lock SPI 替代证据。单次私有管道 release 信号被本地锁存以等待屏障,不在每次采样后丢失。++WindowServer 元数据并不提供像素或 compositor 原子交接保证;1 秒连续稳定仍是保守观测条件,需要两块物理屏幕现场验证。未放宽原 coverage、动作排空和输入保护;没有添加反复重锁或超时自动撤罩。11 项 Guardian / 呈现屏障策略回归通过,真实部署复测待完成。+++### 呈现屏障首次失败与本地恢复修正++首次新屏障完整测试 AX / SCK 通过,停留 5.005 秒并确认重锁,但两进程持续 waitingForCoverage,控制器 3 秒释放等待超时。根因是错误将 loginwindow layer 要求达到 CGShieldingWindowLevel(本机 2147483628),实际系统背景 / 锁屏窗口 layer 2001 / 2003 / 2004;该条件永不成立。该轮明确失败,不作为无桌面闪现证据。++用户报告无法正常回桌面并要求恢复;没有继续发起测试。正常登录尝试会与仍处于 relocking 的旧 Guardian 冲突。只停止本轮已核对完整可执行路径、角色参数和当前 UID 的两进程,未动其他守护或认证策略;随后原生会话检查 unlocked,两个故障进程均已退出。恢复结束不等于故障注入验收通过。诊断中尝试的临时备用覆盖自检未通过,因此未据此执行保护交接,也没有把其当作成功证据。++离线修正使用系统 screenSaverWindow 窗口级别判断 Apple loginwindow 的背景,而不是 Guardian 的极高 shield level。另增加有界权限边界的本地恢复通道:只有 Root 已确认事务 / 动作排空、确实观察到原会话重新 locked、且 IOHID 监视器观察到真实本地活动,才让输入回到系统 loginwindow,保持不透明遮罩直至同一原会话由用户实际解锁,再退出而不重复锁定。没有 Root 排空、没有已观察锁定、没有真实硬件活动或身份不同,都不能通过此通道撤罩;不因超时自动露出桌面。主 / watchdog 各自保留上述门槛,合成 tap 事件不生成硬件恢复意图;普通自动结束仍要求锁屏呈现稳定屏障。++完整 Swift 280 项(1 跳过、0 失败)通过,包括没有排空 / 锁定前的硬件意图不足、无硬件意图的解锁仍请求保护、增加新在途工作撤销旧恢复屏障。新恢复路径真实效果和无桌面闪现仍待现场验证;不自动锁屏复测,生产仍关闭,未合并。++### 固定品牌遮罩++用户已确认修正后的交接无桌面闪现、解锁正常。按新外观要求,将两套保护表面统一为本地壁纸模糊背景、当前账户圆形头像和 OCU 标志,使用两行固定英文;保留 alpha=1、overscan、覆盖检查及排空 / 系统锁屏呈现屏障。先做离屏渲染和不锁屏预览,再验证签名组件上的闭环。启动截止只保留于协议和日志,不驱动产品文本。++品牌预览覆盖两块显示器约 10.8 秒后由 Esc 正常结束;用户确认外观正常,提出标志上移和圆形外框,已实现并渲染检查。签名 Guardian 已部署新外观;本轮未新增锁屏验证,不把外观验收当作生产故障矩阵完成。++### 品牌遮罩闭环已验收(物理双屏)++首轮暴露准备阶段误用 live heartbeat,修正为 shielding 后才检查;补准备耗时和覆盖诊断,随后发现新增虚拟屏的窗口坐标偏移。主进程在创建窗口前完成 AppKit 初始化,严格覆盖检查和原有超时不放宽。用户删除虚拟屏后完成物理双屏 legacy 闭环:自动解锁、受保护 AX/SCK、保持 5.005 秒、重锁、双保护释放、手动解锁与隔离数据清理全部通过,用户确认无桌面闪现。虚拟屏兼容不在本轮验收范围;生产证据仍待完整故障 / 会话认证矩阵。++录屏演示增加 `--keep-fixture`,成功清理后保留实际 Increment Counter 窗口供用户核对;后续演示使用该选项,不为保留窗口延长租约。++录屏保留复测补齐两处寿命问题:terminal ACK 由独立恢复连接确认,finished 主进程不再被旧周期报告影响;目标在 --keep-fixture 下采用独立进程 session,避免 runner 回收进程组。真实完整演示已通过并在脚本结束后确认同一目标 Counter: 1 仍可见。两套守护已退出,仅保留无租约的原生目标供用户录屏。diff --git a/docs/exec-plans/completed/20261010-locked-use-component-names.md b/docs/exec-plans/completed/20261010-locked-use-component-names.mdnew file mode 100644index 0000000..d0a90f9--- /dev/null+++ b/docs/exec-plans/completed/20261010-locked-use-component-names.md@@ -0,0 +1,15 @@+# Locked Use 组件命名++## 目标+更新 PR #92:正式 App 使用 Open Computer Use.app / OCU Guardian.app;开发构建保留 Dev 显示后缀。后台程序统一为 OCULockService / OCULockInstaller,插件为 OCULockAuth.bundle,测试目标为 OCU Lock Demo,诊断插件为 OCULockProbe.bundle。++## 约束+保持内部签名标识、launchd Label、权限与许可规则稳定。组件目录按 debug / release 隔离,正式 App 不嵌入测试 App 或诊断插件。系统 Guardian 使用固定安装路径,显示名称仍区分构建配置。已有旧安装只经旧签名 installer 正常停用卸载后再安装;不在线重命名插件,不自动修改当前机器认证策略。++## 步骤+- [x] 同步构建产品、运行路径、安装器、诊断、授权机制和测试脚本。+- [x] 构建并校验两种配置的签名制品,运行回归及文档检查。+- [x] 更新历史、发布说明、PR 正文并推送。++## 验证结果+Swift 301 项(7 跳过)、Node 25 项、Python 29 项通过;debug / release 组件与 App 构建、严格签名、运行组件集合、plist 名称及诊断插件 ABI 校验通过。变更补充到 PR #92;未触碰当前机器的已安装认证组件。diff --git a/docs/exec-plans/completed/20261010-locked-use-pr-extraction.md b/docs/exec-plans/completed/20261010-locked-use-pr-extraction.mdnew file mode 100644index 0000000..1dbc799--- /dev/null+++ b/docs/exec-plans/completed/20261010-locked-use-pr-extraction.md@@ -0,0 +1,26 @@+# Locked Use 独立 PR 提取++## 目标和范围+从 awesome-extension 的最终 Locked Use 实现提取独立 PR,基于最新 main,不携带虚拟工作区、独立电源模块、AX diff 或 ColorSync 调查。保留 main 已合并的后台窗口、sky_key 与 agent display 生命周期。++## 约束和风险+- 不修改 awesome-extension 或既有运行实例;所有操作在独立 worktree。+- 保留管理员显式验证 profile、原生认证 fallback 和生产证据门槛,不为提取自动锁屏或安装系统组件。+- main 的新增 SkyLight 输入路径也必须检查租约;租约内捕获明确走 ScreenCaptureKit,普通后台窗口保持原捕获行为。+- main 没有 AX diff API,固定验证器继续读取其完整快照;保留 post-merge 失败先结束租约的修正和实际计数 / 图像变化日志。+- 保留 MCP endSession 的 agent display / occlusion 恢复,不用 turn-ended 替代最终清理。++## 步骤+1. [x] 同步 main,提取原独立 feature diff 和合并后的必要修正。+2. [x] 处理共享构建及退出路径冲突,补齐新输入路径门和捕获选择。+3. [x] 运行 Swift / Node / Python 回归、文档检查和构建检查。+4. [x] 核对 diff 范围,记录历史 / 发布说明,提交并推送独立分支,创建 main PR。++## 验证边界+既有双物理屏完整 legacy 闭环及用户确认属于 awesome-extension 的实机证据;本次独立分支另跑离线 / 构建集成检查,不将旧实测当作新分支的真实锁屏验收。完整 Data Protection、Secure Input、组件死亡和显示器矩阵仍未完成,生产保持关闭。++## 检查结果+Swift 301 项(7 跳过、0 失败),Node 25 项,Python 28 项,文档检查、组件 / App 签名构建与 ABI 检查通过。make check-repo 的模板缺失属于 main 的既有问题,不在本次修复范围。++## 交付+独立分支 `codex/macos-locked-use-pr` 已推送,创建 [PR #92](https://github.com/iFurySt/open-codex-computer-use/pull/92),目标 main;awesome-extension 保持原样,等待用户评审与合并。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.mdnew file mode 100644index 0000000..0f748e1--- /dev/null+++ b/docs/histories/2026-10/20261005-1109-macos-locked-use-preflight.md@@ -0,0 +1,382 @@+## [2026-10-05 11:09] | Task: 实现 macOS Locked Use 预检与独立认证插件实验++### Execution Context++- Agent ID:`/root`+- Base Model:GPT-6(会话未提供细分型号)+- Runtime:Codex desktop,独立 macOS worktree++### 用户诉求++在本地 awesome-extension 的独立 worktree 中推进 macOS 锁屏后继续 Computer Use 的实现,完成后本地合并,避免影响另一个会话。首次显式启用并授权客户端,后续锁屏自动进入;轮次结束 / 30 秒空闲 / 本地输入触发重锁。用户已关闭原有 Codex Locked Use 插件。++### 已交付改动++- 新增原生 `locked-use status [--json]`、doctor 和 npm help 入口,报告会话、runtime 权限、组件存在性和未通过的门槛。+- 会话读取使用 SessionGetInfo audit-session identity、CGSession 的 on-console / login-done / UID 状态;兼容当前系统缺少 console-set key 的情况。+- 真实 snapshot、缓存复用和输入事件路径在锁屏 / 未知会话时明确拒绝;fixture 保持 headless 可用。+- 新增可测试的保护状态机,覆盖一次性许可、所有者、短期授权、heartbeat、空闲和绝对期限、接管抑制、取消 / 排空 barrier 和重锁确认。+- 新增始终 deny 的最小 Authorization 插件 ABI probe、离线测试,以及只操作独立诊断 right 的管理员安装 / 卸载脚本。构建产物隔离在 .build,不修改 screensaver right。+- 同步架构、安全、可靠性、实验步骤及 active execution plan。++### 实现边界++这不是完成的 Locked Use 功能。独立 guardian / watchdog 已实现开发 rehearsal;Broker 的内核 peer 签名验证、root 批准记录与一次性许可组件已实现。生产 Broker IPC、客户端授权 UI、guardian 集成与真实 loginwindow unlock backend 尚未完成。`available` / `enabled` 始终 false;无生产 backend 时不可开启自动解锁。需先完成屏幕 / 输入保护与真正解锁、Keychain 保持验证。++系统现有 Codex 插件已由用户关闭,只读确认 bundle 和 remote screensaver rule 移除。实验插件完成 Developer ID 签名与离线验证,并通过 macOS 原生管理员授权窗口安装独立 deny-only right。4 次真实 AuthorizationCopyRights 返回 denied,SecurityAgentHelper 日志确认机制实际调用。首次有 Library Validation 报错后仍实际执行,记录此差异。实验后独立 right、原 bundle 与自身 staged 副本均已移除;screensaver 规则保持不变。未执行真正解锁,未读取密码或用户 Keychain 项。++### 验证++继续开发新增 `OpenComputerUseGuardian` app、独立 heartbeat watchdog、过滤型输入 tap、全显示器遮罩与 WindowServer coverage 观测、受控 AX / SCK fixture、只读 loginwindow 结构探针,以及有应急结束路径的人工 rehearsal controller。没有触发锁屏或解锁;等待用户准备好后实测。Developer ID 签名 bundle 的 runtime 检查显示 AX / Input Monitoring / 重锁符号均可用,secure input 未启用;socket peer 自检成功取得内核身份并验证签名,错误 signer 被拒绝。++Broker 基础组件补充 LOCAL_PEERTOKEN / Security 动态验证、固定路径 root 批准记录安全读取、Secure Random 一次性 permit。测试覆盖错误身份 / 角色、要求字符串注入、会话不匹配、过期与重放、断开撤销、guardian 心跳 / 热插拔 / 动作排空 barrier。生产 IPC / 安装登记仍未实现。++- `swift test`:188 项,1 项 gated live test 跳过,0 失败;其中 LockedUseTests 20 项。+- JS REPL / CLI:21 项通过;使用 bundled Node 绕过系统 Node 的既有动态库故障,没有修改系统安装。+- fixture 9-tool smoke 与 cursor idle smoke 通过。+- 插件 ABI / 生命周期 / deny-only 行为及 codesign 验证通过;离线通过不等同于系统加载或 notarization;另有上述 SecurityAgent 实机日志证据,仅覆盖独立诊断 right。+- shell syntax 与 git diff whitespace 检查通过。+- 继续开发后完整 Swift:206 项,1 项 gated live test 跳过,0 失败;Locked Use 的 38 项策略 / 许可 / 身份 / 批准记录测试通过。fixture 9-tool 与 cursor idle smoke 再次通过;增加 extended ACL mutation 回归,防止仅凭 mode bits 将可写配置当可信。+- Developer ID / hardened runtime Guardian 的内核 socket 身份与角色批准自检通过;同签名、同 identifier 但带 get-task-allow 的独立测试副本被批准策略拒绝。未在系统安装批准文件。+- Guardian runtime preflight:AX、Input Monitoring、Screen Recording 与重锁符号均可用。尚未执行真实遮罩、锁屏、loginwindow AX 或自动解锁测试;等待用户确认测试时间。++### Guardian 实机调试补充++- 用户配合进行了锁屏 rehearsal。会话观察确认真实系统锁定,随后用户正常认证解锁;带提示文字的黑屏是 Guardian 遮罩,系统认证页面是原生锁屏。+- 部分测试因启动阶段 mouseMoved 接管而很快重锁。增加事件类型、source PID / state、capture 阶段、stop reason 和单调时间;不读取或保存按键内容,来源字段本身不足以区分真人与系统事件。+- 同进程 fixture 的后台 AXPress 引发 AppKit / MainActor 断言退出;改为 MainActor AXPress,独立自检验证 counter 变化。开发 controller 不再在 guardian 异常退出时立即终止 watchdog,先请求 / 观察重锁再清理测试进程组。+- 按用户要求先拆出纯遮罩 preview,复用同一覆盖实现,显示 15 秒倒计时,Esc 退出;不执行 AX / capture,不请求锁定或解锁。两块显示器持续约 15 秒 WindowServer 覆盖检查通过且无输入事件;用户确认两块物理屏幕完整覆盖、倒计时正常、结束正常恢复桌面。+- 修改后完整 Swift 206 项、1 项 gated live test 跳过、0 失败。+- 用户保持输入静止后的受控动作 rehearsal 验证通过:AXPress 使 counter 0→1,SCK 捕获被遮挡窗口的预期蓝色内容,动作后图像不同;guardian / watchdog 健康,约 15 秒 leaseExpired 后确认真实锁定再释放遮罩。用户确认两块物理屏幕持续遮住、未露出桌面 / fixture、手动解锁正常;没有执行真正自动解锁。+- 新增 4 项离线 controller 回归通过,覆盖异常 / 超时先请求重锁再清理、preview 不请求锁屏、锁定会话不启动 GUI。与物理测试结合,仍不能宣称组件死亡时零泄漏或生产 backend 已完成。++### 接管与 watchdog 故障注入补充++- 用户在约剩 10 秒时移动鼠标,立即 localInput 停止,约 90 毫秒后观测原会话锁定才撤罩;用户确认接管 / 解锁正常。倒计时不是接管等待时间,收到本地输入立即重锁。+- 后续只记录首次 inputTakeover,避免停止后的高频 mouseMoved 刷屏,输入仍持续被过滤。+- 新增显式 `--confirm-watchdog-test`:仅在受控 AX / SCK 验证通过后阻塞 Guardian 主线程 5 秒,依赖独立 child watchdog。增加 request-only 回报,恢复前锁定和原 session 确认的通过门槛;不将普通租约结束当作故障测试通过。该测试不验证进程死亡时零泄漏。+- controller 离线回归现为 5 项通过,包含 watchdog 测试异常恢复顺序。+- 首次 watchdog 实机尝试在约 0.4 秒健康检查失败,尚未执行卡死注入;测试明确失败并经 controller 确认锁定。新增 coverage 具体失败项、tap disable、Secure Input 和 watchdog 心跳 / 管道健康埋点,再定位;不把提前重锁视为故障测试通过。+- 第二次 watchdog 验证通过:受控动作 / 截图验证完成后 Guardian 主线程实际卡死约 5 秒,恢复时 session 已锁定,同时收到独立 watchdog 重锁请求回报;原会话锁定策略随后才释放遮罩。用户确认未露出桌面、手动解锁正常。此通过不追溯解释第一次健康检查失败,也不涵盖遮罩进程死亡 / 热插拔。++### 认证安装边界补充++- 新增纯离线 `LockedUseAuthorizationRules` 安装 / 卸载规划,保留现有 OR fallback、拒绝更高阈值与不兼容格式、重复本项目引用、第三方规则修改和篡改备份。7 项回归通过;没有写入系统认证数据库。+- 沉淀 Apple opaque 认证 session 与内核 audit session 的区别,以及上游 Platform SSO fallback 被替换的机器报告;不把报告当作本机复现或自动解锁通过。+- 完整 Swift 回归现为 213 项,1 项 gated live test 跳过,0 失败;controller 离线回归 5 项通过。++### 本地合并进度++开发提交保留在隔离分支。目标工作区的另一个会话仍有与 app agent、入口、snapshot / service 重叠的未提交改动;不 stash / reset / 覆盖其工作。等待目标改动提交后执行本地合并和集成验证,不推远端。++### 关键路径++- `packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseStateMachine.swift`+- `packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseDiagnostics.swift`+- `packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseTests.swift`+- `experiments/LockedUse/`+- `scripts/build-locked-use-plugin.sh`+- `scripts/manage-locked-use-probe.sh`+- `docs/locked-use.md`++## Broker 与 remote 机制实现++新增独立签名 Broker、受角色约束的内核身份认证 IPC、Guardian challenge 和一次性 remote 插件许可。IPC 限制消息 / 排队大小并使用绝对截止时间,重验动态签名身份;放行不等于桌面解锁,动作仍需独立 Guardian 观测和健康证明。取消后不以旧锁屏状态提前撤罩。Guardian 接入锁屏 AXConfirm 和不读取键值的硬件活动监测,后者尚待 Secure Input 实机验证。++验证:完整 Swift 222 项、1 项 gated live test 跳过、0 失败;已签名 remote 插件离线 ABI 验证拒绝、重复调用与取消。系统安装、OCU 租约入口和真实解锁仍在后续计划内,未合并目标分支。++### 原生租约接入与恢复开发++用户要求先提交当前开发,再继续完成全部实现 / 验证,最后一次性本地合并;已有开发 checkpoint,未合并目标分支。补齐签名 native Installer、CLI / settings 的安装 / 停用 / 部分恢复与验证转生产入口,以及 SCM_RIGHTS 原始 CLI 内核身份、app-agent 连接级租约 / 动作排空、客户端 EOF 和 JS reset / timeout 旧 epoch 停止。++root Broker 增加 boot-bound crash journal,回复授权前 fsync,不保存 / 恢复 permit;旧 peer 只能重连接续排空 / 重锁。Guardian / 独立 watchdog 双进程遮罩与输入保护、root 健康回报和 release ACK 防止新租约 / 卸载跨越未释放保护。认证策略改变后撤销本 epoch,新保护健康要求和恢复边界有离线测试。++新增固定真实 AX / SCK fixture 和自有 Keychain probe / 监督式控制器,图片 / 随机值不落盘或输出;完整测试证据由 root 记录并匹配 OS / 组件哈希,生产 promotion 仍要求实测和管理员认证。构建支持匹配 profile 的自有 Keychain group;本机缺少匹配 profile,Data Protection 尚未实测。未锁屏 legacy 自有项目创建 / 读取 / 清理通过;原生 AX / SCK preflight 因新 app 权限缺失被拒绝,已打开引导。修复旧 agent 的启动时间懒初始化,构建 UUID 阻止复用旧代码。++当前完整 Swift 234 项(1 项跳过、0 失败)、Node 24 项、fixture / cursor smoke、签名插件离线 ABI 和 profile 校验测试通过。还没有真实自动解锁、系统 Installer / recovery / promotion、Secure Input 键鼠、进程死亡 / 服务重启 / 显示器变化与完整 Keychain 保持的实测证据;保留生产关闭,不提前合并。++- 用户完成隔离 app 授权并重启验证实例后,固定独立 native fixture 的真实 AXPress、计数器变化、前后 SCK 图像变化及 legacy 自有测试项通过;没有执行锁屏或自动解锁,测试项已清理。++- 首次系统验证 profile 安装与安全卸载成功,screensaver 的原 fallback 保留并恢复。发现管理员 staging 的 umask 077 使系统 namespace 不可供用户遍历,已修正为明确的系统目录权限;锁屏测试在启动前退出,没有尝试解锁。恢复 / 验证记录改为从创建起 0600、清除继承 ACL、原子替换和 fsync,不先公开再 chmod;增加继承读取 ACL 和不可信目录回归。修正版已完成管理员认证和重新安装。++- 修正版系统目录可遍历、客户端批准及认证策略完整性诊断通过。第一次真实锁屏事务在 preparing 阶段因独立 watchdog 未完成健康注册中止,未发出解锁许可;用户正常解锁。补充 watchdog 停止原因及 Broker 注册诊断。会话门单测以受控 validator 隔离系统安装状态;完整 Swift 236 项、1 项跳过、0 失败。++- 真实锁屏复测定位独立 watchdog 的 `shieldNotInWindowServer`,Broker 注册本身成功;未放行解锁。主 / 备用遮罩增加公开 AppKit `canBecomeVisibleWithoutLogin`;主遮罩锁屏覆盖检查通过,备用进程补齐 `finishLaunching` 与首帧 RunLoop 绘制后待实测。++- watchdog 首帧健康检查新增独立、不锁屏的 surface self-test。实测缩放后的窗口矩形与完整显示器不同;禁用 NSWindow 出现动画后自检通过。全屏窗口禁用 AppKit frame constraint,并增加真实矩形诊断。控制器支持观察正常手动解锁替代 stdin 确认,遵循用户固定解锁节奏;不以等待时间当作解锁证据。++- 双保护真实锁屏准备检查已通过,Broker 进入 authorizing;解锁触发未找到可提交 AX secure field,实际会话保持锁定,保护正常收束。加入有界 AX publication 等待与仅结构的诊断,尚未证明自动解锁。++- 固定 Return 提交未证明自动解锁。失败后 Broker 通信超时、agent 排空 ACK 缺失,保护反复锁定并阻碍用户登录数分钟;终止本项目验证 agent 后保护正常收束。已卸载验证组件、恢复原认证策略,并暂停进一步锁屏测试。+- 修复已观测到锁定时仍重复请求锁屏的主 / 备用保护行为;新增独立 agent 准备 8 秒 / 停止 5 秒 deadline,重试不能延长期限,超时只结束自身进程。保留实际锁定、动作和解锁工作排空的释放 barrier,补充排空通信诊断。独立进程主线程故意卡住时按预期退出码 70 自动结束,不调用锁屏或 UI;全系统故障恢复时延仍待验证。+- 完整 Swift 241 项、1 项跳过、0 失败;签名独立进程 deadline、签名 peer identity 和 remote 插件 ABI 检查通过。此次修复没有重新安装组件或执行锁屏测试。++- 参考用户提供的锁屏方案后,移除主动账户选择、AXConfirm 与固定 Return,改为双保护准备后的单次公开显示器唤醒,随后等待系统认证与实际解锁证据。新增独立 display-sleep assertion;不把唤醒等同于授权成功。资料中的返回码、Keychain 保证、AX 树绝对断言和提前撤罩顺序不能直接采用。+- 将 AuthorizationRightGet 移出 Broker 协调队列;签发 / 消费只接受有界新鲜策略观察,超时拒绝新许可而保留清理通信。新增只限验证 profile 的 recovery-only 事务,准备双保护后在签发任何许可前主动停止并检查双方释放 ACK;下一步先实测此链路,再验证自动解锁。++- 第一轮恢复专项约 3.1 秒清理,两个保护进程均退出,随后观测正常手动解锁;但备用进程注册前准备计时已到期,不算完整双保护通过。修正准备期与运行期心跳计时边界;准备总期限仍为 8 秒,Guardian 等待独立子进程就绪最多 3.5 秒。新增 root recoveryProbePrepared 证据和启动失败不能假报成功的回归。++- 修正版 recovery-only 实机通过:备用进程完成 root 注册,主保护报告 shieldReady,Root 记录双方就绪后主动停止;约 2.0 秒收到动作排空、实际锁定与双保护释放证据。检查保护进程已退出,并观测用户正常手动解锁。没有签发任何解锁许可,未执行 GUI / Keychain 动作;下一轮仅测单次唤醒和立即重锁。++- 2026-10-05:按更新参考实现 identifier-only、有界固定 AXValue 可写性探测;不读密码、不发送认证动作。新增取消 / 在途写入排空回归;完整 Swift 249 项,跳过 1 项,0 失败。快速控制器在真实 GUI 验证后立即重锁、等待双方释放,并保存不含原始日志 / 字段 / 图像的私有诊断时间线。自动解锁与完整生产验证仍待实测,尚未合并。++- 2026-10-05:首轮快速真实流程找到 14 节点、唯一 FocusedUser,但预查询不可写而未执行固定值探测,未触发机制 / 自动解锁;失败后进入 awaitingManualUnlock、双方保护退出。移除将可写性预查询作为写入前置条件的差异,保持其仅作诊断;实际写入仍仅限固定 AXValue、取消与同会话检查。++- 2026-10-05:第二轮固定 AXValue 实际写入返回成功,但未触发认证机制 / 自动解锁;约 6.6 秒保护事务失败结束,控制器确认双保护释放。正常手动登录中的 Broker 校验出现 -67061;另一个不锁屏、无租约的 remote-only 探测中全部签名校验成功,Broker 正确拒绝无许可 claim。暂不能归因于签名材料本身,需继续核对认证宿主环境与认证发起时序。新增独立不锁屏诊断入口,Python 报告过滤 4 项通过。尚未完成 / 合并。++- 2026-10-05:核对两级认证规则、4-byte length + JSON 协议与显式 SetResult;独立 remote 分支在真实 SecurityAgent 已可达。新增 macOS 14.4+ public SecTask / ProcessCodeRequirement 验证,签名类别 + 固定 ID / Team + 动态有效 / runtime / LV + 注入 entitlement 检查,不做 identifier-only 放宽。独立签名合法 / 错误 ID / ad hoc / get-task-allow 正反检查与原 ABI 通过;Python 白名单报告 6 项通过。+- 2026-10-05:实机裁决链第一次通过:同 audit session claim 成功、consume 返回 authorized、SetResult(Allow) 返回成功;约 1 秒后因遮罩尺寸缩为 90% 而 guardLost,中止重锁并确认双保护退出。正常手动解锁与自有 Keychain 清理通过。仍不能记作完整 GUI 闭环通过;遮罩改为 nonactivating NSPanel,等待切换复测。++- 2026-10-05:nonactivating NSPanel + 主屏蔽层级 +1 的不锁屏 surface 自检通过;完整 Swift 249 项、1 跳过、0 失败。下一轮真实切换仍待系统管理员完成旧验证版卸载认证后安装新版,不将尺寸自检记为解锁切换覆盖证明。++- 补充诊断边界:合成修改 PID-version 的独立内核 verifier 实验出现诊断进程退出未完成,未计为通过;撤销该实验用例并记录原生异常待查,不据此开放故障认证。实际 socket audit-token 路径、合法 / 错误身份 / ad hoc / debug 的完整签名构建与 ABI 检查通过;测试制品改用每轮独立目录和 fresh inode,避免原地重签的内核缓存歧义。+### 实机补充:NSPanel 快速闭环复测++- 双保护准备与固定 AXValue 探针成功,但 5 秒授权窗口内没有插件调用,因 unlockTimeout 安全收束;锁定观测后约 7.1 秒得到双方释放确认。+- 正常手动登录才调用插件,现代 Broker 签名校验通过,已失效许可被拒绝,系统原 fallback 完成登录;自有 legacy Keychain 测试项验证与清理通过。+- 未到达 active / 原生 AX-SCK 操作阶段,不能将本轮记为完整闭环或自动解锁时遮罩覆盖验证。仍需定位认证事务启动时机差异;生产保持关闭,未合并。+- 测试后验证配置卸载成功,原认证策略恢复;主保护、watchdog 和 Broker 已退出。++- 2026-10-05:复核新认证时序资料与本机 Guardian build 1001365,发现参考路径实际写空字符串、AXValue 是属性名,并调用 SynthesizedEvent.click / send;未确认 Return 或真实认证效果,未照搬到日常账户。历史 SetResult(Allow) 不排除人工认证重叠,不能算自动唤醒成功。新增锁屏前只读实时白名单采集、schema 2 许可 / 手动恢复分窗和不锁屏被动入口,缺失日志不证明缺失事务。遮罩使用 Quartz 全局坐标完整包含,仍拒绝任何未覆盖边缘和 90% 缩小。Swift 251 项(1 跳过、0 失败)、Python 报告 10 项 / rehearsal 5 项、签名组件 / ABI / 内核签名正反例、不锁屏 surface 自检通过;被动采集完成。本轮没有安装 / 真实解锁;新认证路径的 Keychain 可用状态尚待验证(后续复核纠正了重设归因)。生产关闭,未合并。++- 2026-10-05:用户要求按官方 API 复核 Keychain 风险。纠正此前错误归因:上游 #40226 是插件介入后的会话级访问失败,明确排除文件损坏并称重启恢复,没有空输入或重设证据。SetResult 只定义授权结果;Apple 公开 Security 源码区分登录处理与显式重设,不能当作当前 loginwindow 完整调用链。同步修正文档,将隔离环境明确为开发建议而非 API 要求;本轮无代码或系统认证变更。++- 2026-10-05:用户批准当前账户短测试,重新打包 / 管理员安装后运行 wake-only 基线,未加入空输入 / 点击 / Return,不创建 Keychain 测试项、不执行 GUI 动作。双保护成功准备;5 秒 authorizing 窗口内未观察到 screensaver right 求值或机制调用,AX 扫描只有根节点且不完整,未写固定值;unlockTimeout 后锁屏观测至双方释放约 7.9 秒。后续 Touch ID 人工登录出现 right 求值、签名验证通过、过期 claim 拒绝 / SetResult(Deny) 成功、原系统 right 成功。约 27 秒确认会话正常解锁;并无自动解锁成功证据。测试后成功卸载 / 恢复原策略,保护和 Broker 退出。采集过程中实时 / 历史日志重复阶段,修复 authorizing 重复开窗并新增回归;Python 报告 11 项、rehearsal 5 项通过。后续仍需定位 AX 发布时序并验证真正的认证入口,生产关闭,未合并。++- 2026-10-06:用户要求在当前账户持续实测迭代,不再重复未修改基线。验证入口改为 3 秒内重试完整 AXIdentifier 扫描,找到唯一候选后写空字符串,再尝试一次 FocusedUser AXPress;保留签名、同会话、取消 / 在途排空和 5 秒许可,不读取字段、不发送 Return。首轮在 preparing 因 physicalInput 收束,锁定观测后约 1.6 秒确认双保护释放;认证动作尚未执行,正常手动解锁通过。复测 readiness 在锁屏前因 Broker RPC 超时拒绝,未再次锁屏。补充原客户端死亡 / socket EOF 检查,先拒绝失效 SCM_RIGHTS 连接再签名重验;原因尚待重装实测确认。签名组件 / app 构建与 ABI / 内核身份正反例通过,Swift 251 项(1 跳过、0 失败)、Python 报告 11 项通过。正在等待系统管理员卸载认证;不得将本轮计为自动解锁或新认证入口验证成功。++- 2026-10-06:重装后实测完整 AX 树 14 节点、唯一 FocusedUser,空字符串写入成功;AXPress 返回 actionUnsupported(-25206),5 秒许可窗没有认证求值 / 插件调用,双方保护释放和正常手动解锁通过。恢复后的 readiness 仍超时,原客户端断开检查没有证明已解决该问题。下一版实测 public CGEvent 目标进程点击已发送,但仍未观察到认证;未将 queued 当作投递成功或自动解锁。继续加入一次目标进程 Return(不含密码)及 Broker observer 各阶段固定日志,待验证。组件 / app 签名构建及 ABI / 内核身份正反例通过,Python 报告 12 项通过。生产保持关闭,尚未合并。++- 2026-10-06:保护待命与许可签发分离:首次已认证插件 claim 才签发,许可 deadline 不超过原 8 秒启动上限。原等待版本实测没有机制,agent 的同刻 8 秒退出造成报告失败;修正为 8 秒启动 + 2 秒 RPC 排空余量,控制器容忍已退出 stdin 的 BrokenPipeError。Swift 253 项(1 跳过、0 失败),Python 报告 13 / controller 1 / rehearsal 5 项通过,签名组件 / ABI / 内核身份正反例与 app 构建通过。+- 短实测确认失败结果约启动 8.1 秒返回,约 0.3 秒后双保护退出 ACK,正常手动解锁和报告保存通过;没有机制 / 许可 / 自动解锁。一次 annotated-stage 点击因同 PID 几何包含目标不唯一而未发出,改为先匹配 AXWindow 完整几何再确定唯一 CGWindow,拒绝模糊目标。原 postToPid 点击 / Return 实验无认证证据,已撤回。参考 build 动态 CGEventAPI.post 路径支持会话级点击,不能再用零导入证明纯观察;实际认证效果仍未证明。生产关闭,未合并。++- 2026-10-06 后续:AXWindow 完整几何匹配后唯一目标和 annotated-stage queued 已实测,仍无机制;NSEvent.windowNumber 版本也未自动解锁,并出现一次 native RPC 超时,独立只读检查确认会话已解锁、保护已退出,但未取得该轮退出 ACK,不能算恢复验证通过。补齐 timer phase 与慢签名检查日志。+- 新增会话入口的一次性点击能力:独立随机标记经继承管道共享,双过滤器验证 Guardian 来源、有序同窗口 / 坐标点击、5 秒能力 / 250ms 配对;硬件接管与停止撤销,不使用 PID-only 豁免,标记不落日志。离线 Swift 257 项(1 跳过、0 失败)、报告 14 项、controller 1 项 / rehearsal 5 项通过,签名 / ABI / 内核身份正反例通过。第一轮点击被 watchdog 拒绝,约启动 2 秒收束并确认双保护退出 / 手动解锁,未证明跨过滤器投递;补充固定拒绝枚举并为 NSEvent 的 CGEvent 显式指定私有 source,待复测。生产关闭,未合并。++- 事件 source 复测仍由 watchdog 在 flags 检查处拒绝,未观察到一次放行。双保护退出 ACK 与正常手动解锁通过。将过严的所有 flags 为零检查收敛到四个会改变左键语义的键盘修饰键,保留能力 / 来源 / 几何 / 顺序 / 时限,并只记录整数 flags 与固定拒绝枚举,待投递复测。++- 2026-10-06:会话点击经过双过滤器放行已实测(down/up 均有 main / watchdog 记录),flags=0x20000000,四个点击修饰键为零;仍未见机制,约 8.6 秒后双保护退出 ACK / 正常手动解锁通过。参考进一步静态复核定位 CGEventSetWindowLocation 与 mouse subtype=3;本项目补齐编码,并在原 3 秒唤醒预算内有界重新扫描点击后出现的密码字段,不二次点击。+- 结合用户的待命建议,显式验证 profile 改为 20 秒总等待,双保护准备仍限于 8 秒;插件首次 claim 才签发最多 5 秒许可,截止裁剪到本轮起始 deadline。Root 的绝对 uptime 截止经 IPC 与继承管道传给 agent 和双遮罩,统一倒计时,agent 只增加既有 2 秒 RPC 排空余量。默认 profile 不变。新增晚到 claim、20 秒过期不可重启、待命时本地输入撤销回归;Swift 260 项(1 跳过、0 失败)、报告 14 / controller 1 项通过,签名组件 / ABI / 内核身份正反例与 app 构建通过。系统安装等待管理员认证;新的 20 秒 / 编码路径尚未实测,生产关闭,未合并。++- 2026-10-06:20 秒窗口 / 私有窗口坐标编码实测:双过滤器放行 down/up,点击约 200ms 后重新扫描出现唯一 UserPasswordTextField,可写且空写成功;启动约 20 秒后 unlockTimeout,未观察到机制 / 许可。双方释放 ACK 约失败后 0.15 秒,随后 Touch ID 手动解锁触发真正的 right 求值与 remote 机制;此时 Broker 已 awaitingManualUnlock 并正确拒绝,不算自动解锁。修复测试控制器复用旧常驻 agent 的问题,每轮采用新独立 namespace。当前瓶颈是可交互密码 UI 到授权链之间,非 5 秒许可提前过期或 guardLost。+- 下一验证版仅管理员验证 profile 在唯一真实密码字段支持 AXConfirm 且空写成功时尝试一次确认;Root hello 显式传递开关,默认与旧协议关闭,未知动作不盲试,不合成全局 Return。新增固定布尔 / OSStatus 日志;同时修复报告 PATTERNS 重复 Watchdog 键覆盖导致部分退出原因丢失。待签名构建与实际测试,不作为成功证据。++- 确认实验离线验证:原完整 Swift 260 项(1 跳过、0 失败)通过;新增验证 profile / Guardian 身份 / 旧协议开关回归后 coordinator 10 项通过。报告 15 项与控制器 1 项通过,签名组件、插件 ABI、内核身份正反例和 app 构建通过。旧系统验证版已卸载并恢复原规则,新版正在安装;实际 AXConfirm 结果仍待验证。++- 确认实验实测:点击后约 200ms 唯一真实密码框出现;空写成功,字段明确支持 AXConfirm,单次 AXConfirm 返回 success。仍等满原 20 秒截止,没有观察到 right 求值 / 机制 / 许可;失败后约 0.17 秒确认双保护释放,随后用户 Touch ID 解锁才出现 right 求值与 remote 机制。Root 此时正确拒绝过期 claim,普通解锁成功。不可把本轮算作自动解锁;后续关键未知是无用户凭据条件下 loginwindow 如何进入 screensaver right 求值,不再仅延长等待或重复等价 UI 动作。只读检查参考 InstallerTool / service 未找到 screenUnlockMode 字符串(不证明完整实现不存在间接路径),本机该偏好未设置。实验结束已卸载并恢复原认证策略;生产关闭、尚未合并。++- HID 单变量实验:用户授权尝试仅将受控 down/up 投递从 session 改到 HID;复用已认证 Root 的验证 profile 开关,生产 / 旧协议保持 session。事件字段、双会话过滤的一次性能力、硬件活动接管、空写 + 单次支持确认、20 秒截止不变。新增固定 clickTap 枚举日志;此改动不保证被系统视作真实硬件或启动认证,待实测。++- HID 实测已完成:明确 clickTap=hid,双 session 过滤器放行同一对 down/up;点击后先短暂 AX 发布不完整,再出现唯一真实密码框,空写成功且声明支持 AXConfirm,但单次确认返回 cannotComplete (-25204)。20 秒截止内无观察到的 right 求值 / 机制 / 许可 / 自动解锁;失败后约 0.22 秒收到双保护释放 ACK,用户随后正常手动解锁才触发 remote 机制。不能宣布 HID 活动假设成立,或仅凭此轮失败排除所有 HID 路径。完整 Swift 261 项(1 跳过、0 失败)、报告 15 项通过;签名 / ABI / 内核身份正反例和 app 构建通过。未合并,生产关闭。++- 本轮 HID 实验卸载完成,只读复核 screensaver 原认证规则已恢复。++- 确认超时修正:扫描给候选 AX 对象设置的 50ms 消息超时会被后续 action 沿用。Apple AXUIElementPerformAction 文档明确 cannotComplete 可能源自超时 / 模态处理,但不能仅据错误码确认因果或动作未执行。session 轮先前已执行同一确认并返回成功,不是 HID 轮首次加入。验证版为单次确认独立设置最多 2 秒、裁剪到原 3 秒 UI 请求截止的超时,结束恢复扫描超时;记录配置结果、实际调用开始、调用耗时与结果。不自动重试,避免无法确认是否执行时重复提交。Root 总 20 秒截止、取消 / 排空与双保护不变。待实测比较。++- 超时分离首次实测:2 秒动作超时配置成功,AXConfirm 实际 37ms 返回 success;之后仍未观察到 right 求值 / 机制 / 许可。因此不能确认上一轮 -25204 唯一源自 50ms,也不能以确认返回成功推出认证已提交。本轮总起始约 18.9 秒出现 guardLost,主 Guardian 私有状态持续报告遮罩 / tap / watchdog 健康,收到 root stopRequested 后退出;失败后约 0.25 秒确认双保护释放、正常手动解锁。新增 Broker 两类报告 age / watchdogProtected 固定诊断,进一步区分 IPC 陈旧与真实遮罩不健康;新增只读按钮 enabled 计数与密码框焦点布尔,明确没有收集标题、标识字符串或值。修正等待期间每秒常规 300 秒 active 标签覆盖 20 秒启动倒计时的问题,只有观察到解锁后显示 active 标签。确认只有一次,无模糊结果重试。系统验证版已卸载并恢复原规则,下一诊断版待复测。++- 第二轮 2 秒确认实测:真实密码框 focused=true,扫描按钮 enabled=2 / disabled=0 / unknown=0;AXConfirm 34ms 返回 success,无观察到的认证求值 / 许可。约启动 14 秒 guardLost 的 Broker 固定证据显示 guardian report age≈1570ms / watchdog report age≈1577ms,watchdogProtected=true;本地 Guardian 仍持续健康。不能将本轮归因为动作超时或 UI 未聚焦,Root 失联新鲜度仍待定位。双保护释放与正常手动解锁完成,卸载恢复原认证规则。按用户新要求,暂停受保护复测,下一步独立无遮罩 / 无 watchdog 解锁诊断;不得假造生产 guardsReady、不得执行 GUI 应用动作或签发生产验证记录。++## 无遮罩解锁诊断(仅管理员验证 profile)++用户明确要求拆开解锁与保护问题后,新增独立 `LockedUseUnshieldedDiagnostic`,不复用生产 guardsReady 或 GUI action 状态机。Root 只接受管理员验证 profile 下、已批准签名 UI 探针的原锁定 UID / audit session;诊断总期限 20 秒,插件首次同会话 claim 才签发最多 5 秒且裁剪到原截止的一次性许可。无守护健康 / 心跳条件,也不伪造覆盖证据。断开、认证策略失效、期限到达或许可过期撤销后不能恢复。所有应用 action、生产验证 / promotion 与正常租约入口在诊断活跃时拒绝;重启不恢复任何诊断许可。++签名工具的独立 `--unshielded-unlock-diagnostic --confirm-visible-desktop-test` 入口复用 `LockScreenInteractor`,没有构造 DisplayGuardian、遮罩、输入 tap、硬件 monitor 或 child watchdog。因此桌面若被解锁会实际可见,不能视为生产 Locked Use。它只观察原会话解锁并立即请求 / 确认重锁,最后向 Root 结束诊断;结果与私有报告始终 productionEvidenceEligible=false,不访问应用窗口 / ScreenCaptureKit / Keychain。外部控制器入口为:++```sh+python3 scripts/run-locked-use-unshielded-diagnostic.py --confirm-visible-desktop-test+```++该入口针对人为配合的单次故障定位,没有完整保护路径的进程崩溃与遮蔽保证。实现回归覆盖生产 profile 拒绝、原 session / role 绑定、跨 audit session / 重复 claim / 许可重放、晚到许可裁剪、5 秒过期 / 20 秒过期 / 取消不可重启、非原会话结束与 GUI / 生产验证拒绝。当前 Swift 266 项(1 跳过、0 失败)通过,真实诊断待安装运行。+++### 无遮罩实测归因与报告修正++首轮诊断观察到原会话解锁、插件消费许可和重锁,但系统时间线先出现 Touch ID match,约 0.67 秒后才出现 remote mechanism。因此它证明手动认证与待命许可重叠时插件链可完成,不能证明自动解锁;测试后的再次解锁也由用户完成。++修正控制器将原生 stdout 缓冲到进程退出才记录的时间偏差:改为有界逐行读取,以原生 uptime 对齐本轮时间线;修正 trace 清理调用为 finish,确保保存报告。报告增加 authorizing 窗口内 Touch ID 介入标记,拒绝将这类结果当作自动解锁证据;没有该标记也不自动认定为成功。新增 3 项归因回归测试,覆盖窗内 / 窗外 Touch ID 与单独 evaluatePolicy 不能证明人工操作。++第二轮明确不操作鼠标、密码或 Touch ID,无遮罩、无输入过滤、无 watchdog 等满原 20 秒:唯一真实密码框已聚焦,空写成功,单次 AXConfirm 88ms 返回 success,但未观察到认证 right 求值、mechanism、许可消费或原会话解锁。结束后确认原会话锁定、Root 返回 idle。这说明撤掉保护逻辑本身没有解决认证入口;AXConfirm success 不能替代实际解锁证据。生产保持关闭,尚未合并。+++### Return 单变量诊断(待实测)++用户提供成功时间线中 secure textfield Return → loginPressed → authBegan → authCopyRights → 插件的链路,作为新的待验证假设。Apple 文档仍将 AXConfirm 定义为模拟 Return,不能据该样本断言所有实现中它只聚焦或按钮永远不能提交;当前系统上的 AXConfirm 实测未产生同样授权链。++仅独立无遮罩诊断改为固定 keyCode 36 的单对 HID down/up,替代 AXConfirm,未加入保护路径。要求同一原锁定会话、完整扫描唯一密码框、空写成功且可写 / focused、Apple loginwindow 签名有效、无 Shift / Control / Option / Command,签名检查后再校验焦点与会话 / 请求截止。私有事件源,无修饰键、重复或文字载荷,派发按下后立即释放,即使期间取消也释放;不重试。Root 20 秒诊断窗口及首次 claim 才发一次性许可不变,观察实际解锁后立即重锁。受保护输入过滤器没有键盘许可,不能直接推广该实验。++新增固定枚举日志 secureReturnObserved / localAuthenticationBegan / loginwindowRightsRequested 与 Return dispatch / queued 标记,不保存 surrounding 账户 / 认证上下文。Swift 编译通过,报告回归 17 项、诊断归因 3 项通过。Developer ID 签名两次返回 errSecInternalComponent,新制品未部署 / 未实测;等待用户恢复系统构建签名私钥访问。旧已签名 components 未替换,生产关闭,尚未合并。+++### 签名与已安装机制回溯++主 checkout 仅只读核对:Dev App 严格 deep 校验通过、Hardened Runtime、既有签名时间为本地 12:19;不是新的签名成功证据。worktree 最后成功组件签名约 12:42,新 Guardian 首次观察到签名失败约 16:55,中间没有连续签名探测,不能断言故障发生于某一次解锁。隔离 /usr/bin/true 副本(未执行)同一 Developer ID 签名也失败,最新重试仍失败,因此不局限于 Guardian 构建内容或一次偶发错误。++当前 system.login.screensaver OR 首分支和 remote evaluate-mechanisms 仍指向 OCU;安装插件 strict 签名有效、SHA256 与本 worktree 制品一致,安装 Broker 二进制与本地制品一致且运行,未观察到当前被替换。历史 authd 日志本地 15:18 调用了 OCU mechanism,15:30 / 15:31 则调用 CodexComputerUseAuthorizationPlugin;15:31 后 loginwindow SecKeychainLogin 返回 -25293。这证明历史机制确有差异,不证明当前仍被顶掉,也不能仅据日志确定何人或何时改过 policy。钥匙串状态 flags=7 与签名认证失败并存,未更改权限、信任、搜索链或钥匙串数据。需分开验证图形会话认证状态与签名环境,禁止把空值认证导致的普通 keychain login 失败直接判为钥匙串损坏。+++### 密码解锁恢复签名与 Return 首轮通过++用户用账户密码正常解锁后,同一 Developer ID 签名命令立即通过严格校验,未修改证书、私钥 ACL、信任、钥匙串搜索链或数据。这支持先前签名认证拒绝与会话认证状态有关,但仍不能将变化唯一归因到 OCU / Codex 某个插件。签名通过的新 UI 探针替换本地 components,未替换系统安装插件。++首次新探针诊断在 beginUnshieldedDiagnostic 被 Root 拒绝、未发 Return。只读回溯证实本地 15:30:12 installationPolicyInvalidated;Broker 对认证策略变化永久关闭该 service epoch 的 accepting,恢复相同规则不能自动重新授权。校验当前规则、安装插件 / Broker 与本地制品一致、无活跃保护后,经 macOS 管理员认证仅 kickstart 验证 Broker,未改规则或削弱策略失效时的关闭行为。++随后无遮罩复测出现完整自动链:FocusedUser 空写 → 单次 HID 点击 → 唯一密码框空写、focused=true → Return 单对派发 → loginPressed / authBegan / loginwindow rights request → OCU mechanism claim / 一次性 permit consume / SetResult allowed → 原会话实际 unlocked → 立即请求且确认 locked → Root idle。原生诊断起始约 8.358s,观察解锁约 9.692s,结束 / 重锁确认约 10.137s(相对控制器开始,含 5 秒初始提示)。报告内无 Touch ID match;未访问应用 GUI、SCK 或 Keychain。不能视为完整生产验收,报告仍 productionEvidenceEligible=false,自动归因没有因缺失 Touch ID 就签发证书。用户现场观察仍待补充。++下一步是为受保护主 / watchdog 过滤器增加严格的一次性 Return 能力,保留硬件接管 / 重锁、原会话及焦点校验,再验证遮罩期间应用操作和故障恢复。本轮 Return 尚未启用到受保护路径;生产关闭,未合并 awesome-extension。+++### 受保护 Return 接入(待真实完整复测)++用户确认无遮罩通过后要求提交并恢复 Guardian。此前实现与证据已分别提交 b444978 / 48d918f。新增 LockedUseReturnAllowance,通过 Guardian → watchdog 私有继承管道传递独立随机 returnTag,只在 Root 管理员 validation profile 下创建,不与鼠标 clickTag 混用。两套 session tap 分别验证同一原锁定 UID / audit session、Guardian 来源 PID、能力 tag、有效目标 PID、固定 keyCode 36、无重复 / 修饰键、5 秒总有效期和 250ms 匹配 down/up;重放、错序、取消和真实硬件接管均不能重开。watchdog / 主 Guardian 停止会撤销两类输入能力。++LockScreenInteractor 在完整扫描唯一密码框、空写成功、可写且焦点确认、Apple loginwindow 签名 / 会话再次检查后才提交 Return;受保护事件写入来源 / 目标和独立 tag。没有通用键盘放行、没有 PID-only 绕过。无 Return 能力的旧 bootstrap 不获得键盘权限。生产 profile 暂不启用。新增 6 项策略回归覆盖两独立 gate、nonce / 来源错误、其他按键 / 修饰 / repeat、跨会话 / 过期、顺序 / 目标 / 间隔 / 重放、取消与旧 bootstrap。Swift 272 项(1 跳过、0 失败)、Python 报告 17 项与归因 3 项通过;签名组件、ABI、内核身份检查与 Dev app 构建通过。真实受保护完整链待安装复测,未合并。+++### 受保护首轮:Return / 插件通过,遮罩过渡失败++新验证版安装和普通已解锁真实 AX / SCK preflight 通过。完整 fast / legacy-only 轮两套过滤器均放行鼠标 down/up,Return 派发后 OCU 插件 claim / consume / SetResult 成功。还未确认 active GUI 就遇 watchdog shieldBoundsMismatch:实际 Quartz bounds 在系统解锁动画缩至 2404×1352 且偏移 78,44,未覆盖原 2560×1440。watchdog 正确请求 guardLost 重锁;约 9.594 秒(含 5 秒提示)Root 确认双保护释放,没有循环遮罩。不得把此轮算完整成功,也没有观察到 returnAdmitted 日志,Secure Input 时事件是否经过 session tap 仍须谨慎描述。++修正使用居中 1.5× 实际不透明窗口,使系统 zoom 缩放后仍覆盖屏幕;不是放宽 coverage 判定。保留对 WindowServer 实际 bounds 完整包含 CGDisplayBounds、alpha=1、owner / layer / active topology 的严格要求。新增负坐标 / 不同比例缩放下 overscan 实际覆盖测试及不足覆盖拒绝,Swift 273 项(1 跳过、0 失败)通过。仅更新经 Developer ID 签名的 staged Guardian,保持 root 所有与普通用户不可写,Broker / auth rules 不变,待复测。++用户提供 Native Fixture “not open anymore” 提示。控制器在失败恢复后会关闭 RPC 并终止固定测试 fixture,当前没有发现其相关新 crash report,无法仅凭截图判定为崩溃;Finder 最新状态未见该弹窗。将其作为测试窗口生命周期诊断,未改私钥或认证策略。+++### 受保护完整流程首次通过(overscan 修正版)++更新 staged Guardian 后,同一 fast / legacy-only 真实测试通过:约 11.532s 派发单对 Return,11.534s loginwindow 观察 secure Return,11.539s authBegan,12.555s 首次 claim 签发许可,12.560s consume,12.561s SetResult allowed,12.564s 系统报告解锁,12.815s Root 在双保护健康下进入 active。固定签名 Native Fixture 在 13.421s 捕获 counter=0,14.198s AX 操作验证 counter 增加且 SCK 图像改变;14.560s 确认重锁,14.825s 确认双保护释放。用户随后正常手动解锁,30.859s 自有隔离 legacy Keychain 项验证 / 清理通过。报告无 failureType,没有本轮 guardLost / shieldBoundsMismatch。时间均相对控制器开始,含初始 5 秒提示;实时 / 历史副本不代表重复派发。++本轮首次证明受保护自动解锁 → GUI / SCK 变化 → 重锁 → 双保护释放的实际闭环。没有观察到 returnAdmitted 日志,不能宣称 Secure Input 下两个 session tap 实际接收了该按键;需要继续验证硬件接管。现场两块物理显示器的持续覆盖仍待用户补充。legacy-only 报告 productionEvidenceEligible=false,不覆盖 Data Protection Keychain、崩溃 / 拓扑变化或生产 promotion;默认生产 profile 仍关闭 Return。未合并 awesome-extension。+++### 5 秒受保护停留复测通过++用户指出首轮遮罩不足 5 秒。核对首轮 --fast 将 hold_seconds 设为 0:authorizing 到双方释放约 3.683 秒,active 到观察重锁约 1.745 秒,结束原因 turnEnded,非遮罩失效。为控制器补充 protectedHoldStarted / protectedHoldEnded,实际等待采用 monotonic 计时;没有更改 Root 截止、遮罩或输入策略。++随后不使用 --fast、指定 --hold-seconds 5 的同账号 legacy-only 复测通过:12.659s active,13.799s AX counter 增加且 SCK 图像变化;13.815s 开始停留,18.817s 结束,实际 5.002 秒;18.834s turnEnded 重锁,19.108s 确认锁定,19.203s 双保护释放,22.703s 普通手动解锁后自有隔离项验证 / 清理通过。authorizing 至双方释放约 7.780 秒,无报告覆盖故障 / guardLost。两轮完整流程均通过,但仍不能替代生产验收;物理显示器持续覆盖及剩余故障 / Data Protection Keychain 等验证需继续,生产关闭,未合并。+++### 遮罩文字跳变修正++用户现场观察认证倒计时 / 使用倒计时反复跳变。代码确认主 Guardian 的 startup 倒计时在 hasObservedUnlock 后仍每秒更新,与 active 标签互相覆盖;watchdog 又未离开 startup 标签。新增两套遮罩共用的纯显示状态 LockedUseShieldStatus:等待认证(同一 Root startup deadline)→ 正在操作 → 正在锁屏,阶段只前进,只有文字改变时绘制。操作阶段显示稳定提示,不再展示与固定 5 秒测试停留无关的 300 秒上限。此显示状态不授予 GUI 权限、不改变 Broker / 输入 / coverage 策略。新增两项回归覆盖解锁后旧 locked 样本 / 认证截止不能覆盖 active 文案、停止后不回退和主 / watchdog 同输入一致,均通过;真实部署复测待完成。+++显示状态修正版 e25dd37 已签名部署。相同 5 秒停留实测的 AX / SCK 闭环通过,实际停留 5.005 秒,约 19.625s 确认重锁、19.679s 双保护释放;没有以显示文案变化代替认证 / coverage / 释放证据。现场文字稳定性与正常手动解锁清理待反馈。+++用户因上一轮离开要求重新现场观察。上一轮双保护约 19.679s 已释放,之后仅等手动解锁,最终 120 秒手动验证等待超时;不应描述为完整验收或遮罩保留数分钟。此次相同显示状态修正版、legacy-only / hold=5 复测通过:10.647s 固定 AX / SCK 验证通过,实际停留 5.005 秒,16.260s 确认重锁,16.445s 双保护释放,20.439s 正常手动解锁后隔离项验证 / 清理通过。现场文字稳定性待用户反馈,报告 productionEvidenceEligible=false,未合并。+++### 退出前文字重排修正++用户确认整体遮罩和主要文字状态正常,但消失前文字仍轻微跳动。退出状态原先立即替换为“正在锁屏”,触发一次新文字布局;两个窗口的释放时刻不同,可能放大视觉切换。改为停止时冻结最后呈现帧,不再更新标签或倒计时,直到已确认锁定 / 排空后关闭窗口。没有增加延迟、关闭动画或绕过双保护释放屏障。回归验证停止后包括晚到 unlocked 样本都不会触发绘制。现场修正版尚待观察,不将已知文字布局机制当作所有末帧视觉变化的唯一原因。+++退出帧冻结修正版 714c020 真实复测的软件闭环通过:10.138s 固定 AX / SCK 验证完成,再停留 5.000 秒;15.764s 确认重锁、16.228s 双保护释放,23.080s 正常手动解锁后自有隔离 legacy 项验证 / 清理通过。现场退出文字是否稳定待用户反馈,不由软件流程成功推断;productionEvidenceEligible=false,未合并。+++### 撤罩后桌面闪现:锁屏呈现屏障++用户确认退出字体稳定,但撤罩后桌面闪现再进入锁屏;该反馈推翻了此前“软件锁定 / 覆盖检查即可证明整个视觉交接无泄露”的假设。原 main policy 和 watchdog 都仅根据原会话 locked / 排空决定释放,缺少系统锁屏界面的呈现稳定检查。普通锁屏的只读元数据采样看到 Apple loginwindow 的全局背景层从 alpha=0 到 alpha=1 的过渡,不采集像素、标题或密码。++新增两进程各自执行的 LockScreenPresentation:验证 Apple loginwindow 动态签名,原 UID / audit session locked、所有活动显示器均由屏蔽层级及以上的 loginwindow alpha=1 窗口完整覆盖,显示器与背景几何指纹连续稳定至少 1 秒、采样间隔不超过 0.5 秒,才允许本进程释放。主 policy 默认缺少呈现证据不释放;watchdog 保留独立观察和 root / 主进程排空信号。窗口变化、覆盖缺失、跨会话、解锁、时钟异常均重置,不以固定睡眠、客户端标记或新一轮 lock SPI 替代证据。单次私有管道 release 信号被本地锁存以等待屏障,不在每次采样后丢失。++WindowServer 元数据并不提供像素或 compositor 原子交接保证;1 秒连续稳定仍是保守观测条件,需要两块物理屏幕现场验证。未放宽原 coverage、动作排空和输入保护;没有添加反复重锁或超时自动撤罩。11 项 Guardian / 呈现屏障策略回归通过,真实部署复测待完成。+++### 呈现屏障首次失败与本地恢复修正++首次新屏障完整测试 AX / SCK 通过,停留 5.005 秒并确认重锁,但两进程持续 waitingForCoverage,控制器 3 秒释放等待超时。根因是错误将 loginwindow layer 要求达到 CGShieldingWindowLevel(本机 2147483628),实际系统背景 / 锁屏窗口 layer 2001 / 2003 / 2004;该条件永不成立。该轮明确失败,不作为无桌面闪现证据。++用户报告无法正常回桌面并要求恢复;没有继续发起测试。正常登录尝试会与仍处于 relocking 的旧 Guardian 冲突。只停止本轮已核对完整可执行路径、角色参数和当前 UID 的两进程,未动其他守护或认证策略;随后原生会话检查 unlocked,两个故障进程均已退出。恢复结束不等于故障注入验收通过。诊断中尝试的临时备用覆盖自检未通过,因此未据此执行保护交接,也没有把其当作成功证据。++离线修正使用系统 screenSaverWindow 窗口级别判断 Apple loginwindow 的背景,而不是 Guardian 的极高 shield level。另增加有界权限边界的本地恢复通道:只有 Root 已确认事务 / 动作排空、确实观察到原会话重新 locked、且 IOHID 监视器观察到真实本地活动,才让输入回到系统 loginwindow,保持不透明遮罩直至同一原会话由用户实际解锁,再退出而不重复锁定。没有 Root 排空、没有已观察锁定、没有真实硬件活动或身份不同,都不能通过此通道撤罩;不因超时自动露出桌面。主 / watchdog 各自保留上述门槛,合成 tap 事件不生成硬件恢复意图;普通自动结束仍要求锁屏呈现稳定屏障。++完整 Swift 280 项(1 跳过、0 失败)通过,包括没有排空 / 锁定前的硬件意图不足、无硬件意图的解锁仍请求保护、增加新在途工作撤销旧恢复屏障。新恢复路径真实效果和无桌面闪现仍待现场验证;不自动锁屏复测,生产仍关闭,未合并。++### 已停止保护进程的管理员恢复++- 新增 `reconcile-stopped-guards` 维护入口:只允许 idle、agent 已排空且内核确认记录中所有保护进程均退出的旧 epoch 归档;重查状态、独占 daemon 锁并保留私有恢复记录。失败时恢复原记录与服务,不伪造 release ACK、不修改认证规则。+- 恢复策略相关 9 项测试通过;签名维护入口已实测恢复旧 epoch。修正后的完整 legacy 验证通过自动解锁、AX/SCK、约 5 秒操作保持及重锁后双保护释放,用户确认无桌面闪现、后续解锁正常。+- 完整 Data Protection 预检在锁屏前因缺少 entitlement(-34018)中止;生产资格与故障矩阵仍待验证。++### 壁纸、头像与固定品牌提示++- 共享 ShieldAppearance 将各屏幕本地壁纸模糊并暗化,读取当前本地用户头像,右下叠加签名 bundle 内的圆形 OCU logo(按现场反馈上移,贴住头像);缺少资源时保持不透明备用展示。没有桌面截图或密码读取。+- 两行固定英文为 `Open Computer Use is Using Your Mac` / `Press any key or click to unlock`;认证阶段和操作阶段不更换文字,排空期间继续冻结。独立 preview 倒计时留在日志,产品不显示事务内部状态。+- 保留 alpha=1、不透明 1.5× overscan、严格 WindowServer 覆盖健康检查和重锁呈现屏障。添加不创建租约、不锁屏的离屏渲染诊断,图像仅本地构建目录保存,不进入版本库。+- Developer ID Guardian 构建 / 严格签名验证、两项显示状态测试通过;离屏图已检查。双屏预览约 10.8 秒后由 Esc 结束,期间覆盖检查通过;未把主动提前退出记为完整 15 秒验收。+- 用户确认新版外观整体正常;随后按反馈上移标志并采用圆形裁剪框,离屏渲染再次检查,系统 Guardian 已更新。++### 品牌遮罩完整闭环复测++- 首轮在准备阶段因调用运行期 heartbeat 提前触发 heartbeatExpired,未发起自动解锁。第二轮增加准备阶段日志,发现新增虚拟显示器上的实际窗口偏移,严格覆盖检查中止;两轮均观察到双保护释放和正常手动恢复,不计为成功。+- 主 Guardian 仅在 shielding 状态执行运行期心跳;AppKit finishLaunching 在构建保护窗口前完成,避免 run() 的初始化与已发布窗口布局竞争。准备仍受原有 3.5 秒限制,运行期 1.5 秒心跳和原会话保护未放宽。添加仅含耗时 / ready / 几何失败枚举的准备日志及私有报告白名单。+- 用户移除 virtual display 后,只对两块物理屏幕复测,不将这轮成功外推为虚拟显示器兼容验收。实际链路通过:插件 claim / consume 放行,原会话自动解锁,受保护 AX counter 递增且 SCK 图像改变;实际保持 5.005 秒,确认重锁,约 1.458 秒后双保护释放;手动解锁和隔离测试数据清理完成。+- 用户确认双屏持续覆盖、撤罩无桌面闪现、手动解锁正常。Guardian 签名构建 / 部署通过,12 项 Guardian 策略测试通过。此次使用 legacy-only,productionEvidenceEligible=false;Data Protection / Secure Input / 故障矩阵仍未完成。++### 录屏后保留 Increment 结果++用户要求手动解锁后继续看到操作计数。验证控制器增加 `--keep-fixture`:仅完整成功并清理结束后保留原生测试窗口,失败仍退出;不保留保护租约或延迟撤罩,计数来自同一实际被点击窗口。录屏后手动退出目标即可。命令帮助与 Python 语法检查通过;本轮不重复发起锁屏。++### 撤罩 ACK 竞态与演示窗口进程寿命++- 保留窗口的首次锁屏演示已验证真实点击 / 图像变化和重锁,但旧 Guardian 在 release 过程中漏发终止 ACK,控制器有界等待失败,因此走失败关闭目标分支。Root idle、内核确认保护进程均已退出后,通过既有管理员维护入口归档该已排空 epoch,不更改认证规则。+- 主 / watchdog 在本地呈现 / 排空屏障撤罩后,专门重新认证同一签名 / audit-token 身份提交 terminal ACK,最多 3 次,检查服务回复而不忽略拒绝。已 finished 的主进程不再让在途周期报告清掉退出连接;新增固定 ACK / retry 结果日志。控制器只将 ACK 观察期限从 3 秒改为 8 秒,不延长许可或绕过呈现条件。Broker 相关 10 项回归及报告 3 项回归通过,签名 Guardian 构建 / 部署通过。+- 一轮准备阶段收到本地鼠标移动,按接管规则安全中止;两进程 terminal ACK 均通过。随后完整闭环通过并报告保留窗口,但宿主回收脚本进程组仍使目标退出。`--keep-fixture` 现在让真实目标采用独立 session 且不继承 stdin,保留同一个被点击窗口,不重启或伪造计数。+- 不锁屏自检证实脚本退出后目标继续存活;关闭该自检目标再跑完整物理双屏 legacy 闭环,AX / SCK 通过,保持 5.005 秒,重锁后约 1.452 秒完成两保护 ACK,正常手动解锁和隔离数据清理通过。脚本退出后只读 AX 确认同一存活目标显示 `Counter: 1`,保留供用户录屏。+- 这是演示闭环证据,不是完整生产故障矩阵资格;虚拟屏、Data Protection 和其余生产验证范围仍待完成。++### 本地合并到 awesome-extension++用户要求将隔离 Locked Use 分支全部提交合并回 awesome-extension。合并开始时两边均无未提交改动;保留目标分支已有虚拟工作区、电源模块及 ColorSync 调查提交,采用非快进 merge。++冲突处理保留虚拟显示器 SwiftPM 产品 / cursor 资源并加入 LockedUseNative 依赖;保留 agent 的安全 retire 和虚拟屏所有权检查,补齐构建身份;真实输入同时执行 Locked Use 会话检查与虚拟会话输入门,缓存沿用 session/window key 并在会话失效时清空。Node 的虚拟 / AX diff 测试和租约退出测试均保留,安全 / 可靠性文档两边内容合并。未改系统认证配置、未发起锁屏或热插拔测试。++合并后 Swift 330 项(2 跳过、0 失败)、Node REPL 28 项、Python 28 项均通过,根构建覆盖主 app、Guardian、Broker、Installer 与虚拟显示器产品。此前物理双屏录屏闭环与保留 Counter: 1 的证据仍有效,但此次集成不新增真实场景验收,也不开放生产 backend。仅本地提交,不推送。++### 合并后主目录实机回归++从合并后的 awesome-extension 构建并严格校验签名的 App、Guardian、Broker、Installer 和授权插件;在无保护会话时通过正常管理员安装流程更新系统组件。首轮自动解锁成功,但固定验证器未指定完整 AX 输出,被目标分支新加入的增量快照误判为 verification 失败。验证器现在显式使用 full 快照,并仅记录计数与图像变化;失败路径先结束租约再等待释放,避免控制器仍连接时等待无效。++构建期间 Broker 策略观察超过有效期,触发持续拒绝;现场确认保护已释放、用户正常解锁后,经管理员重启空闲服务,不更改策略校验期限。修正后的不锁屏原生 AX / SCK 验证通过,随后完整 legacy-only 实测通过:自动解锁、固定窗口 AX 点击和 SCK 图像变化、保持 5.001 秒、重锁、双保护释放 ACK、手动解锁后隔离项验证 / 清理、保留原 Counter: 1 窗口。用户确认两块物理屏幕全程遮蔽、撤罩无桌面闪现、手动解锁正常并看到 Counter: 1。++相关 Swift 回归 128 项零失败,五个 Python 回归脚本全部通过。完整生产证据与故障矩阵仍未补齐,productionEvidenceEligible=false,生产 backend 保持关闭。仅本地提交,不推送。++### 从 awesome-extension 提取独立 main PR(2026-10-10)++用户要求只提交 Locked Use,保留 awesome-extension 的其他功能供独立评审。基于最新 main 的独立 worktree 提取原功能 diff,保留失败先结束租约及计数 / 图像变化诊断;不带入虚拟工作区、电源模块或 AX diff。main 不提供 snapshotMode API,其完整树读取仍适用于固定验证器。保留 main 的 MCP endSession 清理,新增 sky_click / sky_key 的租约门检查;租约内明确使用 ScreenCaptureKit,非租约保持 main 的硬件捕获优先。补充无事件投递的失效许可检查及作用域退出回归、发布说明和执行计划。++独立分支 Swift 301 项(7 跳过、0 失败)、Node 25 项、Python 28 项、make check-docs、签名组件 / App 构建及严格嵌套签名检查通过。授权插件 ABI 与 live task verifier 的身份 / 签名负例检查通过。系统 Node 缺少已有动态库,Node 回归使用可用的 bundled runtime 完成,不修改系统安装。make check-repo 的旧 hygiene 脚本在未修改的 main 即缺少其要求的模板 / CI 文件,本任务不扩张范围补这些文件。++本轮未安装系统组件、未修改认证规则、未锁屏;既有双物理屏 legacy-only 实测仍作为 awesome-extension 的历史证据,不能冒充提取分支实机验收。生产 backend 保持关闭。++独立提取已交付为 [PR #92](https://github.com/iFurySt/open-codex-computer-use/pull/92),目标 main;原 awesome-extension 未修改。提取执行计划已归档至 completed,等待用户合并。++### PR 组件命名与正式 / 开发构建(2026-10-10)++按用户确认的短名称更新 PR #92:主 App 正式显示 Open Computer Use.app;Guardian 正式 / 开发分别为 OCU Guardian.app / OCU Guardian (Dev).app,可执行文件 OCUGuardian;服务、安装器和授权插件为 OCULockService、OCULockInstaller、OCULockAuth.bundle。测试目标改名 OCU Lock Demo (Dev).app,独立诊断插件 OCULockProbe.bundle。Watchdog 仍为 Guardian 的进程模式。++构建支持 --configuration debug|release,组件输出目录隔离;App 按其构建配置选取组件,内嵌与系统安装的 Guardian 路径固定为 OCU Guardian.app,plist 显示名区分配置。签名 ID / launchd Label / remote right 保持稳定,授权 mechanism 同步为 OCULockAuth:remote,生产门槛不变。新版停用入口可校验并调用旧安装的签名 installer;安装器拒绝旧插件残留,要求先正常停用卸载,不在线改名认证插件。日志诊断兼容新旧进程 / 机制名称。++Swift 301 项(7 跳过、0 失败)、Node 25 项、Python 29 项和文档检查通过。debug / release 组件与 App 签名构建、授权插件 ABI / task verifier 检查、严格嵌套签名验证通过;实际 plist / 文件检查确认名称正确,两种 App 均只嵌入四个运行组件,没有测试 App / 诊断插件。诊断探针独立构建和 ABI 检查通过。未安装新系统组件、修改当前认证规则或锁屏测试;旧实机证据不自动授予改名制品生产资格。++推送前同步 main 的 1.0.0 发版提交,保留两条发布记录;同步后 Swift 301 项(8 跳过、0 失败),额外跳过为需要 unlocked console 的无事件输入门验证。PR 的正式名称与升级说明通过 GitHub REST API 同步。++### 本地开发安装清理与使用文档(2026-10-10)++按用户要求,通过签名 App 的正常停用入口卸载旧开发安装。确认 Broker 服务、系统安装目录、自有授权插件与独立探针 right 均已移除,system.login.screensaver 恢复 use-login-window-ui。未移除第三方插件或修改用户权限、凭据。++新增中英文简明使用文档,按配置位置 / JSON 示例、命令行使用、完整配置与命令表组织,并从对应 README 链接。区分安装开关与程序维护的验证字段,说明 Guardian 权限申请和当前验证模式入口;正式生产验证仍未完成。文档检查及 diff 格式检查通过,本轮未进行锁屏测试。++推送前同步 main 的截图配置改动,保留 libwebp 依赖与截图配置参数,同时保留 Locked Use 租约强制 ScreenCaptureKit 的捕获条件,两条发布记录均保留。同步后 Swift 307 项(7 跳过、0 失败)、Node 33 项和文档检查通过。++### 使用文档改为开启与安装指南(2026-10-10)++按用户反馈移除面向用户的配置字段说明,中英文改为开启 / 卸载命令、权限表、组件安装位置表和服务职责简介。保留验证模式与生产状态的真实边界;说明 watchdog 复用 Guardian,系统认证组件不是额外安装项。两份文档复用用户提供的同一张原始架构图,图片收录到 docs/assets,沿用语言切换链接。文档与格式检查通过;未改代码或系统安装。++### 同步 main 并解决 PR 冲突(2026-10-13)++合并 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 对象解析。本轮未安装组件、锁屏或更改系统认证策略。diff --git a/docs/locked-use.en.md b/docs/locked-use.en.mdnew file mode 100644index 0000000..e7f67f2--- /dev/null+++ b/docs/locked-use.en.md@@ -0,0 +1,69 @@+# Locked Use++[简体中文](locked-use.zh-CN.md)++Locked Use lets an agent keep using GUI apps while your Mac is locked. Shields cover every display during the task. When the task ends, or you move the mouse or press a key, the Mac locks again so you can unlock it normally.++## How to enable it++You need macOS 14 or later and a signed OCU app that includes the Locked Use components. For a source build, set `OPEN_COMPUTER_USE_INCLUDE_LOCKED_USE=1`.++Unlock your Mac normally, then run this command and complete the administrator prompt:++```bash+ocu locked-use enable --validation+```++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.++```bash+# Check installation and permissions+ocu locked-use status++# Disable and uninstall, restoring the original system lock-screen policy+ocu locked-use disable+```++## Required permissions++Allow these under **System Settings → Privacy & Security**:++| Component | Permissions | Purpose |+| --- | --- | --- |+| Open Computer Use | Accessibility, Screen Recording | Read and control the target app, and capture screenshots |+| OCU Guardian | Accessibility, Input Monitoring | Interact with the lock-screen UI and detect local keyboard or mouse takeover |++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:++```bash+"/Library/Application Support/OpenComputerUse/LockedUse/OCU Guardian.app/Contents/MacOS/OCUGuardian" --request-permissions+```++## What gets installed++In this table, `ROOT` means `/Library/Application Support/OpenComputerUse/LockedUse`. The main app stays in your existing OCU installation. Enabling Locked Use adds:++| Component / file | Installation path | Purpose |+| --- | --- | --- |+| OCU Guardian | `ROOT/OCU Guardian.app` | Show shields and handle unlock, relock, and local takeover |+| Broker service | `ROOT/OCULockService` | Manage authorization permits, task leases, and protection state; runs as root |+| Installer | `ROOT/OCULockInstaller` | Install, remove, and recover components; runs with administrator privileges when needed |+| Authorization plug-in | `/Library/Security/SecurityAgentPlugins/OCULockAuth.bundle` | Ask Broker whether unlock is allowed during system authentication |+| launchd service definition | `/Library/LaunchDaemons/dev.opencomputeruse.locked-use.broker.plist` | Start and maintain the Broker service |+| State files | JSON files and the `run/` directory under `ROOT/` | App-managed installation, approval, validation, and recovery records, plus local communication sockets |++Installation also registers its own authorization rule and adds a Locked Use branch to `system.login.screensaver`, preserving the existing system authentication path. Normal uninstallation restores the original rule and removes the components above.++## How the services work together++OCU controls the target app. When the Mac is locked, it first requests a task lease from Broker. Broker decides whether the task may proceed. Guardian shields the displays, interacts with the lock-screen UI, and reports protection health. Once the system starts authentication, the authorization plug-in asks Broker for permission; the system completes authentication.++Guardian also has a separate watchdog process that uses the same app. It provides backup shields and recovery if the main protection process fails. There is no additional app to install for it.++++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.diff --git a/docs/locked-use.md b/docs/locked-use.mdnew file mode 100644index 0000000..2b14d84--- /dev/null+++ b/docs/locked-use.md@@ -0,0 +1,349 @@+# macOS Locked Use(实验阶段)++目标是在已登录用户的屏幕锁定后,允许已授权客户端临时解锁 GUI 会话,同时遮蔽所有物理显示器,继续通过 AX / ScreenCaptureKit / 输入执行任务,最后重锁。++**当前仍处于实机验证阶段,生产自动解锁默认关闭。** 已实现签名 root Broker、remote Authorization 机制、Guardian / 独立 watchdog、管理员安装 / 停用 / 恢复入口,以及 OCU GUI 请求的自动租约接入。真实 loginwindow 解锁、Secure Input 硬件交付与两类 Keychain 保持尚未通过实测;不能以离线测试通过或安装成功代替这些证据。++## 当前可用入口++```sh+ocu locked-use status+ocu locked-use status --json+ocu doctor+```++诊断分别报告 AX、Screen Recording 和 Input Monitoring 的当前进程 runtime preflight,以及会话状态、系统组件是否存在、其他 Authorization 插件名称和未完成的门槛。查询不请求权限,不安装、不解锁、不锁屏;安装文件存在也不表示签名、注册或运行已验证。`enabled` 来自 root 所有的安装配置;`available` 还要求 macOS build 和组件签名哈希与实测证据匹配。批准记录匹配当前 app agent 且安装认证规则完整也是 `available` 的必要条件。没有证据时生产自动解锁保持关闭。++原生诊断由 `.app` agent 执行,与真实控制进程保持相同权限身份。源码 CLI 的开发验证应绕过已经安装的旧版本 agent:++```sh+swift build+OPEN_COMPUTER_USE_DISABLE_APP_AGENT_PROXY=1 .build/debug/OpenComputerUse locked-use status --json+```++无完成登录的控制台 GUI session、切换用户或未知会话时,真实 app 控制明确拒绝。正常锁屏中的 GUI 请求由 app agent 尝试获取受保护租约;没有可用 Broker / 批准 / 验证 profile 时立即返回错误,动作自身的 session gate 仍拒绝无租约的锁定会话。缓存的真实 AX snapshot 每次复用前重新检查会话;输入事件投递和 AX 动作 / 属性变更路径补充检查。fixture 是测试数据,不代表真实桌面,仍可用于 headless smoke。会话检查不能提供与 WindowServer 事务原子性相同的保证。++## 保护状态机++`LockedUseStateMachine` 是由独立 Broker 串行驱动的纯状态 / effect reducer。真实解锁仍需管理员验证 profile 实测;执行 effect 不构成系统成功证据。++- `idle → preparing → authorizing → unlocking → active → relocking`+- 先收到全部显示器遮蔽、输入拦截和独立 watchdog 健康证据,才发一次性许可并请求解锁。+- 许可绑定 connection UUID、用户 UID 和 audit session;只允许认证后的插件回执消费一次,5 秒失效。+- 消费许可后还要确认相同会话已解锁,才能允许工具动作。+- 单调时间计时:3 秒 heartbeat 期限、10 秒启动期限、30 秒空闲期限、300 秒绝对租约上限。真实 guardian 需独立于 GUI action 维持 heartbeat。+- `turn-ended`、EOF、JS reset / timeout 或租约结束应撤销许可并重锁;app agent 已接入 turn-ended / EOF / 空闲期限;JS reset / timeout 结束原生连接,独立 EOF 监测可停止尚在执行的租约,动作完成后才确认排空。+- 本地输入、显示器 topology generation 改变、guardian 失效或会话异常立即停止并重锁;未知输入按接管处理。+- Broker 确认许可撤销已提交、解锁尝试取消 / 排空、动作投递停止后,还需确认原会话锁定,才能释放遮蔽。原锁屏仍可见不代表排队解锁已取消。未知 / 其他用户的锁定事件不算重锁成功;失败保留保护并重试。+- 接管和异常后进入 `awaitingManualUnlock`。正常人工解锁事件才清除抑制,排队请求不能重新解锁。++## Guardian 与锁屏实测++开发构建,不安装系统组件:++```sh+./scripts/build-locked-use-guardian.sh --identity 'Developer ID Application: <your identity>'+'.build/locked-use/OCU Guardian (Dev).app/Contents/MacOS/OCUGuardian' --diagnose+'.build/locked-use/OCU Guardian (Dev).app/Contents/MacOS/OCUGuardian' --peer-self-test+```++缺少权限时显式执行同一 binary 的 `--request-permissions`,由用户在系统设置授予 Accessibility 与 Input Monitoring。`--diagnose` 本身不请求权限、不锁屏。++先单独确认所有物理显示器遮蔽与倒计时,再验证遮罩期间的动作:++```sh+python3 scripts/run-locked-use-rehearsal.py --shield-preview+```++该独立 preview 复用 rehearsal 的显示器覆盖与 WindowServer 检查,覆盖确认后显示 15 秒倒计时。输入事件仅按类型 / source PID / source state 汇总,不保存按键或文本;鼠标移动不会提前结束,Esc 立即退出。它不创建 AX fixture、不截图、不执行应用动作、不启动重锁 watchdog、不请求锁定或解锁。结束或 controller 的开发应急超时只撤掉预览;不能复用该输入策略或超时退出作为生产保护。物理屏幕需人工观察,枚举的 NSScreen 数量也可能包含虚拟显示器。++**只有用户准备好锁屏、并有人观察物理屏幕时运行:**++```sh+python3 scripts/run-locked-use-rehearsal.py --confirm-lock-test+```++测试从已正常解锁的会话开始,创建专用蓝色窗口,再使用独立、覆盖所有 NSScreen 的黑色 window 遮蔽。它检查 WindowServer 中的窗口 PID、frame、alpha、layer 和物理显示器映射,不能把 `isVisible` 单独当成已覆盖。过滤型 session event tap 不读取或记录按键内容,对所有全局输入保守接管;定向 `postToPid` 不走这条全局 stream。Secure Event Input、tap disable、显示器 topology 改变、watchdog 失效均停止测试并请求锁屏。软件 overlay 无法提供原子热插拔、系统级 overlay 或进程死亡时零泄漏的证明,必须实际观察。++`shieldReady` 后,使用 AXPress 点击专用窗口按钮,并以 ScreenCaptureKit 的 desktop-independent window filter 验证遮挡后的蓝色内容和动作前后画面变化。AX / capture 未完成时不提前宣告 quiescence。输出只有结果与状态,截图不写磁盘。最长 15 秒租约到期或本地输入都会请求重锁;只有原 UID / audit session 观测到锁定、且动作已排空,才移除遮罩。++child watchdog 与 UI event loop 分离,监测 inherited pipe 心跳;1.5 秒超时、EOF 或非法输入会独立请求重锁。该测试 watchdog 从未接收解锁许可。测试完成后,Guardian 只读取 loginwindow 的 AX role / subrole / action names,最多 300 节点、12 层、3 秒;不读取值、用户名、输入框、选中文本或密码,也不执行 loginwindow 动作。单次 AX RPC 额外有 0.5 秒 timeout,因此整个 traversal 可能比预算略长。++独立 watchdog 的人工故障注入入口:++```sh+python3 scripts/run-locked-use-rehearsal.py --confirm-watchdog-test+```++受控 AX / SCK 闭环通过后,故意阻塞 Guardian 主线程 5 秒,停止该进程的 UI loop 和 heartbeat,已有遮罩窗口保留。watchdog 用 inherited pipe 的 `S` byte 回报实际重锁请求;Guardian 恢复时必须已经观测到锁定,之后策略再次确认原 session 锁定再释放窗口,才能报告测试通过。请求回报本身不算锁定证据。该实验只覆盖主线程卡死,不证明遮罩进程被杀死、热插拔或系统 overlay 时零泄漏;人工应保持输入静止并观察物理屏幕。++开发 controller 默认提前 5 秒提示用户放开输入。rehearsal 的非正常退出 / 35 秒超时会先保留 child watchdog,同时请求重锁并观察会话状态,再清理自身测试进程组;preview 的恢复不请求锁屏。这是只供人工实验的应急路径,**不能在生产 Locked Use 中用超时移除遮罩**。rehearsal 没有改变认证规则,也不自动解锁;用户随后按普通方式解锁。++事件输出包含单调时间与 capture 阶段 / stop reason,便于区分覆盖失败、输入接管、动作失败及租约到期。同进程受控 fixture 的 AXPress 在 MainActor 上执行;AppKit 会直接在调用线程派发按钮动作,不能从后台队列调用带 MainActor 隔离的 target。`--fixture-ax-self-test` 可独立验证此路径,不遮蔽、不锁屏。++### Broker 认证组件++- `LockedUseAuthorizationRules` 生成离线安装 / 恢复计划,只对现有 OR rule 添加本项目 branch,保留原 fallback 和其他语义字段。旧计划或原规则被更改、阈值不兼容、已有本项目引用时拒绝;规划本身不执行系统写入。Installer 已实现 root 存储、互斥和写入前后校验;验证 profile 的安装 / 卸载与原规则恢复已实测,生产和故障链仍待验证。认证事务的 opaque ID 不能当作 audit session,详见 [认证边界](references/macos-locked-use-authentication.md)。++- `LockedUseNative` 用 `LOCAL_PEERTOKEN` 获得 kernel audit token,包含 PID version;不把客户端自报 PID 转成身份。+- `LockedUsePeerIdentity` 用 token 查询动态 SecCode,并验证 administrator-approved requirement。+- `LockedUseClientApprovals` 固定从 `/Library/Application Support/OpenComputerUse/LockedUse/clients.json` 读取,逐层 `openat` / `O_NOFOLLOW`,检查 root ownership、group/other 不可写与无允许修改的 extended ACL,拒绝 symlink、非 regular file、超大配置、无效 signer / team 和重复记录。不在仓库保存真实批准记录。Installer 只登记当前用户、同团队的 OCU 原生 CLI / app agent 与 Guardian;本阶段不开放任意第三方 agent 登记。+- 批准记录绑定 UID、角色、signing identifier 和 Team ID;角色按连接 endpoint 选择,不取请求 payload。批准 peer 必须启用 hardened runtime,并拒绝 get-task-allow、禁用 Library Validation、允许 DYLD 环境注入或 unsigned executable memory 等 entitlement。Developer ID 签名的 self-test 验证正确 signer / role 成功及错误 signer / role 拒绝;这不代替真实 unlock 链路验证。+- `LockedUsePermitRegistry` 使用 SecRandomCopyBytes 生成 32-byte nonce,绑定 connection UUID、attempt UUID、UID、audit session,5 秒过期,单次消费,断开撤销,重放拒绝。最多 32 个 pending permit;单个 registry 最多保存 4096 个 retired attempt;只有上一租约完全释放并可开始新租约时,Broker 才创建新 registry epoch。旧 lease ID / nonce 不能跨越 epoch。该 registry 不验证插件身份,调用它之前必须先认证 Apple SecurityAgent peer。++## Authorization 插件实验++先在普通用户进程内验证 ABI,不注册系统 right:++```sh+./scripts/build-locked-use-plugin.sh+```++产物全部在 `.build/locked-use/`:插件 bundle、ABI tests、`authorization-probe`。该插件仅支持 `preflight`,每次 `MechanismInvoke` 都返回 `kAuthorizationResultDeny`;不读取任何认证上下文,不设置密码,不执行解锁。未知机制(包括 `allow`)不能创建。++离线 `dlopen` 与 codesign 验证不证明 SecurityAgent 的 Library Validation 可以加载插件。要测试实际系统加载,需要先用自己的 Developer ID Application identity 签名:++```sh+./scripts/build-locked-use-plugin.sh --identity 'Developer ID Application: <your identity>'+sudo ./scripts/manage-locked-use-probe.sh install+.build/locked-use/authorization-probe+/usr/bin/log show --last 2m --style compact --predicate 'eventMessage CONTAINS "OpenComputerUseAuthorizationProbe invoked"'+sudo ./scripts/manage-locked-use-probe.sh uninstall+```++安装脚本是独立实验入口,不是 `ocu locked-use enable`。只注册 `dev.opencomputeruse.locked-use.preflight`,只安装自己的 bundle,不修改 `system.login.screensaver`;拒绝覆盖已有 right / bundle。注册失败会移除本次复制的 bundle。卸载前核对 right 和 bundle 仍属于实验,再删除 right、bundle 与自己的系统 staged 副本。脚本要求 root 和 Developer ID 签名,拒绝 ad-hoc 安装。不关闭 SIP / Library Validation,也不承诺仅签名即可通过系统加载限制。++探针预期返回 `errAuthorizationDenied`。**denied 也可能来自插件加载失败**,只有实际机制的固定日志 marker 才是加载证据。探针不请求 screensaver right;输出 `sessionUnlockRequested=false` 指本探针没有请求解锁,不是对桌面状态的观测。实验日志不得加入用户名、密码、Keychain 内容或授权上下文。++## 测试前清理其他插件++若诊断显示 `CodexComputerUseAuthorizationPlugin.bundle`,它是 Codex / ChatGPT 的 Locked Use Authorization 插件。优先在应用 **Settings → Computer Use → Locked use** 中关闭该功能,然后用只读命令核对:++```sh+security authorizationdb read system.login.screensaver+ls /Library/Security/SecurityAgentPlugins+```++正常清理后不应再有 `com.openai.sky.CUAService.AuthorizationPlugin.remote` 引用和 Codex 插件 bundle。`StagedPlugins` 目录本身不代表它仍启用。不要只删除 bundle,也不要把整个 screensaver right 覆盖成固定模板:其他认证产品可能也有规则。关闭后若残留,先保存规则并诊断其所有者,不在此实验中自动删除第三方组件。++## 当前实机结果++在 Apple Silicon / macOS 26.5.1 上,Developer ID 签名的独立 probe 已实际安装、调用和卸载。4 次 AuthorizationCopyRights 都返回预期 denied;SecurityAgentHelper 的固定机制日志证明插件实际执行。首次加载曾记录 platform-binary Library Validation 错误,随后同一 helper 仍执行了机制,不能仅据那条错误判定全部调用失败,也不能只凭 denied 推断加载成功。++实验后诊断 right、原 bundle 和自身 StagedPlugins 副本均已移除,screensaver right 没有变化。没有尝试真实解锁或读取用户 Keychain 项,因此这些结果不证明真实 loginwindow unlock / Keychain 保持、完整 guardian 或系统版本兼容性已通过。++## 生产 backend 的开放门槛++1. 实际 SecurityAgent 加载、正常认证不被阻塞;保留 `use-login-window-ui`。+2. 真正 loginwindow 解锁事务可由短期许可驱动;AuthorizationCopyRights 成功本身不算桌面解锁。+3. 解锁过渡、所有显示器与 Spaces、热插拔及保护进程退出时的实测遮蔽与重锁行为;软件截图无法验证物理显示泄漏。+4. AX / ScreenCaptureKit 可以捕获遮挡的目标窗口,fixture 点击 / 输入后 AX 和画面验证一致。+5. 普通密码 / Touch ID 解锁,以及 login / Data Protection Keychain 不受破坏;用测试项验证,不读取用户凭据,不做密码重置或 Keychain 修复。+6. 认证 IPC 来源、客户端登记、许可重放和撤销、并发所有者、宿主断开与接管抑制全部通过。++测试账户有助于隔离业务数据,但 Authorization 数据库和插件是系统级的;账户隔离不等同于系统隔离。实际认证实验要有可恢复的机器 / VM 和管理员操作路径。++## 参考++- [Apple Authorization 插件](https://developer.apple.com/documentation/security/extending-authorization-services-with-plug-ins)+- [AuthorizationCopyRights](https://developer.apple.com/documentation/security/authorizationcopyrights(_:_:_:_:_:))+- [NullAuthPlugin ABI 示例](https://developer.apple.com/library/archive/samplecode/NullAuthPlugin/Introduction/Intro.html)+- [Apple DTS 关于 Data Protection Keychain 的已知问题](https://developer.apple.com/forums/thread/796487):FB13128730,没有公开可靠 workaround,不能假定本系统已修复。+- [官方 Computer Use / Locked Use 设置](https://learn.chatgpt.com/docs/computer-use)+- [DispatchShield](https://github.com/VenusOne-Lee/DispatchShield):已解锁桌面遮蔽参考,不是锁屏自动解锁实现。+- [trycua Authorization 插件讨论](https://github.com/trycua/cua/issues/1744):方案参考,不是完成链路的证据。+++## 管理员安装与 OCU 接入(待实机验证)++先构建、签名组件,再将它们嵌入同一签名团队的开发 app:++```sh+scripts/build-locked-use-components.sh --identity 'Developer ID Application: <your identity>'+OPEN_COMPUTER_USE_INCLUDE_LOCKED_USE=1 scripts/build-open-computer-use-app.sh debug+'dist/Open Computer Use (Dev).app/Contents/MacOS/OpenComputerUse' locked-use settings+```++安装 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。此路径仍待系统验证。++普通 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)。++开发 Keychain 检查仅使用 `ocu/locked-use/keychain/prepare`、`verify`、`cleanup` 等原生 MCP 方法。为 login 和 Data Protection Keychain 分别创建本项目 UUID / 随机值测试项,verify 禁止弹出认证 UI,返回布尔结果与 OSStatus;不枚举、读取或修改已有用户项目。cleanup 失败会保留对象以便正常解锁后重试。独立 native fixture 与 FixtureBridge 无关,后续闭环必须走真实 AX 和 ScreenCaptureKit。+++## 崩溃恢复与双进程保护++Broker 在回复授权 / active 之前,把同一 kernel boot epoch 的旧租约、内核 peer token / code hash、解锁观察、动作排空与保护 ACK 写入 root 的 `lease-recovery.json` 并 fsync 文件和目录。私密记录从创建到原子发布均为 0600,移除继承的 extended ACL;读取时也拒绝公开权限或 ACL。**不保存、不恢复授权 permit nonce。** 同一 boot 的服务重启只继续旧事务的排空和重锁,要求正常手动解锁后才解除抑制。原进程重连必须匹配已记录的完整内核 token 与签名哈希;原生 CLI 死亡后恢复连接只能用于清理,不能继续动作。kernel reboot 会摧毁原 GUI / 排队认证事务,属于新的会话 epoch。++独立 watchdog 经私有 pipe 注册到 root,持有另一个进程的备用遮罩、过滤 tap 和硬件活动 monitor;Broker 要求两套保护健康且心跳新鲜。Guardian 主线程卡死或进程死亡时,备用窗口仍可保持遮蔽,watchdog 的 root RPC 在另一个队列执行,不能拖延 inherited heartbeat 的重锁期限。主 Guardian / watchdog 都要在原会话已锁定、事务与动作已排空后释放自己的保护并向 root 回报 ACK。新的租约和卸载都等待这些 ACK。软件窗口仍不构成系统级原子热插拔 / 所有 secure overlay / 双进程同时死亡的零泄漏证明;需针对目标系统验证。++Broker 在独立 policy 队列每秒读取本项目认证策略,主队列不等待 AuthorizationRightGet,以免阻塞正在等待 Broker 的授权机制和恢复通信。签发 / 消费许可必须有不足 2 秒的有效观察;待定 / 过期 / 失败观察拒绝新许可,失败或过期后本 epoch 撤销租约但保留恢复通道。读取时间从开始读取时计,慢请求的迟到结果不能视为新鲜策略。不会自动覆盖第三方的新规则。++## 专用真实 GUI / Keychain 验证++```sh+# 普通已解锁状态,先验证独立测试项与真实 AX / SCK。+python3 scripts/run-locked-use-native-validation.py --prepare-only --legacy-only+python3 scripts/run-locked-use-native-validation.py --unlocked-fixture-test --legacy-only++# 管理员安装验证 profile 后,由用户配合锁屏测试。+python3 scripts/run-locked-use-native-validation.py --confirm-lock-test+```++控制器保持同一原生 MCP 连接:正常解锁时创建本项目 UUID 的测试项,从真实锁屏调用固定 native validation,受保护解锁后只对签名的 `OCU Lock Demo` 执行 AXPress,检查计数器变化和前后真实 SCK 图片哈希,再读取自己的测试项。图片与 secret 只在内存;输出只有结果。结束后发送 turn-ended、观察重锁,用户正常解锁并输入 `continue`,再验证 / 清理测试项。带 `--wait-for-manual-unlock` 时控制器直接观测真实会话解锁,不需要 stdin 确认;等待本身不代表通过。备用遮罩可以通过签名 Guardian 的 `--watchdog-surface-self-test` 单独检查,不请求锁屏或解锁。任何失败都不杀 Guardian / watchdog,也不凭旧锁屏拆除保护。连接退出时无法删除的自有项目会留在 app agent 内重试正常解锁后的清理;进程死亡会丢失内存清理对象,应保留监督式测试连接直到 cleanup 完成。++Data Protection Keychain 使用受限 entitlement,需要为该 OCU bundle 匹配的 macOS Developer ID provisioning profile:++```sh+OPEN_COMPUTER_USE_PROVISIONING_PROFILE='<profile path>' \+OPEN_COMPUTER_USE_INCLUDE_LOCKED_USE=1 scripts/build-open-computer-use-app.sh debug+```++构建只从 profile 提取当前 app 自己的 App ID / Keychain group,拒绝过期、其他平台、其他 app 和带 debugging entitlement 的 profile;macOS 在进程启动时仍独立验证签名 / profile。详情见 [Apple TN3137](https://developer.apple.com/documentation/Technotes/tn3137-on-mac-keychains)。`--legacy-only` 是明确缩小范围的开发检查,不能产出生产验证证据;缺少 profile 时不能把 Data Protection 检查记为通过。++签名 native agent 的固定测试全部通过后才向 root 提交验证回报。Broker 保存组件 / OS 哈希及真实重锁、双方保护释放、手动解锁后的 Keychain 验证到 `validation-report.json`。`locked-use certify` 要求用户确认物理屏幕、Secure Input 键鼠接管、进程 / 服务故障、显示器变化以及正常密码 / Touch ID 的实测结果,再通过系统管理员认证;Installer 还独立检查完整 root 记录和当前哈希,并冻结 / 重启服务为生产 profile。此入口尚未实机通过,不能将已实现入口描述为验证完成。macOS 或组件升级会使旧证据失效;停用 / 恢复原策略后重装新组件并重新验证。++app bundle 含每次构建唯一的标识,app agent 在启动时固定捕获该标识和启动时间,避免懒初始化把旧进程误判为新构建。MCP 获取租约或验证失败仍返回对应 JSON-RPC id 的错误;不会让调用方一直等待响应。JS reset / timeout / turn-ended 关闭旧 native epoch;旧 Worker 的排队请求被丢弃,下次请求启动新的 native MCP,不重放失败的 GUI 请求。++失败恢复增加独立于 RPC / AppKit 队列的 agent deadline:独立进程 deadline 跟随已认证 Root 的启动截止 + 现有 RPC 排空余量 2 秒;默认启动上限 8 秒,显式验证 profile 的总待命上限 20 秒,准备双保护仍最多 8 秒;进入停止 / 清理或 Broker 轮询失败后最多 5 秒,重试只能缩短、不能延长已有期限。期限到达时 agent 结束自身进程,不杀用户应用或保护进程。Broker 仍须通过原进程退出、解锁工作排空和实际锁定证据决定释放双遮罩;这个期限是停止动作的上限,**不等于系统恢复可登录的实测上限**。已观测到原会话锁定时,主 / 备用保护不重复调用锁屏 SPI;等待排空仍保留遮罩。++真实实验曾出现 Broker 清理通信超时、保护持续数分钟并干扰用户正常解锁。已安全卸载验证组件并恢复原认证规则;自动解锁没有通过。下一轮锁屏测试之前,必须先验证独立 deadline、进程退出到保护释放的故障链路,以及 Broker 清理通信时延,不能继续用长时间循环锁屏定位问题。`OCUGuardian --recovery-deadline-self-test` 只阻塞自己的主线程、用独立计时结束自身进程,预期退出码 70;不调用锁屏、认证或显示遮罩。++恢复专项入口 `python3 scripts/run-locked-use-native-validation.py --confirm-recovery-test` 仅供已安装验证 profile 的人工测试:真实锁屏、创建双保护,然后由 Broker 在签发许可前直接终止事务;要求 root 回报两个保护确曾就绪,再等待实际锁定、动作排空和两个保护退出 ACK;准备失败后清理成功不算双保护恢复通过。生产 profile 拒绝此入口。输出恢复耗时与布尔结果,不创建 Keychain 项、不执行 GUI 动作,不作为自动解锁通过的证据。++`--confirm-wake-test` 只验证受保护的实际解锁并立即发送 turn-ended / 观察重锁,不操作 GUI、不捕获窗口、不访问 Keychain;它也不能生成完整生产验证证据。++快速完整开发检查:++```sh+python3 scripts/run-locked-use-native-validation.py --confirm-lock-test --legacy-only --fast --wait-for-manual-unlock+```++每轮锁屏前 `ocu/locked-use/ready` 必须观察正常解锁且双保护已释放,避免新连接沿用失败事务。`--fast` 在真实 AX / SCK 验证后立即重锁并等待双方释放 ACK,不额外保持租约。控制器将阶段耗时、固定返回码和通过结果写到 `.build/locked-use/reports/` 的私有 JSON(文件 0600);只保留白名单诊断字段,不保存原始日志、截图、字段内容或密码。该报告与生产认证证据分开,不能开放生产。++认证宿主诊断可在正常解锁、验证 profile 已安装时独立运行,无需再锁屏:++```sh+xcrun swiftc -framework Security -framework CoreGraphics experiments/LockedUse/Sources/RemoteVerificationProbe.swift -o .build/locked-use/remote-verification-probe+.build/locked-use/remote-verification-probe+```++它仅评估本项目独立 remote right,不创建租约、不请求 screensaver right、不提交密码;无租约时预期 denied。通过仍须核对实际机制日志、Broker 签名返回码和无许可 claim 被拒绝,不能仅凭 denied 判定成功。快速测试失败后,控制器先检查双保护已释放;指定自动观测手动解锁时,随后等待正常登录并重试隔离测试项清理,再保存报告,以纳入手动认证阶段的诊断。++授权插件在 macOS 14.4+ 使用 `SecTaskValidateForRequirement` 的内核进程检查,要求正确 signing ID / Team、Developer ID 验证类别、动态有效签名、hardened runtime 与 Library Validation,拒绝危险 entitlement。旧系统保留 SecCode;现代检查失败不回退。构建流程含独立签名的正确 / 错误 ID / ad hoc / get-task-allow 反例,不安装这些测试 executable。单轮日志分别记录连接、task verification、claim、consume、SetResult、阶段和停止原因;authd / loginwindow / 认证宿主原始字段仅在内存中归一化为固定诊断枚举,不保存账户或 caller。++共享遮罩采用不激活的 NSPanel(borderless + nonactivatingPanel、关闭 hidesOnDeactivate;主遮罩位于 CGShieldingWindowLevel + 1,备用低一层),避免普通窗口参与登录切换的缩放;实际 WindowServer bounds 与 CGDisplayBounds 均按 Quartz 全局坐标检查完整包含,允许大于屏幕的遮罩;任何未覆盖边缘或无效矩形仍拒绝,layer / owner / alpha / 可见性 / 拓扑检查继续保留,动画时覆盖不合格也必须重锁。+++锁屏前实时采集认证诊断,私有报告 schema 2 区分 authorizing 保护待命阶段与之后的手动恢复;permitIssuedObservedAt 单独记录实际许可签发。日志活动、机制 Allow 和实际自动解锁是不同证据;缺失日志不证明事务或 helper 不存在。采集器最长 150 秒、最多 2000 条固定诊断、单条原始记录最多 64 KiB,不保存原始字段;不可用时不改变保护或授权。仅需正常桌面观察时可执行:++```sh+python3 scripts/run-locked-use-native-validation.py --observe-auth-only --observe-seconds 5+```++该入口不需要安装验证 profile,不锁屏、不请求认证、不创建租约。当前验证实现为有界完整 AX 发布重试、唯一字段空字符串写入和一次窗口限定 session-stage 点击(双过滤器的一次性私有能力);不再执行 AXPress / Return。点击只是一项投递实验,不能据此认定认证事务或自动解锁成功。详见 [认证时序复核](references/macos-locked-use-auth-transaction-timing-review.md)。++`--confirm-wake-test` / `--confirm-recovery-test` 配合 `--wait-for-manual-unlock` 时,双方释放后继续最多 60 秒只读观察正常手动登录,不保留遮罩、不启动 GUI 验证。实时与历史日志可能重复报告同一阶段,重复 authorizing 不创建新许可窗口。++原始客户端的 SCM_RIGHTS socket 在身份复核前先检查进程退出与 EOF;断开立即拒绝,健康连接仍完整重验内核身份和签名。此检查不替代签名验证,也不保证所有 Security.framework 查询都有界;恢复后的 readiness 必须实际通过才启动下一次锁屏。++双保护就绪的 authorizing 现在是保护待命,不等于已有许可。首次合法 pluginClaim 才签发许可,截止取 claim 后 5 秒与本轮 Root 启动截止的较早值;默认等待最多 8 秒,显式验证 profile 最多 20 秒,不因唤醒、AX 探测、重复 claim 或手动登录延长。控制器关闭已退出 native 连接时容忍 BrokenPipeError,仍保存诊断报告。++会话入口事件实验使用 NSEvent.windowNumber,并通过 Guardian → watchdog 继承管道共享独立随机点击标记。双过滤器均验证来源、顺序、同目标 / 窗口 / 坐标和短时限,只放行一次 down/up;真实硬件活动不会获得豁免。能力不是认证许可,不能授权 SetResult;认证仍须插件 claim / consume 和原会话解锁观察。原 annotated-stage 实验即使 queued 成功也没有自动解锁;NSEvent 版本曾出现 RPC 超时,timer 阶段及慢签名检查已新增诊断。++Root 通过 IPC 返回绝对 uptime 截止,原生 agent 校验其有限且不超过 20 秒,并使用同一截止控制等待和独立退出余量;客户端不能延长 Root 期限。启动截止保留在日志与协议中,产品遮罩不显示认证倒计时。20 秒仅为验证 profile 的有界待命,不是 20 秒授权许可;常驻服务或 socket 生命周期也不是放行期限。参考事件还显式编码窗口内坐标和鼠标 subtype 3,本项目复用现有 SkyLight 编码器,缺符号时不投递。这是私有鼠标编码,不是解锁 / 认证 API。点击后只在原 3 秒唤醒限额内重新查找密码字段(最多额外 1.5 秒),不复用旧 AX 元素、不发第二次点击、不提交密码 / Return。++- HID 单变量实验:用户授权尝试仅将受控 down/up 投递从 session 改到 HID;复用已认证 Root 的验证 profile 开关,生产 / 旧协议保持 session。事件字段、双会话过滤的一次性能力、硬件活动接管、空写 + 单次支持确认、20 秒截止不变。新增固定 clickTap 枚举日志;此改动不保证被系统视作真实硬件或启动认证,待实测。++- 确认超时修正:扫描给候选 AX 对象设置的 50ms 消息超时会被后续 action 沿用。Apple AXUIElementPerformAction 文档明确 cannotComplete 可能源自超时 / 模态处理,但不能仅据错误码确认因果或动作未执行。session 轮先前已执行同一确认并返回成功,不是 HID 轮首次加入。验证版为单次确认独立设置最多 2 秒、裁剪到原 3 秒 UI 请求截止的超时,结束恢复扫描超时;记录配置结果、实际调用开始、调用耗时与结果。不自动重试,避免无法确认是否执行时重复提交。Root 总 20 秒截止、取消 / 排空与双保护不变。待实测比较。++## 无遮罩解锁诊断(仅管理员验证 profile)++用户明确要求拆开解锁与保护问题后,新增独立 `LockedUseUnshieldedDiagnostic`,不复用生产 guardsReady 或 GUI action 状态机。Root 只接受管理员验证 profile 下、已批准签名 UI 探针的原锁定 UID / audit session;诊断总期限 20 秒,插件首次同会话 claim 才签发最多 5 秒且裁剪到原截止的一次性许可。无守护健康 / 心跳条件,也不伪造覆盖证据。断开、认证策略失效、期限到达或许可过期撤销后不能恢复。所有应用 action、生产验证 / promotion 与正常租约入口在诊断活跃时拒绝;重启不恢复任何诊断许可。++签名工具的独立 `--unshielded-unlock-diagnostic --confirm-visible-desktop-test` 入口复用 `LockScreenInteractor`,没有构造 DisplayGuardian、遮罩、输入 tap、硬件 monitor 或 child watchdog。因此桌面若被解锁会实际可见,不能视为生产 Locked Use。它只观察原会话解锁并立即请求 / 确认重锁,最后向 Root 结束诊断;结果与私有报告始终 productionEvidenceEligible=false,不访问应用窗口 / ScreenCaptureKit / Keychain。外部控制器入口为:++```sh+python3 scripts/run-locked-use-unshielded-diagnostic.py --confirm-visible-desktop-test+```++该入口针对人为配合的单次故障定位,没有完整保护路径的进程崩溃与遮蔽保证。实现回归覆盖生产 profile 拒绝、原 session / role 绑定、跨 audit session / 重复 claim / 许可重放、晚到许可裁剪、5 秒过期 / 20 秒过期 / 取消不可重启、非原会话结束与 GUI / 生产验证拒绝。当前 Swift 266 项(1 跳过、0 失败)通过,真实诊断待安装运行。+++无遮罩诊断的实际结果:首轮存在 Touch ID 手动认证与许可窗口重叠,不算自动解锁;随后不手动介入的 20 秒复测没有解锁或许可消费。控制器按原生 uptime 记录事件,并标记许可窗口内的 Touch ID match。AXConfirm 返回 success、插件放行和自动解锁必须分别验证,不能相互替代。+++独立无遮罩诊断现用固定 Return HID 按下 / 松开替代 AXConfirm,要求唯一且已聚焦、可写的密码框及签名 / 原锁定会话再次校验,只发送一次。该键盘实验尚未实测,不在受保护解锁路径启用;保护过滤器当前没有键盘许可。派发成功仅表示排队,必须另外观察 loginwindow 提交、插件许可与原会话实际解锁。+++Return 独立无遮罩诊断已实测跑通:空写 / 点击后对聚焦的唯一密码框发送单对 Return,loginwindow 提交认证、OCU 插件消费许可、原会话解锁后立即重锁,报告中无 Touch ID match。它仅证明本轮无保护的解锁 / 重锁链,不替代受保护 GUI / 捕获 / 故障验收。认证规则一度变更后 Broker 会持续关闭该进程周期的解锁接受能力;恢复规则本身不能重开,须完整复核后经管理员重启服务。+++受保护管理员验证 profile 现支持独立 Return 一次性能力:主 / watchdog 两个 session tap 必须各自验证原锁定会话、来源 PID 和随机 tag、固定 keyCode 36、无修饰 / repeat、5 秒有效期与 250ms 成对时限。实际派发前还需唯一密码框焦点、空写与 Apple loginwindow 签名复查。任何硬件接管或停止均撤销;默认生产 profile 仍不签发键盘能力。完整 AX / SCK / 重锁已在管理员验证 profile 的 legacy-only 轮通过;不作为生产 promotion 证据。+++遮罩采用居中 1.5× 不透明面板,为 loginwindow 解锁动画的缩放留出实际不透明覆盖余量;健康检查不容忍任何实际未覆盖边缘,仍严格比较 WindowServer 实际边界与显示器。受保护首轮已进入插件放行,但动画缩小遮罩导致 guardLost,overscan 修正版随后通过真实受保护 GUI / SCK / 重锁闭环,未发生覆盖失败。+++overscan 修正版首次完整实测通过:Return → loginwindow 认证 → 插件一次性许可 → 原会话实际解锁 → 双保护健康下 AX 修改固定 fixture 且 SCK 图像变化 → 重锁 → 双保护释放。手动正常解锁后的自有隔离 legacy Keychain 项验证 / 清理通过。物理屏幕持续覆盖待现场确认;本轮未覆盖 Data Protection Keychain、Secure Input 硬件接管和组件死亡 / 显示器变化,因此 productionEvidenceEligible=false,生产保持关闭,尚未合并。+++停留计时复测:--fast 会将停留设为 0,因此首轮双保护就绪至释放约 3.68 秒。使用 --hold-seconds 5 后,AX / SCK 通过再实际停留 5.002 秒,随后 turnEnded 正常重锁和双保护释放;双保护就绪至释放约 7.78 秒。控制器现输出停留开始 / 结束及单调时钟实际耗时;现场观察不应把初始“5 秒后锁屏”提示当作遮罩停留承诺。+++主 / watchdog 遮罩使用同一固定展示:`Open Computer Use is Using Your Mac` 与 `Press any key or click to unlock`。认证、操作和排空不切换文字,停止后冻结最后一帧。共享视图从各屏幕的 NSWorkspace 壁纸文件读取并模糊处理,只查询当前本地账户的 OpenDirectory 头像,叠加 bundle 内的 OCU 图标;不截图桌面,不读密码或 Keychain。资源缺失时使用不透明备用背景 / 默认头像,窗口仍为 alpha=1 的 1.5× overscan,覆盖检查和重锁呈现屏障保持不变。隔离诊断可显示额外说明;15 秒不锁屏 preview 的倒计时只记录在日志中。+++用户现场确认显示状态修正版整体正常、两块物理屏幕覆盖稳定;退出前轻微文字跳动另以冻结最后一帧修正,待现场复测。+++撤罩另需主 / watchdog 各自确认锁屏呈现屏障:原会话 locked、已排空,并观察到经 Apple 签名验证的 loginwindow 不透明屏蔽层窗口覆盖所有活动显示器,几何 / 拓扑连续稳定至少 1 秒。仅会话锁定不再允许释放。该元数据条件不是 compositor 原子交接证明,仍须现场验证;缺少证据时继续保留保护,不重新发送锁屏请求去打断正常恢复登录。+++撤罩屏障首次实测因将 loginwindow layer 与极高 CGShieldingWindowLevel 比较而永久等待,已纠正为 screenSaverWindow 级别。新增独立本地恢复:Root 排空后已观察原会话锁定且真实 IOHID 活动发生,才把输入交回系统 loginwindow;仍维持遮蔽,直到用户实际解锁同一会话才释放,不反复重锁。此恢复不签发远程 GUI 许可;软件超时和模拟输入不能启动它。新呈现屏障 / 恢复仍待现场验收,不能视为生产可用。++### 遮罩外观渲染++签名 Guardian 的 `--render-shield <output.png>` 在当前主屏壁纸和头像上离屏渲染外观,不创建保护租约、输入 tap 或锁屏请求。输出可能包含用户头像及壁纸,应仅留在忽略的本地构建目录,不上传或纳入版本控制。动态 / 视频壁纸无法解码静态帧时使用备用背景。`--shield-preview` 则对全部显示器执行 15 秒覆盖检查,Esc 可提前结束,无自动解锁 / 锁定动作。++品牌遮罩物理双屏闭环已现场通过:插件一次性放行、原会话自动解锁、遮罩下 AX/SCK 图像变化、保持 5.005 秒、重锁与双保护撤罩、正常手动解锁和隔离数据清理;用户确认无桌面闪现。主进程在创建窗口前完成 AppKit 初始化,只在保护准备完成后运行 live heartbeat,原有覆盖与超时要求保持。额外虚拟屏的窗口偏移曾导致安全中止,本轮由用户移除后不再纳入验收,不能据此宣称虚拟屏兼容。该轮 legacy-only 不生成生产资格。++录屏演示可在完整验证命令上增加 `--keep-fixture`。仅在验证成功、手动解锁及隔离数据清理完成后保留 Increment Counter 原生窗口,便于查看实际计数;Broker 租约、保护窗口和 agent 连接按原流程结束。失败仍关闭测试目标。录屏后请手动退出该测试 app,再启动下一轮,避免多个同 bundle 目标影响 AX 定位。该开关不延长受保护操作时间,也不生成生产资格。++```sh+python3 scripts/run-locked-use-native-validation.py --confirm-lock-test --legacy-only --hold-seconds 5 --wait-for-manual-unlock --keep-fixture+```++退出 ACK 由 main / watchdog 在各自真实撤罩后,经同一签名与 audit-token 的恢复连接提交,最多 3 次并检查回复;不以窗口进程死亡冒充 ACK。周期报告的 IPC 失败不再跳过 terminal 确认。控制器最多等待 8 秒观测 Root 的双 ACK,此等待不生成许可或代替呈现屏障。演示的 `--keep-fixture` 目标采用独立进程 session 和空 stdin,因此 runner 结束不带走原有计数窗口;已实测脚本退出后只读 AX 仍见 `Counter: 1`。+++## 独立 main PR 的集成边界++Locked Use 从 awesome-extension 单独提取,不依赖该分支的虚拟工作区、电源模块或 AX diff。main 的普通 `get_app_state` 返回完整树,原生固定验证继续读取完整 Counter;未来引入增量输出时必须显式请求完整快照。失败后控制器先发送 turn-ended 再等待双保护释放。main 的 sky_click / sky_key 原生投递及菜单动作也执行会话 / 租约检查;租约内窗口捕获明确走 ScreenCaptureKit,普通非租约捕获沿用 main 的硬件截图优先路径。MCP 断开仍执行 endSession 恢复 main 的 agent display 和窗口 occlusion 状态。++该独立 PR 的验证为回归测试、签名构建和 ABI 检查;先前双物理屏实测是 awesome-extension 的证据,不代表本次分支重新进行真实锁屏验收。生产 backend 继续关闭。+++## 组件命名与正式构建++| 组件 | 正式构建 | 开发构建 |+| --- | --- | --- |+| 主 App | Open Computer Use.app | Open Computer Use (Dev).app |+| 遮罩 App | OCU Guardian.app | OCU Guardian (Dev).app |+| root 服务 | OCULockService | OCULockService |+| 安装工具 | OCULockInstaller | OCULockInstaller |+| 授权插件 | OCULockAuth.bundle | OCULockAuth.bundle |++Watchdog 是 OCUGuardian 的另一进程模式,不新增 App。OCU Lock Demo (Dev).app 和 OCULockProbe.bundle 仅供开发验证,正式 App 不打包这两项。正式组件构建输出 components-release,开发仍输出 components;主 App 按自身配置选择对应组件,内嵌及系统安装的 Guardian 路径固定为 OCU Guardian.app,plist 中的显示名称保留配置差异。++签名 ID、launchd Label 与 remote right 保持已有内部标识;授权机制同步改为 OCULockAuth:remote。Guardian 的内部签名 ID 保留原标识,即使正式显示名称不带 Dev。此命名调整不开放生产后端。++```sh+scripts/build-locked-use-components.sh --identity "$IDENTITY" --configuration release+OPEN_COMPUTER_USE_INCLUDE_LOCKED_USE=1 OPEN_COMPUTER_USE_CODESIGN_MODE=identity \+OPEN_COMPUTER_USE_CODESIGN_IDENTITY="$IDENTITY" scripts/build-open-computer-use-app.sh release+```++已有旧验证安装先在正常解锁、保护已结束时执行新 App 的 `locked-use disable`;新 App 会校验并调用旧安装中的签名 installer 完成其原始卸载,再执行新版本 enable。安装器发现旧插件残留时拒绝安装,不直接改名在用插件或自动替换认证链。旧版本生产资格不能复用,新制品须重新验证。diff --git a/docs/locked-use.zh-CN.md b/docs/locked-use.zh-CN.mdnew file mode 100644index 0000000..25a22e1--- /dev/null+++ b/docs/locked-use.zh-CN.md@@ -0,0 +1,69 @@+# Locked Use++[English](locked-use.en.md)++Locked Use 可以让 Agent 在 Mac 锁屏时继续操作 GUI。期间所有屏幕都有遮罩,任务结束或你移动鼠标、按键时,会重新锁屏,再由你正常解锁。++## 如何开启++需要 macOS 14 或更新版本,以及包含 Locked Use 组件的签名 OCU App。自行构建时设置 `OPEN_COMPUTER_USE_INCLUDE_LOCKED_USE=1`。++先正常解锁 Mac,然后运行下面的命令,完成管理员授权:++```bash+ocu locked-use enable --validation+```++这个命令会安装所需组件并开启验证模式,不需要手动修改配置。Locked Use 不会随 OCU 的普通权限引导自动开启。++目前先用验证模式测试。正式模式的完整验证尚未完成;`ocu locked-use enable` 不带 `--validation` 时,缺少有效验证记录就不会自动解锁。++```bash+# 查看安装和权限状态+ocu locked-use status++# 停用并卸载,恢复原来的系统锁屏认证规则+ocu locked-use disable+```++## 需要什么权限++在「系统设置 → 隐私与安全性」中允许:++| 组件 | 权限 | 用途 |+| --- | --- | --- |+| Open Computer Use | 辅助功能、屏幕录制 | 读取和操作目标 App,获取截图 |+| OCU Guardian | 辅助功能、输入监控 | 操作锁屏 UI,检测本地键鼠接管 |++安装、卸载还需要管理员授权。Broker 和授权插件不需要单独申请上述权限。开发版的 App 名称会带 `(Dev)`。++安装后运行下面的命令,弹出 Guardian 的权限申请,再按系统提示授权:++```bash+"/Library/Application Support/OpenComputerUse/LockedUse/OCU Guardian.app/Contents/MacOS/OCUGuardian" --request-permissions+```++## 会安装什么++下表中的 `ROOT` 指 `/Library/Application Support/OpenComputerUse/LockedUse`。主 App 沿用你已有的 OCU 安装,开启 Locked Use 时会新增:++| 组件 / 文件 | 安装位置 | 用途 |+| --- | --- | --- |+| OCU Guardian | `ROOT/OCU Guardian.app` | 显示遮罩,处理解锁、重锁和本地接管 |+| Broker 服务 | `ROOT/OCULockService` | 管理授权许可、任务租约和保护状态,以 root 身份运行 |+| 安装器 | `ROOT/OCULockInstaller` | 安装、卸载和恢复组件,按需以管理员权限运行 |+| 授权插件 | `/Library/Security/SecurityAgentPlugins/OCULockAuth.bundle` | 系统认证时向 Broker 查询是否允许解锁 |+| launchd 服务定义 | `/Library/LaunchDaemons/dev.opencomputeruse.locked-use.broker.plist` | 启动并维护 Broker 服务 |+| 状态文件 | `ROOT/` 下的 JSON 文件与 `run/` 目录 | 保存安装、批准、验证及恢复记录和本地通信 socket,由程序维护 |++安装还会登记自己的授权规则,并为 `system.login.screensaver` 加入 Locked Use 分支,保留系统原有的认证方式。正常卸载会恢复原规则并移除上面的组件。++## 这些服务怎么配合++OCU 负责实际操作目标 App。锁屏时,它先向 Broker 申请任务租约。Broker 决定是否允许任务继续;Guardian 负责遮住屏幕、操作锁屏 UI,并持续报告保护状态。系统发起认证后,授权插件向 Broker 查询许可,认证仍由系统完成。++Guardian 还有一个独立的 watchdog 进程,使用同一个 App,负责主保护进程异常时的备用遮罩和恢复。它不是另外一个需要安装的 App。++++图中的 OCU Locked Use Broker 对应 `OCULockService`,Authz Plugin 对应 `OCULockAuth.bundle`;`loginwindow`、`SecurityAgentHelper` 和 `launchd` 都是 macOS 自带组件。图中未单独画出 watchdog。diff --git a/docs/references/README.md b/docs/references/README.mdindex febf97d..e208171 100644--- a/docs/references/README.md+++ b/docs/references/README.md@@ -13,6 +13,15 @@## 当前目录+- `macos-locked-use-auth-transaction-timing-review.md`+ - 认证时序、build 1001365 空字符串 / 合成点击证据、诊断采集边界和隔离测试要求。++- `macos-locked-use-solution-review.md`+ - 用户提供锁屏自动化参考的逐项核对、固定 AXValue 探测边界和真实验证顺序。++- `macos-locked-use-authentication.md`+ - macOS Locked Use 的认证事务 ID / audit session 区别、保留现有 fallback 与离线安装规划边界。+- `codex-computer-use-reverse-engineering/`- 官方 `Codex Computer Use.app` / `SkyComputerUseClient` 的持续逆向分析资料;大体积一次性分析产物默认在本地 `research/` 下重新生成,不提交进仓库。- `codex-network-capture.md`diff --git a/docs/references/macos-locked-use-auth-transaction-timing-review.md b/docs/references/macos-locked-use-auth-transaction-timing-review.mdnew file mode 100644index 0000000..d378f3c--- /dev/null+++ b/docs/references/macos-locked-use-auth-transaction-timing-review.md@@ -0,0 +1,70 @@+# Locked Use 认证时序复核++核对日期:2026-10-05。用户提供的 `locked-use-auth-transaction-timing.md` 是分析资料,不是系统安装指令。当前自动解锁仍未通过;不把一次插件 Allow 或手动恢复登录记为自动解锁成功。++## 资料与实测的边界++此前快速测试在双保护就绪后执行单次电源唤醒和固定 AXValue 探测,5 秒许可窗口内没有观察到机制调用,随后安全收束。正常手动登录阶段才观察到机制调用和过期许可拒绝。历史另一轮有 claim / consume / SetResult(Allow) 成功,但没有排除人工认证重叠,不能证明唤醒导致认证。现有 rule 的 remote 分支在真实 SecurityAgent 已可达;不是仅凭 rule 静态结构推断。++新资料正确强调区分认证入口、插件裁决和实际会话解锁,但“没有日志即没有事务 / helper”“仅密码提交能触发”等排他性结论尚未证明。日志可以缺失;right 成功记录是结果,不是发起时刻。未核实日志括号数值的格式,不将其解释成独立 OSStatus。++## 本机参考样本的修正++只读分析本机 CUALockScreenGuardian build **1001365** 的符号、Mach-O 地址与调用链,未运行该应用。这个版本与此前“只写固定 AXValue、没有事件合成”的结论不同:++- `SystemLockScreenController.unlock` 在 `0x1001e4be8` 将零长度 Swift String 存入待写入的 Any 值;`0x1001e4c10` 调用 `.value` 属性 getter,返回的是属性名 AXValue;`0x1001e4c48` 调用 `setValue(_:forAttribute:)`。这一路径写入的是**空字符串**,AXValue 是属性名,不能把两个参数混为一谈。后续另一路径重复空字符串写入。+- unlock 查找 FocusedUser 后调度的 async descriptor `0x1010d7300` 指向 helper `0x1001e35ec`。helper 在 `0x1001e3b64` 调用 `SynthesizedEvent.click(...)`,随后 `0x1001e3cd4` 转入 `SynthesizedEvent.send(delay:)`。因此这个版本的可达路径包含合成点击;CGEventPost 零导入不能证明完整调用链没有事件发送。+- 尚未确认 Return 提交、该点击的实际认证效果或 Keychain 行为。不能从这些静态证据直接宣布已经找到完整自动解锁方案,也不能泛化到其他 build。++大体积二进制 / 反汇编留在私有忽略目录,不提交供应商二进制、原始系统日志或账户数据。固定 AXValue 探针是历史实现,当前版本见末尾更新;没有加入私有解锁 SPI。++## 本轮实现与测试++控制器在锁屏之前启动只读 debug log stream,白名单归一化 authd right 求值 / 机制、loginwindow 本地提交 / Touch ID / 认证求值 / Keychain 固定故障标记、SecurityAgentHelper 日志活动。记录上限 2000 条,单条原始记录上限 64 KiB,流最长 150 秒;只在内存处理原始记录,报告只保存固定枚举及经过白名单验证的本项目日志。采集失败不改变认证或保护状态。缺失事件不证明不存在。++私有报告 schema 2 按 Broker authorizing 开始、relocking / awaitingManualUnlock / idle 结束分窗,保留 unlocking 阶段的 SetResult,排除之后的手动恢复阶段;窗口内本地认证标记仍需核对,不能仅凭 Allow 自动归因。新增被动观察模式,不锁屏、不请求授权、不创建租约。++主 / 备用保护复用 Quartz 全局坐标的完整包含检查:允许遮罩大于屏幕,拒绝任何未覆盖边缘、非有限 / 无效矩形和实际缩小到 90% 的窗口;其余身份、层级、alpha、可见性和拓扑检查继续保留。并未放宽实际覆盖要求,也未证明登录切换时的缩放已消失。++离线 Swift 251 项(1 项跳过、0 失败)、Python 报告 10 项、rehearsal 5 项通过;签名组件构建、remote ABI / 内核签名正反例通过。不锁屏 surface 自检通过;5 秒被动采集完成,无授权或锁屏请求。本轮没有安装验证规则、没有真实自动解锁测试。++## 下一轮实际验证条件++先在独立测试账户 / 测试 Mac 或 macOS VM 验证空字符串清理与合成点击的作用(隔离环境是开发建议,不是 Apple API 的规定),逐步确认认证求值是否开始、插件是否放行及会话是否真正可用;没有证据前不发送 Return。每轮继续使用短许可和已验证双保护释放,失败不延长锁屏循环。使用隔离 Keychain 测试项并检查正常登录后的访问,不能因为插件没有调用 Keychain 就认为系统没有改变它。++重新完整核对[上游故障报告](https://github.com/openai/codex/issues/40226):它记录插件介入后 SecKeychainLogin 失败、后续屏幕解锁跳过 Keychain 解锁,导致当前登录会话无法访问凭据;报告者明确称文件完整、哈希稳定、重启并密码登录恢复。报告没有空输入证据,也没有证明 Keychain 被重设。此前将它写成空输入导致重设不准确,已纠正。隔离环境仍是减少开发故障影响的建议,不能引用此报告宣称会永久丢失凭据或强制该环境。++[Apple DTS 的 screenUnlockMode 说明](https://developer.apple.com/forums/thread/737268)针对旧式 SFAuthorizationPluginView 插件与 UI 兼容问题,不证明本项目非 UI remote 机制必须设置该全局偏好。本轮不修改它。[trycua 的提案](https://github.com/trycua/cua/issues/1744)也不是已验证的自动解锁实现。++生产保持关闭;Data Protection Keychain、Secure Input、真实进程 / Broker 故障、显示器变化与完整自动闭环仍未完成,不能合并或开放生产。++## 官方 API 核对补充++[SetResult](https://developer.apple.com/documentation/security/authorizationcallbacks/setresult) 定义机制授权结果:Allow 后继续剩余机制,全部允许才授权成功;没有承诺会解锁 GUI / Keychain,也没有规定重设 Keychain。++[Apple Security 公开源码](https://github.com/apple-oss-distributions/Security/blob/main/OSX/libsecurity_keychain/lib/SecKeychain.cpp) 区分 SecKeychainLogin 的 login / stash 路径与 SecKeychainResetLogin 的重设路径。公开代码说明登录关联的 Keychain 处理存在,但不是当前 macOS loginwindow 的完整源码,不能据此断言每次屏幕解锁如何选择分支。++[Apple Support](https://support.apple.com/guide/keychain-access/kyca2429/mac) 说明用户登录密码与 login Keychain 密码及重设的关系;其上下文是登录 / 密码变更,不能直接外推为插件 Allow 会重设。当前应验证的是 GUI 解锁后 Keychain 是否保持可用,而不是把它当作实现所需的凭据环节。本轮仅资料核对,未执行认证 / 锁屏 / Keychain API。++2026-10-06 更新:用户要求在当前账户持续迭代;验证路径已改为 3 秒 AX 完整发布重试、唯一候选空字符串写入、一次 FocusedUser AXPress,替代固定 AXValue 探针。没有加入 Return / 全局事件;不以 AX 返回成功算认证开始。此前固定探针边界是历史实现,不再代表当前验证版本。实测结果见执行计划。++2026-10-06 后续复核:参考 build 的 send 路径在 0x1007150cc 调用 0x10021875c(CGEventAPI.post(_:tap:)),传入 tap=1,封装经缓存函数指针发送事件。这支持会话级合成点击路径,CGEventPost 零导入不能排除动态发送;仍不证明认证效果。我们之前的 postToPid 点击 / Return 均没有观察到机制调用,已撤回。验证实验改用公开 annotated application stage、显式目标 PID / 窗口字段、唯一有效几何的一次点击;保留两级会话过滤和硬件监测。此路由与参考 tap=1 不同,尚待实测,不能声称照搬或保证成功。[Apple 的 stage 定义](https://developer.apple.com/documentation/coregraphics/cgeventtaplocation/cgannotatedsessioneventtap) 和 [post API](https://developer.apple.com/documentation/coregraphics/cgevent/post(tap:)) 只说明投递位置,不保证锁屏认证被触发。++许可模型改为保护待命 → 首次合法插件 claim → 签发 / 消费许可;保留原 8 秒启动截止,晚签发不会延长测试锁屏。待命实测完整 AX 树和空写返回成功,但原截止内没有机制,仍无法证明自动解锁。agent 独立上限增加现有 2 秒 RPC 排空余量,控制器修复 BrokenPipeError 掩盖失败与报告丢失。++后续验证版本改用参考一致的 session stage,不再绕过两个会话过滤器。Guardian 通过继承私有管道向 watchdog 传递独立随机标记;两个过滤器各只接受一次短时、有序、同目标 / 窗口 / 坐标的 mouse down/up,且要求 Guardian 来源与无 Shift / Control / Option / Command 点击修饰键。PID 本身不能放行,真实硬件活动保持独立接管。这是事件传递实验,不是认证许可或解锁成功证据。纯策略的错误标记、错误来源、过期、重复、目标改变和撤销回归通过;真实过滤与认证效果仍需分开判定。++2026-10-06 时限与编码补充:socket 长期存活只证明 Broker 常驻,不能推出许可始终有效;本项目 Broker 同样常驻,但本轮 lease 有界。显式验证 profile 改为最多 20 秒保护待命(准备仍 8 秒),首次 claim 才签发最多 5 秒许可并裁剪到原截止,硬件接管立即撤销。参考 mouseEvent 在 0x1007144c8 调用 0x10022c4cc,即 WindowServerSPI.setWindowLocation;之前仅有全球 / 屏幕坐标还缺窗口内坐标。同时参考设置 field 7 subtype=3。已复用现有 CGEventSetWindowLocation 编码器并加入该 subtype,不能把这段私有鼠标编码称为发起认证 API。待实测验证点击后 AX / 认证的变化。++- 2026-10-06:20 秒窗口 / 私有窗口坐标编码实测:双过滤器放行 down/up,点击约 200ms 后重新扫描出现唯一 UserPasswordTextField,可写且空写成功;启动约 20 秒后 unlockTimeout,未观察到机制 / 许可。双方释放 ACK 约失败后 0.15 秒,随后 Touch ID 手动解锁触发真正的 right 求值与 remote 机制;此时 Broker 已 awaitingManualUnlock 并正确拒绝,不算自动解锁。修复测试控制器复用旧常驻 agent 的问题,每轮采用新独立 namespace。当前瓶颈是可交互密码 UI 到授权链之间,非 5 秒许可提前过期或 guardLost。+- 下一验证版仅管理员验证 profile 在唯一真实密码字段支持 AXConfirm 且空写成功时尝试一次确认;Root hello 显式传递开关,默认与旧协议关闭,未知动作不盲试,不合成全局 Return。新增固定布尔 / OSStatus 日志;同时修复报告 PATTERNS 重复 Watchdog 键覆盖导致部分退出原因丢失。待签名构建与实际测试,不作为成功证据。++- 确认实验实测:点击后约 200ms 唯一真实密码框出现;空写成功,字段明确支持 AXConfirm,单次 AXConfirm 返回 success。仍等满原 20 秒截止,没有观察到 right 求值 / 机制 / 许可;失败后约 0.17 秒确认双保护释放,随后用户 Touch ID 解锁才出现 right 求值与 remote 机制。Root 此时正确拒绝过期 claim,普通解锁成功。不可把本轮算作自动解锁;后续关键未知是无用户凭据条件下 loginwindow 如何进入 screensaver right 求值,不再仅延长等待或重复等价 UI 动作。只读检查参考 InstallerTool / service 未找到 screenUnlockMode 字符串(不证明完整实现不存在间接路径),本机该偏好未设置。实验结束已卸载并恢复原认证策略;生产关闭、尚未合并。++- HID 单变量实验:用户授权尝试仅将受控 down/up 投递从 session 改到 HID;复用已认证 Root 的验证 profile 开关,生产 / 旧协议保持 session。事件字段、双会话过滤的一次性能力、硬件活动接管、空写 + 单次支持确认、20 秒截止不变。新增固定 clickTap 枚举日志;此改动不保证被系统视作真实硬件或启动认证,待实测。++- HID 实测已完成:明确 clickTap=hid,双 session 过滤器放行同一对 down/up;点击后先短暂 AX 发布不完整,再出现唯一真实密码框,空写成功且声明支持 AXConfirm,但单次确认返回 cannotComplete (-25204)。20 秒截止内无观察到的 right 求值 / 机制 / 许可 / 自动解锁;失败后约 0.22 秒收到双保护释放 ACK,用户随后正常手动解锁才触发 remote 机制。不能宣布 HID 活动假设成立,或仅凭此轮失败排除所有 HID 路径。完整 Swift 261 项(1 跳过、0 失败)、报告 15 项通过;签名 / ABI / 内核身份正反例和 app 构建通过。未合并,生产关闭。++- 确认超时修正:扫描给候选 AX 对象设置的 50ms 消息超时会被后续 action 沿用。Apple AXUIElementPerformAction 文档明确 cannotComplete 可能源自超时 / 模态处理,但不能仅据错误码确认因果或动作未执行。session 轮先前已执行同一确认并返回成功,不是 HID 轮首次加入。验证版为单次确认独立设置最多 2 秒、裁剪到原 3 秒 UI 请求截止的超时,结束恢复扫描超时;记录配置结果、实际调用开始、调用耗时与结果。不自动重试,避免无法确认是否执行时重复提交。Root 总 20 秒截止、取消 / 排空与双保护不变。待实测比较。++- 超时分离首次实测:2 秒动作超时配置成功,AXConfirm 实际 37ms 返回 success;之后仍未观察到 right 求值 / 机制 / 许可。因此不能确认上一轮 -25204 唯一源自 50ms,也不能以确认返回成功推出认证已提交。本轮总起始约 18.9 秒出现 guardLost,主 Guardian 私有状态持续报告遮罩 / tap / watchdog 健康,收到 root stopRequested 后退出;失败后约 0.25 秒确认双保护释放、正常手动解锁。新增 Broker 两类报告 age / watchdogProtected 固定诊断,进一步区分 IPC 陈旧与真实遮罩不健康;新增只读按钮 enabled 计数与密码框焦点布尔,明确没有收集标题、标识字符串或值。修正等待期间每秒常规 300 秒 active 标签覆盖 20 秒启动倒计时的问题,只有观察到解锁后显示 active 标签。确认只有一次,无模糊结果重试。系统验证版已卸载并恢复原规则,下一诊断版待复测。diff --git a/docs/references/macos-locked-use-authentication.md b/docs/references/macos-locked-use-authentication.mdnew file mode 100644index 0000000..a1e9e6e--- /dev/null+++ b/docs/references/macos-locked-use-authentication.md@@ -0,0 +1,17 @@+# macOS Locked Use 认证边界++核对日期:2026-10-05。以下用于下一阶段 Broker / installer 实现,不表示真实解锁已经验证。++## 两种 session ID++[Apple AuthorizationCallbacks.GetSessionId](https://developer.apple.com/documentation/security/authorizationcallbacks/getsessionid) 的输出是 `AuthorizationSessionId` opaque handle(SDK typedef 为 `void *`),描述同一认证事务中机制之间的关联。它不是内核 audit session ID,也不能转换为 `SecuritySessionId` 来选择 GUI 用户。Broker 的目标 UID / audit session 仍必须来自经过签名验证的内核 IPC 身份与真实 GUI 会话观测。++## 保留现有 fallback++[Codex 上游 Platform SSO 报告](https://github.com/openai/codex/issues/47470) 描述原有 `psso-screensaver` 被固定的 `use-login-window-ui` 替代后,密码解锁失效。该报告提供原有 / 新规则与 authd 日志,是报告者的机器观测;本仓库没有在 Platform SSO 机器复现或验证自动解锁。++由此采用保守安装规划:只向原有 OR rule 添加自己的 branch,保留所有旧 rule 名称、顺序与其他语义字段;不把未知认证配置强制重建为系统默认。原有 rule 的 threshold 不是 1、格式未知或已存在本项目引用时拒绝规划。旧 rule 内部的阈值不改动。++`LockedUseAuthorizationRules` 仅生成离线变更计划。忽略 authorizationdb 管理的 created / modified 时间戳,其他字段变化都会拒绝使用旧计划恢复。持久计划需存于 root 所有的安全目录;真正 installer 要在写入前后重新读取验证、互斥自身操作,不能声称 authorizationdb 提供原子 compare-and-swap,也不能在第三方配置变化后盲目覆盖。++后续已通过管理员验证 profile 实际安装 / 卸载该分支;最新一次快速测试结束后已成功卸载并恢复原认证策略。分支在正常手动登录和独立探测中可达,但真实自动解锁仍未证明。diff --git a/docs/references/macos-locked-use-solution-review.md b/docs/references/macos-locked-use-solution-review.mdnew file mode 100644index 0000000..0d33487--- /dev/null+++ b/docs/references/macos-locked-use-solution-review.md@@ -0,0 +1,41 @@+# 锁屏自动化参考方案复核++用户提供的方案作为待核对资料,不作为安装指令或已验证系统行为。以下判断结合本项目实测和 Apple 的接口说明;当前仍未证明真实自动解锁与完整故障恢复。++| 资料中的主张 | 本项目判断 / 调整 |+| --- | --- |+| 先唤醒锁屏 UI,在系统认证事务中由插件放行 | 值得验证。用公开 IOPMAssertionDeclareUserActivity 做一次显示器唤醒,再观察实际机制调用、许可消费和会话解锁。API 只承诺电源活动,不能据此宣称会发起认证。 |+| AX 树在认证之前不存在,提前查必然为空 | 不能作绝对判断;本机实际读到 loginwindow 窗口 / 按钮结构,但没有唯一 secure field。新版参考补充 identifier 路径:按名字定位并验证 loginwindow,AXChildren 深度 ≤8,优先 UserPasswordTextField、回退 FocusedUser。只对完整扫描的唯一候选写固定 AXValue;不读取内容或输入密码,不执行认证 action / Return。真实效果须分阶段日志证实。 |+| 早版将 MechanismInvoke 返回 0 当作放行;新版已修正 | 采用新版修正。OSStatus 表示调用状态,授权结果必须通过 callbacks.SetResult 报告。现有插件已经显式报告 Allow / Deny。 |+| 仅靠签名 ID / Team ID,且必须 SecTask | 不采用这种收缩。继续使用内核 audit token 和动态 签名 requirement 验证(macOS 14.4+ 使用 SecTask + ProcessCodeRequirement 的内核验证,包含 Developer ID 验证类别、正确 ID / 团队和有效运行时标志;旧系统保留 SecCode),检查 hardened runtime、危险 entitlement、角色与会话;不能仅把签名字符串当作有效签名证明。 |+| 单向固定 ALLOW 字串即可 | 不采用。继续使用有界协议、双向签名验证、一次性随机许可及会话 / 原客户端 / 租约绑定;短字串不能表达取消和排空。 |+| 整体 screensaver rule 改为 evaluate-mechanisms | 不覆盖原认证流程;保持原 OR fallback,只添加独立 remote right。插件不可用时仍须保留系统密码认证路径。 |+| 不读写 Keychain 就能保证 Keychain 正常 | 未被证明。login 与 Data Protection Keychain 是不同实现,必须用自身测试项覆盖临时解锁、重锁、正常解锁后的访问;不能仅凭插件代码没有 Keychain API 宣称无影响。 |+| 排除自身 PID 的输入 | 不直接采用。继续对硬件活动和过滤 tap 保持严格接管;PID 标签本身不应成为绕过实体输入保护的凭据。 |+| 撤罩、释放断言后再锁定 | 不采用。先撤销许可、停止动作、排空可能在途解锁,观测原会话锁定后才撤罩;保活断言随保护释放。 |+| socket 目录 0700 / 文件 0600 | 要结合跨用户 SecurityAgent 与 root Broker 拓扑。当前系统路径不可由普通用户写入,连接准入由内核身份和签名控制;不能照搬单用户私有目录而使系统 helper 无法连接。 |++## 本轮验证顺序++1. 离线证明认证服务器卡住时 Broker 的协调队列仍可处理恢复,策略过期时不会签发许可。+2. 独立进程 deadline 与纯恢复 barrier 回归。+3. 仅限管理员验证 profile 的 recovery-only 实机事务:不签发任何解锁许可,确认两个保护 ACK 与恢复耗时。+4. 单次显示器唤醒实测:按日志区分“唤醒成功”“机制调用”“许可消费”“实际解锁”,失败后验证正常登录恢复。+5. 自动解锁通过后继续 AX / SCK、两种 Keychain、Secure Input、故障和显示器变化。全部通过后再合并 / 开放生产。++## 一手依据++- [Apple AuthorizationCallbacks.SetResult](https://developer.apple.com/documentation/security/authorizationcallbacks/setresult):异步 MechanismInvoke 也需要显式结果回报。+- [Apple IOPMAssertionDeclareUserActivity](https://developer.apple.com/documentation/iokit/1557127-iopmassertiondeclareuseractivity):声明活动、开启显示器;没有自动授权保证。+- [Apple IOPMLib 源码接口](https://github.com/apple-oss-distributions/IOKitUser/blob/main/pwr_mgt.subproj/IOPMLib.h):显示保活、断言超时与释放接口。+- [Apple TN3137](https://developer.apple.com/documentation/Technotes/tn3137-on-mac-keychains):两种 Mac Keychain 实现及 Data Protection 的用户上下文 / profile 约束。++系统行为随 macOS 版本变化。以上 API 文档不能替代本机真实锁屏和正常密码 / Touch ID 恢复验证。++此前用户补充的分析认为参考样本只写固定 AXValue、没有事件合成;本机 build 1001365 的后续调用链核对发现实际写入空字符串、AXValue 是属性名,并有可达的 SynthesizedEvent.click / send。该差异不能推广到所有版本,详见 [认证时序复核](macos-locked-use-auth-transaction-timing-review.md)。本项目仍保留取消可阻断的固定 AXValue 观察性探测,没有据此加入空输入认证。Keychain API 仅存在于隔离验证测试项路径,不参与解锁;系统认证自身的 Keychain 影响仍需验证。++## 探针与裁决链的证据区分++固定 AXValue 写入成功记录为锁屏 UI 探针成功,不能单独证明插件已执行、许可被消费或 GUI 会话已解锁。此前将缺少机制日志直接称为“认证没有开始”不够准确;应区分界面可交互、authd right 求值、机制调用、Broker 裁决、SetResult 回报及真实会话。++本项目不是只有 screensaver 的两分支数组:独立 remote right 已定义 class=evaluate-mechanisms 和 mechanisms。正常手动登录与不锁屏探测都曾实际调用插件,证明分支 / bundle 可达。wire 是 4 字节网络序长度加 JSON,不采用 ALLOW 文本或换行协议。插件显式 SetResult;新的正负裁决日志不保留 nonce、身份或原始字段。历史恢复握手的预期拒绝和无租约诊断不能混算为一次解锁的失败原因。diff --git a/docs/releases/feature-release-notes.md b/docs/releases/feature-release-notes.mdindex 7bc0518..93b69a6 100644--- a/docs/releases/feature-release-notes.md+++ b/docs/releases/feature-release-notes.md@@ -4,6 +4,7 @@| 日期 | 功能域 | 用户价值 | 变更摘要 || --- | --- | --- | --- |+| 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()`,按文字、角色和窗口查找元素,返回完整性元数据;查询索引仅在同一会话内有效,操作前重新验证目标和位置。 || 2026-10-10 | macOS 截图配置 | 普通用户可用 `ocu config` 持久化截图偏好,无需维护 shell ENV。 | 新增用户 JSON、ENV 覆盖、PNG/JPG/WebP 格式、明确的超大缩小/丢弃开关、最小总像素数过滤、质量/SCK 超时;取消字节预算缩小,支持关闭长边上限,省略截图时说明原因,保留 #65 捕获路径与坐标映射。 || 2026-10-10 | 结构化权限查询 | 宿主可以读取和轮询 macOS 授权状态,无需解析文本或重复弹引导。 | 新增 `ocu doctor --json`,输出权限布尔值、`allGranted` 和缺失权限列表;普通 `doctor` 保留权限引导,Linux/Windows 明确返回不支持。 |diff --git a/experiments/LockedUse/AuthorizationPlugin/Plugin.c b/experiments/LockedUse/AuthorizationPlugin/Plugin.cnew file mode 100644index 0000000..8aa0680--- /dev/null+++ b/experiments/LockedUse/AuthorizationPlugin/Plugin.c@@ -0,0 +1,75 @@+/* Experimental ABI probe only. No unlock mechanism is shipped until the+ * loginwindow + Keychain + guardian gates pass. This plugin ALWAYS denies.+ * It does not read or write username/password/authentication context. */+#include <Security/AuthorizationPlugin.h>+#include <os/log.h>+#include <stdlib.h>+#include <string.h>++struct Plugin { const AuthorizationCallbacks *callbacks; };+struct Mechanism { struct Plugin *plugin; AuthorizationEngineRef engine; };++static OSStatus destroyPlugin(AuthorizationPluginRef ref) {+ if (!ref) return errAuthorizationInvalidRef;+ free((void *)ref);+ return errAuthorizationSuccess;+}++static OSStatus createMechanism(AuthorizationPluginRef ref, AuthorizationEngineRef engine,+ AuthorizationMechanismId name, AuthorizationMechanismRef *out) {+ if (!out) return errAuthorizationInvalidPointer;+ *out = NULL;+ if (!ref || !engine || !name) return errAuthorizationInvalidRef;+ if (strcmp(name, "preflight") != 0) return errAuthorizationInternal;+ struct Mechanism *mechanism = calloc(1, sizeof(*mechanism));+ if (!mechanism) return errAuthorizationInternal;+ mechanism->plugin = (struct Plugin *)ref;+ mechanism->engine = engine;+ *out = (AuthorizationMechanismRef)mechanism;+ return errAuthorizationSuccess;+}++static OSStatus invokeMechanism(AuthorizationMechanismRef ref) {+ if (!ref) return errAuthorizationInvalidRef;+ struct Mechanism *mechanism = (struct Mechanism *)ref;+ os_log(OS_LOG_DEFAULT, "OpenComputerUseAuthorizationProbe invoked; denying without reading credentials");+ return mechanism->plugin->callbacks->SetResult(mechanism->engine, kAuthorizationResultDeny);+}++static OSStatus deactivateMechanism(AuthorizationMechanismRef ref) {+ if (!ref) return errAuthorizationInvalidRef;+ struct Mechanism *mechanism = (struct Mechanism *)ref;+ return mechanism->plugin->callbacks->DidDeactivate(mechanism->engine);+}++static OSStatus destroyMechanism(AuthorizationMechanismRef ref) {+ if (!ref) return errAuthorizationInvalidRef;+ free((void *)ref);+ return errAuthorizationSuccess;+}++static const AuthorizationPluginInterface interface = {+ .version = kAuthorizationPluginInterfaceVersion,+ .PluginDestroy = destroyPlugin,+ .MechanismCreate = createMechanism,+ .MechanismInvoke = invokeMechanism,+ .MechanismDeactivate = deactivateMechanism,+ .MechanismDestroy = destroyMechanism+};++__attribute__((visibility("default")))+OSStatus AuthorizationPluginCreate(const AuthorizationCallbacks *callbacks,+ AuthorizationPluginRef *outPlugin,+ const AuthorizationPluginInterface **outInterface) {+ if (outPlugin) *outPlugin = NULL;+ if (outInterface) *outInterface = NULL;+ if (!callbacks || !outPlugin || !outInterface || !callbacks->SetResult || !callbacks->DidDeactivate)+ return errAuthorizationInvalidPointer;+ if (callbacks->version < 1) return errAuthorizationInternal;+ struct Plugin *plugin = calloc(1, sizeof(*plugin));+ if (!plugin) return errAuthorizationInternal;+ plugin->callbacks = callbacks;+ *outPlugin = (AuthorizationPluginRef)plugin;+ *outInterface = &interface;+ return errAuthorizationSuccess;+}diff --git a/experiments/LockedUse/AuthorizationPlugin/PluginTests.c b/experiments/LockedUse/AuthorizationPlugin/PluginTests.cnew file mode 100644index 0000000..a29d327--- /dev/null+++ b/experiments/LockedUse/AuthorizationPlugin/PluginTests.c@@ -0,0 +1,48 @@+#include <Security/AuthorizationPlugin.h>+#include <assert.h>+#include <dlfcn.h>+#include <stdio.h>++static unsigned results = 0, deactivations = 0;+static AuthorizationResult lastResult;+static OSStatus setResult(AuthorizationEngineRef engine, AuthorizationResult result) {+ assert(engine);+ results++;+ lastResult = result;+ return errAuthorizationSuccess;+}+static OSStatus deactivate(AuthorizationEngineRef engine) {+ assert(engine);+ deactivations++;+ return errAuthorizationSuccess;+}++int main(int argc, char **argv) {+ assert(argc == 2);+ void *handle = dlopen(argv[1], RTLD_NOW | RTLD_LOCAL);+ if (!handle) { fprintf(stderr, "%s\n", dlerror()); return 1; }+ typedef OSStatus (*Create)(const AuthorizationCallbacks *, AuthorizationPluginRef *, const AuthorizationPluginInterface **);+ Create create = (Create)dlsym(handle, "AuthorizationPluginCreate");+ assert(create);+ AuthorizationCallbacks callbacks = { .version = 1, .SetResult = setResult, .DidDeactivate = deactivate };+ AuthorizationPluginRef plugin = NULL;+ const AuthorizationPluginInterface *interface = NULL;+ assert(create(NULL, &plugin, &interface) != errAuthorizationSuccess);+ assert(!plugin && !interface);+ assert(create(&callbacks, &plugin, &interface) == errAuthorizationSuccess);+ assert(interface->version == kAuthorizationPluginInterfaceVersion);+ AuthorizationMechanismRef mechanism = NULL;+ // A probe may never be repurposed as an "allow" mechanism by changing auth.db.+ assert(interface->MechanismCreate(plugin, (AuthorizationEngineRef)&callbacks, "allow", &mechanism) != errAuthorizationSuccess);+ assert(!mechanism);+ assert(interface->MechanismCreate(plugin, (AuthorizationEngineRef)&callbacks, "preflight", &mechanism) == errAuthorizationSuccess);+ assert(interface->MechanismInvoke(mechanism) == errAuthorizationSuccess);+ assert(results == 1 && lastResult == kAuthorizationResultDeny);+ assert(interface->MechanismDeactivate(mechanism) == errAuthorizationSuccess);+ assert(deactivations == 1);+ assert(interface->MechanismDestroy(mechanism) == errAuthorizationSuccess);+ assert(interface->PluginDestroy(plugin) == errAuthorizationSuccess);+ assert(dlclose(handle) == 0);+ puts("Authorization plugin ABI probe passed; mechanism denied; no system rights evaluated.");+ return 0;+}diff --git a/experiments/LockedUse/AuthorizationPlugin/RemotePlugin.m b/experiments/LockedUse/AuthorizationPlugin/RemotePlugin.mnew file mode 100644index 0000000..2cabfe5--- /dev/null+++ b/experiments/LockedUse/AuthorizationPlugin/RemotePlugin.m@@ -0,0 +1,261 @@+// Minimal remote mechanism. No credential context/hints are read or written.+// The diagnostic deny-only plugin remains a separate artifact/right.+#import <Foundation/Foundation.h>+#import <Security/AuthorizationPlugin.h>+#import <Security/Security.h>+#include "LockedUseNative.h"+#include <arpa/inet.h>+#include <fcntl.h>+#include <poll.h>+#include <sys/socket.h>+#include <sys/un.h>+#include <time.h>+#include <unistd.h>+#include <os/log.h>++#ifndef OCU_SIGNING_TEAM+#error "Remote mechanism requires a fixed Developer ID signing team"+#endif++extern int32_t ocu_verify_broker_task(const void *auditToken, const char *team);++static const char *socketPath = "/Library/Application Support/OpenComputerUse/LockedUse/run/plugin.sock";+static double monotonic(void) {+ struct timespec value;+ if (clock_gettime(CLOCK_MONOTONIC, &value) != 0) return -1;+ return value.tv_sec + value.tv_nsec / 1e9;+}++static bool ready(int fd, short events, double deadline) {+ for (;;) {+ double remaining = deadline - monotonic();+ if (remaining <= 0 || remaining > 3) return false;+ struct pollfd entry = {.fd = fd, .events = events};+ int result = poll(&entry, 1, (int)(remaining * 1000 + 1));+ if (result < 0 && errno == EINTR) continue;+ return result > 0 && !(entry.revents & POLLNVAL);+ }+}++static bool transfer(int fd, void *bytes, size_t length, bool sending, double deadline) {+ size_t offset = 0;+ while (offset < length) {+ if (!ready(fd, sending ? POLLOUT : POLLIN, deadline)) return false;+ ssize_t count = sending ? write(fd, (char *)bytes + offset, length - offset)+ : read(fd, (char *)bytes + offset, length - offset);+ if (count < 0 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) continue;+ if (count <= 0) return false;+ offset += (size_t)count;+ }+ return true;+}++static bool verifyBroker(int fd) {+ OCUPeerIdentity peer;+ if (ocu_copy_peer_identity(fd, &peer) != 0 || peer.effective_user_id != 0) return false;+ int32_t taskStatus = ocu_verify_broker_task(peer.audit_token, OCU_SIGNING_TEAM);+ os_log_t taskLogger = os_log_create("dev.opencomputeruse.locked-use", "AuthorizationMechanism");+ os_log_with_type(taskLogger, OS_LOG_TYPE_DEFAULT, "brokerTaskVerification status=%{public}d", taskStatus);+ // Older systems retain the legacy verifier. A modern failure never falls+ // back to a weaker identifier-only or on-disk check.+ if (taskStatus != -1) return taskStatus == 1;+ NSData *audit = [NSData dataWithBytes:peer.audit_token length:sizeof(peer.audit_token)];+ NSDictionary *attributes = @{(__bridge NSString *)kSecGuestAttributeAudit: audit};+ SecCodeRef guest = NULL;+ SecRequirementRef requirement = NULL;+ SecStaticCodeRef staticCode = NULL;+ CFDictionaryRef info = NULL;+ CFStringRef text = CFSTR("identifier \"dev.opencomputeruse.locked-use.broker\" and anchor apple generic and certificate leaf[subject.OU] = \"" OCU_SIGNING_TEAM "\"");+ os_log_t logger = os_log_create("dev.opencomputeruse.locked-use", "AuthorizationMechanism");+ OSStatus guestStatus = SecCodeCopyGuestWithAttributes(NULL, (__bridge CFDictionaryRef)attributes, kSecCSDefaultFlags, &guest);+ OSStatus requirementStatus = errAuthorizationInternal, validityStatus = errAuthorizationInternal;+ OSStatus staticStatus = errAuthorizationInternal, infoStatus = errAuthorizationInternal;+ if (guestStatus == errSecSuccess) requirementStatus = SecRequirementCreateWithString(text, kSecCSDefaultFlags, &requirement);+ if (requirementStatus == errSecSuccess) validityStatus = SecCodeCheckValidity(guest, kSecCSDefaultFlags, requirement);+ if (validityStatus == errSecSuccess) staticStatus = SecCodeCopyStaticCode(guest, kSecCSDefaultFlags, &staticCode);+ if (staticStatus == errSecSuccess) infoStatus = SecCodeCopySigningInformation(staticCode, kSecCSSigningInformation, &info);+ os_log_with_type(logger, OS_LOG_TYPE_DEFAULT, "brokerVerification guest=%{public}d requirement=%{public}d validity=%{public}d static=%{public}d info=%{public}d",+ (int)guestStatus, (int)requirementStatus, (int)validityStatus, (int)staticStatus, (int)infoStatus);+ bool valid = infoStatus == errSecSuccess;+ if (valid) {+ NSDictionary *metadata = (__bridge NSDictionary *)info;+ unsigned int flags = [metadata[(__bridge NSString *)kSecCodeInfoFlags] unsignedIntValue];+ NSDictionary *entitlements = metadata[(__bridge NSString *)kSecCodeInfoEntitlementsDict];+ valid = (flags & kSecCodeSignatureRuntime) != 0;+ for (NSString *key in @[@"get-task-allow", @"com.apple.security.get-task-allow",+ @"com.apple.security.cs.disable-library-validation", @"com.apple.security.cs.allow-dyld-environment-variables",+ @"com.apple.security.cs.allow-unsigned-executable-memory"]) {+ if ([entitlements[key] boolValue]) valid = false;+ }+ valid = valid && SecCodeCheckValidity(guest, kSecCSDefaultFlags, requirement) == errSecSuccess;+ }+ if (info) CFRelease(info);+ if (staticCode) CFRelease(staticCode);+ if (requirement) CFRelease(requirement);+ if (guest) CFRelease(guest);+ return valid;+}++static NSDictionary *exchange(int fd, NSString *operation, NSDictionary *extra, double deadline) {+ NSString *identifier = NSUUID.UUID.UUIDString;+ NSMutableDictionary *request = [@{@"version": @1, @"id": identifier, @"operation": operation} mutableCopy];+ [request addEntriesFromDictionary:extra ?: @{}];+ NSData *payload = [NSJSONSerialization dataWithJSONObject:request options:0 error:NULL];+ if (!payload || payload.length == 0 || payload.length > 16384) return nil;+ uint32_t size = htonl((uint32_t)payload.length);+ if (!transfer(fd, &size, sizeof(size), true, deadline)+ || !transfer(fd, (void *)payload.bytes, payload.length, true, deadline)+ || !transfer(fd, &size, sizeof(size), false, deadline)) return nil;+ size = ntohl(size);+ if (size == 0 || size > 16384) return nil;+ NSMutableData *response = [NSMutableData dataWithLength:size];+ if (!transfer(fd, response.mutableBytes, size, false, deadline)) return nil;+ id decoded = [NSJSONSerialization JSONObjectWithData:response options:0 error:NULL];+ if (![decoded isKindOfClass:NSDictionary.class] || ![decoded[@"id"] isEqual:identifier]+ || ![decoded[@"version"] isEqual:@1]) return nil;+ return decoded;+}++@interface OCUPlugin : NSObject+@property(nonatomic, assign) const AuthorizationCallbacks *callbacks;+@end+@implementation OCUPlugin+@end++@interface OCUMechanism : NSObject+@property(nonatomic, strong) OCUPlugin *plugin;+@property(nonatomic, strong) NSRecursiveLock *mutex;+@property(nonatomic, assign) AuthorizationEngineRef engine;+@property(nonatomic, assign) int descriptor;+@property(nonatomic, assign) BOOL cancelled;+@property(nonatomic, assign) BOOL invoked;+@end+@implementation OCUMechanism+@end++static OSStatus pluginDestroy(AuthorizationPluginRef ref) {+ if (!ref) return errAuthorizationInvalidRef;+ (void)CFBridgingRelease(ref);+ return errAuthorizationSuccess;+}++static OSStatus mechanismCreate(AuthorizationPluginRef pluginRef, AuthorizationEngineRef engine,+ AuthorizationMechanismId name, AuthorizationMechanismRef *out) {+ if (!out) return errAuthorizationInvalidPointer;+ *out = NULL;+ if (!pluginRef || !engine || !name) return errAuthorizationInvalidRef;+ if (strcmp(name, "remote") != 0) return errAuthorizationInternal;+ OCUMechanism *mechanism = [OCUMechanism new];+ mechanism.plugin = (__bridge OCUPlugin *)pluginRef;+ mechanism.mutex = [NSRecursiveLock new];+ mechanism.engine = engine;+ mechanism.descriptor = -1;+ *out = (AuthorizationMechanismRef)CFBridgingRetain(mechanism);+ return errAuthorizationSuccess;+}++static OSStatus mechanismInvoke(AuthorizationMechanismRef ref) {+ if (!ref) return errAuthorizationInvalidRef;+ @autoreleasepool {+ OCUMechanism *mechanism = (__bridge OCUMechanism *)ref;+ os_log_t logger = os_log_create("dev.opencomputeruse.locked-use", "AuthorizationMechanism");+ os_log_with_type(logger, OS_LOG_TYPE_DEFAULT, "mechanismInvoked");+ [mechanism.mutex lock];+ if (mechanism.cancelled || mechanism.invoked) {+ [mechanism.mutex unlock]; return errAuthorizationInternal;+ }+ mechanism.invoked = YES;+ int fd = socket(AF_UNIX, SOCK_STREAM, 0);+ mechanism.descriptor = fd;+ [mechanism.mutex unlock];+ BOOL allowed = NO;+ double deadline = monotonic() + 2;+ if (fd >= 0) {+ int value = 1;+ struct sockaddr_un address = {.sun_family = AF_UNIX, .sun_len = sizeof(struct sockaddr_un)};+ strlcpy(address.sun_path, socketPath, sizeof(address.sun_path));+ BOOL configured = fcntl(fd, F_SETFD, FD_CLOEXEC) == 0 && fcntl(fd, F_SETFL, O_NONBLOCK) == 0+ && setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &value, sizeof(value)) == 0;+ int result = configured ? connect(fd, (struct sockaddr *)&address, sizeof(address)) : -1;+ if (result < 0 && configured && errno == EINPROGRESS && ready(fd, POLLOUT, deadline)) {+ int failure = 0;+ socklen_t size = sizeof(failure);+ if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &failure, &size) == 0 && failure == 0) result = 0;+ }+ os_log_with_type(logger, OS_LOG_TYPE_DEFAULT, "brokerConnect connected=%{public}d", result == 0);+ if (result == 0 && verifyBroker(fd)) {+ os_log_with_type(logger, OS_LOG_TYPE_DEFAULT, "brokerVerified");+ NSDictionary *claim = exchange(fd, @"pluginClaim", nil, deadline);+ os_log_with_type(logger, OS_LOG_TYPE_DEFAULT, "pluginClaim replied=%{public}d authorizing=%{public}d denied=%{public}d", claim != nil, [claim[@"phase"] isEqual:@"authorizing"], [claim[@"result"] isEqual:@"denied"]);+ NSString *lease = [claim[@"leaseID"] isKindOfClass:NSString.class] ? claim[@"leaseID"] : nil;+ NSString *token = [claim[@"token"] isKindOfClass:NSString.class] ? claim[@"token"] : nil;+ NSData *nonce = token ? [[NSData alloc] initWithBase64EncodedString:token options:0] : nil;+ if ([claim[@"phase"] isEqual:@"authorizing"] && lease && [[NSUUID alloc] initWithUUIDString:lease] && nonce.length == 32) {+ NSDictionary *reply = exchange(fd, @"pluginConsume", @{@"leaseID": lease, @"token": token}, deadline);+ allowed = [reply[@"result"] isEqual:@"authorized"] && [reply[@"phase"] isEqual:@"unlocking"];+ os_log_with_type(logger, OS_LOG_TYPE_DEFAULT, "pluginConsume replied=%{public}d allowed=%{public}d", reply != nil, allowed);+ }+ }+ }+ [mechanism.mutex lock];+ OSStatus status = errAuthorizationSuccess;+ if (!mechanism.cancelled) {+ status = mechanism.plugin.callbacks->SetResult(mechanism.engine,+ allowed ? kAuthorizationResultAllow : kAuthorizationResultDeny);+ os_log_with_type(logger, OS_LOG_TYPE_DEFAULT, "resultDelivered allowed=%{public}d status=%{public}d", allowed, (int)status);+ }+ [mechanism.mutex unlock];+ if (fd >= 0) {+ // Best effort completion, bounded by the same absolute deadline.+ (void)exchange(fd, @"pluginFinished", allowed && status == errAuthorizationSuccess+ ? nil : @{@"stopReason": @"operationFailed"}, deadline);+ [mechanism.mutex lock];+ mechanism.descriptor = -1;+ close(fd);+ [mechanism.mutex unlock];+ }+ return status;+ }+}++static OSStatus mechanismDeactivate(AuthorizationMechanismRef ref) {+ if (!ref) return errAuthorizationInvalidRef;+ OCUMechanism *mechanism = (__bridge OCUMechanism *)ref;+ [mechanism.mutex lock];+ mechanism.cancelled = YES;+ if (mechanism.descriptor >= 0) shutdown(mechanism.descriptor, SHUT_RDWR);+ OSStatus status = mechanism.plugin.callbacks->DidDeactivate(mechanism.engine);+ [mechanism.mutex unlock];+ return status;+}++static OSStatus mechanismDestroy(AuthorizationMechanismRef ref) {+ if (!ref) return errAuthorizationInvalidRef;+ OCUMechanism *mechanism = CFBridgingRelease(ref);+ [mechanism.mutex lock];+ mechanism.cancelled = YES;+ if (mechanism.descriptor >= 0) shutdown(mechanism.descriptor, SHUT_RDWR);+ [mechanism.mutex unlock];+ return errAuthorizationSuccess;+}++static const AuthorizationPluginInterface interface = {+ .version = kAuthorizationPluginInterfaceVersion,+ .PluginDestroy = pluginDestroy, .MechanismCreate = mechanismCreate,+ .MechanismInvoke = mechanismInvoke, .MechanismDeactivate = mechanismDeactivate,+ .MechanismDestroy = mechanismDestroy+};++__attribute__((visibility("default")))+OSStatus AuthorizationPluginCreate(const AuthorizationCallbacks *callbacks,+ AuthorizationPluginRef *out, const AuthorizationPluginInterface **outInterface) {+ if (out) *out = NULL;+ if (outInterface) *outInterface = NULL;+ if (!callbacks || !out || !outInterface || callbacks->version < 1 || !callbacks->SetResult || !callbacks->DidDeactivate)+ return errAuthorizationInvalidPointer;+ OCUPlugin *plugin = [OCUPlugin new];+ plugin.callbacks = callbacks;+ *out = (AuthorizationPluginRef)CFBridgingRetain(plugin);+ *outInterface = &interface;+ return errAuthorizationSuccess;+}diff --git a/experiments/LockedUse/AuthorizationPlugin/RemotePluginTests.c b/experiments/LockedUse/AuthorizationPlugin/RemotePluginTests.cnew file mode 100644index 0000000..4a42618--- /dev/null+++ b/experiments/LockedUse/AuthorizationPlugin/RemotePluginTests.c@@ -0,0 +1,52 @@+#include <Security/AuthorizationPlugin.h>+#include <assert.h>+#include <dlfcn.h>+#include <stdio.h>++static unsigned results, deactivations;+static OSStatus setResult(AuthorizationEngineRef engine, AuthorizationResult result) {+ assert(engine && result == kAuthorizationResultDeny);+ results++;+ return errAuthorizationSuccess;+}+static OSStatus deactivate(AuthorizationEngineRef engine) {+ assert(engine); deactivations++;+ return errAuthorizationSuccess;+}++int main(int argc, char **argv) {+ assert(argc == 2);+ void *handle = dlopen(argv[1], RTLD_NOW | RTLD_LOCAL);+ if (!handle) { fprintf(stderr, "%s\n", dlerror()); return 1; }+ typedef OSStatus (*Create)(const AuthorizationCallbacks *, AuthorizationPluginRef *, const AuthorizationPluginInterface **);+ Create create = (Create)dlsym(handle, "AuthorizationPluginCreate");+ assert(create);+ AuthorizationCallbacks callbacks = {.version = 1, .SetResult = setResult, .DidDeactivate = deactivate};+ AuthorizationPluginRef plugin = NULL;+ const AuthorizationPluginInterface *interface = NULL;+ assert(create(NULL, &plugin, &interface) != errAuthorizationSuccess);+ assert(create(&callbacks, &plugin, &interface) == errAuthorizationSuccess);+ AuthorizationMechanismRef mechanism = NULL;+ 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.+ // Even if a Broker is installed it must not grant this caller a permit.+ assert(interface->MechanismInvoke(mechanism) == errAuthorizationSuccess);+ assert(results == 1);+ assert(interface->MechanismInvoke(mechanism) != errAuthorizationSuccess);+ assert(results == 1);+ assert(interface->MechanismDeactivate(mechanism) == errAuthorizationSuccess);+ assert(deactivations == 1);+ assert(interface->MechanismDestroy(mechanism) == errAuthorizationSuccess);+ // Cancellation before invoke must never allow or send a late result.+ assert(interface->MechanismCreate(plugin, (AuthorizationEngineRef)&callbacks, "remote", &mechanism) == errAuthorizationSuccess);+ assert(interface->MechanismDeactivate(mechanism) == errAuthorizationSuccess);+ assert(interface->MechanismInvoke(mechanism) != errAuthorizationSuccess);+ assert(results == 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.");+ return 0;+}diff --git a/experiments/LockedUse/AuthorizationPlugin/TaskVerifier.swift b/experiments/LockedUse/AuthorizationPlugin/TaskVerifier.swiftnew file mode 100644index 0000000..725eca8--- /dev/null+++ b/experiments/LockedUse/AuthorizationPlugin/TaskVerifier.swift@@ -0,0 +1,34 @@+import Foundation+import Security+import LightweightCodeRequirements++/// Kernel-backed live verification avoids CMS/keychain work in the lock-screen+/// helper. IDs alone are insufficient: require Developer ID validation and+/// live hardened/signature flags, then reject injection entitlements.+@_cdecl("ocu_verify_broker_task")+public func verifyBrokerTask(_ bytes: UnsafeRawPointer?, _ teamBytes: UnsafePointer<CChar>?) -> Int32 {+ guard #available(macOS 14.4, *) else { return -1 }+ guard let bytes, let teamBytes else { return -2 }+ let team = String(cString: teamBytes)+ guard team.utf8.count == 10, team.utf8.allSatisfy({ (48...57).contains($0) || (65...90).contains($0) }) else { return -2 }+ var token = audit_token_t()+ withUnsafeMutableBytes(of: &token) { $0.copyMemory(from: UnsafeRawBufferPointer(start: bytes, count: 32)) }+ guard let task = SecTaskCreateWithAuditToken(nil, token) else { return -3 }+ do {+ let requirement = try ProcessCodeRequirement.allOf {+ SigningIdentifier("dev.opencomputeruse.locked-use.broker")+ TeamIdentifier(team)+ ValidationCategory(.developerID)+ ProcessCodeSigningFlags.isSuperset(of: [.isDynamicallyValid, .isSigned, .isHardenedRuntimeEnforced, .isLibraryValidationRequired])+ }+ guard try SecTaskValidateForRequirement(task: task, requirement: requirement) else { return 0 }+ for key in ["get-task-allow", "com.apple.security.get-task-allow", "com.apple.security.cs.disable-library-validation",+ "com.apple.security.cs.allow-dyld-environment-variables", "com.apple.security.cs.allow-unsigned-executable-memory"] {+ var error: Unmanaged<CFError>?+ let value = SecTaskCopyValueForEntitlement(task, key as CFString, &error)+ if error != nil { _ = error?.takeRetainedValue(); return -3 }+ if (value as? NSNumber)?.boolValue == true { return 0 }+ }+ return try SecTaskValidateForRequirement(task: task, requirement: requirement) ? 1 : 0+ } catch { return -3 }+}diff --git a/experiments/LockedUse/AuthorizationPlugin/TaskVerifierTests.c b/experiments/LockedUse/AuthorizationPlugin/TaskVerifierTests.cnew file mode 100644index 0000000..e9decbe--- /dev/null+++ b/experiments/LockedUse/AuthorizationPlugin/TaskVerifierTests.c@@ -0,0 +1,24 @@+#include <assert.h>+#include <mach/mach.h>+#include <stdio.h>+#include <stdint.h>+#include <string.h>+extern int32_t ocu_verify_broker_task(const void *, const char *);+#ifndef OCU_SIGNING_TEAM+#error "Signing team required"+#endif+int main(int argc, char **argv) {+ assert(argc == 2);+ audit_token_t token = {0};+ mach_msg_type_number_t count = TASK_AUDIT_TOKEN_COUNT;+ assert(task_info(mach_task_self(), TASK_AUDIT_TOKEN, (task_info_t)&token, &count) == KERN_SUCCESS);+ int32_t result = ocu_verify_broker_task(&token, OCU_SIGNING_TEAM);+ if (result == -1) { puts("Kernel task verifier unavailable; legacy verification remains required."); return 0; }+ assert(result == (strcmp(argv[1], "match") == 0 ? 1 : 0));+ assert(ocu_verify_broker_task(&token, "AAAAAAAAAA") == 0);+ assert(ocu_verify_broker_task(&token, "malformed") == -2);+ assert(ocu_verify_broker_task(NULL, OCU_SIGNING_TEAM) == -2);++ puts("Kernel task verifier: live signature/category/runtime identity checked; wrong team and malformed input rejected.");+ return 0;+}diff --git a/experiments/LockedUse/Sources/AuthorizationProbe.swift b/experiments/LockedUse/Sources/AuthorizationProbe.swiftnew file mode 100644index 0000000..21d7982--- /dev/null+++ b/experiments/LockedUse/Sources/AuthorizationProbe.swift@@ -0,0 +1,32 @@+import Foundation+import Security++// Runs only when deliberately invoked after installing the isolated diagnostic+// right. A denied result alone is NOT proof that SecurityAgent loaded the plugin;+// verify its fixed unified-log marker as described in the experiment README.+let rightName = "dev.opencomputeruse.locked-use.preflight"+var authorization: AuthorizationRef?+let created = AuthorizationCreate(nil, nil, [], &authorization)+guard created == errAuthorizationSuccess, let authorization else {+ print("AuthorizationCreate failed: \(created)")+ exit(1)+}+defer { AuthorizationFree(authorization, [.destroyRights]) }+let status = rightName.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(authorization, &rights, nil, [.extendRights, .destroyRights], nil)+ }+}+let report: [String: Any] = [+ "right": rightName,+ "status": status,+ "expectedDenied": status == errAuthorizationDenied,+ "pluginLoaded": "unverified; check the fixed plugin log marker",+ "sessionUnlockRequested": false,+ "note": "No screensaver right requested and no credentials supplied."+]+print(String(decoding: try JSONSerialization.data(withJSONObject: report, options: [.prettyPrinted, .sortedKeys]), as: UTF8.self))+// Permission success would contradict the deny-only experiment.+exit(status == errAuthorizationDenied ? 0 : 1)diff --git a/experiments/LockedUse/Sources/Broker/BrokerMain.swift b/experiments/LockedUse/Sources/Broker/BrokerMain.swiftnew file mode 100644index 0000000..4418e21--- /dev/null+++ b/experiments/LockedUse/Sources/Broker/BrokerMain.swift@@ -0,0 +1,486 @@+import Darwin+import Dispatch+import Foundation+import LockedUseNative+import OpenComputerUseKit+import os+import Security++@main+enum BrokerMain {+ static func main() {+ do {+ guard CommandLine.arguments.count == 2,+ ["--serve", "--serve-validation"].contains(CommandLine.arguments[1]), geteuid() == 0 else {+ throw BrokerError.message("Usage: OCULockService --serve | --serve-validation (administrator installed service only)")+ }+ let approvals = try LockedUseClientApprovals.loadInstalled()+ 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)+ let server = try BrokerServer(approvals: approvals, enabled: configuration.enabled,+ backendValidated: validation || matched, validationMode: validation)+ try server.start()+ withExtendedLifetime(server) { dispatchMain() }+ } catch {+ // Never log bodies, capabilities, AX content or peer credentials.+ fputs("Locked Use Broker startup failed: \(error)\n", stderr)+ exit(1)+ }+ }+}++enum BrokerError: Error { case message(String) }++/// All mutable state lives on this one queue, independent of GUI tool actions.+private final class BrokerServer: @unchecked Sendable {+ private let logger = Logger(subsystem: "dev.opencomputeruse.locked-use", category: "Broker")+ private let queue = DispatchQueue(label: "dev.opencomputeruse.locked-use.broker")+ private let approvals: LockedUseClientApprovals+ private var coordinator: LockedUseBrokerCoordinator+ private var listeners: [DispatchSourceRead] = []+ private var connections: [UUID: BrokerConnection] = [:]+ private var timer: DispatchSourceTimer?+ private var lastPolicyCheck: TimeInterval = 0+ private var policyInvalidated = false+ private let policyMonitor = LockedUsePolicyMonitor {+ try LockedUseAuthorizationRules.installedRulesObserved()+ }+ private var validationReport: LockedUseValidationReport?+ private var lastValidationData: Data?+ private var recoverySeed: LockedUseRecoveryRecord?+ private var ownerClientToken: Data?+ private var lastRecoveryData: Data?+ private let instanceLock: Int32++ init(approvals: LockedUseClientApprovals, enabled: Bool, backendValidated: Bool, validationMode: Bool) throws {+ self.approvals = approvals+ coordinator = .init(enabled: enabled, backendValidated: backendValidated, requiresWatchdog: true, validationMode: validationMode)+ try Self.validateRunDirectory()+ let fd = open("/Library/Application Support/OpenComputerUse/LockedUse/run/broker.lock", O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0o600)+ guard fd >= 0 else { throw BrokerError.message("instance lock unavailable") }+ var info = stat()+ guard fstat(fd, &info) == 0, info.st_uid == 0, info.st_mode & S_IFMT == S_IFREG,+ info.st_mode & 0o077 == 0, ocu_has_mutating_acl(fd) == 0,+ flock(fd, LOCK_EX | LOCK_NB) == 0 else {+ Darwin.close(fd); throw BrokerError.message("instance already running or insecure lock file")+ }+ instanceLock = fd+ let bootID = try LockedUseComponentValidation.bootSessionID()+ recoverySeed = try LockedUseRecoveryRecord.loadInstalled()+ if let record = recoverySeed, record.bootSessionID != bootID {+ // A kernel reboot destroys the old GUI session and queued native+ // authorization work. A new completed login is a separate epoch.+ guard unlink("/Library/Application Support/OpenComputerUse/LockedUse/lease-recovery.json") == 0 else { throw BrokerError.message("old boot recovery fence unavailable") }+ recoverySeed = nil+ }+ ownerClientToken = recoverySeed?.originalClientToken+ coordinator = .init(enabled: enabled, backendValidated: backendValidated, requiresWatchdog: true, recovery: recoverySeed, bootSessionID: bootID, validationMode: validationMode)+ }++ func start() throws {+ policyMonitor.refresh()+ for endpoint in [LockedUseIPCEndpoint.agent, .guardian, .plugin, .observer, .admin] {+ let fd = socket(AF_UNIX, SOCK_STREAM, 0)+ guard fd >= 0 else { throw BrokerError.message("socket unavailable") }+ do {+ try Self.removeStaleEndpoint(endpoint.path)+ try LockedUseIPCSocket.configure(fd)+ guard fcntl(fd, F_SETFL, O_NONBLOCK) == 0 else { throw BrokerError.message("nonblocking socket unavailable") }+ var address = try LockedUseIPCSocket.address(path: endpoint.path)+ // Never unlink an unknown/still-running service's socket.+ let bound = withUnsafePointer(to: &address) { pointer in+ pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) {+ bind(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size))+ }+ }+ guard bound == 0, chmod(endpoint.path, 0o666) == 0, listen(fd, 16) == 0 else {+ throw BrokerError.message("endpoint already exists or cannot be secured")+ }+ let source = DispatchSource.makeReadSource(fileDescriptor: fd, queue: queue)+ source.setEventHandler { [weak self] in self?.accept(fd: fd, endpoint: endpoint) }+ source.setCancelHandler { Darwin.close(fd) }+ listeners.append(source)+ source.resume()+ } catch { Darwin.close(fd); throw error }+ }+ let timer = DispatchSource.makeTimerSource(queue: queue)+ timer.schedule(deadline: .now(), repeating: .milliseconds(100), leeway: .milliseconds(10))+ timer.setEventHandler { [weak self] in+ guard let self else { return }+ do {+ let previousPhase = self.coordinator.phase+ defer {+ 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()+ }+ }+ let now = ProcessInfo.processInfo.systemUptime+ if now - self.lastPolicyCheck >= 1 {+ self.policyMonitor.refresh(now: now)+ self.lastPolicyCheck = now+ }+ try self.checkInstallationPolicy(requireFresh: false)+ for connection in Array(self.connections.values) where connection.endpoint == .agent && connection.clientDescriptor < 0 && now - connection.created > 2 {+ self.close(connection)+ }+ if let owner = self.coordinator.owner,+ let connection = self.connections[owner.connectionID], !connection.clientInvalidated {+ do { try self.verifyOriginalClient(connection) }+ catch {+ connection.clientInvalidated = true+ try self.coordinator.disconnected(connection.context)+ }+ }+ try self.coordinator.tick(now: now)+ if let guardian = self.coordinator.recordedGuardian, kill(guardian.processID, 0) != 0, errno == ESRCH {+ try self.coordinator.guardianProcessExited()+ }+ if let owner = self.coordinator.recordedOwner, kill(owner.processID, 0) != 0, errno == ESRCH {+ try self.coordinator.ownerProcessExited()+ }+ try self.persistRecovery()+ try self.persistValidation()+ }+ catch { self.stopAll() }+ }+ self.timer = timer+ timer.resume()+ }++ private func accept(fd: Int32, endpoint: LockedUseIPCEndpoint) {+ for _ in 0..<16 {+ let client = Darwin.accept(fd, nil, nil)+ if client < 0 { return }+ guard connections.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)+ }+ connection.readSource = source+ source.resume()+ } catch { logger.notice("peerRejected endpoint=\(endpoint.rawValue, privacy: .public)"); Darwin.close(client) }+ }+ }++ private func authenticate(fd: Int32, endpoint: LockedUseIPCEndpoint) throws -> LockedUsePeerIdentity {+ let began = ProcessInfo.processInfo.systemUptime+ defer {+ let elapsed = ProcessInfo.processInfo.systemUptime - began+ if elapsed > 0.25 {+ logger.notice("verificationSlow endpoint=\(endpoint.rawValue, privacy: .public) elapsedMilliseconds=\(Int(elapsed * 1000), privacy: .public)")+ }+ }+ switch endpoint {+ case .agent: return try approvals.verifiedPeer(socket: fd, role: .agent)+ case .guardian: return try approvals.verifiedPeer(socket: fd, role: .guardian)+ case .observer: return try approvals.verifiedPeer(socket: fd, role: .client)+ case .admin:+ guard let team = try LockedUseSigningIdentity.current().teamIdentifier else { throw BrokerError.message("signer unavailable") }+ let requirement = "identifier \"dev.opencomputeruse.locked-use.installer\" and anchor apple generic and certificate leaf[subject.OU] = \"\(team)\""+ let peer = try LockedUsePeerIdentity.verified(socket: fd, requirement: requirement)+ guard peer.userID == 0, peer.hardenedRuntime, !peer.permitsCodeInjection else { throw BrokerError.message("untrusted installer") }+ return peer+ case .plugin:+ // SecurityAgent is Apple signed, not signed by the application's+ // 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 peer = try LockedUsePeerIdentity.verified(socket: fd, requirement: requirement)+ guard peer.auditSessionID > 0, !peer.permitsCodeInjection else { throw BrokerError.message("untrusted authorization helper") }+ return peer+ }+ }++ private func read(_ connection: BrokerConnection) {+ if connection.endpoint == .agent && connection.clientDescriptor < 0 {+ let fd = ocu_receive_peer_socket(connection.fd)+ if fd < 0, [EAGAIN, EWOULDBLOCK, EINTR].contains(errno) { return }+ guard fd >= 0 else { close(connection); return }+ do {+ var native = OCUPeerIdentity()+ 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")+ }+ connection.clientDescriptor = fd; connection.clientIdentity = client; connection.clientAuditToken = token+ } catch { Darwin.close(fd); close(connection) }+ return+ }+ var bytes = [UInt8](repeating: 0, count: 4096)+ let count = Darwin.read(connection.fd, &bytes, bytes.count)+ if count < 0, [EAGAIN, EWOULDBLOCK, EINTR].contains(errno) { return }+ 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)+ 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") }+ for frame in try connection.decoder.append(Data(bytes.prefix(count))) {+ let request = try JSONDecoder().decode(LockedUseIPCMessage.self, from: frame).validated()+ // Keep the authenticated agent alive to revoke and acknowledge+ // drainage after its original native client has exited.+ if connection.endpoint == .admin && ![LockedUseIPCMessage.Operation.status, .disable].contains(request.operation) { throw BrokerError.message("invalid installer request") }+ if connection.endpoint == .observer && request.operation != .status { throw BrokerError.message("observer cannot mutate") }+ let previousPhase = coordinator.phase+ let reply: LockedUseIPCReply+ do {+ if [.begin, .beginRecoveryProbe, .beginUnshieldedDiagnostic, .pluginClaim, .pluginConsume].contains(request.operation) { try checkInstallationPolicy() }+ if connection.endpoint == .agent && [.begin, .beginRecoveryProbe, .action, .validationPassed, .validationManual].contains(request.operation) {+ do { try verifyOriginalClient(connection) }+ catch {+ connection.clientInvalidated = true+ try coordinator.disconnected(connection.context)+ throw error+ }+ }+ if connection.endpoint == .observer { logger.notice("observerStage=handling") }+ reply = try coordinator.handle(request, context: connection.context, now: ProcessInfo.processInfo.systemUptime)+ if connection.endpoint == .observer { logger.notice("observerStage=handled") }+ } catch {+ reply = .init(id: request.id, result: .denied, phase: coordinator.phase,+ detail: "Request denied by Broker policy")+ }+ if previousPhase != coordinator.phase {+ logger.notice("phase=\(self.coordinator.phase.rawValue, privacy: .public) stopReason=\(self.coordinator.stopReason?.rawValue ?? "none", privacy: .public)")+ logProtectionLoss()+ }+ if request.operation == .pluginClaim, reply.result != .denied {+ logger.notice("permitIssued maximumLifetimeSeconds=5")+ }+ if [.pluginClaim, .pluginConsume, .pluginFinished].contains(request.operation) {+ logger.notice("pluginDecision operation=\(request.operation.rawValue, privacy: .public) result=\(reply.result.rawValue, privacy: .public) phase=\(self.coordinator.phase.rawValue, privacy: .public) sessionMatches=\(connection.context.auditSessionID == self.coordinator.owner?.auditSessionID, privacy: .public) auditUserMatches=\(connection.identity.auditUserID == self.coordinator.owner?.userID, privacy: .public)")+ }+ if reply.result == .denied { logger.notice("denied operation=\(request.operation.rawValue, privacy: .public) sessionMatches=\(connection.context.auditSessionID == self.coordinator.owner?.auditSessionID, privacy: .public) auditUserMatches=\(connection.identity.auditUserID == self.coordinator.owner?.userID, privacy: .public)") }+ // Persist before exposing a consumed authorization or active+ // GUI lease. No permit nonce is ever saved or restored.+ if connection.endpoint == .observer { logger.notice("observerStage=persisting") }+ try persistRecovery()+ if connection.endpoint == .observer { logger.notice("observerStage=persisted") }+ if reply.result != .denied, request.operation == .validationPassed, let leaseID = request.leaseID {+ let team = try LockedUseSigningIdentity.current().teamIdentifier!+ validationReport = .init(leaseID: leaseID, evidence: try LockedUseComponentValidation.current(team: team), ownerToken: connection.identity.auditToken)+ }+ if reply.result != .denied, request.operation == .validationManual {+ guard var report = validationReport, report.leaseID == request.leaseID,+ report.ownerToken == connection.identity.auditToken, report.lockedAndReleased else { throw BrokerError.message("validation owner mismatch") }+ report.afterManualUnlockPassed = true; validationReport = report+ }+ try persistValidation()+ connection.pending.append(try LockedUseIPCFrame.encode(reply))+ guard connection.pending.count <= 64 * 1024 else { throw LockedUseIPCFrame.Failure.oversized }+ }+ flush(connection)+ } catch { close(connection) }+ }++ private func logProtectionLoss() {+ guard coordinator.stopReason == .guardLost else { return }+ let evidence = coordinator.protectionDiagnostics(now: ProcessInfo.processInfo.systemUptime)+ logger.notice("guardLostEvidence guardianAgeMilliseconds=\(Int(evidence.guardianAge * 1000), privacy: .public) watchdogAgeMilliseconds=\(Int(evidence.watchdogAge * 1000), privacy: .public) watchdogProtected=\(evidence.watchdogProtected, privacy: .public)")+ }++ private func persistRecovery() throws {+ if let context = coordinator.recordedOwner,+ let token = connections[context.id]?.clientAuditToken { ownerClientToken = token }+ let path = "/Library/Application Support/OpenComputerUse/LockedUse/lease-recovery.json"+ if let token = ownerClientToken, let record = coordinator.recoveryRecord(clientToken: token) {+ _ = try record.validated()+ let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys]+ let data = try encoder.encode(record)+ if data == lastRecoveryData { return }+ try LockedUsePrivateRecord.writeInstalled(data, name: "lease-recovery.json")+ lastRecoveryData = data+ } else if lastRecoveryData != nil || recoverySeed != nil {+ if unlink(path) != 0, errno != ENOENT { throw BrokerError.message("recovery fence removal failed") }+ lastRecoveryData = nil; recoverySeed = nil+ } else { return }+ let directory = open("/Library/Application Support/OpenComputerUse/LockedUse", O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ guard directory >= 0 else { throw BrokerError.message("recovery directory unavailable") }+ let synced = fsync(directory); Darwin.close(directory)+ guard synced == 0 else { throw BrokerError.message("recovery directory durability unavailable") }+ }++ private func persistValidation() throws {+ guard var report = validationReport else { return }+ if coordinator.isFullyReleased, [.idle, .awaitingManualUnlock].contains(coordinator.phase),+ coordinator.recordedOwner?.auditToken == report.ownerToken {+ report.lockedAndReleased = true+ }+ validationReport = report+ // A Broker restart loses incomplete proof; it never certifies resumed+ // recovery as a successful fresh unlock test.+ let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys]+ let data = try encoder.encode(report)+ if data == lastValidationData { return }+ try LockedUsePrivateRecord.writeInstalled(data, name: "validation-report.json")+ lastValidationData = data+ }++ private func checkInstallationPolicy(requireFresh: Bool = true) throws {+ guard !policyInvalidated else {+ if requireFresh { throw BrokerError.message("authentication policy invalidated") }+ return+ }+ let observation = policyMonitor.status()+ if observation == .invalid || observation == .stale {+ try coordinator.invalidateInstallation()+ policyInvalidated = true+ logger.error("installationPolicyInvalidated")+ }+ if requireFresh, observation != .valid {+ throw BrokerError.message("authentication policy observation unavailable")+ }+ }++ private func verifyOriginalClient(_ connection: BrokerConnection) throws {+ let began = ProcessInfo.processInfo.systemUptime+ defer {+ let elapsed = ProcessInfo.processInfo.systemUptime - began+ if elapsed > 0.25 { logger.notice("originalClientVerificationSlow elapsedMilliseconds=\(Int(elapsed * 1000), privacy: .public)") }+ }+ guard !connection.clientInvalidated, let previous = connection.clientIdentity else { throw BrokerError.message("client unavailable") }+ // A retained SCM_RIGHTS descriptor can outlive its originating client.+ // Reject EOF/dead peers before asking Security.framework to resolve a+ // stale audit token. Live peers still require full signature verification.+ guard kill(previous.processID, 0) == 0 || errno == EPERM else { throw BrokerError.message("client exited") }+ var byte: UInt8 = 0+ let peeked = recv(connection.clientDescriptor, &byte, 1, MSG_PEEK | MSG_DONTWAIT)+ 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)+ guard client.auditToken == previous.auditToken,+ client.codeDirectoryHash == previous.codeDirectoryHash else { throw BrokerError.message("client changed") }+ }++ private func flush(_ connection: BrokerConnection) {+ guard !connection.closed else { return }+ while !connection.pending.isEmpty {+ let count = connection.pending.withUnsafeBytes { buffer in+ Darwin.write(connection.fd, buffer.baseAddress, buffer.count)+ }+ if count < 0, errno == EINTR { continue }+ if count < 0, errno == EAGAIN || errno == EWOULDBLOCK {+ if connection.writeSource == nil {+ let source = DispatchSource.makeWriteSource(fileDescriptor: connection.fd, queue: queue)+ source.setEventHandler { [weak self, weak connection] in+ guard let connection, !connection.closed else { return }+ self?.flush(connection)+ }+ connection.writeSource = source+ source.resume()+ }+ return+ }+ guard count > 0 else { close(connection); return }+ connection.pending.removeFirst(count)+ }+ connection.writeSource?.cancel()+ connection.writeSource = nil+ }++ private func close(_ connection: BrokerConnection) {+ guard !connection.closed else { return }+ connection.closed = true+ if connection.clientDescriptor >= 0 { Darwin.close(connection.clientDescriptor); connection.clientDescriptor = -1 }+ try? coordinator.disconnected(connection.context)+ try? persistRecovery()+ connection.readSource?.cancel(); connection.writeSource?.cancel()+ 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 static func validateRunDirectory() throws {+ var fd = open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC)+ guard fd >= 0 else { throw BrokerError.message("root directory unavailable") }+ defer { Darwin.close(fd) }+ for component in ["Library", "Application Support", "OpenComputerUse", "LockedUse", "run"] {+ let next = openat(fd, component, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ guard next >= 0 else { throw BrokerError.message("installer runtime directory missing") }+ var info = stat()+ guard fstat(next, &info) == 0, info.st_uid == 0,+ info.st_mode & 0o022 == 0, ocu_has_mutating_acl(next) == 0 else {+ Darwin.close(next); throw BrokerError.message("insecure runtime directory")+ }+ Darwin.close(fd); fd = next+ }+ }++ /// The exclusive instance lock prevents this service's restart from racing+ /// another copy. The enclosing path is root owned and not user writable.+ private static func removeStaleEndpoint(_ path: String) throws {+ var before = stat()+ if lstat(path, &before) != 0 {+ guard errno == ENOENT else { throw BrokerError.message("endpoint inspection failed") }+ return+ }+ guard before.st_uid == 0, before.st_mode & S_IFMT == S_IFSOCK else {+ throw BrokerError.message("unknown object at endpoint")+ }+ let fd = socket(AF_UNIX, SOCK_STREAM, 0)+ guard fd >= 0 else { throw BrokerError.message("endpoint probe unavailable") }+ defer { Darwin.close(fd) }+ try LockedUseIPCSocket.configure(fd)+ guard fcntl(fd, F_SETFL, O_NONBLOCK) == 0 else { throw BrokerError.message("endpoint probe unavailable") }+ var address = try LockedUseIPCSocket.address(path: path)+ let result = withUnsafePointer(to: &address) { pointer in+ pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) {+ Darwin.connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size))+ }+ }+ guard result < 0, errno == ECONNREFUSED else { throw BrokerError.message("endpoint in use") }+ var after = stat()+ guard lstat(path, &after) == 0, after.st_ino == before.st_ino,+ after.st_dev == before.st_dev, after.st_uid == 0,+ after.st_mode & S_IFMT == S_IFSOCK, unlink(path) == 0 else {+ throw BrokerError.message("endpoint changed during restart")+ }+ }+ deinit { Darwin.close(instanceLock) }+}++private final class BrokerConnection: @unchecked Sendable {+ let fd: Int32+ let endpoint: LockedUseIPCEndpoint+ let identity: LockedUsePeerIdentity+ let context: LockedUseBrokerCoordinator.Context+ var decoder = LockedUseIPCFrame()+ var pending = Data()+ var readSource: DispatchSourceRead?+ var writeSource: DispatchSourceWrite?+ var closed = false+ let created = ProcessInfo.processInfo.systemUptime+ var clientAuditToken: Data?+ var clientInvalidated = false+ var clientDescriptor: Int32 = -1+ var clientIdentity: LockedUsePeerIdentity?+ init(fd: Int32, endpoint: LockedUseIPCEndpoint, identity: LockedUsePeerIdentity,+ context: LockedUseBrokerCoordinator.Context) {+ self.fd = fd; self.endpoint = endpoint; self.identity = identity; self.context = context+ }+}diff --git a/experiments/LockedUse/Sources/Guardian/DisplayGuardian.swift b/experiments/LockedUse/Sources/Guardian/DisplayGuardian.swiftnew file mode 100644index 0000000..4f3009a--- /dev/null+++ b/experiments/LockedUse/Sources/Guardian/DisplayGuardian.swift@@ -0,0 +1,566 @@+import AppKit+import ApplicationServices+import Carbon+import CryptoKit+import Darwin+import Foundation+import OpenComputerUseKit+import os+@preconcurrency import ScreenCaptureKit++private final class FixtureActionGate: @unchecked Sendable {+ private let lock = NSLock()+ private var closed = false+ func close() { lock.lock(); closed = true; lock.unlock() }+ func allowsAction() -> Bool { lock.lock(); defer { lock.unlock() }; return !closed }+}++/// Live rehearsal adapter. This does not grant production permits or unlock.+/// The root Broker must eventually own action cancellation/quiescence. Here+/// only the controlled fixture performs actions; no unlock requests exist.+@MainActor+final class DisplayGuardian: NSObject {+ private var policy: LockedUseGuardianPolicy+ private let lock = ScreenLock()+ private let shields = DisplayShieldSurface()+ private var displayPower: DisplayPowerAssertion?+ private var tap: CFMachPort?+ private var tapSource: CFRunLoopSource?+ private var timer: Timer?+ private var watchdog: Process?+ private var watchdogInput: FileHandle?+ private var watchdogOutput: FileHandle?+ private var watchdogReader: HeartbeatPipe?+ private var watchdogReady = false+ private var lastWatchdogHeartbeat: TimeInterval+ private let preparationLogger = Logger(subsystem: "dev.opencomputeruse.locked-use", category: "GuardianPreparation")+ private var preparationLoggedAt = -Double.infinity+ private var started: TimeInterval+ private var lastReport: TimeInterval = 0+ private var topology = ""+ private var stopping = false+ private var fixtureWindow: NSWindow?+ private var fixtureCounter = 0+ private var fixtureLabel: NSTextField?+ private var fixtureVerificationStarted = false+ private let injectWatchdogStall: Bool+ private var watchdogRelockSeen = false+ private var stallResumedLocked = false+ private(set) var watchdogTestPassed = false+ private(set) var fixtureAXSelfTestPassed = false+ private let fixtureGate = FixtureActionGate()+ private let brokerBootstrap: LockedUseGuardianBootstrap?+ private var brokerClient: LockedUseIPCClient?+ private var watchdogBootstrap: LockedUseGuardianBootstrap?+ private var clickAllowance: LockedUseClickAllowance?+ private var returnAllowance: LockedUseReturnAllowance?+ private var validationConfirmation = false+ private var shieldStatus = LockedUseShieldStatus()+ private lazy var lockPresentation = LockScreenPresentation(session: policy.session)+ private var hasObservedUnlock = false+ private var brokerReportInFlight = false+ private var lastBrokerReport: TimeInterval = 0+ private var unlockWorkPending = false+ private var unlockRequested = false+ private let unlockCancellation = UnlockCancellation()+ private let lockUIObservation = LockUIObservation()+ private var physicalInput: PhysicalInputMonitor?++ init(session: LockedUseSession, injectWatchdogStall: Bool = false, brokerBootstrap: LockedUseGuardianBootstrap? = nil) throws {+ guard session.state == (brokerBootstrap == nil ? .unlocked : .locked) else {+ throw GuardianError.message("Start rehearsal unlocked; start Broker Guardian only in the original locked session")+ }+ self.brokerBootstrap = brokerBootstrap+ brokerClient = try brokerBootstrap.map { _ in+ try LockedUseIPCClient(endpoint: .guardian, brokerRequirement: LockedUseSigningIdentity.brokerRequirement())+ }+ started = ProcessInfo.processInfo.systemUptime+ lastWatchdogHeartbeat = started+ policy = try .init(session: session, now: started, lifetime: brokerBootstrap == nil ? 15 : 300)+ self.injectWatchdogStall = injectWatchdogStall+ if brokerBootstrap == nil { policy.confirmQuiescence() }+ super.init()+ }++ func start() throws {+ guard AXIsProcessTrusted(), CGPreflightListenEventAccess() else {+ throw GuardianError.message("Grant Accessibility and Input Monitoring to the Guardian app before rehearsal")+ }+ guard lock.available, brokerBootstrap != nil || !IsSecureEventInputEnabled() else {+ throw GuardianError.message("Relock unavailable or Secure Event Input active")+ }+ try installTap()+ do {+ if let bootstrap = brokerBootstrap, let client = brokerClient {+ let observer = PhysicalInputMonitor(activity: { [weak self] in+ guard let self else { return }+ self.policy.requestLocalRecovery()+ if self.policy.phase != .relocking { self.stop(.localInput) }+ },+ failure: { [weak self] in self?.stop(.guardianFailure) })+ physicalInput = observer+ try observer.start()+ let hello = try client.request(.init(operation: .guardianHello, leaseID: bootstrap.leaseID, token: bootstrap.token))+ guard hello.result != .denied, let token = hello.token else { throw GuardianError.message("Broker rejected Guardian identity/challenge") }+ validationConfirmation = hello.validationConfirmation == true+ let clickTag = Int64.random(in: 1...Int64.max)+ clickAllowance = .init(tag: clickTag, sender: getpid(), now: ProcessInfo.processInfo.systemUptime)+ let returnTag = validationConfirmation ? Int64.random(in: 1...Int64.max) : nil+ if let returnTag { returnAllowance = .init(tag: returnTag, sender: getpid(), session: policy.session, now: ProcessInfo.processInfo.systemUptime) }+ watchdogBootstrap = try .init(leaseID: bootstrap.leaseID, token: token, clickTag: clickTag, returnTag: returnTag,+ startupDeadline: bootstrap.startupDeadline)+ } else { createCaptureFixture() }+ try coverDisplays()+ displayPower = try DisplayPowerAssertion()+ try startWatchdog()+ let timer = Timer(timeInterval: 0.05, repeats: true) { [weak self] _ in+ MainActor.assumeIsolated { self?.poll() }+ }+ self.timer = timer+ RunLoop.main.add(timer, forMode: .common)+ emit("preparing", details: ["displayCount": shields.count, "seconds": brokerBootstrap == nil ? 15 : 300,+ "unlockRequested": false, "productionReady": false])+ } catch {+ // Preparation can fail before a live test is armed. No unlocking is+ // possible here; dispose only resources that actually exist.+ cleanup()+ throw error+ }+ }++ private func createCaptureFixture() {+ let window = NSWindow(contentRect: NSRect(x: 80, y: 100, width: 420, height: 240),+ styleMask: [.titled], backing: .buffered, defer: false)+ window.title = "Locked Use Capture Fixture"+ window.backgroundColor = NSColor(srgbRed: 0.1, green: 0.3, blue: 0.8, alpha: 1)+ window.isReleasedWhenClosed = false+ let label = NSTextField(labelWithString: "Counter: 0")+ label.frame = NSRect(x: 40, y: 120, width: 300, height: 40)+ label.textColor = .white+ let button = NSButton(title: "Increment", target: self, action: #selector(incrementFixture))+ button.setAccessibilityIdentifier("ocu.locked-use.rehearsal.increment")+ button.frame = NSRect(x: 40, y: 50, width: 160, height: 40)+ window.contentView?.addSubview(label)+ window.contentView?.addSubview(button)+ fixtureLabel = label+ fixtureWindow = window+ window.orderFrontRegardless()+ }++ @objc private func incrementFixture() {+ fixtureCounter += 1+ fixtureLabel?.stringValue = "Counter: \(fixtureCounter)"+ }++ func runFixtureAXSelfTest() throws {+ createCaptureFixture()+ defer { fixtureWindow?.close(); fixtureWindow = nil }+ guard performFixtureAXPress(), fixtureCounter == 1 else {+ throw GuardianError.message("MainActor same-process AX fixture did not change")+ }+ fixtureAXSelfTestPassed = true+ emit("fixtureAXSelfTest", details: ["passed": true, "counter": fixtureCounter, "lockRequested": false])+ }++ private func performFixtureAXPress() -> Bool {+ let root = AXUIElementCreateApplication(getpid())+ AXUIElementSetMessagingTimeout(root, 0.2)+ var remaining = 100+ func find(_ element: AXUIElement, depth: Int) -> AXUIElement? {+ guard depth < 12, remaining > 0 else { return nil }+ remaining -= 1+ var identifier: CFTypeRef?+ _ = AXUIElementCopyAttributeValue(element, kAXIdentifierAttribute as CFString, &identifier)+ if identifier as? String == "ocu.locked-use.rehearsal.increment" { return element }+ for attribute in [kAXWindowsAttribute, kAXChildrenAttribute] {+ var children: CFTypeRef?+ if AXUIElementCopyAttributeValue(element, attribute as CFString, &children) == .success {+ for child in children as? [AXUIElement] ?? [] {+ if let match = find(child, depth: depth + 1) { return match }+ }+ }+ }+ return nil+ }+ return find(root, depth: 0).map {+ fixtureGate.allowsAction() && AXUIElementPerformAction($0, kAXPressAction as CFString) == .success+ } ?? false+ }++ private func verifyCaptureFixture() async {+ guard policy.phase == .shielding else { return }+ policy.requireQuiescence()+ defer { policy.confirmQuiescence() }+ guard CGPreflightScreenCaptureAccess(), let fixtureWindow else {+ emit("captureVerification", details: ["passed": false, "reason": "screenRecordingUnavailable"])+ return+ }+ do {+ emit("captureStage", details: ["stage": "shareableContent"])+ let content = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: false)+ guard let window = content.windows.first(where: { $0.windowID == CGWindowID(fixtureWindow.windowNumber) }),+ window.owningApplication?.processID == getpid() else {+ throw GuardianError.message("Fixture SCWindow unavailable")+ }+ let filter = SCContentFilter(desktopIndependentWindow: window)+ let configuration = SCStreamConfiguration()+ configuration.width = 420+ configuration.height = 262+ configuration.showsCursor = false+ configuration.ignoreShadowsSingleWindow = true+ emit("captureStage", details: ["stage": "beforeImage"])+ let before = try await SCScreenshotManager.captureImage(contentFilter: filter, configuration: configuration)+ let pixels = NSBitmapImageRep(cgImage: before)+ guard let sample = pixels.colorAt(x: pixels.pixelsWide / 2, y: pixels.pixelsHigh / 2)?.usingColorSpace(.sRGB),+ sample.blueComponent > 0.5, sample.blueComponent > sample.redComponent * 2 else {+ throw GuardianError.message("Covered fixture capture did not contain the expected blue background")+ }+ guard policy.phase == .shielding else { throw GuardianError.message("Rehearsal stopped before action") }+ emit("captureStage", details: ["stage": "axPress"])+ // Same-process AX invokes AppKit directly on the caller's thread.+ // This fixture therefore performs AXPress on MainActor. Dispatching+ // to a background queue violates its AppKit/Swift actor isolation.+ let pressed = performFixtureAXPress()+ guard policy.phase == .shielding, pressed, fixtureCounter == 1 else {+ throw GuardianError.message("AXPress did not change the controlled fixture counter")+ }+ fixtureWindow.displayIfNeeded()+ try await Task.sleep(for: .milliseconds(150))+ let after = try await SCScreenshotManager.captureImage(contentFilter: filter, configuration: configuration)+ let changed = NSBitmapImageRep(cgImage: before).representation(using: .png, properties: [:])+ != NSBitmapImageRep(cgImage: after).representation(using: .png, properties: [:])+ emit("captureVerification", details: ["passed": changed, "axCounterChanged": true,+ "windowCaptureChanged": changed, "coveredFixtureVisible": true])+ if changed, injectWatchdogStall, policy.phase == .shielding {+ emit("faultInjected", details: ["kind": "guardianMainLoopStall", "seconds": 5,+ "lockRequestedByGuardian": false])+ // Development-only fault injection: keep the existing windows+ // alive while stopping the UI loop and its outgoing heartbeat.+ stallMainLoopForWatchdogTest()+ let resumedSession = LockedUseSession.current()+ stallResumedLocked = resumedSession.state == .locked+ emit("faultResumed", details: ["session": resumedSession.state.rawValue])+ }+ } catch {+ emit("captureVerification", details: ["passed": false, "reason": String(describing: error)])+ }+ }++ private func installTap() throws {+ let types: [CGEventType] = [.leftMouseDown, .leftMouseUp, .rightMouseDown, .rightMouseUp,+ .mouseMoved, .leftMouseDragged, .rightMouseDragged, .keyDown, .keyUp, .flagsChanged,+ .scrollWheel, .tabletPointer, .tabletProximity, .otherMouseDown, .otherMouseUp, .otherMouseDragged]+ // NX_SYSDEFINED (14) includes media/power keys; no keystrokes are logged.+ let mask = types.reduce(CGEventMask(1) << 14) { $0 | (CGEventMask(1) << $1.rawValue) }+ let context = Unmanaged.passUnretained(self).toOpaque()+ tap = CGEvent.tapCreate(tap: .cgSessionEventTap, place: .headInsertEventTap,+ options: .defaultTap, eventsOfInterest: mask, callback: { _, type, event, pointer in+ guard let pointer else { return Unmanaged.passUnretained(event) }+ let admitted = MainActor.assumeIsolated { () -> Bool in+ let guardian = Unmanaged<DisplayGuardian>.fromOpaque(pointer).takeUnretainedValue()+ if type == .tapDisabledByTimeout || type == .tapDisabledByUserInput {+ emit("inputTapDisabled", details: ["kind": type == .tapDisabledByTimeout ? "timeout" : "userInput",+ "phase": guardian.policy.phase.rawValue])+ guardian.stop(.guardianFailure)+ return false+ }+ if guardian.policy.localRecoveryReady { return true }+ if !guardian.stopping, guardian.unlockRequested,+ guardian.returnAllowance?.accepts(event, type: type, filter: "main") == true { return true }+ if !guardian.stopping, guardian.unlockRequested,+ guardian.clickAllowance?.accepts(event, type: type, filter: "main") == true {+ recordLockUIClickAdmission(filter: "main", type: type)+ return true+ }+ // Only the one-use inherited lock-UI capability is admitted.+ // Every other global event still requests takeover.+ if guardian.policy.phase != .relocking {+ emit("inputTakeover", details: ["type": type.rawValue,+ "sourcePID": event.getIntegerValueField(.eventSourceUnixProcessID),+ "sourceState": event.getIntegerValueField(.eventSourceStateID),+ "phase": guardian.policy.phase.rawValue])+ guardian.stop(.localInput)+ }+ return false+ }+ return admitted ? Unmanaged.passUnretained(event) : nil+ }, userInfo: context)+ guard let tap, let source = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, tap, 0) else {+ throw GuardianError.message("Cannot create a filtering event tap")+ }+ tapSource = source+ CFRunLoopAddSource(CFRunLoopGetMain(), source, .commonModes)+ CGEvent.tapEnable(tap: tap, enable: true)+ }++ // Intentionally synchronous: Task.sleep would keep servicing the run loop+ // and heartbeats, so it would not simulate a stuck Guardian.+ private func stallMainLoopForWatchdogTest() {+ Thread.sleep(forTimeInterval: 5)+ }++ private func displayTopology() -> String { shields.displayTopology() }+ private func coverDisplays() throws {+ let message = brokerBootstrap == nil ? "Open Computer Use · 测试中\n移动鼠标或按键将重新锁屏"+ : shieldStatus.update(now: ProcessInfo.processInfo.systemUptime,+ startupDeadline: brokerBootstrap?.startupDeadline, unlocked: false, stopping: false)!+ try shields.coverDisplays(message: message)+ topology = displayTopology()+ }+ private func coverageHealthy() -> Bool { shields.coverageHealthy() }++ private func startWatchdog() throws {+ let process = Process()+ process.executableURL = Bundle.main.executableURL ?? URL(fileURLWithPath: CommandLine.arguments[0])+ process.arguments = brokerBootstrap == nil ? ["--watchdog"] : ["--broker-watchdog"]+ let input = Pipe(), output = Pipe()+ process.standardInput = input+ process.standardOutput = output+ process.standardError = FileHandle.standardError+ try process.run()+ input.fileHandleForReading.closeFile()+ output.fileHandleForWriting.closeFile()+ watchdog = process+ watchdogInput = input.fileHandleForWriting+ watchdogOutput = output.fileHandleForReading+ if let watchdogBootstrap {+ try input.fileHandleForWriting.write(contentsOf: LockedUseIPCFrame.encode(watchdogBootstrap))+ }+ watchdogReader = HeartbeatPipe(output.fileHandleForReading.fileDescriptor)+ }++ private func poll() {+ let now = ProcessInfo.processInfo.systemUptime+ if stopping, unlockCancellation.quiesced { unlockWorkPending = false }+ let bytes = watchdogReader?.drain(allowed: [72, 82, 83]) ?? []+ if bytes.contains(83) {+ watchdogRelockSeen = true+ emit("watchdogRelockReported", details: ["lockConfirmed": false])+ }+ if bytes.contains(82) { watchdogReady = true }+ if !bytes.isEmpty { lastWatchdogHeartbeat = now }+ let watchdogHealthy = watchdogReady && watchdog?.isRunning == true && watchdogReader?.failed == false && now - lastWatchdogHeartbeat < 1.5+ if let watchdogInput, !HeartbeatPipe.send(72, to: watchdogInput.fileDescriptor) { stop(.parentDisconnected) }+ do {+ if policy.phase == .preparing {+ if now - preparationLoggedAt >= 0.5 {+ preparationLoggedAt = now+ let failure = shields.coverageFailure() ?? "none"+ preparationLogger.notice("preparing elapsedMilliseconds=\(Int((now - self.started) * 1000), privacy: .public) watchdogReady=\(self.watchdogReady, privacy: .public) coverage=\(failure, privacy: .public)")+ }+ // Initial AppKit drawing and child launch can take a few frames.+ if now - started >= 3.5 {+ emit("preparationFailed", details: ["coverageFailure": shields.coverageFailure() ?? "",+ "watchdogReady": watchdogReady, "watchdogRunning": watchdog?.isRunning == true,+ "watchdogPipeFailed": watchdogReader?.failed ?? true])+ stop(.guardianFailure)+ }+ else if watchdogHealthy, coverageHealthy(), let tap, CGEvent.tapIsEnabled(tap: tap) {+ try policy.prepared(topology: topology, now: now)+ emit("shieldReady", details: ["displayCount": shields.count, "guardianPID": getpid(),+ "watchdogPID": watchdog?.processIdentifier ?? 0, "backendValidated": false])+ if brokerBootstrap == nil, !fixtureVerificationStarted {+ fixtureVerificationStarted = true+ Task { await self.verifyCaptureFixture() }+ }+ }+ }+ // prepared() starts the live heartbeat only once *all* protection+ // is ready. A child heartbeat alone cannot arm it during startup.+ if watchdogHealthy, policy.phase == .shielding { execute(try policy.heartbeat(now: now)) }+ let current = LockedUseSession.current()+ if current.state == .unlocked, brokerBootstrap != nil { hasObservedUnlock = true }+ if brokerBootstrap != nil, let message = shieldStatus.update(now: now,+ startupDeadline: brokerBootstrap?.startupDeadline,+ unlocked: hasObservedUnlock, stopping: stopping) {+ shields.updateMessage(message)+ }+ let tapHealthy = tap.map { CGEvent.tapIsEnabled(tap: $0) } ?? false+ // Secure input is expected at loginwindow after relock. Prior to+ // stopping it is a coverage gap and must stop the rehearsal.+ let coverageFailure = shields.coverageFailure()+ let coverage = coverageFailure == nil+ let secureInput = IsSecureEventInputEnabled()+ let inputHealthy = tapHealthy && (brokerBootstrap == nil ? !secureInput : physicalInput?.healthy == true)+ let healthy = watchdogHealthy && inputHealthy && coverage+ if !healthy, policy.phase == .shielding {+ emit("guardHealthFailure", details: ["watchdogHealthy": watchdogHealthy,+ "watchdogRunning": watchdog?.isRunning == true,+ "watchdogPipeFailed": watchdogReader?.failed ?? true,+ "watchdogHeartbeatAge": now - lastWatchdogHeartbeat,+ "inputTapEnabled": tapHealthy, "coverageHealthy": coverage,+ "coverageFailure": coverageFailure ?? "",+ "topologyUnchanged": displayTopology() == topology, "secureInput": secureInput])+ }+ if policy.phase != .preparing {+ if policy.localRecoveryReady { shields.allowLocalLoginInput() }+ execute(try policy.poll(session: current, topology: displayTopology(), guardsHealthy: healthy,+ lockPresentationReady: lockPresentation.ready(session: current, requested: policy.phase == .relocking, now: now), now: now))+ }+ if policy.phase != .preparing, policy.phase != .finished {+ reportToBroker(now: now, session: current, coverage: coverage,+ inputHealthy: inputHealthy, watchdogHealthy: watchdogHealthy)+ }+ if now - lastReport >= 1 {+ lastReport = now+ if policy.phase == .shielding, brokerBootstrap == nil {+ let remaining = max(0, Int(ceil(15 - (now - started))))+ shields.updateMessage("Open Computer Use · 遮罩期间操作测试\n剩余 \(remaining) 秒\n结束后将锁屏 · 请保持鼠标键盘不动")+ }+ emit("guardianState", details: ["phase": policy.phase.rawValue, "session": current.state.rawValue,+ "reason": policy.reason?.rawValue ?? "", "inputTapEnabled": tapHealthy,+ "watchdogHealthy": watchdogHealthy, "elapsed": now - started])+ }+ } catch { stop(.guardianFailure) }+ }++ private func stop(_ reason: LockedUseGuardianPolicy.Reason) {+ clickAllowance?.revoke(); returnAllowance?.revoke()+ fixtureGate.close()+ unlockCancellation.cancel()+ if unlockCancellation.quiesced { unlockWorkPending = false }+ if !stopping { stopping = true; emit("stopping", details: ["reason": reason.rawValue]) }+ execute(policy.stop(reason, now: ProcessInfo.processInfo.systemUptime))+ }++ private func execute(_ effects: [LockedUseGuardianPolicy.Effect]) {+ for effect in effects {+ switch effect {+ case .requestRelock:+ fixtureGate.close()+ unlockCancellation.cancel()+ if !stopping {+ stopping = true+ emit("stopping", details: ["reason": policy.reason?.rawValue ?? "", "elapsed": ProcessInfo.processInfo.systemUptime - started])+ }+ let current = LockedUseSession.current()+ if current.userID != policy.session.userID || current.auditSessionID != policy.session.auditSessionID || current.state != .locked {+ lock.request()+ }+ case .releaseShield:+ if injectWatchdogStall {+ watchdogTestPassed = stallResumedLocked && watchdogRelockSeen+ emit("watchdogTestResult", details: ["passed": watchdogTestPassed,+ "lockedBeforeGuardianResumed": stallResumedLocked,+ "independentRelockReported": watchdogRelockSeen])+ }+ if let watchdogInput { _ = HeartbeatPipe.send(76, to: watchdogInput.fileDescriptor) }+ let localRecovery = policy.localRecoveryReady && LockedUseSession.current().state == .unlocked+ emit(localRecovery ? "localRecoveryReleased" : "lockConfirmed",+ details: ["shieldReleased": true, "unlockRequested": false])+ if let bootstrap = brokerBootstrap {+ let observed = hasObservedUnlock+ cleanup()+ Task { @MainActor in+ let acknowledged = await Task.detached {+ GuardReleaseAcknowledgement.send(bootstrap: bootstrap, watchdog: false, observedUnlock: observed)+ }.value+ emit("guardianReleaseAcknowledged", details: ["passed": acknowledged])+ self.stopApplication()+ }+ } else {+ cleanup()+ stopApplication()+ }+ }+ }+ }++ private func stopApplication() {+ NSApplication.shared.stop(nil)+ if let event = NSEvent.otherEvent(with: .applicationDefined, location: .zero, modifierFlags: [],+ timestamp: 0, windowNumber: 0, context: nil, subtype: 0, data1: 0, data2: 0) {+ NSApplication.shared.postEvent(event, atStart: true)+ }+ }++ private func cleanup(closeBroker: Bool = true) {+ timer?.invalidate()+ timer = nil+ if let tapSource { CFRunLoopRemoveSource(CFRunLoopGetMain(), tapSource, .commonModes) }+ if let tap { CFMachPortInvalidate(tap) }+ tapSource = nil+ tap = nil+ shields.close()+ displayPower?.close(); displayPower = nil+ fixtureWindow?.close()+ fixtureWindow = nil+ watchdogInput?.closeFile()+ watchdogOutput?.closeFile()+ physicalInput?.stop()+ physicalInput = nil+ if closeBroker, let client = brokerClient { Task.detached { client.close() } }+ }++ private func reportToBroker(now: TimeInterval, session: LockedUseSession, coverage: Bool,+ inputHealthy: Bool, watchdogHealthy: Bool) {+ guard policy.phase != .finished, let bootstrap = brokerBootstrap,+ !brokerReportInFlight, now - lastBrokerReport >= 0.1 else { return }+ brokerReportInFlight = true+ lastBrokerReport = now+ let generation = SHA256.hash(data: Data(topology.utf8)).prefix(8).reduce(UInt64(0)) { ($0 << 8) | UInt64($1) }+ let guards = LockedUseStateMachine.Guards(allDisplaysCovered: coverage,+ inputTapHealthy: inputHealthy, watchdogHealthy: watchdogHealthy, displayGeneration: generation)+ let reason: LockedUseStateMachine.StopReason? = stopping+ ? policy.reason == .localInput ? .physicalInput : .guardLost : nil+ let message = LockedUseIPCMessage(operation: .guardianReport, leaseID: bootstrap.leaseID,+ session: session, guards: guards, stopReason: reason, unlockWorkPending: unlockWorkPending)+ Task { @MainActor in+ defer { brokerReportInFlight = false }+ do {+ let client: LockedUseIPCClient+ if let existing = brokerClient { client = existing }+ else {+ let observed = hasObservedUnlock+ let recovered = try await Task.detached {+ let candidate = try LockedUseIPCClient(endpoint: .guardian, brokerRequirement: LockedUseSigningIdentity.brokerRequirement())+ let hello = try candidate.request(.init(operation: .guardianRecoveryHello, leaseID: bootstrap.leaseID,+ session: .current(), unlockWorkPending: false, hasObservedUnlock: observed))+ guard hello.result != .denied else { candidate.close(); throw GuardianError.message("Guardian recovery denied") }+ return candidate+ }.value+ brokerClient = recovered; client = recovered+ }+ let reply = try await Task.detached { try client.request(message) }.value+ guard policy.phase != .finished else { return }+ guard reply.result != .denied else { throw GuardianError.message("Broker denied Guardian report") }+ for effect in reply.effects {+ switch effect {+ case "requestUnlock": requestNativeUnlock()+ case "cancelUnlock": unlockCancellation.cancel()+ case "requestRelock": stop(.stopRequested)+ case "releaseGuards":+ policy.confirmQuiescence()+ execute(policy.stop(.stopRequested, now: ProcessInfo.processInfo.systemUptime))+ default: throw GuardianError.message("Unknown Broker Guardian effect")+ }+ }+ } catch {+ guard policy.phase != .finished else { return }+ stop(.parentDisconnected)+ if let failed = brokerClient { Task.detached { failed.close() } }+ brokerClient = nil+ }+ }+ }++ private func requestNativeUnlock() {+ guard !stopping, !unlockRequested, policy.phase == .shielding else { return }+ unlockRequested = true+ unlockWorkPending = true+ let session = policy.session+ let cancellation = unlockCancellation+ let ui = lockUIObservation+ let clickTag = watchdogBootstrap?.clickTag+ let returnTag = watchdogBootstrap?.returnTag+ let validationConfirmation = self.validationConfirmation+ emit("unlockRequestStarting", details: ["lockedSessionObserved": true])+ Task { @MainActor in+ let accepted = await Task.detached { LockScreenInteractor.wake(session: session, cancellation: cancellation, ui: ui, clickTag: clickTag, validationConfirmation: validationConfirmation, returnTag: returnTag) }.value+ unlockWorkPending = false+ emit("unlockRequestReturned", details: ["displayWakeAccepted": accepted,+ "session": LockedUseSession.current().state.rawValue])+ if !accepted, LockedUseSession.current().state != .unlocked { stop(.guardianFailure) }+ }+ }+}diff --git a/experiments/LockedUse/Sources/Guardian/DisplayPowerAssertion.swift b/experiments/LockedUse/Sources/Guardian/DisplayPowerAssertion.swiftnew file mode 100644index 0000000..5461c6f--- /dev/null+++ b/experiments/LockedUse/Sources/Guardian/DisplayPowerAssertion.swift@@ -0,0 +1,28 @@+import Foundation+import OpenComputerUseKit+import IOKit.pwr_mgt++/// Independently owned by both guards; powerd releases it on process death or+/// at the maximum lease duration. It does not authenticate or unlock a user.+final class DisplayPowerAssertion {+ private var identifier: IOPMAssertionID = 0++ init() throws {+ let properties: [String: Any] = [+ kIOPMAssertionTypeKey: kIOPMAssertionTypePreventUserIdleDisplaySleep,+ kIOPMAssertionNameKey: "Open Computer Use display protection",+ kIOPMAssertionLevelKey: kIOPMAssertionLevelOn,+ kIOPMAssertionTimeoutKey: LockedUseStateMachine.maximumLease,+ kIOPMAssertionTimeoutActionKey: kIOPMAssertionTimeoutActionRelease,+ ]+ guard IOPMAssertionCreateWithProperties(properties as CFDictionary, &identifier) == kIOReturnSuccess else {+ throw GuardianError.message("Display sleep protection unavailable")+ }+ }++ func close() {+ if identifier != 0 { _ = IOPMAssertionRelease(identifier); identifier = 0 }+ }++ deinit { close() }+}diff --git a/experiments/LockedUse/Sources/Guardian/DisplayShieldSurface.swift b/experiments/LockedUse/Sources/Guardian/DisplayShieldSurface.swiftnew file mode 100644index 0000000..abf1f6b--- /dev/null+++ b/experiments/LockedUse/Sources/Guardian/DisplayShieldSurface.swift@@ -0,0 +1,116 @@+import AppKit+import Foundation+import OpenComputerUseKit++private final class ShieldWindow: NSPanel {+ override var canBecomeKey: Bool { false }+ override var canBecomeMain: Bool { false }+ // AppKit may constrain ordinary windows to the menu/Dock visible frame+ // after finishLaunching. A privacy surface must cover the full display.+ override func constrainFrameRect(_ frameRect: NSRect, to screen: NSScreen?) -> NSRect { frameRect }+}++/// Shared visual surface for both the isolated preview and guarded rehearsal.+@MainActor+final class DisplayShieldSurface {+ private var windows: [CGDirectDisplayID: ShieldWindow] = [:]+ private var appearances: [CGDirectDisplayID: ShieldAppearance] = [:]+ private var topology = ""+ var count: Int { windows.count }++ func updateMessage(_ message: String) {+ for (id, appearance) in appearances {+ appearance.updateMessage(message)+ windows[id]?.displayIfNeeded()+ }+ }++ /// Only after root drain, an observed original-session lock and actual+ /// hardware takeover. Keep opaque coverage while loginwindow takes input.+ func allowLocalLoginInput() {+ for window in windows.values { window.ignoresMouseEvents = true }+ }++ func close() {+ for window in windows.values { window.close() }+ windows.removeAll()+ appearances.removeAll()+ }++ private func screenIDs() -> [(CGDirectDisplayID, NSScreen)] {+ NSScreen.screens.compactMap { screen in+ guard let number = screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber else { return nil }+ return (number.uint32Value, screen)+ }+ }++ func displayTopology() -> String {+ screenIDs().sorted { $0.0 < $1.0 }.map { id, screen in+ "\(id):\(NSStringFromRect(screen.frame)):\(screen.backingScaleFactor)"+ }.joined(separator: "|")+ }++ func coverDisplays(message: String, levelOffset: Int = 0) throws {+ let screens = screenIDs()+ guard !screens.isEmpty else { throw GuardianError.message("No display available") }+ topology = displayTopology()+ for (id, screen) in screens {+ let frame = LockedUseShieldCoverage.surfaceFrame(for: screen.frame)+ let window = ShieldWindow(contentRect: frame, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false, screen: screen)+ window.animationBehavior = .none+ window.hidesOnDeactivate = false+ window.isFloatingPanel = true+ window.becomesKeyOnlyIfNeeded = true+ window.setFrame(frame, display: true)+ window.level = NSWindow.Level(rawValue: Int(CGShieldingWindowLevel()) + 1 + levelOffset)+ // Default user windows disappear at loginwindow. Both protection+ // surfaces must remain onscreen across the lock/unlock transition.+ window.canBecomeVisibleWithoutLogin = true+ window.canHide = false+ window.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .stationary, .ignoresCycle]+ window.backgroundColor = .black+ window.isOpaque = true+ window.alphaValue = 1+ window.hasShadow = false+ window.ignoresMouseEvents = false+ window.sharingType = .none+ window.isReleasedWhenClosed = false+ let appearance = ShieldAppearance(frame: NSRect(origin: .zero, size: frame.size), screen: screen, message: message)+ window.contentView = appearance+ window.orderFrontRegardless()+ window.displayIfNeeded()+ windows[id] = window+ appearances[id] = appearance+ }+ }++ /// WindowServer evidence, not just `isVisible`. Other secure/system overlays+ /// and hotplug races still require live validation; this is not a proof that+ /// ordinary windows provide an OS-enforced privacy barrier.+ func coverageHealthy() -> Bool { coverageFailure() == nil }++ func coverageFailure() -> String? {+ guard displayTopology() == topology else { return "topologyChanged" }+ var count: UInt32 = 0+ guard CGGetActiveDisplayList(0, nil, &count) == .success, count > 0, count <= 64 else { return "activeDisplayCountUnavailable" }+ var active = [CGDirectDisplayID](repeating: 0, count: Int(count))+ guard CGGetActiveDisplayList(count, &active, &count) == .success else { return "activeDisplayListUnavailable" }+ for id in active.prefix(Int(count)) {+ let mirrored = CGDisplayMirrorsDisplay(id)+ guard windows[id] != nil || (mirrored != kCGNullDirectDisplay && windows[mirrored] != nil) else { return "activeDisplayUncovered" }+ }+ guard let infos = CGWindowListCopyWindowInfo([.optionOnScreenOnly], kCGNullWindowID) as? [[String: Any]] else { return "windowListUnavailable" }+ for (id, window) in windows {+ guard window.isVisible else { return "shieldNotVisible" }+ guard let info = infos.first(where: { ($0[kCGWindowNumber as String] as? NSNumber)?.intValue == window.windowNumber }) else { return "shieldNotInWindowServer" }+ guard (info[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value == getpid() else { return "shieldOwnerMismatch" }+ guard (info[kCGWindowAlpha as String] as? NSNumber)?.doubleValue == 1 else { return "shieldAlphaMismatch" }+ guard (info[kCGWindowLayer as String] as? NSNumber)?.intValue == window.level.rawValue else { return "shieldLayerMismatch" }+ guard let bounds = info[kCGWindowBounds as String] as? [String: Any],+ let rect = CGRect(dictionaryRepresentation: bounds as CFDictionary) else { return "shieldBoundsUnavailable" }+ guard LockedUseShieldCoverage.covers(rect, display: CGDisplayBounds(id)) else { return "shieldBoundsMismatch expected=\(NSStringFromRect(CGDisplayBounds(id))) actual=\(NSStringFromRect(rect))" }+ }+ return nil+ }++}diff --git a/experiments/LockedUse/Sources/Guardian/ExternalFixture.swift b/experiments/LockedUse/Sources/Guardian/ExternalFixture.swiftnew file mode 100644index 0000000..ff4b720--- /dev/null+++ b/experiments/LockedUse/Sources/Guardian/ExternalFixture.swift@@ -0,0 +1,28 @@+import AppKit++/// A separate native AX target, intentionally unrelated to FixtureBridge.+/// Real OCU get_app_state/click calls must traverse Accessibility and SCK.+@MainActor+final class ExternalFixture: NSObject {+ private let window: NSWindow+ private let label = NSTextField(labelWithString: "Counter: 0")+ private var counter = 0+ override init() {+ window = NSWindow(contentRect: NSRect(x: 100, y: 100, width: 460, height: 220),+ styleMask: [.titled, .closable], backing: .buffered, defer: false)+ super.init()+ window.title = "Locked Use Native Validation"+ window.backgroundColor = .systemBlue+ window.isReleasedWhenClosed = false+ let button = NSButton(title: "Increment Counter", target: self, action: #selector(increment))+ button.setAccessibilityIdentifier("locked-use-validation-increment")+ button.frame = NSRect(x: 100, y: 50, width: 240, height: 44)+ label.frame = NSRect(x: 100, y: 120, width: 250, height: 34)+ label.font = .systemFont(ofSize: 24)+ label.textColor = .white+ window.contentView?.addSubview(button)+ window.contentView?.addSubview(label)+ }+ func show() { window.makeKeyAndOrderFront(nil); NSApp.activate(ignoringOtherApps: true) }+ @objc private func increment() { counter += 1; label.stringValue = "Counter: \(counter)" }+}diff --git a/experiments/LockedUse/Sources/Guardian/GuardReleaseAcknowledgement.swift b/experiments/LockedUse/Sources/Guardian/GuardReleaseAcknowledgement.swiftnew file mode 100644index 0000000..8505b1f--- /dev/null+++ b/experiments/LockedUse/Sources/Guardian/GuardReleaseAcknowledgement.swift@@ -0,0 +1,30 @@+import Foundation+import OpenComputerUseKit+import os++/// Called only after a guard's own drain/presentation barrier closed its+/// windows. Reauthenticate the same audit-token/code identity for the ACK;+/// a failed periodic report must not make terminal cleanup silently vanish.+enum GuardReleaseAcknowledgement {+ static func send(bootstrap: LockedUseGuardianBootstrap, watchdog: Bool, observedUnlock: Bool) -> Bool {+ let logger = Logger(subsystem: "dev.opencomputeruse.locked-use", category: "GuardRelease")+ let role = watchdog ? "watchdog" : "main"+ for attempt in 1...3 {+ do {+ let client = try LockedUseIPCClient(endpoint: .guardian, brokerRequirement: LockedUseSigningIdentity.brokerRequirement())+ defer { client.close() }+ let hello = try client.request(.init(operation: watchdog ? .watchdogRecoveryHello : .guardianRecoveryHello,+ leaseID: bootstrap.leaseID, session: .current(), hasObservedUnlock: observedUnlock))+ guard hello.result != .denied else { throw GuardianError.message("Release identity rejected") }+ let reply = try client.request(.init(operation: watchdog ? .watchdogReleased : .guardianReleased,+ leaseID: bootstrap.leaseID))+ guard reply.result != .denied else { throw GuardianError.message("Release acknowledgment rejected") }+ logger.notice("releaseAcknowledged role=\(role, privacy: .public) attempt=\(attempt, privacy: .public)")+ return true+ } catch {+ logger.notice("releaseRetry role=\(role, privacy: .public) attempt=\(attempt, privacy: .public)")+ }+ }+ return false+ }+}diff --git a/experiments/LockedUse/Sources/Guardian/GuardianMain.swift b/experiments/LockedUse/Sources/Guardian/GuardianMain.swiftnew file mode 100644index 0000000..c416410--- /dev/null+++ b/experiments/LockedUse/Sources/Guardian/GuardianMain.swift@@ -0,0 +1,306 @@+import AppKit+@preconcurrency import ApplicationServices+import Carbon+import Darwin+import Foundation+import OpenComputerUseKit+import os++func emit(_ event: String, details: [String: Any] = [:]) {+ var value = details+ value["event"] = event+ value["uptime"] = ProcessInfo.processInfo.systemUptime+ if let data = try? JSONSerialization.data(withJSONObject: value, options: [.sortedKeys]) {+ FileHandle.standardOutput.write(data)+ FileHandle.standardOutput.write(Data([10]))+ }+}++@main+struct GuardianMain {+ @MainActor static func main() {+ signal(SIGPIPE, SIG_IGN)+ do {+ switch Array(CommandLine.arguments.dropFirst()) {+ case ["--recovery-deadline-self-test"]:+ // A deliberately wedged main thread, without AppKit, shields,+ // input interception, authorization, or any lock request.+ let deadline = LockedUseRecoveryDeadline { _exit(70) }+ deadline.arm(after: 0.5)+ withExtendedLifetime(deadline) { Thread.sleep(forTimeInterval: 30) }+ throw GuardianError.message("Recovery deadline did not stop the wedged process")+ case ["--external-fixture"]:+ let app = NSApplication.shared+ app.setActivationPolicy(.regular)+ let fixture = ExternalFixture()+ fixture.show()+ withExtendedLifetime(fixture) { app.run() }+ case ["--unshielded-unlock-diagnostic", "--confirm-visible-desktop-test"]:+ try runUnshieldedUnlockDiagnostic()+ case ["--broker-guardian"]:+ let bootstrap = try readGuardianBootstrap()+ let app = NSApplication.shared+ app.setActivationPolicy(.accessory)+ // Initialize AppKit's screen/layout state before publishing+ // full-display shields; run() must not relocate them afterward.+ app.finishLaunching()+ let guardian = try DisplayGuardian(session: .current(), brokerBootstrap: bootstrap)+ try guardian.start()+ withExtendedLifetime(guardian) { app.run() }+ case ["--watchdog-surface-self-test"]:+ let app = NSApplication.shared+ app.setActivationPolicy(.accessory)+ app.finishLaunching()+ let shield = try WatchdogShield(stop: { _ in })+ _ = RunLoop.main.run(mode: .default, before: Date(timeIntervalSinceNow: 0.1))+ let failure = shield.healthFailure+ shield.close()+ emit("watchdogSurfaceSelfTest", details: ["passed": failure == nil,+ "failure": failure ?? "", "unlockRequested": false, "lockRequested": false])+ guard failure == nil else { throw GuardianError.message("Independent surface self-test failed") }+ case ["--broker-watchdog"]:+ try runWatchdog(persistent: true)+ case let args where args.count == 2 && args[0] == "--render-shield":+ let app = NSApplication.shared+ app.setActivationPolicy(.accessory)+ app.finishLaunching()+ guard let screen = NSScreen.main else { throw GuardianError.message("No screen for appearance render") }+ let view = ShieldAppearance(frame: NSRect(x: 0, y: 0, width: 1800, height: 1200), screen: screen, message: LockedUseShieldStatus.message)+ view.layoutSubtreeIfNeeded()+ let visible = NSRect(x: 300, y: 200, width: 1200, height: 800)+ guard let bitmap = view.bitmapImageRepForCachingDisplay(in: visible) else { throw GuardianError.message("Cannot render appearance") }+ view.cacheDisplay(in: visible, to: bitmap)+ guard let png = bitmap.representation(using: .png, properties: [:]) else { throw GuardianError.message("Cannot encode appearance") }+ try png.write(to: URL(fileURLWithPath: args[1]), options: .atomic)+ try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: args[1])+ emit("shieldAppearanceRendered", details: ["lockRequested": false, "unlockRequested": false])+ case ["--shield-preview"]:+ let app = NSApplication.shared+ app.setActivationPolicy(.accessory)+ let preview = ShieldPreview()+ try preview.start()+ withExtendedLifetime(preview) { app.run() }+ guard preview.passed else { throw GuardianError.message("Shield preview ended before completing coverage") }+ case ["--fixture-ax-self-test"]:+ let app = NSApplication.shared+ app.setActivationPolicy(.accessory)+ let guardian = try DisplayGuardian(session: .current())+ Task { @MainActor in+ do { try guardian.runFixtureAXSelfTest() }+ catch { emit("error", details: ["message": String(describing: error)]) }+ app.stop(nil)+ if let event = NSEvent.otherEvent(with: .applicationDefined, location: .zero,+ modifierFlags: [], timestamp: 0, windowNumber: 0, context: nil, subtype: 0, data1: 0, data2: 0) {+ app.postEvent(event, atStart: true)+ }+ }+ app.run()+ guard guardian.fixtureAXSelfTestPassed else { throw GuardianError.message("Fixture AX self-test failed") }+ case ["--request-lock"]:+ let lock = ScreenLock()+ guard lock.available else { throw GuardianError.message("Relock SPI unavailable") }+ lock.request()+ emit("lockRequested", details: ["confirmed": false, "unlockRequested": false])+ case ["--peer-self-test"]:+ var descriptors: [Int32] = [-1, -1]+ guard socketpair(AF_UNIX, SOCK_STREAM, 0, &descriptors) == 0 else {+ throw GuardianError.message("socketpair failed")+ }+ defer { close(descriptors[0]); close(descriptors[1]) }+ let requirement = "identifier \"dev.opencomputeruse.locked-use.guardian.dev\" and anchor apple generic"+ let identity = try LockedUsePeerIdentity.verified(socket: descriptors[0], requirement: requirement)+ guard identity.userID == geteuid(), identity.processID == getpid(),+ identity.auditSessionID == LockedUseSession.current().auditSessionID else {+ throw GuardianError.message("Kernel peer identity disagrees with the current process")+ }+ var denied = false+ do { _ = try LockedUsePeerIdentity.verified(socket: descriptors[0], requirement: "identifier \"dev.invalid.client\"") }+ catch { denied = true }+ guard denied else { throw GuardianError.message("Wrong signing identifier was accepted") }+ guard let team = identity.teamIdentifier else { throw GuardianError.message("Developer ID team is missing") }+ let approval = try LockedUseClientApprovals.Approval(userID: identity.userID, role: .guardian,+ signingIdentifier: identity.signingIdentifier, teamIdentifier: team)+ let records = try LockedUseClientApprovals(approvals: [approval])+ _ = try records.verifiedPeer(socket: descriptors[0], role: .guardian)+ var wrongRoleDenied = false+ do { _ = try records.verifiedPeer(socket: descriptors[0], role: .client) }+ catch { wrongRoleDenied = true }+ guard wrongRoleDenied else { throw GuardianError.message("Unapproved role was accepted") }+ emit("peerSelfTest", details: ["verified": true, "wrongSignerRejected": denied,+ "identifier": identity.signingIdentifier, "auditSessionMatches": true,+ "approvedRoleVerified": true, "wrongRoleRejected": wrongRoleDenied])+ case ["--request-permissions"]:+ _ = AXIsProcessTrustedWithOptions([kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary)+ _ = CGRequestListenEventAccess()+ emit("permissionRequests", details: ["accessibility": AXIsProcessTrusted(),+ "inputMonitoring": CGPreflightListenEventAccess()])+ case ["--session-only"]:+ emit("sessionState", details: ["session": LockedUseSession.current().state.rawValue])+ case ["--diagnose"]:+ emit("diagnostics", details: ["accessibility": AXIsProcessTrusted(),+ "inputMonitoring": CGPreflightListenEventAccess(),+ "screenRecording": CGPreflightScreenCaptureAccess(),+ "lockSPIAvailable": ScreenLock().available,+ "secureInput": IsSecureEventInputEnabled(),+ "session": LockedUseSession.current().state.rawValue,+ "backendValidated": false])+ case ["--inspect-loginwindow"]:+ try inspectLoginwindow()+ case ["--watchdog"]:+ try runWatchdog()+ case ["--rehearse", "--confirm-lock-test"]:+ let app = NSApplication.shared+ app.setActivationPolicy(.accessory)+ let guardian = try DisplayGuardian(session: .current())+ try guardian.start()+ withExtendedLifetime(guardian) { app.run() }+ if LockedUseSession.current().state == .locked { try inspectLoginwindow() }+ case ["--watchdog-test", "--confirm-lock-test"]:+ let app = NSApplication.shared+ app.setActivationPolicy(.accessory)+ let guardian = try DisplayGuardian(session: .current(), injectWatchdogStall: true)+ try guardian.start()+ withExtendedLifetime(guardian) { app.run() }+ guard guardian.watchdogTestPassed else { throw GuardianError.message("Independent watchdog stall test did not pass") }+ if LockedUseSession.current().state == .locked { try inspectLoginwindow() }+ default:+ fputs("Usage: OCUGuardian --diagnose | --request-permissions | --inspect-loginwindow | --shield-preview | --rehearse --confirm-lock-test\nPreview shows the shield for 15 seconds without locking; countdown is logged. Rehearsal consumes local input and locks the Mac. No unlock is attempted.\n", stderr)+ exit(64)+ }+ } catch {+ emit("error", details: ["message": String(describing: error)])+ exit(1)+ }+ }++ /// Read structure and advertised actions. Classify public button labels only+ /// against fixed Apple resources/current account; never output labels or+ /// fetch field values, selected text or authorization password context.+ @MainActor static func inspectLoginwindow() throws {+ guard AXIsProcessTrusted() else { throw GuardianError.message("Accessibility permission is required") }+ guard LockedUseSession.current().state == .locked else {+ throw GuardianError.message("Inspect loginwindow only during a manually locked, completed user session")+ }+ guard let process = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.loginwindow").first else {+ throw GuardianError.message("No loginwindow process")+ }+ var count = 0+ let deadline = ProcessInfo.processInfo.systemUptime + 3+ func visit(_ element: AXUIElement, depth: Int) {+ guard count < 300, depth < 12, ProcessInfo.processInfo.systemUptime < deadline else { return }+ count += 1+ func string(_ attribute: String) -> String {+ var value: CFTypeRef?+ guard AXUIElementCopyAttributeValue(element, attribute as CFString, &value) == .success else { return "" }+ return value as? String ?? ""+ }+ if string(kAXRoleAttribute) == kAXButtonRole {+ let labels = [string(kAXTitleAttribute), string(kAXDescriptionAttribute), string(kAXHelpAttribute)]+ let owners = Set([NSUserName(), NSFullUserName()].filter { !$0.isEmpty })+ emit("buttonPublicLabelClass", details: ["depth": depth,+ "matchesCurrentAccount": labels.contains(where: owners.contains),+ "systemKeys": LockScreenPublicLabels.matchingKeys(labels)])+ }+ var actions: CFArray?+ let actionStatus = AXUIElementCopyActionNames(element, &actions)+ emit("axStructure", details: ["depth": depth, "role": string(kAXRoleAttribute),+ "subrole": string(kAXSubroleAttribute), "actions": actions as? [String] ?? [],+ "actionStatus": actionStatus.rawValue])+ var children: CFTypeRef?+ let childrenStatus = AXUIElementCopyAttributeValue(element, kAXChildrenAttribute as CFString, &children)+ if childrenStatus == .success {+ for child in (children as? [AXUIElement] ?? []).prefix(300 - count) { visit(child, depth: depth + 1) }+ } else {+ emit("axChildrenUnavailable", details: ["depth": depth, "status": childrenStatus.rawValue])+ }+ }+ let root = AXUIElementCreateApplication(process.processIdentifier)+ AXUIElementSetMessagingTimeout(root, 0.5)+ visit(root, depth: 0)+ var focused: CFTypeRef?+ let focusStatus = AXUIElementCopyAttributeValue(root, kAXFocusedUIElementAttribute as CFString, &focused)+ if let focused, CFGetTypeID(focused) == AXUIElementGetTypeID() {+ emit("focusedElementStructure", details: ["status": focusStatus.rawValue])+ visit(unsafeDowncast(focused, to: AXUIElement.self), depth: 0)+ } else { emit("focusedElementUnavailable", details: ["status": focusStatus.rawValue]) }+ emit("inspectionComplete", details: ["nodes": count, "unlockRequested": false])+ }+}++enum GuardianError: Error { case message(String) }++/// Separate process and protection surface. Root IPC uses a separate queue;+/// inherited heartbeat loss requests relock without waiting for root replies.+@MainActor func runWatchdog(persistent: Bool = false) throws {+ let bootstrap = persistent ? try readGuardianBootstrap() : nil+ let initial = LockedUseSession.current()+ guard (initial.state == .unlocked || (persistent && initial.state == .locked)), initial.userID != nil, initial.auditSessionID != nil,+ isatty(STDIN_FILENO) == 0 else { throw GuardianError.message("Watchdog requires an inherited pipe and an unlocked GUI session") }+ let lock = ScreenLock()+ guard lock.available else { throw GuardianError.message("Relock SPI is unavailable") }+ let pipe = HeartbeatPipe(STDIN_FILENO)+ var lastHeartbeat = ProcessInfo.processInfo.systemUptime+ var lastLock = -Double.infinity+ var stopping = false+ let logger = Logger(subsystem: "dev.opencomputeruse.locked-use", category: "Watchdog")+ var stopReason: String?+ func stop(_ reason: String) {+ if stopReason == nil { logger.notice("stopping reason=\(reason, privacy: .public)"); stopReason = reason }+ stopping = true+ }+ if persistent {+ let app = NSApplication.shared+ app.setActivationPolicy(.accessory)+ app.finishLaunching()+ }+ let shield = persistent ? try WatchdogShield(clickTag: bootstrap?.clickTag, returnTag: bootstrap?.returnTag,+ startupDeadline: bootstrap?.startupDeadline, stop: stop) : nil+ // Unlike the parent, this process drives RunLoop directly instead of+ // NSApplication.run(). Publish the first AppKit frame before health/RPC.+ if persistent { _ = RunLoop.main.run(mode: .default, before: Date(timeIntervalSinceNow: 0.05)) }+ lastHeartbeat = ProcessInfo.processInfo.systemUptime+ let lockPresentation = LockScreenPresentation(session: initial)+ var releaseSignalSeen = false+ var lockedAfterRelease = false+ let brokerLink = bootstrap.map { WatchdogBrokerLink(bootstrap: $0, protected: shield?.healthy == true) }+ if !persistent { _ = HeartbeatPipe.send(82, to: STDOUT_FILENO) } // R requires root registration in broker mode+ while true {+ let now = ProcessInfo.processInfo.systemUptime+ let bytes = pipe.drain(allowed: [72, 76]) // H heartbeat, L guardian saw lock+ if bytes.contains(72), !stopping, now - lastHeartbeat < 1.5 { lastHeartbeat = now }+ if pipe.failed { stop("parentPipeFailed") }+ else if now - lastHeartbeat >= 1.5 { stop("parentHeartbeatExpired") }+ if stopping { shield?.cancelNativeClick() }+ let current = LockedUseSession.current()+ shield?.updateStatus(now: now, session: current, stopping: stopping)+ let same = current.userID == initial.userID && current.auditSessionID == initial.auditSessionID+ let protected = shield?.healthy ?? true+ if !protected { stop(shield?.healthFailure ?? "protectionUnavailable") }+ brokerLink?.observe(current, protected: protected, stopping: stopping)+ if brokerLink?.ready == true { _ = HeartbeatPipe.send(82, to: STDOUT_FILENO) }+ releaseSignalSeen = releaseSignalSeen || bytes.contains(76) || brokerLink?.releaseRequested == true+ let releaseRequested = releaseSignalSeen+ if releaseRequested, same, current.state == .locked { lockedAfterRelease = true }+ let localRecovery = releaseRequested && lockedAfterRelease && shield?.localRecoveryRequested == true+ if localRecovery { shield?.allowLocalLoginInput() }+ let presentationReady = lockPresentation.ready(session: current, requested: releaseRequested, now: now)+ if releaseRequested, same, (current.state == .locked && presentationReady || current.state == .unlocked && localRecovery) {+ shield?.close()+ brokerLink?.finish()+ return+ }+ if stopping {+ if same, current.state == .locked, !persistent { return }+ if !localRecovery, !(same && current.state == .locked), now - lastLock >= 0.5 {+ // S reports a request only; the Guardian must still observe+ // the original session locked before releasing its windows.+ _ = HeartbeatPipe.send(83, to: STDOUT_FILENO)+ lock.request()+ lastLock = now+ }+ } else if !same || current.state == .unavailable { stop("sessionChanged") }+ _ = HeartbeatPipe.send(72, to: STDOUT_FILENO)+ if persistent { _ = RunLoop.main.run(mode: .default, before: Date(timeIntervalSinceNow: 0.1)) }+ else { Thread.sleep(forTimeInterval: 0.1) }+ }+}diff --git a/experiments/LockedUse/Sources/Guardian/LockScreenInteractor.swift b/experiments/LockedUse/Sources/Guardian/LockScreenInteractor.swiftnew file mode 100644index 0000000..2e51a78--- /dev/null+++ b/experiments/LockedUse/Sources/Guardian/LockScreenInteractor.swift@@ -0,0 +1,323 @@+import Foundation+@preconcurrency import ApplicationServices+import AppKit+import Security+import OpenComputerUseKit+import os+import IOKit.pwr_mgt++typealias UnlockCancellation = LockedUseUnlockCancellation++enum LockScreenInteractor {+ /// Wake once, await complete AX publication and clear the selected field.+ /// This observes readiness, not authentication. The mechanism claim starts+ /// the short permit; the original session must separately become unlocked.+ static func wake(session: LockedUseSession, cancellation: UnlockCancellation, ui: LockUIObservation, clickTag: Int64? = nil, validationConfirmation: Bool = false, unshieldedReturn: Bool = false, returnTag: Int64? = nil) -> Bool {+ guard cancellation.allowsRequest(), session.state == .locked,+ LockedUseSession.current() == session else { return false }+ var activity: IOPMAssertionID = 0+ let status = IOPMAssertionDeclareUserActivity("Open Computer Use protected lock UI" as CFString,+ kIOPMUserActiveLocal, &activity)+ if activity != 0 { _ = IOPMAssertionRelease(activity) }+ let logger = Logger(subsystem: "dev.opencomputeruse.locked-use", category: "UnlockTrigger")+ logger.notice("displayWakeReturned status=\(status, privacy: .public) authenticationRequested=false")+ guard status == kIOReturnSuccess else { return false }+ let began = ProcessInfo.processInfo.systemUptime+ let deadline = began + 3+ var attempt = 0+ var confirmationAttempted = false+ while ProcessInfo.processInfo.systemUptime < deadline {+ guard cancellation.allowsRequest() else { return false }+ let current = LockedUseSession.current()+ if current.userID == session.userID, current.auditSessionID == session.auditSessionID,+ current.state == .unlocked { return true }+ guard current == session else { return false }+ attempt += 1+ logger.notice("AXPublication attempt=\(attempt, privacy: .public)")+ if probe(session: session, cancellation: cancellation, logger: logger, clickTag: clickTag, validationConfirmation: validationConfirmation, confirmationAttempted: &confirmationAttempted, requestDeadline: deadline, unshieldedReturn: unshieldedReturn, returnTag: returnTag) {+ // The fallback tile can reveal the real password field only+ // after click delivery. Re-query, never reuse a stale element+ // or spend another input capability. Stay within the same limit.+ let followupDeadline = min(deadline, ProcessInfo.processInfo.systemUptime + 1.5)+ while clickTag != nil, ProcessInfo.processInfo.systemUptime < followupDeadline,+ cancellation.allowsRequest(), LockedUseSession.current() == session {+ Thread.sleep(forTimeInterval: 0.15)+ logger.notice("AXPublication followup=true")+ if probe(session: session, cancellation: cancellation, logger: logger,+ clickTag: nil, passwordOnly: true, validationConfirmation: validationConfirmation, confirmationAttempted: &confirmationAttempted, requestDeadline: deadline, unshieldedReturn: unshieldedReturn, returnTag: returnTag) { break }+ }+ break+ }+ Thread.sleep(forTimeInterval: 0.1)+ }+ logger.notice("lockUISettled elapsed=\(ProcessInfo.processInfo.systemUptime - began, privacy: .public) notificationObserved=\(ui.observed, privacy: .public)")+ return cancellation.allowsRequest()+ }++ private static func probe(session: LockedUseSession, cancellation: UnlockCancellation, logger: Logger,+ clickTag: Int64?, passwordOnly: Bool = false, validationConfirmation: Bool = false, confirmationAttempted: inout Bool, requestDeadline: TimeInterval, unshieldedReturn: Bool = false, returnTag: Int64? = nil) -> Bool {+ guard cancellation.allowsRequest(), LockedUseSession.current() == session, AXIsProcessTrusted() else { return false }+ let processes = NSWorkspace.shared.runningApplications.filter {+ $0.localizedName == "loginwindow" || $0.bundleIdentifier == "com.apple.loginwindow"+ }+ guard processes.count == 1, let process = processes.first else {+ logger.notice("AXProbe processUnavailable=true"); return false+ }+ func trusted() -> Bool {+ var code: SecCode?+ var requirement: SecRequirement?+ guard !process.isTerminated,+ SecCodeCopyGuestWithAttributes(nil,+ [kSecGuestAttributePid as String: NSNumber(value: process.processIdentifier)] as CFDictionary,+ [], &code) == errSecSuccess, let code,+ SecRequirementCreateWithString("anchor apple and identifier \"com.apple.loginwindow\"" as CFString,+ [], &requirement) == errSecSuccess, let requirement else { return false }+ return SecCodeCheckValidity(code, [], requirement) == errSecSuccess+ }+ guard trusted() else { logger.notice("AXProbe processSignatureRejected=true"); return false }+ let root = AXUIElementCreateApplication(process.processIdentifier)+ let deadline = ProcessInfo.processInfo.systemUptime + 0.75+ var visited: [AXUIElement] = []+ var primary: [AXUIElement] = [], fallback: [AXUIElement] = []+ var enabledButtons = 0, disabledButtons = 0, unknownButtons = 0+ var complete = true+ func visit(_ element: AXUIElement, depth: Int) {+ guard depth <= 8 else { complete = false; return }+ guard !visited.contains(where: { CFEqual($0, element) }) else { return }+ guard visited.count < 300, ProcessInfo.processInfo.systemUptime < deadline,+ cancellation.allowsRequest() else { complete = false; return }+ visited.append(element)+ AXUIElementSetMessagingTimeout(element, 0.05)+ var role: CFTypeRef?+ if AXUIElementCopyAttributeValue(element, kAXRoleAttribute as CFString, &role) == .success,+ role as? String == kAXButtonRole {+ var enabled: CFTypeRef?+ if AXUIElementCopyAttributeValue(element, kAXEnabledAttribute as CFString, &enabled) == .success,+ let flag = enabled as? Bool {+ if flag { enabledButtons += 1 } else { disabledButtons += 1 }+ } else { unknownButtons += 1 }+ }+ var identifier: CFTypeRef?+ _ = AXUIElementCopyAttributeValue(element, kAXIdentifierAttribute as CFString, &identifier)+ if identifier as? String == "UserPasswordTextField" { primary.append(element) }+ if identifier as? String == "FocusedUser" { fallback.append(element) }+ guard ProcessInfo.processInfo.systemUptime < deadline else { complete = false; return }+ var children: CFTypeRef?+ let result = AXUIElementCopyAttributeValue(element, kAXChildrenAttribute as CFString, &children)+ if result == .success {+ for child in children as? [AXUIElement] ?? [] { visit(child, depth: depth + 1) }+ } else if result != .noValue && result != .attributeUnsupported { complete = false }+ }+ visit(root, depth: 0)+ logger.notice("AXProbe nodes=\(visited.count, privacy: .public) primaryMatches=\(primary.count, privacy: .public) fallbackMatches=\(fallback.count, privacy: .public) complete=\(complete, privacy: .public)")+ let candidates = passwordOnly ? primary : primary.isEmpty ? fallback : primary+ let uiState = complete && candidates.count == 1 ? "candidateFound" : complete ? "candidateUnavailable" : "unknown"+ logger.notice("lockUIState=\(uiState, privacy: .public) authenticationEvidence=false")+ guard complete, candidates.count == 1, cancellation.allowsRequest(),+ LockedUseSession.current() == session, trusted() else { return false }+ var settable: DarwinBoolean = false+ let availability = AXUIElementIsAttributeSettable(candidates[0], kAXValueAttribute as CFString, &settable)+ logger.notice("AXProbe writable=\(settable.boolValue, privacy: .public) status=\(availability.rawValue, privacy: .public)")+ // Clear only the unique identifier-selected field; never read its value.+ // A successful write does not prove authentication has started.+ guard cancellation.allowsRequest(), LockedUseSession.current() == session else { return false }+ let result = cancellation.performProbe {+ AXUIElementSetAttributeValue(candidates[0], kAXValueAttribute as CFString, "" as CFString)+ }+ logger.notice("AXTrigger emptyValueWrite status=\(result?.rawValue ?? -1, privacy: .public)")+ if primary.count == 1 {+ logger.notice("AXProbe passwordUI enabledButtons=\(enabledButtons, privacy: .public) disabledButtons=\(disabledButtons, privacy: .public) unknownButtons=\(unknownButtons, privacy: .public)")+ var focused: CFTypeRef?+ let focusStatus = AXUIElementCopyAttributeValue(candidates[0], kAXFocusedAttribute as CFString, &focused)+ logger.notice("AXProbe passwordFocused=\((focused as? Bool) == true, privacy: .public) status=\(focusStatus.rawValue, privacy: .public)")+ // Return requires the explicit unshielded diagnostic or a separate+ // inherited one-pair capability admitted by both protected taps.+ if unshieldedReturn || returnTag != nil, !confirmationAttempted, result == .success,+ availability == .success, settable.boolValue, focusStatus == .success,+ (focused as? Bool) == true {+ confirmationAttempted = true+ let sent = cancellation.performProbe {+ guard ProcessInfo.processInfo.systemUptime < requestDeadline,+ LockedUseSession.current() == session, trusted(),+ CGEventSource.flagsState(.combinedSessionState)+ .intersection([.maskShift, .maskControl, .maskAlternate, .maskCommand]).isEmpty,+ let source = CGEventSource(stateID: .privateState),+ let down = CGEvent(keyboardEventSource: source, virtualKey: 36, keyDown: true),+ let up = CGEvent(keyboardEventSource: source, virtualKey: 36, keyDown: false)+ else { return false }+ // Recheck focus after signature lookup, before posting.+ var currentFocus: CFTypeRef?+ guard AXUIElementCopyAttributeValue(candidates[0], kAXFocusedAttribute as CFString, ¤tFocus) == .success,+ (currentFocus as? Bool) == true,+ LockedUseSession.current() == session,+ ProcessInfo.processInfo.systemUptime < requestDeadline else { return false }+ down.flags = []; up.flags = []+ if let returnTag {+ for event in [down, up] {+ event.setIntegerValueField(.eventSourceUserData, value: returnTag)+ event.setIntegerValueField(.eventSourceUnixProcessID, value: Int64(getpid()))+ event.setIntegerValueField(.eventTargetUnixProcessID, value: Int64(process.processIdentifier))+ }+ }+ down.setIntegerValueField(.keyboardEventAutorepeat, value: 0)+ up.setIntegerValueField(.keyboardEventAutorepeat, value: 0)+ logger.notice("AXTrigger returnDispatching=true keyCode=36 tap=hid")+ down.post(tap: .cghidEventTap)+ // Always release once dispatched, even if cancellation+ // arrives between the pair. No repeat or text payload.+ up.post(tap: .cghidEventTap)+ return true+ }+ logger.notice("AXTrigger returnPairQueued=\(sent == true, privacy: .public) authenticationEvidence=false")+ }+ // Validation experiment: ask the real field which actions it+ // supports before attempting one confirmation of the empty value.+ // Do not infer support from writability or synthesize a global key.+ var actions: CFArray?+ let actionStatus = AXUIElementCopyActionNames(candidates[0], &actions)+ let supportsConfirm = actionStatus == .success &&+ (actions as? [String] ?? []).contains(kAXConfirmAction)+ logger.notice("AXTrigger passwordConfirmSupported=\(supportsConfirm, privacy: .public) status=\(actionStatus.rawValue, privacy: .public)")+ if validationConfirmation, !unshieldedReturn, returnTag == nil, !confirmationAttempted, supportsConfirm, result == .success {+ confirmationAttempted = true+ let confirm = cancellation.performProbe {+ guard LockedUseSession.current() == session, trusted() else { return AXError.cannotComplete }+ // The traversal timeout belongs to reads. An action may+ // need longer to reply; never exceed the original request+ // deadline and never retry an ambiguously completed action.+ let remaining = requestDeadline - ProcessInfo.processInfo.systemUptime+ guard remaining >= 0.1 else {+ logger.notice("AXTrigger passwordConfirmSkipped=deadline")+ return AXError.cannotComplete+ }+ let timeout = Float(min(2, remaining))+ let configured = AXUIElementSetMessagingTimeout(candidates[0], timeout)+ logger.notice("AXTrigger passwordConfirmTimeout milliseconds=\(Int(timeout * 1000), privacy: .public) status=\(configured.rawValue, privacy: .public)")+ guard configured == .success else { return configured }+ defer { _ = AXUIElementSetMessagingTimeout(candidates[0], 0.05) }+ logger.notice("AXTrigger passwordConfirmDispatching=true")+ let began = ProcessInfo.processInfo.systemUptime+ let actionResult = AXUIElementPerformAction(candidates[0], kAXConfirmAction as CFString)+ let elapsed = Int((ProcessInfo.processInfo.systemUptime - began) * 1000)+ logger.notice("AXTrigger passwordConfirmElapsed milliseconds=\(elapsed, privacy: .public) status=\(actionResult.rawValue, privacy: .public)")+ return actionResult+ }+ logger.notice("AXTrigger passwordConfirm status=\(confirm?.rawValue ?? -1, privacy: .public) authenticationEvidence=false")+ }+ }+ // One window-bound session-stage click, admitted by both independent+ // filters through the inherited one-use capability. No PID-only bypass.+ guard primary.isEmpty, let clickTag else { return true }+ var positionValue: CFTypeRef?, sizeValue: CFTypeRef?+ guard result == .success,+ AXUIElementCopyAttributeValue(candidates[0], kAXPositionAttribute as CFString, &positionValue) == .success,+ AXUIElementCopyAttributeValue(candidates[0], kAXSizeAttribute as CFString, &sizeValue) == .success,+ let positionValue, let sizeValue,+ CFGetTypeID(positionValue) == AXValueGetTypeID(), CFGetTypeID(sizeValue) == AXValueGetTypeID() else { return true }+ var position = CGPoint.zero, size = CGSize.zero+ guard AXValueGetValue(positionValue as! AXValue, .cgPoint, &position),+ AXValueGetValue(sizeValue as! AXValue, .cgSize, &size),+ [position.x, position.y, size.width, size.height].allSatisfy({ $0.isFinite }),+ size.width > 0, size.height > 0 else { return true }+ let point = CGPoint(x: position.x + size.width / 2, y: position.y + size.height / 2)+ var axWindow: CFTypeRef?+ guard AXUIElementCopyAttributeValue(candidates[0], kAXWindowAttribute as CFString, &axWindow) == .success,+ let axWindow, CFGetTypeID(axWindow) == AXUIElementGetTypeID() else {+ logger.notice("AXTrigger sessionClickWindowAvailable=false"); return true+ }+ let windowElement = axWindow as! AXUIElement+ var windowPositionValue: CFTypeRef?, windowSizeValue: CFTypeRef?+ guard AXUIElementCopyAttributeValue(windowElement, kAXPositionAttribute as CFString, &windowPositionValue) == .success,+ AXUIElementCopyAttributeValue(windowElement, kAXSizeAttribute as CFString, &windowSizeValue) == .success,+ let windowPositionValue, let windowSizeValue,+ CFGetTypeID(windowPositionValue) == AXValueGetTypeID(), CFGetTypeID(windowSizeValue) == AXValueGetTypeID() else {+ logger.notice("AXTrigger sessionClickWindowAvailable=false"); return true+ }+ var windowPosition = CGPoint.zero, windowSize = CGSize.zero+ guard AXValueGetValue(windowPositionValue as! AXValue, .cgPoint, &windowPosition),+ AXValueGetValue(windowSizeValue as! AXValue, .cgSize, &windowSize),+ [windowPosition.x, windowPosition.y, windowSize.width, windowSize.height].allSatisfy({ $0.isFinite }),+ windowSize.width > 0, windowSize.height > 0 else { return true }+ let axFrame = CGRect(origin: windowPosition, size: windowSize)+ let windows = CGWindowListCopyWindowInfo(.optionOnScreenOnly, kCGNullWindowID) as? [[String: Any]] ?? []+ let targets = windows.filter { info in+ guard (info[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value == process.processIdentifier,+ let bounds = info[kCGWindowBounds as String] as? NSDictionary,+ let frame = CGRect(dictionaryRepresentation: bounds) else { return false }+ return frame.contains(point) && abs(frame.minX - axFrame.minX) <= 1 &&+ abs(frame.minY - axFrame.minY) <= 1 && abs(frame.width - axFrame.width) <= 1 &&+ abs(frame.height - axFrame.height) <= 1+ }+ logger.notice("AXTrigger sessionClickWindowMatches=\(targets.count, privacy: .public)")+ guard targets.count == 1,+ let windowID = targets[0][kCGWindowNumber as String] as? NSNumber,+ let source = CGEventSource(stateID: .privateState),+ let down = NSEvent.mouseEvent(with: .leftMouseDown,+ location: CGPoint(x: point.x - axFrame.minX, y: axFrame.maxY - point.y),+ modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime,+ windowNumber: windowID.intValue, context: nil, eventNumber: 1, clickCount: 1, pressure: 1)?.cgEvent,+ let up = NSEvent.mouseEvent(with: .leftMouseUp,+ location: CGPoint(x: point.x - axFrame.minX, y: axFrame.maxY - point.y),+ modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime,+ windowNumber: windowID.intValue, context: nil, eventNumber: 2, clickCount: 1, pressure: 0)?.cgEvent else {+ logger.notice("AXTrigger sessionClickTargetAvailable=false"); return true+ }+ for event in [down, up] {+ event.setSource(source)+ event.location = point+ event.flags = []+ event.setIntegerValueField(.eventTargetUnixProcessID, value: Int64(process.processIdentifier))+ event.setIntegerValueField(.mouseEventWindowUnderMousePointer, value: windowID.int64Value)+ event.setIntegerValueField(.mouseEventWindowUnderMousePointerThatCanHandleThisEvent, value: windowID.int64Value)+ event.setIntegerValueField(.mouseEventClickState, value: 1)+ event.setIntegerValueField(.mouseEventSubtype, value: 3)+ event.setIntegerValueField(.eventSourceUserData, value: clickTag)+ do {+ try encodeLockedUseWindowLocation(event,+ point: CGPoint(x: point.x - axFrame.minX, y: axFrame.maxY - point.y))+ } catch {+ logger.notice("AXTrigger sessionClickWindowEncodingAvailable=false")+ return true+ }+ }+ let queued = cancellation.performProbe {+ guard LockedUseSession.current() == session, trusted() else { return false }+ // Single-variable validation experiment, enabled only by the+ // authenticated Root validation profile. Keep the same event pair+ // and both session filters; HID posting grants no input exemption.+ let tap: CGEventTapLocation = validationConfirmation ? .cghidEventTap : .cgSessionEventTap+ logger.notice("AXTrigger clickTap=\(validationConfirmation ? "hid" : "session", privacy: .public)")+ down.post(tap: tap)+ up.post(tap: tap)+ return true+ } ?? false+ logger.notice("AXTrigger sessionClickQueued=\(queued, privacy: .public)")+ return true+ }++}++/// Notifications are UI timing hints, never authentication/session evidence.+final class LockUIObservation: @unchecked Sendable {+ private let mutex = NSLock()+ private var lastHint: TimeInterval?+ private var tokens: [NSObjectProtocol] = []+ init() {+ for prefix in ["com.apple.", "com.apple.sessionagent."] {+ for suffix in ["screenIsLocked", "screenIsUnlocked", "screenLockUIIsShown"] {+ tokens.append(DistributedNotificationCenter.default().addObserver(+ forName: Notification.Name(prefix + suffix), object: nil, queue: nil) { [weak self] _ in+ guard let self else { return }+ self.mutex.lock(); self.lastHint = ProcessInfo.processInfo.systemUptime; self.mutex.unlock()+ })+ }+ }+ }+ var observed: Bool { mutex.lock(); defer { mutex.unlock() }; return lastHint != nil }+ func settled(since began: TimeInterval) -> Bool {+ mutex.lock(); let hint = lastHint; mutex.unlock()+ let now = ProcessInfo.processInfo.systemUptime+ return now - began >= 3 || hint.map { now - $0 >= 1.5 } == true+ }+ deinit { for token in tokens { DistributedNotificationCenter.default().removeObserver(token) } }+}diff --git a/experiments/LockedUse/Sources/Guardian/LockScreenPresentation.swift b/experiments/LockedUse/Sources/Guardian/LockScreenPresentation.swiftnew file mode 100644index 0000000..5a9dfd4--- /dev/null+++ b/experiments/LockedUse/Sources/Guardian/LockScreenPresentation.swift@@ -0,0 +1,64 @@+import AppKit+import Security+import OpenComputerUseKit+import os++/// Window metadata is a conservative handoff signal, not a pixel/compositor+/// guarantee. Both guards independently retain their opaque surfaces until it+/// is continuously stable; live physical-display validation remains required.+@MainActor+final class LockScreenPresentation {+ private let original: LockedUseSession+ private var barrier = LockedUseReleaseBarrier()+ private var process: NSRunningApplication?+ private var lastState: String?+ private let logger = Logger(subsystem: "dev.opencomputeruse.locked-use", category: "LockPresentation")+ init(session: LockedUseSession) { original = session }++ func ready(session: LockedUseSession, requested: Bool, now: TimeInterval) -> Bool {+ let locked = requested && session.state == .locked && session.userID == original.userID+ && session.auditSessionID == original.auditSessionID+ let evidence = locked ? presentation() : nil+ let ready = barrier.observe(locked: locked, presentation: evidence, now: now)+ let state = !locked ? "waitingForLock" : evidence == nil ? "waitingForCoverage" : ready ? "ready" : "stabilizing"+ if state != lastState {+ lastState = state+ logger.notice("releaseBarrier state=\(state, privacy: .public)")+ }+ return ready+ }+ private func presentation() -> String? {+ if process == nil || process?.isTerminated == true {+ let candidates = NSWorkspace.shared.runningApplications.filter { $0.bundleIdentifier == "com.apple.loginwindow" }+ guard candidates.count == 1, let candidate = candidates.first else { return nil }+ var code: SecCode?, requirement: SecRequirement?+ guard SecCodeCopyGuestWithAttributes(nil,+ [kSecGuestAttributePid as String: NSNumber(value: candidate.processIdentifier)] as CFDictionary, [], &code) == errSecSuccess,+ let code, SecRequirementCreateWithString("anchor apple and identifier \"com.apple.loginwindow\"" as CFString, [], &requirement) == errSecSuccess,+ let requirement, SecCodeCheckValidity(code, [], requirement) == errSecSuccess else { return nil }+ process = candidate+ }+ guard let process, !process.isTerminated,+ let windows = CGWindowListCopyWindowInfo(.optionOnScreenOnly, kCGNullWindowID) as? [[String: Any]] else { return nil }+ var count: UInt32 = 0+ guard CGGetActiveDisplayList(0, nil, &count) == .success, count > 0, count <= 64 else { return nil }+ var displays = [CGDirectDisplayID](repeating: 0, count: Int(count))+ guard CGGetActiveDisplayList(count, &displays, &count) == .success else { return nil }+ let backgrounds: [CGRect] = windows.compactMap { info in+ guard (info[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value == process.processIdentifier,+ (info[kCGWindowAlpha as String] as? NSNumber)?.doubleValue == 1,+ (info[kCGWindowLayer as String] as? NSNumber)?.intValue ?? -1 >= Int(CGWindowLevelForKey(.screenSaverWindow)),+ let bounds = info[kCGWindowBounds as String] as? [String: Any],+ let rect = CGRect(dictionaryRepresentation: bounds as CFDictionary) else { return nil }+ return rect+ }+ var fingerprint: [String] = []+ for id in displays.prefix(Int(count)).sorted() {+ let display = CGDisplayBounds(id)+ guard backgrounds.contains(where: { LockedUseShieldCoverage.covers($0, display: display) }) else { return nil }+ fingerprint.append("\(id):\(NSStringFromRect(display))")+ }+ fingerprint += backgrounds.map(NSStringFromRect).sorted()+ return fingerprint.joined(separator: "|")+ }+}diff --git a/experiments/LockedUse/Sources/Guardian/LockScreenPublicLabels.swift b/experiments/LockedUse/Sources/Guardian/LockScreenPublicLabels.swiftnew file mode 100644index 0000000..f8b34d6--- /dev/null+++ b/experiments/LockedUse/Sources/Guardian/LockScreenPublicLabels.swift@@ -0,0 +1,28 @@+import Foundation++/// Diagnostic classification against OS-owned localization resources. Return+/// only static resource keys, never an AX label, account name or field value.+enum LockScreenPublicLabels {+ private static let keys: [String: Set<String>] = {+ var result: [String: Set<String>] = [:]+ let roots = ["/System/Library/CoreServices/loginwindow.app/Contents/Resources",+ "/System/Library/PrivateFrameworks/LoginUIKit.framework/Versions/A/Resources",+ "/System/Library/PrivateFrameworks/LoginUIKit.framework/Versions/A/Frameworks/LoginUICore.framework/Versions/A/Resources"]+ for root in roots {+ for name in (try? FileManager.default.contentsOfDirectory(atPath: root)) ?? [] where name.hasSuffix(".loctable") {+ guard let data = try? Data(contentsOf: URL(fileURLWithPath: root).appendingPathComponent(name)), data.count <= 2 * 1024 * 1024,+ let table = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] else { continue }+ for locale in table.values {+ guard let values = locale as? [String: String] else { continue }+ for (key, value) in values where !value.isEmpty && key.utf8.count <= 100 && key.range(of: "^[A-Z0-9_]+$", options: .regularExpression) != nil {+ result[value, default: []].insert(key)+ }+ }+ }+ }+ return result+ }()+ static func matchingKeys(_ labels: [String]) -> [String] {+ Array(Set(labels.flatMap { Array(keys[$0] ?? []) })).sorted()+ }+}diff --git a/experiments/LockedUse/Sources/Guardian/LockUIClickFilter.swift b/experiments/LockedUse/Sources/Guardian/LockUIClickFilter.swiftnew file mode 100644index 0000000..28c4bb3--- /dev/null+++ b/experiments/LockedUse/Sources/Guardian/LockUIClickFilter.swift@@ -0,0 +1,62 @@+import CoreGraphics+import Foundation+import OpenComputerUseKit+import os++func recordLockUIClickAdmission(filter: String, type: CGEventType) {+ let logger = Logger(subsystem: "dev.opencomputeruse.locked-use", category: "LockUIClickFilter")+ let button = type == .leftMouseDown ? "down" : "up"+ logger.notice("clickAdmitted filter=\(filter, privacy: .public) type=\(button, privacy: .public)")+}++extension LockedUseClickAllowance {+ mutating func accepts(_ event: CGEvent, type: CGEventType, filter: String) -> Bool {+ let logger = Logger(subsystem: "dev.opencomputeruse.locked-use", category: "LockUIClickFilter")+ func reject(_ reason: String) -> Bool {+ logger.notice("clickRejected filter=\(filter, privacy: .public) reason=\(reason, privacy: .public)")+ return false+ }+ guard type == .leftMouseDown || type == .leftMouseUp else { return reject("type") }+ // Quartz adds non-keyboard flags during delivery. Only modifiers that+ // change a left click's semantics are prohibited; metadata flags and+ // Caps Lock cannot turn this capability into a keyboard event.+ let modifiers: CGEventFlags = [.maskShift, .maskControl, .maskAlternate, .maskCommand]+ logger.notice("clickFlags raw=\(event.flags.rawValue, privacy: .public) modifiers=\(event.flags.intersection(modifiers).rawValue, privacy: .public)")+ guard event.flags.intersection(modifiers).isEmpty else { return reject("flags") }+ guard event.getIntegerValueField(.mouseEventWindowUnderMousePointer) ==+ event.getIntegerValueField(.mouseEventWindowUnderMousePointerThatCanHandleThisEvent) else { return reject("window") }+ let accepted = accept(button: type == .leftMouseDown ? .down : .up,+ tag: event.getIntegerValueField(.eventSourceUserData),+ sender: Int32(clamping: event.getIntegerValueField(.eventSourceUnixProcessID)),+ target: Int32(clamping: event.getIntegerValueField(.eventTargetUnixProcessID)),+ window: event.getIntegerValueField(.mouseEventWindowUnderMousePointer),+ x: event.location.x, y: event.location.y,+ now: ProcessInfo.processInfo.systemUptime, locked: LockedUseSession.current().state == .locked)+ return accepted ? true : reject(rejection?.rawValue ?? "inactive")+ }+}+++extension LockedUseReturnAllowance {+ mutating func accepts(_ event: CGEvent, type: CGEventType, filter: String) -> Bool {+ guard type == .keyDown || type == .keyUp else { return false }+ let modifiers: CGEventFlags = [.maskShift, .maskControl, .maskAlternate, .maskCommand]+ let accepted = accept(isDown: type == .keyDown,+ tag: event.getIntegerValueField(.eventSourceUserData),+ sender: Int32(clamping: event.getIntegerValueField(.eventSourceUnixProcessID)),+ target: Int32(clamping: event.getIntegerValueField(.eventTargetUnixProcessID)),+ keyCode: event.getIntegerValueField(.keyboardEventKeycode),+ repeated: event.getIntegerValueField(.keyboardEventAutorepeat) != 0,+ modified: !event.flags.intersection(modifiers).isEmpty,+ session: LockedUseSession.current(), now: ProcessInfo.processInfo.systemUptime)+ let logger = Logger(subsystem: "dev.opencomputeruse.locked-use", category: "LockUIClickFilter")+ if accepted {+ let button = type == .keyDown ? "down" : "up"+ logger.notice("returnAdmitted filter=\(filter, privacy: .public) type=\(button, privacy: .public)")+ } else {+ let reason = rejection?.rawValue ?? "inactive"+ logger.notice("returnRejected filter=\(filter, privacy: .public) reason=\(reason, privacy: .public)")+ }+ return accepted+ }+}diff --git a/experiments/LockedUse/Sources/Guardian/PhysicalInputMonitor.swift b/experiments/LockedUse/Sources/Guardian/PhysicalInputMonitor.swiftnew file mode 100644index 0000000..369ef92--- /dev/null+++ b/experiments/LockedUse/Sources/Guardian/PhysicalInputMonitor.swift@@ -0,0 +1,63 @@+import ApplicationServices+import Foundation+import IOKit.hid++/// Supplement the filtering CG tap with hardware activity detection. No HID+/// values, key usages, text, device names or serial numbers are read or logged.+/// Secure Event Input delivery must be validated on the target OS before the+/// Broker's production validation stamp may be written.+@MainActor+final class PhysicalInputMonitor {+ private var manager: IOHIDManager?+ private let activity: @MainActor () -> Void+ private let failure: @MainActor () -> Void+ private(set) var healthy = false++ init(activity: @escaping @MainActor () -> Void, failure: @escaping @MainActor () -> Void) {+ self.activity = activity; self.failure = failure+ }++ func start() throws {+ guard CGPreflightListenEventAccess() else { throw GuardianError.message("Input Monitoring missing") }+ let manager = IOHIDManagerCreate(kCFAllocatorDefault, IOOptionBits(kIOHIDOptionsTypeNone))+ let matches: [[String: Int]] = [+ [kIOHIDDeviceUsagePageKey: kHIDPage_GenericDesktop, kIOHIDDeviceUsageKey: kHIDUsage_GD_Keyboard],+ [kIOHIDDeviceUsagePageKey: kHIDPage_GenericDesktop, kIOHIDDeviceUsageKey: kHIDUsage_GD_Mouse],+ [kIOHIDDeviceUsagePageKey: kHIDPage_GenericDesktop, kIOHIDDeviceUsageKey: kHIDUsage_GD_Pointer],+ [kIOHIDDeviceUsagePageKey: kHIDPage_Consumer, kIOHIDDeviceUsageKey: kHIDUsage_Csmr_ConsumerControl],+ ]+ IOHIDManagerSetDeviceMatchingMultiple(manager, matches as CFArray)+ let context = Unmanaged.passUnretained(self).toOpaque()+ IOHIDManagerRegisterInputValueCallback(manager, { pointer, result, _, _ in+ guard let pointer else { return }+ MainActor.assumeIsolated {+ let observer = Unmanaged<PhysicalInputMonitor>.fromOpaque(pointer).takeUnretainedValue()+ if result == kIOReturnSuccess { observer.activity() }+ else { observer.healthy = false; observer.failure() }+ }+ }, context)+ IOHIDManagerRegisterDeviceRemovalCallback(manager, { pointer, _, _, _ in+ guard let pointer else { return }+ MainActor.assumeIsolated {+ let observer = Unmanaged<PhysicalInputMonitor>.fromOpaque(pointer).takeUnretainedValue()+ observer.healthy = false; observer.failure()+ }+ }, context)+ IOHIDManagerScheduleWithRunLoop(manager, CFRunLoopGetMain(), CFRunLoopMode.commonModes.rawValue)+ self.manager = manager+ guard IOHIDManagerOpen(manager, IOOptionBits(kIOHIDOptionsTypeNone)) == kIOReturnSuccess,+ let devices = IOHIDManagerCopyDevices(manager), CFSetGetCount(devices) > 0 else {+ stop(); throw GuardianError.message("Hardware input activity monitor unavailable")+ }+ healthy = true+ }++ func stop() {+ healthy = false+ if let manager {+ IOHIDManagerUnscheduleFromRunLoop(manager, CFRunLoopGetMain(), CFRunLoopMode.commonModes.rawValue)+ _ = IOHIDManagerClose(manager, IOOptionBits(kIOHIDOptionsTypeNone))+ }+ manager = nil+ }+}diff --git a/experiments/LockedUse/Sources/Guardian/ScreenLock.swift b/experiments/LockedUse/Sources/Guardian/ScreenLock.swiftnew file mode 100644index 0000000..94b1352--- /dev/null+++ b/experiments/LockedUse/Sources/Guardian/ScreenLock.swift@@ -0,0 +1,48 @@+import Darwin+import Foundation++/// This private SPI requests a lock; only session observation confirms it.+/// Kept outside GUI tool dispatch and never used as an unlock primitive.+final class ScreenLock {+ private let handle: UnsafeMutableRawPointer?+ private let function: (@convention(c) () -> Void)?++ init() {+ handle = dlopen("/System/Library/PrivateFrameworks/login.framework/login", RTLD_NOW | RTLD_LOCAL)+ if let handle, let symbol = dlsym(handle, "SACLockScreenImmediate") {+ function = unsafeBitCast(symbol, to: (@convention(c) () -> Void).self)+ } else { function = nil }+ }+ var available: Bool { function != nil }+ func request() { function?() }+ deinit { if let handle { dlclose(handle) } }+}++/// Small inherited-pipe protocol. No public socket or arbitrary path is opened.+/// EOF, excess input and unknown bytes are failures, never permission to unlock.+final class HeartbeatPipe {+ let descriptor: Int32+ private(set) var failed = false+ init(_ descriptor: Int32) {+ self.descriptor = descriptor+ let flags = fcntl(descriptor, F_GETFL)+ if flags < 0 || fcntl(descriptor, F_SETFL, flags | O_NONBLOCK) < 0 { failed = true }+ }+ func drain(allowed: Set<UInt8>) -> [UInt8] {+ guard !failed else { return [] }+ var buffer = [UInt8](repeating: 0, count: 256)+ let count = Darwin.read(descriptor, &buffer, buffer.count)+ if count == 0 { failed = true; return [] }+ if count < 0 {+ if errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR { failed = true }+ return []+ }+ let result = Array(buffer.prefix(count))+ if count == buffer.count || result.contains(where: { !allowed.contains($0) }) { failed = true; return [] }+ return result+ }+ static func send(_ byte: UInt8, to descriptor: Int32) -> Bool {+ var value = byte+ return Darwin.write(descriptor, &value, 1) == 1+ }+}diff --git a/experiments/LockedUse/Sources/Guardian/ShieldAppearance.swift b/experiments/LockedUse/Sources/Guardian/ShieldAppearance.swiftnew file mode 100644index 0000000..269634f--- /dev/null+++ b/experiments/LockedUse/Sources/Guardian/ShieldAppearance.swift@@ -0,0 +1,115 @@+import AppKit+import CoreImage+import OpenDirectory+import OpenComputerUseKit++/// Local wallpaper files only: never captures the user's desktop or windows.+@MainActor+final class ShieldAppearance: NSView {+ private let wallpaper: NSImage?+ private let diagnostic = NSTextField(labelWithString: "")+ override var isOpaque: Bool { true }++ init(frame: NSRect, screen: NSScreen, message: String) {+ wallpaper = Self.wallpaper(for: screen)+ super.init(frame: frame)+ let avatar = NSImageView()+ avatar.image = Self.avatar() ?? NSImage(systemSymbolName: "person.crop.circle.fill", accessibilityDescription: nil)+ avatar.imageScaling = .scaleAxesIndependently+ avatar.wantsLayer = true+ avatar.layer?.cornerRadius = 40+ avatar.layer?.masksToBounds = true+ avatar.layer?.backgroundColor = NSColor.darkGray.cgColor+ let badge = NSView()+ badge.wantsLayer = true+ badge.layer?.cornerRadius = 20+ badge.layer?.masksToBounds = true+ badge.layer?.borderWidth = 0.5+ badge.layer?.borderColor = NSColor.white.withAlphaComponent(0.3).cgColor+ badge.layer?.backgroundColor = NSColor.darkGray.cgColor+ // Expand the icon's transparent export padding inside the circular+ // clip so its colored artwork fills the badge rather than floating.+ let logo = NSImageView(frame: NSRect(x: -4, y: -4, width: 48, height: 48))+ logo.image = Bundle.main.url(forResource: "OCUShieldLogo", withExtension: "png").flatMap { NSImage(contentsOf: $0) }+ logo.imageScaling = .scaleAxesIndependently+ badge.addSubview(logo)+ let title = NSTextField(labelWithString: "Open Computer Use is Using Your Mac")+ let subtitle = NSTextField(labelWithString: "Press any key or click to unlock")+ title.font = .systemFont(ofSize: 20, weight: .semibold)+ subtitle.font = .systemFont(ofSize: 15, weight: .medium)+ diagnostic.font = .systemFont(ofSize: 12)+ for label in [title, subtitle, diagnostic] {+ label.alignment = .center+ label.textColor = .white+ label.maximumNumberOfLines = 0+ label.setContentCompressionResistancePriority(.required, for: .horizontal)+ }+ for view in [avatar, badge, title, subtitle, diagnostic] {+ view.translatesAutoresizingMaskIntoConstraints = false+ addSubview(view)+ }+ NSLayoutConstraint.activate([+ avatar.centerXAnchor.constraint(equalTo: centerXAnchor),+ avatar.centerYAnchor.constraint(equalTo: centerYAnchor, constant: -55),+ avatar.widthAnchor.constraint(equalToConstant: 80), avatar.heightAnchor.constraint(equalToConstant: 80),+ badge.widthAnchor.constraint(equalToConstant: 40), badge.heightAnchor.constraint(equalToConstant: 40),+ badge.centerXAnchor.constraint(equalTo: avatar.trailingAnchor, constant: -8),+ badge.centerYAnchor.constraint(equalTo: avatar.bottomAnchor, constant: -8),+ title.centerXAnchor.constraint(equalTo: centerXAnchor),+ title.topAnchor.constraint(equalTo: avatar.bottomAnchor, constant: 35),+ subtitle.centerXAnchor.constraint(equalTo: centerXAnchor),+ subtitle.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 16),+ diagnostic.centerXAnchor.constraint(equalTo: centerXAnchor),+ diagnostic.topAnchor.constraint(equalTo: subtitle.bottomAnchor, constant: 20)+ ])+ updateMessage(message)+ }++ required init?(coder: NSCoder) { fatalError("init(coder:) unsupported") }++ func updateMessage(_ message: String) {+ // Only isolated diagnostics have a changing detail. Protected sessions+ // retain exactly the same two lines through authentication and exit.+ diagnostic.stringValue = message == LockedUseShieldStatus.message ? "" : message+ }++ override func draw(_ dirtyRect: NSRect) {+ NSColor(calibratedRed: 0.16, green: 0.21, blue: 0.29, alpha: 1).setFill()+ bounds.fill()+ if let wallpaper, wallpaper.size.width > 0, wallpaper.size.height > 0 {+ // The surface overscans the display for the system unlock animation;+ // keep the wallpaper's scale tied to the physical display area.+ let target = NSRect(x: bounds.width / 6, y: bounds.height / 6,+ width: bounds.width / 1.5, height: bounds.height / 1.5)+ let scale = max(target.width / wallpaper.size.width, target.height / wallpaper.size.height)+ let size = NSSize(width: wallpaper.size.width * scale, height: wallpaper.size.height * scale)+ let rect = NSRect(x: bounds.midX - size.width / 2, y: bounds.midY - size.height / 2, width: size.width, height: size.height)+ wallpaper.draw(in: rect, from: .zero, operation: .sourceOver, fraction: 1)+ }+ NSColor.black.withAlphaComponent(0.28).setFill()+ bounds.fill()+ }++ private static func wallpaper(for screen: NSScreen) -> NSImage? {+ guard let url = NSWorkspace.shared.desktopImageURL(for: screen), url.isFileURL,+ let input = CIImage(contentsOf: url), !input.extent.isEmpty else { return nil }+ // Bound work in both independent guardians; clamp edges before blur.+ let scale = min(1, 1600 / max(input.extent.width, input.extent.height))+ let image = input.transformed(by: CGAffineTransform(scaleX: scale, y: scale))+ let blurred = image.clampedToExtent().applyingFilter("CIGaussianBlur", parameters: [kCIInputRadiusKey: 18]).cropped(to: image.extent)+ guard let output = CIContext(options: [.useSoftwareRenderer: false]).createCGImage(blurred, from: image.extent) else { return nil }+ return NSImage(cgImage: output, size: image.extent.size)+ }++ private static func avatar() -> NSImage? {+ // Query only the current local account. No password or Keychain access.+ guard let node = try? ODNode(session: ODSession.default(), type: UInt32(kODNodeTypeLocalNodes)),+ let record = try? node.record(withRecordType: kODRecordTypeUsers, name: NSUserName(),+ attributes: [kODAttributeTypeJPEGPhoto, kODAttributeTypePicture]) else { return nil }+ if let values = try? record.values(forAttribute: kODAttributeTypeJPEGPhoto),+ let data = values.first as? Data, let image = NSImage(data: data) { return image }+ if let values = try? record.values(forAttribute: kODAttributeTypePicture),+ let path = values.first as? String { return NSImage(contentsOfFile: path) }+ return nil+ }+}diff --git a/experiments/LockedUse/Sources/Guardian/ShieldPreview.swift b/experiments/LockedUse/Sources/Guardian/ShieldPreview.swiftnew file mode 100644index 0000000..59c192a--- /dev/null+++ b/experiments/LockedUse/Sources/Guardian/ShieldPreview.swift@@ -0,0 +1,141 @@+import AppKit+import ApplicationServices+import Foundation+import OpenComputerUseKit++/// Isolated visual diagnostic. Never creates a permit, performs an AX action,+/// captures an application, or requests lock/unlock. Input cannot shorten the+/// countdown except Escape. This is not a production guardian policy.+@MainActor+final class ShieldPreview {+ private let shields = DisplayShieldSurface()+ private var timer: Timer?+ private var tap: CFMachPort?+ private var source: CFRunLoopSource?+ private var started: TimeInterval = 0+ private var lastSecond = -1+ private var inputCounts: [String: Int] = [:]+ private var firstInput: [String: Any] = [:]+ private var stopped = false+ private var ready = false+ private(set) var passed = false++ func start() throws {+ guard LockedUseSession.current().state == .unlocked,+ CGPreflightListenEventAccess() else {+ throw GuardianError.message("Shield preview requires an unlocked session and Input Monitoring")+ }+ try installTap()+ do {+ try shields.coverDisplays(message: message(seconds: 15))+ started = ProcessInfo.processInfo.systemUptime+ emit("previewStarted", details: ["displayCount": shields.count, "seconds": 15,+ "lockRequested": false, "unlockRequested": false, "actionsEnabled": false])+ let timer = Timer(timeInterval: 0.05, repeats: true) { [weak self] _ in+ MainActor.assumeIsolated { self?.poll() }+ }+ self.timer = timer+ RunLoop.main.add(timer, forMode: .common)+ } catch {+ cleanup()+ throw error+ }+ }++ private func message(seconds: Int) -> String {+ LockedUseShieldStatus.message+ }++ private func installTap() throws {+ let context = Unmanaged.passUnretained(self).toOpaque()+ tap = CGEvent.tapCreate(tap: .cgSessionEventTap, place: .headInsertEventTap,+ options: .defaultTap, eventsOfInterest: CGEventMask(UInt32.max),+ callback: { _, type, event, pointer in+ guard let pointer else { return Unmanaged.passUnretained(event) }+ MainActor.assumeIsolated {+ let preview = Unmanaged<ShieldPreview>.fromOpaque(pointer).takeUnretainedValue()+ if type == .tapDisabledByTimeout || type == .tapDisabledByUserInput {+ preview.finish(reason: "inputTapDisabled")+ return+ }+ let key = String(type.rawValue)+ preview.inputCounts[key, default: 0] += 1+ if preview.firstInput.isEmpty {+ preview.firstInput = ["type": type.rawValue,+ "sourcePID": event.getIntegerValueField(.eventSourceUnixProcessID),+ "sourceState": event.getIntegerValueField(.eventSourceStateID),+ "elapsed": ProcessInfo.processInfo.systemUptime - preview.started]+ }+ // Read only the Escape exit key; no text/key data is logged.+ if type == .keyDown, event.getIntegerValueField(.keyboardEventKeycode) == 53 {+ preview.finish(reason: "escape")+ }+ }+ return nil+ }, userInfo: context)+ guard let tap, let source = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, tap, 0) else {+ throw GuardianError.message("Cannot create shield preview input tap")+ }+ self.source = source+ CFRunLoopAddSource(CFRunLoopGetMain(), source, .commonModes)+ CGEvent.tapEnable(tap: tap, enable: true)+ }++ private func poll() {+ guard !stopped else { return }+ let now = ProcessInfo.processInfo.systemUptime+ let coverage = shields.coverageHealthy()+ let tapHealthy = tap.map { CGEvent.tapIsEnabled(tap: $0) } ?? false+ guard tapHealthy, LockedUseSession.current().state == .unlocked else {+ finish(reason: "sessionOrInputTapChanged")+ return+ }+ if !ready {+ if coverage {+ ready = true+ // Begin the visible countdown only after WindowServer coverage.+ started = now+ emit("previewReady", details: ["displayCount": shields.count, "coverageHealthy": true])+ } else if now - started >= 1.5 {+ finish(reason: "coverageNotReady")+ }+ return+ }+ guard coverage else { finish(reason: "coverageChanged"); return }+ let elapsed = now - started+ let remaining = max(0, Int(ceil(15 - elapsed)))+ if remaining != lastSecond {+ lastSecond = remaining+ shields.updateMessage(message(seconds: remaining))+ emit("previewTick", details: ["remainingSeconds": remaining, "elapsed": elapsed,+ "coverageHealthy": coverage, "displayCount": shields.count,+ "inputCounts": inputCounts, "firstInput": firstInput])+ inputCounts.removeAll()+ }+ if elapsed >= 15 { passed = true; finish(reason: "completed") }+ }++ private func finish(reason: String) {+ guard !stopped else { return }+ stopped = true+ emit("previewFinished", details: ["reason": reason, "passed": passed,+ "elapsed": ProcessInfo.processInfo.systemUptime - started,+ "lockRequested": false, "unlockRequested": false])+ cleanup()+ let app = NSApplication.shared+ app.stop(nil)+ if let event = NSEvent.otherEvent(with: .applicationDefined, location: .zero,+ modifierFlags: [], timestamp: 0, windowNumber: 0, context: nil,+ subtype: 0, data1: 0, data2: 0) { app.postEvent(event, atStart: true) }+ }++ private func cleanup() {+ timer?.invalidate()+ timer = nil+ if let source { CFRunLoopRemoveSource(CFRunLoopGetMain(), source, .commonModes) }+ if let tap { CFMachPortInvalidate(tap) }+ source = nil+ tap = nil+ shields.close()+ }+}diff --git a/experiments/LockedUse/Sources/Guardian/UnshieldedUnlockDiagnostic.swift b/experiments/LockedUse/Sources/Guardian/UnshieldedUnlockDiagnostic.swiftnew file mode 100644index 0000000..c5f59cc--- /dev/null+++ b/experiments/LockedUse/Sources/Guardian/UnshieldedUnlockDiagnostic.swift@@ -0,0 +1,64 @@+import AppKit+import Foundation+import OpenComputerUseKit++/// Reuses the signed UI probe, without constructing DisplayGuardian, a shield,+/// an input tap, hardware monitor, or a watchdog. Never runs application tools.+@MainActor+func runUnshieldedUnlockDiagnostic() throws {+ let original = LockedUseSession.current()+ let lock = ScreenLock()+ guard original.state == .locked, lock.available else { throw GuardianError.message("Diagnostic requires the locked original session and a relock backend") }+ let app = NSApplication.shared+ app.setActivationPolicy(.accessory)+ app.finishLaunching()+ let client = try LockedUseIPCClient(endpoint: .guardian, brokerRequirement: LockedUseSigningIdentity.brokerRequirement())+ defer { client.close() }+ let begin = try client.request(.init(operation: .beginUnshieldedDiagnostic, session: original))+ guard begin.result != .denied, begin.detail == "unshieldedDiagnostic",+ let lease = begin.leaseID, let deadline = begin.startupDeadline,+ deadline.isFinite, deadline > ProcessInfo.processInfo.systemUptime,+ deadline - ProcessInfo.processInfo.systemUptime <= 20 else { throw GuardianError.message("Root rejected unshielded diagnostic") }+ let cancellation = UnlockCancellation()+ defer { cancellation.cancel() }+ emit("unshieldedDiagnosticStarted", details: ["shieldProcesses": 0, "inputFilters": 0, "maximumSeconds": 20, "productionEvidenceEligible": false])+ var observedUnlock = false+ var consumedPermit = false+ var relockRequested = false+ func sameOriginal(_ current: LockedUseSession) -> Bool {+ current.userID == original.userID && current.auditSessionID == original.auditSessionID+ }+ defer {+ let current = LockedUseSession.current()+ if sameOriginal(current), current.state == .unlocked, !relockRequested { lock.request() }+ }+ _ = LockScreenInteractor.wake(session: original, cancellation: cancellation, ui: LockUIObservation(),+ clickTag: Int64.random(in: 1...Int64.max), validationConfirmation: true, unshieldedReturn: true)+ while ProcessInfo.processInfo.systemUptime < deadline {+ let current = LockedUseSession.current()+ guard sameOriginal(current) else { throw GuardianError.message("Diagnostic session changed") }+ let reply = try client.request(.init(operation: .status, leaseID: lease, session: current))+ guard reply.result != .denied else { throw GuardianError.message("Root diagnostic polling denied") }+ consumedPermit = consumedPermit || reply.result == .authorized+ if current.state == .unlocked {+ observedUnlock = true+ emit("unshieldedUnlockObserved", details: ["permitConsumed": consumedPermit, "guiActionsPerformed": false])+ break+ }+ if reply.phase == .awaitingManualUnlock { break }+ Thread.sleep(forTimeInterval: 0.2)+ }+ cancellation.cancel()+ guard sameOriginal(.current()) else { throw GuardianError.message("Diagnostic session changed before relock") }+ lock.request(); relockRequested = true+ let drainDeadline = ProcessInfo.processInfo.systemUptime + 5+ while LockedUseSession.current().state != .locked, ProcessInfo.processInfo.systemUptime < drainDeadline {+ Thread.sleep(forTimeInterval: 0.1)+ }+ let current = LockedUseSession.current()+ guard sameOriginal(current), current.state == .locked else { throw GuardianError.message("Diagnostic relock not observed") }+ let end = try client.request(.init(operation: .endUnshieldedDiagnostic, leaseID: lease, session: current))+ guard end.result != .denied, end.phase == .idle else { throw GuardianError.message("Diagnostic end not acknowledged") }+ emit("unshieldedDiagnosticEnded", details: ["unlockObserved": observedUnlock, "permitConsumed": consumedPermit,+ "relockObserved": true, "guiActionsPerformed": false, "productionEvidenceEligible": false])+}diff --git a/experiments/LockedUse/Sources/Guardian/WatchdogBrokerLink.swift b/experiments/LockedUse/Sources/Guardian/WatchdogBrokerLink.swiftnew file mode 100644index 0000000..13830a6--- /dev/null+++ b/experiments/LockedUse/Sources/Guardian/WatchdogBrokerLink.swift@@ -0,0 +1,92 @@+import Foundation+import Darwin+import OpenComputerUseKit+import os++/// Root RPC runs on a separate queue. A wedged or restarting Broker cannot+/// delay the watchdog's inherited-pipe heartbeat deadline or native relock.+final class WatchdogBrokerLink: @unchecked Sendable {+ private let logger = Logger(subsystem: "dev.opencomputeruse.locked-use", category: "WatchdogBroker")+ private var reportedFailure = false+ private let mutex = NSLock()+ private let bootstrap: LockedUseGuardianBootstrap+ private var client: LockedUseIPCClient?+ private var timer: DispatchSourceTimer?+ private var witnessedUnlock = false+ private var release = false+ private var registered = false+ private var protected = false+ private var stopping = false+ private let queue = DispatchQueue(label: "ocu.watchdog.broker")++ init(bootstrap: LockedUseGuardianBootstrap, protected: Bool) {+ self.bootstrap = bootstrap; self.protected = protected+ let timer = DispatchSource.makeTimerSource(queue: queue)+ timer.schedule(deadline: .now(), repeating: .milliseconds(300))+ timer.setEventHandler { [weak self] in self?.report() }+ self.timer = timer; timer.resume()+ }+ func observe(_ session: LockedUseSession, protected: Bool, stopping: Bool) {+ mutex.lock(); defer { mutex.unlock() }+ if session.state == .unlocked { witnessedUnlock = true }+ self.protected = protected; self.stopping = stopping+ }+ var ready: Bool { mutex.lock(); defer { mutex.unlock() }; return registered }+ var releaseRequested: Bool { mutex.lock(); defer { mutex.unlock() }; return release }++ private func report() {+ do {+ mutex.lock(); let observed = witnessedUnlock; let protected = protected; let stopping = stopping; mutex.unlock()+ if client == nil {+ let candidate = try LockedUseIPCClient(endpoint: .guardian, brokerRequirement: LockedUseSigningIdentity.brokerRequirement())+ let recovery = try candidate.request(.init(operation: .watchdogRecoveryHello, leaseID: bootstrap.leaseID,+ session: .current(), hasObservedUnlock: observed))+ if recovery.result == .denied {+ let hello = try candidate.request(.init(operation: .watchdogHello, leaseID: bootstrap.leaseID, token: bootstrap.token))+ guard hello.result != .denied else { candidate.close(); throw GuardianError.message("Watchdog registration denied") }+ }+ client = candidate+ logger.notice("registered")+ }+ let reply = try client!.request(.init(operation: .watchdogReport, leaseID: bootstrap.leaseID,+ session: .current(), guards: .init(allDisplaysCovered: protected, inputTapHealthy: protected,+ watchdogHealthy: protected, displayGeneration: 1), stopReason: stopping ? .guardLost : nil,+ hasObservedUnlock: observed))+ guard reply.result != .denied else { throw GuardianError.message("Watchdog report denied") }+ mutex.lock(); registered = protected && !stopping; mutex.unlock()+ if reply.effects.contains("releaseWatchdog") { mutex.lock(); release = true; mutex.unlock() }+ } catch {+ if !reportedFailure { logger.error("registrationOrReportFailed error=\(String(describing: error), privacy: .public)"); reportedFailure = true }+ client?.close(); client = nil+ mutex.lock(); registered = false; mutex.unlock()+ }+ }+ func finish() {+ timer?.cancel(); timer = nil+ queue.sync {+ client?.close(); client = nil+ mutex.lock(); let observed = witnessedUnlock; mutex.unlock()+ _ = GuardReleaseAcknowledgement.send(bootstrap: bootstrap, watchdog: true, observedUnlock: observed)+ }+ }+}++func readGuardianBootstrap() throws -> LockedUseGuardianBootstrap {+ let deadline = ProcessInfo.processInfo.systemUptime + 3+ func exact(_ size: Int) throws -> Data {+ var result = Data()+ while result.count < size {+ try LockedUseIPCSocket.wait(descriptor: STDIN_FILENO, events: Int16(POLLIN), deadline: deadline)+ var bytes = [UInt8](repeating: 0, count: min(4096, size - result.count))+ let count = Darwin.read(STDIN_FILENO, &bytes, bytes.count)+ guard count > 0 else { throw GuardianError.message("Guardian bootstrap pipe ended") }+ result.append(contentsOf: bytes.prefix(count))+ }+ return result+ }+ let length = try exact(4).reduce(UInt32(0)) { ($0 << 8) | UInt32($1) }+ guard length > 0, length <= LockedUseIPCFrame.maximumPayload else { throw GuardianError.message("Invalid Guardian bootstrap size") }+ let value = try JSONDecoder().decode(LockedUseGuardianBootstrap.self, from: exact(Int(length)))+ guard value.token.count == 32 else { throw GuardianError.message("Invalid Guardian bootstrap token") }+ return value+}diff --git a/experiments/LockedUse/Sources/Guardian/WatchdogShield.swift b/experiments/LockedUse/Sources/Guardian/WatchdogShield.swiftnew file mode 100644index 0000000..aab7c36--- /dev/null+++ b/experiments/LockedUse/Sources/Guardian/WatchdogShield.swift@@ -0,0 +1,101 @@+import AppKit+import ApplicationServices+import OpenComputerUseKit++/// Independent windows and filtering input tap survive the main Guardian's+/// death. Keep them until the Broker's original-session drain/lock barrier.+@MainActor+final class WatchdogShield {+ private let surface = DisplayShieldSurface()+ private var displayPower: DisplayPowerAssertion?+ private var monitor: PhysicalInputMonitor?+ private var tap: CFMachPort?+ private var source: CFRunLoopSource?+ private var clickAllowance: LockedUseClickAllowance?+ private var returnAllowance: LockedUseReturnAllowance?+ private(set) var localRecoveryRequested = false+ private var localRecoveryEnabled = false+ private let startupDeadline: TimeInterval?+ private var shieldStatus = LockedUseShieldStatus()+ private let stop: @MainActor (String) -> Void++ init(clickTag: Int64? = nil, returnTag: Int64? = nil, startupDeadline: TimeInterval? = nil, stop: @escaping @MainActor (String) -> Void) throws {+ self.stop = stop+ self.startupDeadline = startupDeadline+ if let returnTag { returnAllowance = .init(tag: returnTag, sender: getppid(), session: LockedUseSession.current(), now: ProcessInfo.processInfo.systemUptime) }+ if let clickTag { clickAllowance = .init(tag: clickTag, sender: getppid(), now: ProcessInfo.processInfo.systemUptime) }+ NSApplication.shared.setActivationPolicy(.accessory)+ let message = shieldStatus.update(now: ProcessInfo.processInfo.systemUptime,+ startupDeadline: startupDeadline, unlocked: false, stopping: false)!+ try surface.coverDisplays(message: message, levelOffset: -1)+ do {+ displayPower = try DisplayPowerAssertion()+ let context = Unmanaged.passUnretained(self).toOpaque()+ let types: [CGEventType] = [.leftMouseDown, .leftMouseUp, .rightMouseDown, .rightMouseUp,+ .mouseMoved, .leftMouseDragged, .rightMouseDragged, .keyDown, .keyUp, .flagsChanged,+ .scrollWheel, .tabletPointer, .tabletProximity, .otherMouseDown, .otherMouseUp, .otherMouseDragged]+ let mask = types.reduce(CGEventMask(1) << 14) { $0 | (CGEventMask(1) << $1.rawValue) }+ tap = CGEvent.tapCreate(tap: .cgSessionEventTap, place: .headInsertEventTap,+ options: .defaultTap, eventsOfInterest: mask, callback: { _, type, event, pointer in+ if let pointer {+ let admitted = MainActor.assumeIsolated { () -> Bool in+ let shield = Unmanaged<WatchdogShield>.fromOpaque(pointer).takeUnretainedValue()+ if shield.localRecoveryEnabled { return true }+ if shield.returnAllowance?.accepts(event, type: type, filter: "watchdog") == true { return true }+ if shield.clickAllowance?.accepts(event, type: type, filter: "watchdog") == true {+ recordLockUIClickAdmission(filter: "watchdog", type: type)+ return true+ }+ shield.cancelNativeClick()+ shield.stop("filterEvent")+ return false+ }+ if admitted { return Unmanaged.passUnretained(event) }+ }+ return nil+ }, userInfo: context)+ guard let tap, let source = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, tap, 0) else {+ throw GuardianError.message("Independent watchdog input filter unavailable")+ }+ self.source = source+ CFRunLoopAddSource(CFRunLoopGetMain(), source, .commonModes)+ CGEvent.tapEnable(tap: tap, enable: true)+ let monitor = PhysicalInputMonitor(activity: { [weak self] in+ self?.localRecoveryRequested = true+ self?.cancelNativeClick(); stop("hardwareActivity")+ },+ failure: { [weak self] in self?.cancelNativeClick(); stop("hardwareMonitorFailure") })+ self.monitor = monitor+ try monitor.start()+ } catch { close(); throw error }+ }++ var healthFailure: String? {+ if let failure = surface.coverageFailure() { return failure }+ if monitor?.healthy != true { return "hardwareMonitorUnhealthy" }+ if tap.map({ CGEvent.tapIsEnabled(tap: $0) }) != true { return "filterDisabled" }+ return nil+ }+ var healthy: Bool {+ healthFailure == nil+ }+ func close() {+ cancelNativeClick()+ monitor?.stop(); monitor = nil+ if let source { CFRunLoopRemoveSource(CFRunLoopGetMain(), source, .commonModes) }+ if let tap { CGEvent.tapEnable(tap: tap, enable: false); CFMachPortInvalidate(tap) }+ source = nil; tap = nil; surface.close()+ displayPower?.close(); displayPower = nil+ }+ func allowLocalLoginInput() {+ localRecoveryEnabled = true+ surface.allowLocalLoginInput()+ }+ func cancelNativeClick() { clickAllowance?.revoke(); returnAllowance?.revoke() }+ func updateStatus(now: TimeInterval, session: LockedUseSession, stopping: Bool) {+ if let message = shieldStatus.update(now: now, startupDeadline: startupDeadline,+ unlocked: session.state == .unlocked, stopping: stopping) {+ surface.updateMessage(message)+ }+ }+}diff --git a/experiments/LockedUse/Sources/Installer/InstallerMain.swift b/experiments/LockedUse/Sources/Installer/InstallerMain.swiftnew file mode 100644index 0000000..2d2d8c3--- /dev/null+++ b/experiments/LockedUse/Sources/Installer/InstallerMain.swift@@ -0,0 +1,363 @@+import Darwin+import Foundation+import LockedUseNative+import OpenComputerUseKit+import Security++private let root = URL(fileURLWithPath: "/Library/Application Support/OpenComputerUse/LockedUse", isDirectory: true)+private let pluginName = "OCULockAuth.bundle"+private let guardianName = "OCU Guardian.app"+private let service = "dev.opencomputeruse.locked-use.broker"+private let daemon = URL(fileURLWithPath: "/Library/LaunchDaemons/dev.opencomputeruse.locked-use.broker.plist")+private 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) }++@main+struct InstallerMain {+ static func main() {+ do {+ guard geteuid() == 0 else { throw InstallError.untrusted }+ // The administrator staging shell is deliberately private. System+ // client traversal must not inherit that shell's umask 077.+ _ = umask(0o022)+ let identity = try LockedUseSigningIdentity.current()+ guard identity.signingIdentifier == "dev.opencomputeruse.locked-use.installer", let team = identity.teamIdentifier else { throw InstallError.untrusted }+ let lockDirectory = URL(fileURLWithPath: "/Library/Application Support/OpenComputerUseLockedUseStaging", isDirectory: true)+ try makeDirectory(lockDirectory)+ let lockFD = open(lockDirectory.appendingPathComponent("installation.lock").path, O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0o600)+ guard lockFD >= 0 else { throw InstallError.untrusted }+ defer { Darwin.close(lockFD) }+ var lockInfo = stat()+ guard fstat(lockFD, &lockInfo) == 0, lockInfo.st_uid == 0, lockInfo.st_mode & S_IFMT == S_IFREG,+ lockInfo.st_mode & 0o077 == 0, ocu_has_mutating_acl(lockFD) == 0,+ flock(lockFD, LOCK_EX | LOCK_NB) == 0 else { throw InstallError.existingInstallation }+ let args = Array(CommandLine.arguments.dropFirst())+ if args.count == 4, args[0] == "install" {+ guard let uid = UInt32(args[2]), uid > 0,+ ["validation", "production"].contains(args[3]) else { throw InstallError.invalidArguments }+ try install(source: URL(fileURLWithPath: args[1], isDirectory: true), uid: uid, team: team, validation: args[3] == "validation")+ } else if args == ["uninstall"] { try uninstall(team: team) }+ else if args == ["recover"] { try recover(team: team) }+ else if args == ["reconcile-stopped-guards"] { try reconcileStoppedGuards() }+ else if args == ["promote"] { try promote(team: team) }+ else { throw InstallError.invalidArguments }+ } catch {+ fputs("Locked Use installation failed: \(error)\n", stderr)+ exit(1)+ }+ }++ private static func verify(_ url: URL, id: String, team: String) throws -> [String: Any] {+ var code: SecStaticCode?+ guard SecStaticCodeCreateWithPath(url as CFURL, [], &code) == errSecSuccess, let code else { throw InstallError.untrusted }+ var requirement: SecRequirement?+ let text = "identifier \"\(id)\" and anchor apple generic and certificate leaf[subject.OU] = \"\(team)\""+ guard SecRequirementCreateWithString(text as CFString, [], &requirement) == errSecSuccess,+ SecStaticCodeCheckValidity(code, SecCSFlags(rawValue: kSecCSCheckAllArchitectures | kSecCSStrictValidate), requirement) == errSecSuccess else { throw InstallError.untrusted }+ var information: CFDictionary?+ guard SecCodeCopySigningInformation(code, SecCSFlags(rawValue: kSecCSSigningInformation), &information) == errSecSuccess,+ let info = information as? [String: Any],+ let flags = info[kSecCodeInfoFlags as String] as? NSNumber,+ flags.uint32Value & SecCodeSignatureFlags.runtime.rawValue != 0 else { throw InstallError.untrusted }+ let entitlements = info[kSecCodeInfoEntitlementsDict as String] as? [String: Any] ?? [:]+ for key in ["com.apple.security.get-task-allow", "get-task-allow", "com.apple.security.cs.disable-library-validation", "com.apple.security.cs.allow-dyld-environment-variables", "com.apple.security.cs.allow-unsigned-executable-memory"] {+ guard (entitlements[key] as? NSNumber)?.boolValue != true else { throw InstallError.untrusted }+ }+ return info+ }++ /// Every source has already been copied into an administrator-owned staging+ /// directory before execution. Refuse symlinks and writable ancestry so a+ /// source replacement cannot race code validation and installation.+ private static func trustedTree(_ url: URL) throws {+ var ancestor = url.standardizedFileURL+ while ancestor.path != "/" {+ let fd = open(ancestor.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC)+ guard fd >= 0 else { throw InstallError.untrusted }+ defer { Darwin.close(fd) }+ var info = stat()+ guard fstat(fd, &info) == 0, info.st_uid == 0,+ info.st_mode & 0o022 == 0, ocu_has_mutating_acl(fd) == 0 else { throw InstallError.untrusted }+ ancestor.deleteLastPathComponent()+ }+ let urls = FileManager.default.enumerator(at: url, includingPropertiesForKeys: nil, options: [])+ while let item = urls?.nextObject() as? URL {+ var info = stat()+ guard lstat(item.path, &info) == 0, info.st_uid == 0,+ [S_IFREG, S_IFDIR].contains(info.st_mode & S_IFMT), info.st_mode & 0o6022 == 0 else { throw InstallError.untrusted }+ let fd = open(item.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC)+ guard fd >= 0 else { throw InstallError.untrusted }+ let acl = ocu_has_mutating_acl(fd); Darwin.close(fd)+ guard acl == 0 else { throw InstallError.untrusted }+ }+ }++ private static func makeDirectory(_ url: URL) throws {+ if !FileManager.default.fileExists(atPath: url.path) {+ try makeDirectory(url.deletingLastPathComponent())+ guard mkdir(url.path, 0o755) == 0 else { throw InstallError.untrusted }+ }+ try trustedTreeShallow(url)+ }+ private static func trustedTreeShallow(_ url: URL) throws {+ var cursor = url+ while cursor.path != "/" {+ let fd = open(cursor.path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ guard fd >= 0 else { throw InstallError.untrusted }+ var info = stat()+ let valid = fstat(fd, &info) == 0 && info.st_uid == 0 && info.st_mode & 0o022 == 0 && ocu_has_mutating_acl(fd) == 0+ Darwin.close(fd)+ guard valid else { throw InstallError.untrusted }+ cursor.deleteLastPathComponent()+ }+ }+ private static func write<T: Encodable>(_ value: T, name: String, replacing: Bool = false) throws {+ if replacing { _ = try LockedUseBrokerConfiguration.loadInstalled() }+ guard replacing || !FileManager.default.fileExists(atPath: root.appendingPathComponent(name).path) else { throw InstallError.existingInstallation }+ try JSONEncoder().encode(value).write(to: root.appendingPathComponent(name), options: [.atomic])+ guard chmod(root.appendingPathComponent(name).path, 0o644) == 0 else { throw InstallError.untrusted }+ }+ private static func readRight(_ name: String) throws -> Data {+ var dictionary: CFDictionary?+ let result = AuthorizationRightGet(name, &dictionary)+ guard result == errSecSuccess, let dictionary else { throw InstallError.authentication(result) }+ return try PropertyListSerialization.data(fromPropertyList: dictionary, format: .xml, options: 0)+ }+ private static func setRight(_ name: String, data: Data, authorization: AuthorizationRef) throws {+ guard let dictionary = try PropertyListSerialization.propertyList(from: data, format: nil) as? NSDictionary else { throw InstallError.changedPolicy }+ let result = AuthorizationRightSet(authorization, name, dictionary, nil, nil, nil)+ guard result == errSecSuccess else { throw InstallError.authentication(result) }+ }+ private static func authorization() throws -> AuthorizationRef {+ var reference: AuthorizationRef?+ let result = AuthorizationCreate(nil, nil, [], &reference)+ guard result == errSecSuccess, let reference else { throw InstallError.authentication(result) }+ return reference+ }+ private static func remoteDefinition() throws -> Data {+ try PropertyListSerialization.data(fromPropertyList: ["class": "evaluate-mechanisms",+ "mechanisms": ["OCULockAuth:remote"], "shared": false,+ "timeout": 0, "tries": 1, "comment": "Open Computer Use single-use protected-session authorization"], format: .xml, options: 0)+ }+ private static func install(source: URL, uid: UInt32, team: String, validation: Bool) throws {+ try trustedTree(source)+ let broker = source.appendingPathComponent("OCULockService")+ _ = try verify(broker, id: service, team: team)+ _ = try verify(source.appendingPathComponent("OCULockInstaller"), id: "dev.opencomputeruse.locked-use.installer", team: team)+ _ = try verify(source.appendingPathComponent(guardianName), id: "dev.opencomputeruse.locked-use.guardian.dev", team: team)+ _ = try verify(source.appendingPathComponent(pluginName), id: "dev.opencomputeruse.locked-use.authorization", team: team)+ let client = source.appendingPathComponent("Client.app")+ guard let identifier = Bundle(url: client)?.bundleIdentifier,+ ["com.ifuryst.opencomputeruse", "com.ifuryst.opencomputeruse.dev"].contains(identifier) else { throw InstallError.untrusted }+ _ = try verify(client, id: identifier, team: team)+ guard !FileManager.default.fileExists(atPath: root.path), !FileManager.default.fileExists(atPath: plugin.path),+ !FileManager.default.fileExists(atPath: daemon.path),+ !FileManager.default.fileExists(atPath: plugin.deletingLastPathComponent().appendingPathComponent("OpenComputerUseLockedUseAuthorizationPlugin.bundle").path) else { throw InstallError.existingInstallation }+ var existing: CFDictionary?+ guard AuthorizationRightGet(LockedUseAuthorizationRules.remoteRight, &existing) == errAuthorizationDenied else { throw InstallError.existingInstallation }+ let plan = try LockedUseAuthorizationRules.planInstallation(current: readRight(screensaver))+ let reference = try authorization(); defer { AuthorizationFree(reference, []) }+ try makeDirectory(root)+ // Only this application's fixed system namespace is made traversable;+ // private recovery journals still retain their explicit mode 0600.+ guard chmod(root.deletingLastPathComponent().path, 0o755) == 0,+ chmod(root.path, 0o755) == 0 else { throw InstallError.untrusted }+ try makeDirectory(root.appendingPathComponent("run", isDirectory: true))+ try write(plan, name: "authorization-plan.json")+ let approvals = try LockedUseClientApprovals(approvals: [+ .init(userID: uid, role: .client, signingIdentifier: identifier, teamIdentifier: team),+ .init(userID: uid, role: .agent, signingIdentifier: identifier, teamIdentifier: team),+ .init(userID: uid, role: .guardian, signingIdentifier: "dev.opencomputeruse.locked-use.guardian.dev", teamIdentifier: team)+ ])+ try write(approvals, name: "clients.json")+ try write(LockedUseBrokerConfiguration(enabled: true), name: "configuration.json")+ for name in ["OCULockService", guardianName, "OCULockInstaller"] {+ try FileManager.default.copyItem(at: source.appendingPathComponent(name), to: root.appendingPathComponent(name))+ }+ try makeDirectory(plugin.deletingLastPathComponent())+ try FileManager.default.copyItem(at: source.appendingPathComponent(pluginName), to: plugin)+ // Preserve a recoverable plan before writes; never blindly repair a+ // concurrently modified authentication policy in a failure handler.+ do {+ 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)+ guard try LockedUseAuthorizationRules.installationObserved(current: readRight(screensaver), plan: plan) else { throw InstallError.changedPolicy }+ let plist: [String: Any] = ["Label": service,+ "ProgramArguments": [root.appendingPathComponent("OCULockService").path, validation ? "--serve-validation" : "--serve"],+ "RunAtLoad": true, "KeepAlive": true, "ProcessType": "Interactive", "ThrottleInterval": 5]+ try makeDirectory(daemon.deletingLastPathComponent())+ 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").")+ } catch {+ if let current = try? readRight(screensaver), let original = try? LockedUseAuthorizationRules.planUninstallation(current: current, plan: plan) {+ try? setRight(screensaver, data: original, authorization: reference)+ }+ // Retain the root-owned recovery plan on any partial failure.+ throw error+ }+ }+ private static func promote(team: String) throws {+ let evidence = try LockedUseComponentValidation.current(team: team)+ let report = try LockedUseValidationReport.loadInstalled()+ guard report.canPromote(current: evidence) else { throw InstallError.changedPolicy }+ let plan = try LockedUseAuthorizationRules.loadInstalledPlan()+ guard try LockedUseAuthorizationRules.installationObserved(current: readRight(screensaver), plan: plan) else { throw InstallError.changedPolicy }+ try trustedTree(daemon)+ let bytes = try Data(contentsOf: daemon)+ guard var definition = try PropertyListSerialization.propertyList(from: bytes, format: nil) as? [String: Any],+ definition["Label"] as? String == service,+ definition["ProgramArguments"] as? [String] == [root.appendingPathComponent("OCULockService").path, "--serve-validation"] else { throw InstallError.changedPolicy }+ let admin = try LockedUseIPCClient(endpoint: .admin, brokerRequirement: LockedUseSigningIdentity.brokerRequirement())+ let reply = try admin.request(.init(operation: .disable)); admin.close()+ guard reply.result != .denied else { throw InstallError.changedPolicy }+ // No active or incompletely released lease can cross this service epoch.+ try run("/bin/launchctl", ["bootout", "system/" + service])+ try write(LockedUseBrokerConfiguration(enabled: true, validatedOSBuild: evidence.osBuild,+ validatedBrokerHash: evidence.brokerHash, validatedGuardianHash: evidence.guardianHash,+ validatedPluginHash: evidence.pluginHash), name: "configuration.json", replacing: true)+ definition["ProgramArguments"] = [root.appendingPathComponent("OCULockService").path, "--serve"]+ let updated = try PropertyListSerialization.data(fromPropertyList: definition, format: .xml, options: 0)+ try updated.write(to: daemon, options: [.atomic])+ guard chmod(daemon.path, 0o644) == 0 else { throw InstallError.untrusted }+ try run("/bin/launchctl", ["bootstrap", "system", daemon.path])+ print("Enabled production Locked Use for the verified OS and component build.")+ }++ /// Explicit administrator maintenance for missing release ACKs after a+ /// failed test. No policy mutation, permit restoration or certification.+ private static func reconcileStoppedGuards() throws {+ try trustedTreeShallow(root)+ let client = try LockedUseIPCClient(endpoint: .admin, brokerRequirement: LockedUseSigningIdentity.brokerRequirement())+ let status = try client.request(.init(operation: .status))+ client.close()+ guard status.result != .denied, let record = try LockedUseRecoveryRecord.loadInstalled() else {+ throw InstallError.changedPolicy+ }+ func exited(_ context: LockedUseBrokerCoordinator.Context) -> Bool {+ context.processID > 0 && kill(context.processID, 0) != 0 && errno == ESRCH+ }+ let peers = [record.guardian, record.watchdog].compactMap { $0 }+ guard record.canRetireStoppedGuards(phase: status.phase, allGuardsExited: peers.allSatisfy(exited)) else {+ throw InstallError.changedPolicy+ }+ // An idle epoch with unreleased peers cannot accept another begin.+ // Stop it before changing its durable fence; keep the original record.+ try run("/bin/launchctl", ["bootout", "system/" + service])+ var retired: URL?+ do {+ let lockFD = open(root.appendingPathComponent("run/broker.lock").path, O_RDWR | O_NOFOLLOW | O_CLOEXEC)+ guard lockFD >= 0 else { throw InstallError.untrusted }+ defer { Darwin.close(lockFD) }+ var lockInfo = stat()+ guard fstat(lockFD, &lockInfo) == 0, lockInfo.st_uid == 0, lockInfo.st_mode & S_IFMT == S_IFREG,+ lockInfo.st_mode & 0o077 == 0, ocu_has_mutating_acl(lockFD) == 0,+ flock(lockFD, LOCK_EX | LOCK_NB) == 0,+ let current = try LockedUseRecoveryRecord.loadInstalled(), current.leaseID == record.leaseID,+ current.owner.id == record.owner.id,+ current.guardian?.id == record.guardian?.id, current.watchdog?.id == record.watchdog?.id,+ current.canRetireStoppedGuards(phase: .idle, allGuardsExited: peers.allSatisfy(exited)) else {+ throw InstallError.changedPolicy+ }+ let archive = root.appendingPathComponent("retired-lease-" + UUID().uuidString + ".json")+ guard rename(root.appendingPathComponent("lease-recovery.json").path, archive.path) == 0 else {+ throw InstallError.untrusted+ }+ retired = archive+ let directory = open(root.path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ guard directory >= 0 else { throw InstallError.untrusted }+ defer { Darwin.close(directory) }+ guard fsync(directory) == 0 else { throw InstallError.untrusted }+ } catch {+ // Restore service with its original fence on any failed check.+ if let retired, rename(retired.path, root.appendingPathComponent("lease-recovery.json").path) != 0 {+ throw InstallError.untrusted+ }+ try? run("/bin/launchctl", ["bootstrap", "system", daemon.path])+ throw error+ }+ try run("/bin/launchctl", ["bootstrap", "system", daemon.path])+ print("Retired the drained idle epoch after kernel-confirmed guard exits; authentication policy unchanged.")+ }++ private static func recover(team: String) throws {+ // If the service is alive, its authenticated drain/freeze is mandatory.+ if let client = try? LockedUseIPCClient(endpoint: .admin, brokerRequirement: LockedUseSigningIdentity.brokerRequirement()) {+ client.close()+ try uninstall(team: team)+ return+ }+ try trustedTreeShallow(root.appendingPathComponent("run", isDirectory: true))+ let lockFD = open(root.appendingPathComponent("run/broker.lock").path, O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0o600)+ guard lockFD >= 0 else { throw InstallError.untrusted }+ defer { Darwin.close(lockFD) }+ var info = stat()+ guard fstat(lockFD, &info) == 0, info.st_uid == 0, info.st_mode & S_IFMT == S_IFREG,+ info.st_mode & 0o077 == 0, ocu_has_mutating_acl(lockFD) == 0,+ flock(lockFD, LOCK_EX | LOCK_NB) == 0 else { throw InstallError.existingInstallation }+ if let record = try LockedUseRecoveryRecord.loadInstalled(), !record.fullyReleased {+ // Never interpret service death or a visible old lock as drainage.+ // Restart the installed service to reconnect the old guardians.+ throw InstallError.changedPolicy+ }+ let plan = try LockedUseAuthorizationRules.loadInstalledPlan()+ let current = try readRight(screensaver)+ let reference = try authorization(); defer { AuthorizationFree(reference, []) }+ if try LockedUseAuthorizationRules.installationStillApplicable(current: current, plan: plan) {+ // Installation already rolled back its authentication mutation.+ } else {+ try setRight(screensaver, data: LockedUseAuthorizationRules.planUninstallation(current: current, plan: plan), authorization: reference)+ }+ let inspection = Process()+ inspection.executableURL = URL(fileURLWithPath: "/bin/launchctl")+ inspection.arguments = ["print", "system/" + service]+ inspection.standardOutput = FileHandle.nullDevice; inspection.standardError = FileHandle.nullDevice+ try inspection.run(); inspection.waitUntilExit()+ if inspection.terminationStatus == 0 { try run("/bin/launchctl", ["bootout", "system/" + service]) }+ else if ![3, 113].contains(inspection.terminationStatus) { throw InstallError.process(inspection.terminationStatus) }+ try removeOwnArtifacts(team: team, authorization: reference)+ print("Recovered the partial installation and preserved the native authentication policy.")+ }++ private static func uninstall(team: String) throws {+ let observer = try LockedUseIPCClient(endpoint: .admin, brokerRequirement: LockedUseSigningIdentity.brokerRequirement())+ let status = try observer.request(.init(operation: .disable)); observer.close()+ guard status.result != .denied, status.phase == .idle || status.phase == .awaitingManualUnlock else { throw InstallError.changedPolicy }+ let plan = try LockedUseAuthorizationRules.loadInstalledPlan()+ let original = try LockedUseAuthorizationRules.planUninstallation(current: readRight(screensaver), plan: plan)+ _ = try verify(plugin, id: "dev.opencomputeruse.locked-use.authorization", team: team)+ let reference = try authorization(); defer { AuthorizationFree(reference, []) }+ try setRight(screensaver, data: original, authorization: reference)+ try run("/bin/launchctl", ["bootout", "system/" + service])+ try removeOwnArtifacts(team: team, authorization: reference)+ print("Removed Locked Use and restored the original authentication policy.")+ }+ private static func removeOwnArtifacts(team: String, authorization: AuthorizationRef) throws {+ 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 }+ 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)+ }+ }+ if FileManager.default.fileExists(atPath: daemon.path) { try FileManager.default.removeItem(at: daemon) }+ try trustedTreeShallow(root)+ try FileManager.default.removeItem(at: root)+ }+ private static func run(_ path: String, _ args: [String]) throws {+ let process = Process(); process.executableURL = URL(fileURLWithPath: path); process.arguments = args+ try process.run(); process.waitUntilExit()+ guard process.terminationStatus == 0 else { throw InstallError.process(process.terminationStatus) }+ }+}diff --git a/experiments/LockedUse/Sources/RemoteVerificationProbe.swift b/experiments/LockedUse/Sources/RemoteVerificationProbe.swiftnew file mode 100644index 0000000..d3aa2a8--- /dev/null+++ b/experiments/LockedUse/Sources/RemoteVerificationProbe.swift@@ -0,0 +1,28 @@+import Foundation+import Security+import CoreGraphics++// Isolated non-locking diagnostic. No lease is created or permit requested.+// Run only while normally unlocked, with the explicit validation installation.+guard let session = CGSessionCopyCurrentDictionary() as? [String: Any],+ session[kCGSessionOnConsoleKey as String] as? Bool == true,+ session[kCGSessionLoginDoneKey as String] as? Bool == true,+ (session[kCGSessionUserIDKey as String] as? NSNumber)?.uint32Value == getuid(),+ session["CGSSessionScreenIsLocked"] == nil || session["CGSSessionScreenIsLocked"] as? Bool == false else { exit(2) }+var reference: AuthorizationRef?+let created = AuthorizationCreate(nil, nil, [], &reference)+guard created == errAuthorizationSuccess, let reference else { exit(2) }+defer { AuthorizationFree(reference, [.destroyRights]) }+let began = ProcessInfo.processInfo.systemUptime+let status = "dev.opencomputeruse.locked-use.remote".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(reference, &rights, nil, [.extendRights, .destroyRights], nil)+ }+}+let result: [String: Any] = ["event": "remoteVerificationProbe", "status": status,+ "expectedDenied": status == errAuthorizationDenied, "sessionLockRequested": false,+ "elapsedSeconds": ProcessInfo.processInfo.systemUptime - began]+print(String(decoding: try JSONSerialization.data(withJSONObject: result, options: [.sortedKeys]), as: UTF8.self))+exit(status == errAuthorizationDenied ? 0 : 1)diff --git a/packages/LockedUseNative/PeerIdentity.c b/packages/LockedUseNative/PeerIdentity.cnew file mode 100644index 0000000..c4da16d--- /dev/null+++ b/packages/LockedUseNative/PeerIdentity.c@@ -0,0 +1,128 @@+#include "LockedUseNative.h"+#include <bsm/libbsm.h>+#include <errno.h>+#include <unistd.h>+#include <fcntl.h>+#include <string.h>+#include <sys/socket.h>+#include <sys/un.h>+#include <sys/acl.h>+#include <sys/stat.h>++_Static_assert(sizeof(audit_token_t) == 32, "Unexpected Darwin audit token ABI");++int ocu_copy_peer_identity(int socket_fd, OCUPeerIdentity *out) {+ if (!out) { errno = EINVAL; return -1; }+ memset(out, 0, sizeof(*out));+ audit_token_t token = {0};+ socklen_t size = sizeof(token);+ if (getsockopt(socket_fd, SOL_LOCAL, LOCAL_PEERTOKEN, &token, &size) != 0) return -1;+ if (size != sizeof(token)) { errno = EINVAL; return -1; }+ memcpy(out->audit_token, &token, sizeof(token));+ out->effective_user_id = audit_token_to_euid(token);+ out->audit_user_id = audit_token_to_auid(token);+ out->audit_session_id = audit_token_to_asid(token);+ out->process_id = audit_token_to_pid(token);+ return 0;+}++int ocu_has_mutating_acl(int file_fd) {+ acl_t acl = acl_get_fd_np(file_fd, ACL_TYPE_EXTENDED);+ if (!acl) {+ /* Darwin returns ENOENT for an existing fd without an extended ACL. */+ if (errno == ENOENT) {+ struct stat info;+ if (fstat(file_fd, &info) == 0) return 0;+ }+ return -1;+ }+ if (acl_valid(acl) != 0) { acl_free(acl); return -1; }+ acl_entry_t entry;+ int entry_id = ACL_FIRST_ENTRY;+ int result = 0;+ unsigned int entries = 0;+ int entry_status;+ while ((entry_status = acl_get_entry(acl, entry_id, &entry)) == 0) {+ if (++entries > ACL_MAX_ENTRIES) { result = -1; break; }+ entry_id = ACL_NEXT_ENTRY;+ acl_tag_t tag;+ acl_permset_t permissions;+ if (acl_get_tag_type(entry, &tag) != 0 || acl_get_permset(entry, &permissions) != 0) {+ result = -1; break;+ }+ if (tag != ACL_EXTENDED_ALLOW) continue;+ const acl_perm_t mutations[] = {ACL_WRITE_DATA, ACL_APPEND_DATA, ACL_DELETE,+ ACL_DELETE_CHILD, ACL_WRITE_ATTRIBUTES, ACL_WRITE_EXTATTRIBUTES,+ ACL_WRITE_SECURITY, ACL_CHANGE_OWNER};+ for (unsigned int index = 0; index < sizeof(mutations) / sizeof(mutations[0]); index++) {+ int granted = acl_get_perm_np(permissions, mutations[index]);+ if (granted < 0) { result = -1; break; }+ if (granted > 0) { result = 1; break; }+ }+ if (result != 0) break;+ }+ /* Darwin uses EINVAL to indicate that the final entry was exhausted. */+ if (result == 0 && entry_status < 0 && errno != EINVAL) result = -1;+ acl_free(acl);+ return result;+}++int ocu_has_any_acl(int file_fd) {+ acl_t acl = acl_get_fd_np(file_fd, ACL_TYPE_EXTENDED);+ if (!acl) return errno == ENOENT ? 0 : -1;+ acl_entry_t entry;+ int status = acl_get_entry(acl, ACL_FIRST_ENTRY, &entry);+ int result = status == 0 ? 1 : errno == EINVAL ? 0 : -1;+ acl_free(acl); return result;+}++int ocu_remove_extended_acl(int file_fd) {+ acl_t empty = acl_init(0);+ if (!empty) return -1;+ int result = acl_set_fd_np(file_fd, empty, ACL_TYPE_EXTENDED);+ acl_free(empty); return result;+}++int ocu_send_peer_socket(int channel_fd, int peer_fd) {+ unsigned char marker = 0x4f;+ struct iovec vector = { &marker, 1 };+ union { struct cmsghdr alignment; char bytes[CMSG_SPACE(sizeof(int))]; } control = {0};+ struct msghdr message = {0};+ message.msg_iov = &vector; message.msg_iovlen = 1;+ message.msg_control = control.bytes; message.msg_controllen = sizeof(control.bytes);+ struct cmsghdr *header = CMSG_FIRSTHDR(&message);+ header->cmsg_level = SOL_SOCKET; header->cmsg_type = SCM_RIGHTS;+ header->cmsg_len = CMSG_LEN(sizeof(int));+ memcpy(CMSG_DATA(header), &peer_fd, sizeof(peer_fd));+ return sendmsg(channel_fd, &message, 0) == 1 ? 0 : -1;+}++int ocu_receive_peer_socket(int channel_fd) {+ unsigned char marker = 0;+ struct iovec vector = { &marker, 1 };+ union { struct cmsghdr alignment; char bytes[CMSG_SPACE(sizeof(int) * 8)]; } control = {0};+ struct msghdr message = {0};+ message.msg_iov = &vector; message.msg_iovlen = 1;+ message.msg_control = control.bytes; message.msg_controllen = sizeof(control.bytes);+ ssize_t count = recvmsg(channel_fd, &message, 0);+ if (count < 0) return -1;+ int received = -1, descriptors = 0, invalid = 0;+ for (struct cmsghdr *header = CMSG_FIRSTHDR(&message); header;+ header = CMSG_NXTHDR(&message, header)) {+ if (header->cmsg_level != SOL_SOCKET || header->cmsg_type != SCM_RIGHTS ||+ header->cmsg_len < CMSG_LEN(0)) { invalid = 1; continue; }+ size_t length = header->cmsg_len - CMSG_LEN(0);+ if (length % sizeof(int)) invalid = 1;+ for (size_t offset = 0; offset + sizeof(int) <= length; offset += sizeof(int)) {+ int fd; memcpy(&fd, CMSG_DATA(header) + offset, sizeof(fd));+ if (++descriptors == 1) received = fd; else close(fd);+ }+ }+ if (count != 1 || marker != 0x4f || descriptors != 1 || invalid ||+ message.msg_flags & (MSG_CTRUNC | MSG_TRUNC) ||+ fcntl(received, F_SETFD, FD_CLOEXEC) != 0) {+ if (received >= 0) close(received);+ errno = EPROTO; return -1;+ }+ return received;+}diff --git a/packages/LockedUseNative/include/LockedUseNative.h b/packages/LockedUseNative/include/LockedUseNative.hnew file mode 100644index 0000000..7d72a75--- /dev/null+++ b/packages/LockedUseNative/include/LockedUseNative.h@@ -0,0 +1,23 @@+#ifndef OCU_LOCKED_USE_NATIVE_H+#define OCU_LOCKED_USE_NATIVE_H+#include <stdint.h>++typedef struct {+ uint8_t audit_token[32];+ uint32_t effective_user_id;+ uint32_t audit_user_id;+ uint32_t audit_session_id;+ int32_t process_id;+} OCUPeerIdentity;++/* Kernel-supplied connection identity, including pid version in the token.+ * Never reconstruct it from a pid reported by a client. Returns 0 on success. */+int ocu_copy_peer_identity(int socket_fd, OCUPeerIdentity *out_identity);+/* 0: no allow ACE grants mutation; 1: unsafe; -1: inspection failed. */+int ocu_has_mutating_acl(int file_fd);+int ocu_has_any_acl(int file_fd);+int ocu_remove_extended_acl(int file_fd);+/* SCM_RIGHTS transfers a connected endpoint for kernel peer verification only. */+int ocu_send_peer_socket(int channel_fd, int peer_fd);+int ocu_receive_peer_socket(int channel_fd);+#endifdiff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/AccessibilitySnapshot.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/AccessibilitySnapshot.swiftindex ae2213c..96fd6bc 100644--- a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/AccessibilitySnapshot.swift+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/AccessibilitySnapshot.swift@@ -190,6 +190,8 @@ enum SnapshotBuilder {return buildFixtureSnapshot(app: app, state: fixtureState)}+ try requireUsableComputerUseSession()+let permissions = PermissionDiagnostics.current()guard permissions.accessibilityTrusted else {throw ComputerUseError.permissionDenied("Accessibility permission is required. Run `open-computer-use doctor` and grant access to Open Computer Use.")@@ -584,7 +586,8 @@ private struct WindowCapture {/// WindowServer's hardware window capture first (any Space, covered or not,/// ~10-40ms), ScreenCaptureKit when it is unavailable.private static func captureImage(windowID: CGWindowID, bounds: CGRect, config: ImageCaptureConfig) -> CGImage? {- if let image = TimingLog.measure("snapshot.capture_hw") { SkyLightSPI.shared.hardwareCaptureWindow(windowID) } {+ if !LockedUseActionScope.requiresScreenCaptureKit,+ let image = TimingLog.measure("snapshot.capture_hw", { SkyLightSPI.shared.hardwareCaptureWindow(windowID) }) {return image}return TimingLog.measure("snapshot.capture_sck") { captureImageWithScreenCaptureKit(windowID: windowID, bounds: bounds, config: config) }diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/ComputerUseService.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/ComputerUseService.swiftindex f6aca66..179019e 100644--- a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/ComputerUseService.swift+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/ComputerUseService.swift@@ -765,6 +765,7 @@ public final class ComputerUseService {throw ComputerUseError.stateUnavailable("element \(elementIndex) has no backing accessibility object")}+ try requireUsableComputerUseSession()let result = AXUIElementPerformAction(element, rawAction as CFString)guard result == .success else {throw ComputerUseError.message("AXUIElementPerformAction failed with \(result.rawValue)")@@ -799,6 +800,7 @@ public final class ComputerUseService {let rawAction = record.rawActions.first(where: { $0.caseInsensitiveCompare("AXScroll\(normalized.capitalized)ByPage") == .orderedSame }),let element = record.element {for _ in 0..<repeatCount {+ try requireUsableComputerUseSession()_ = AXUIElementPerformAction(element, rawAction as CFString)Thread.sleep(forTimeInterval: 0.05)}@@ -939,6 +941,7 @@ public final class ComputerUseService {moveVisualCursor(to: cursorTarget)do {+ try requireUsableComputerUseSession()let result = AXUIElementSetAttributeValue(element, kAXValueAttribute as CFString, value as CFString)guard result == .success else {throw ComputerUseError.message("AXUIElementSetAttributeValue failed with \(result.rawValue)")@@ -974,11 +977,13 @@ public final class ComputerUseService {guard text.map({ $0.utf16.count <= 1000 }) ?? true, role.map({ $0.utf16.count <= 1000 }) ?? true else {throw ComputerUseError.invalidArguments("query text and role must be at most 1000 UTF-16 code units")}+ try requireUsableComputerUseSession()let app = try AppDiscovery.resolveRunning(query)let context = try SnapshotBuilder.resolveTargetWindow(for: app, windowID: windowID)let criteria = TargetedAX.Criteria(text: text, exact: exact, role: role,limit: min(100, max(1, limit)), maxNodes: min(5000, max(1, maxNodes)))let result = try SnapshotBuilder.targetedSearch(criteria, in: context)+ try requireUsableComputerUseSession()let matches = result.records.map { registerTargetedElement(record: $0, context: context, criteria: criteria) }return ["matches": matches, "truncated": result.truncated,"stop_reason": result.stopReason ?? "complete", "visited_nodes": result.visitedNodes,@@ -1051,6 +1056,14 @@ public final class ComputerUseService {private func currentSnapshot(for query: String) throws -> AppSnapshot {if let snapshot = snapshotsByApp[query.lowercased()] {+ if snapshot.mode != .fixture {+ do {+ try requireUsableComputerUseSession()+ } catch {+ snapshotsByApp.removeAll()+ throw error+ }+ }return snapshot}@@ -1175,6 +1188,7 @@ public final class ComputerUseService {return false}+ try requireUsableComputerUseSession()let result = AXUIElementSetAttributeValue(target.list,kAXSelectedChildrenAttribute as CFString,@@ -1307,6 +1321,7 @@ public final class ComputerUseService {let attempts = max(repeatCount, 1)for index in 0..<attempts {+ try requireUsableComputerUseSession()let result = AXUIElementPerformAction(element, action as CFString)switch result {case .success:@@ -1344,6 +1359,7 @@ public final class ComputerUseService {}private func setBoolAttribute(named attribute: String, on element: AXUIElement) throws -> Bool {+ try requireUsableComputerUseSession()let result = AXUIElementSetAttributeValue(element, attribute as CFString, kCFBooleanTrue)switch result {case .success:@@ -1633,6 +1649,7 @@ public final class ComputerUseService {}let baseValue = editableBaseValue(for: element)+ try requireUsableComputerUseSession()let result = AXUIElementSetAttributeValue(element, kAXValueAttribute as CFString, (baseValue + text) as CFString)switch result {case .success:diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/InputSimulation.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/InputSimulation.swiftindex 4e569a6..fa0e30d 100644--- a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/InputSimulation.swift+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/InputSimulation.swift@@ -114,6 +114,7 @@ enum InputSimulation {}static func scrollTargeted(at point: CGPoint, direction: String, pages: Double, pid: pid_t) throws {+ try requireUsableComputerUseSession()guard let event = CGEvent(scrollWheelEvent2Source: nil, units: .line, wheelCount: 2, wheel1: wheel1(direction: direction, pages: pages), wheel2: wheel2(direction: direction, pages: pages), wheel3: 0) else {throw ComputerUseError.message("Failed to create scroll event.")}@@ -124,6 +125,7 @@ enum InputSimulation {}static func scrollGlobally(at point: CGPoint, direction: String, pages: Double) throws {+ try requireUsableComputerUseSession()guard let event = CGEvent(scrollWheelEvent2Source: nil, units: .line, wheelCount: 2, wheel1: wheel1(direction: direction, pages: pages), wheel2: wheel2(direction: direction, pages: pages), wheel3: 0) else {throw ComputerUseError.message("Failed to create scroll event.")}@@ -181,6 +183,7 @@ enum InputSimulation {static func typeText(_ text: String, pid: pid_t) throws {for chunk in keyboardUnicodeChunks(for: text) {+ try requireUsableComputerUseSession()var mutableChunk = chunkguard let down = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true),let up = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false) else {@@ -227,6 +230,7 @@ enum InputSimulation {}static func pressKey(_ specification: String, pid: pid_t) throws {+ try requireUsableComputerUseSession()let parsed = try KeyPressParser.parse(specification)var activeFlags: CGEventFlags = []@@ -266,6 +270,7 @@ enum InputSimulation {}private static func postMouseEvent(type: CGEventType, source: CGEventSource?, point: CGPoint, button: CGMouseButton, clickState: Int, delta: CGSize? = nil, eventNumber: Int64? = nil) throws {+ try requireUsableComputerUseSession()guard let event = CGEvent(mouseEventSource: source, mouseType: type, mouseCursorPosition: point, mouseButton: button) else {throw ComputerUseError.message("Failed to create mouse event \(type.rawValue).")}@@ -319,6 +324,7 @@ enum InputSimulation {}private static func postMouseEventToPid(type: CGEventType, source: CGEventSource, point: CGPoint, button: CGMouseButton, clickState: Int, pid: pid_t) throws {+ try requireUsableComputerUseSession()guard let event = CGEvent(mouseEventSource: source, mouseType: type, mouseCursorPosition: point, mouseButton: button) else {throw ComputerUseError.message("Failed to create mouse event \(type.rawValue).")}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseActionScope.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseActionScope.swiftnew file mode 100644index 0000000..ee605f5--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseActionScope.swift@@ -0,0 +1,48 @@+import Darwin+import Foundation++/// App-agent requests are serialized across the process. This scope follows+/// synchronous dispatch onto AppKit's main thread as well as capture workers;+/// it cannot be selected from MCP arguments or environment variables.+public enum LockedUseActionScope {+ private final class Storage: @unchecked Sendable {+ let lock = NSLock()+ var validator: (@Sendable () throws -> Void)?+ }+ private static let storage = Storage()++ public static func withValidator<T>(_ validator: @escaping @Sendable () throws -> Void,+ body: () throws -> T) rethrows -> T {+ storage.lock.lock()+ precondition(storage.validator == nil, "GUI request dispatch must be serialized")+ storage.validator = validator+ storage.lock.unlock()+ defer {+ storage.lock.lock(); storage.validator = nil; storage.lock.unlock()+ }+ return try body()+ }++ /// Leased captures must use the ScreenCaptureKit path verified by the+ /// protected validation flow, rather than the optional hardware shortcut.+ static var requiresScreenCaptureKit: Bool {+ storage.lock.lock(); defer { storage.lock.unlock() }+ return storage.validator != nil+ }++ static func validate() throws {+ storage.lock.lock(); let validator = storage.validator; storage.lock.unlock()+ if let validator { try validator() }+ else if FileManager.default.fileExists(atPath: LockedUseIPCEndpoint.observer.path) {+ // An unscoped caller must not use a desktop temporarily unlocked+ // for another client. Refuse on unavailable or untrusted Broker.+ let observer = try LockedUseIPCClient(endpoint: .observer,+ brokerRequirement: LockedUseSigningIdentity.brokerRequirement())+ defer { observer.close() }+ let status = try observer.request(.init(operation: .status))+ guard status.phase == .idle || status.phase == .awaitingManualUnlock else {+ throw ComputerUseError.stateUnavailable("Locked Use belongs to another connection; GUI access is unavailable.")+ }+ }+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseAuthorizationRules.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseAuthorizationRules.swiftnew file mode 100644index 0000000..ba99b3e--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseAuthorizationRules.swift@@ -0,0 +1,111 @@+import CoreFoundation+import Foundation+import Security++/// Pure installation planning. No AuthorizationRightSet, privilege elevation,+/// 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 {+ public static let remoteRight = "dev.opencomputeruse.locked-use.remote"+ public enum Failure: Error { case malformed, unsupported, alreadyPresent, changedSincePlanning }++ public struct Plan: Codable, Sendable {+ public let original: Data+ public let installed: Data+ }++ /// Preserve all original rule names and fields. Only an existing OR rule+ /// (k-of-n absent or exactly 1) can safely have another OR branch prepended.+ /// Nested rules such as psso-screensaver retain their own threshold.+ public static func planInstallation(current: Data) throws -> Plan {+ var rule = try decode(current)+ let fallback = try branches(rule)+ guard !fallback.contains(remoteRight) else { throw Failure.alreadyPresent }+ let original = try encode(rule)+ rule["rule"] = [remoteRight] + fallback+ rule["k-of-n"] = 1+ return .init(original: original, installed: try encode(rule))+ }++ /// Conservative restore: an unrelated installer changing any semantic+ /// field invalidates the plan. Never overwrite a new authentication policy.+ public static func planUninstallation(current: Data, plan: Plan) throws -> Data {+ try validate(plan)+ guard try equivalent(current, plan.installed) else { throw Failure.changedSincePlanning }+ return plan.original+ }++ public static func installationStillApplicable(current: Data, plan: Plan) throws -> Bool {+ try validate(plan)+ return try equivalent(current, plan.original)+ }++ public static func installationObserved(current: Data, plan: Plan) throws -> Bool {+ try validate(plan)+ return try equivalent(current, plan.installed)+ }++ public static func loadInstalledPlan() throws -> Plan {+ let data = try LockedUseSecureStore.read(components: ["Library", "Application Support", "OpenComputerUse", "LockedUse", "authorization-plan.json"])+ let plan = try JSONDecoder().decode(Plan.self, from: data)+ try validate(plan)+ return plan+ }++ public static func installedRulesObserved() throws -> Bool {+ let plan = try loadInstalledPlan()+ var policy: CFDictionary?+ guard AuthorizationRightGet("system.login.screensaver", &policy) == errAuthorizationSuccess,+ let policy else { return false }+ let bytes = try PropertyListSerialization.data(fromPropertyList: policy, format: .xml, options: 0)+ guard try installationObserved(current: bytes, plan: plan) else { return false }+ 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+ }++ private static func validate(_ plan: Plan) throws {+ let expected = try planInstallation(current: plan.original)+ guard try equivalent(expected.installed, plan.installed) else { throw Failure.malformed }+ }++ private static func branches(_ rule: [String: Any]) throws -> [String] {+ guard rule["class"] as? String == "rule",+ let names = rule["rule"] as? [String], !names.isEmpty, names.count <= 64,+ Set(names).count == names.count,+ names.allSatisfy({ !$0.isEmpty && $0.utf8.count <= 255 && !$0.contains("\0") }) else {+ throw Failure.unsupported+ }+ if let threshold = rule["k-of-n"] {+ guard let number = threshold as? NSNumber,+ CFGetTypeID(number) != CFBooleanGetTypeID(),+ number.doubleValue == 1 else { throw Failure.unsupported }+ }+ return names+ }++ private static func decode(_ data: Data) throws -> [String: Any] {+ guard !data.isEmpty, data.count <= 128 * 1024,+ let rule = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any],+ JSONSerialization.isValidJSONObject(rule) else { throw Failure.malformed }+ // authorizationdb generates these timestamps. They are not editable+ // policy and must not make a restored rule appear semantically changed.+ return rule.filter { $0.key != "created" && $0.key != "modified" }+ }++ private static func encode(_ rule: [String: Any]) throws -> Data {+ let data = try PropertyListSerialization.data(fromPropertyList: rule, format: .xml, options: 0)+ guard data.count <= 128 * 1024 else { throw Failure.malformed }+ return data+ }++ private static func equivalent(_ lhs: Data, _ rhs: Data) throws -> Bool {+ // Sorted JSON distinguishes Boolean true from integer 1, unlike common+ // NSNumber/NSDictionary equality, and ignores plist key ordering.+ try JSONSerialization.data(withJSONObject: decode(lhs), options: [.sortedKeys])+ == JSONSerialization.data(withJSONObject: decode(rhs), options: [.sortedKeys])+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseBrokerConfiguration.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseBrokerConfiguration.swiftnew file mode 100644index 0000000..e05f848--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseBrokerConfiguration.swift@@ -0,0 +1,33 @@+import Foundation++/// Administrator-owned configuration. Enabled and validation evidence are+/// independent: installation/enrollment alone cannot validate session unlock.+public struct LockedUseBrokerConfiguration: Codable, Sendable {+ public let schemaVersion: Int+ public let enabled: Bool+ public let validatedOSBuild: String?+ public let validatedBrokerHash: String?+ public let validatedGuardianHash: String?+ public let validatedPluginHash: String?++ public init(enabled: Bool, validatedOSBuild: String? = nil,+ validatedBrokerHash: String? = nil, validatedGuardianHash: String? = nil,+ validatedPluginHash: String? = nil) {+ schemaVersion = 1; self.enabled = enabled; self.validatedOSBuild = validatedOSBuild+ self.validatedBrokerHash = validatedBrokerHash; self.validatedGuardianHash = validatedGuardianHash+ self.validatedPluginHash = validatedPluginHash+ }++ public static func loadInstalled() throws -> Self {+ let data = try LockedUseSecureStore.read(components: ["Library", "Application Support", "OpenComputerUse", "LockedUse", "configuration.json"])+ let value = try JSONDecoder().decode(Self.self, from: data)+ guard value.schemaVersion == 1 else { throw LockedUseClientApprovals.Failure.invalidRecord }+ return value+ }++ public func matchesValidation(osBuild: String, brokerHash: String, guardianHash: String, pluginHash: String) -> Bool {+ enabled && !osBuild.isEmpty && !brokerHash.isEmpty && !guardianHash.isEmpty && !pluginHash.isEmpty+ && validatedOSBuild == osBuild && validatedBrokerHash == brokerHash+ && validatedGuardianHash == guardianHash && validatedPluginHash == pluginHash+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseBrokerCoordinator.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseBrokerCoordinator.swiftnew file mode 100644index 0000000..6082c66--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseBrokerCoordinator.swift@@ -0,0 +1,419 @@+import Foundation+import Security++/// Serialized Broker control plane. The daemon supplies authenticated contexts+/// and monotonic receipt times; requests cannot choose a role, UID or audit ID.+public struct LockedUseBrokerCoordinator: Sendable {+ public enum Role: String, Codable, Sendable { case agent, guardian, plugin, observer }+ public struct Context: Codable, Sendable {+ public let id: UUID+ public let role: Role+ public let userID: UInt32+ public let auditSessionID: UInt32+ public let auditToken: Data+ public let processID: Int32+ public let codeHash: Data+ public init(id: UUID, role: Role, userID: UInt32, auditSessionID: UInt32, auditToken: Data = Data(), processID: Int32 = 0, codeHash: Data = Data()) {+ self.id = id; self.role = role; self.userID = userID; self.auditSessionID = auditSessionID+ self.auditToken = auditToken; self.processID = processID; self.codeHash = codeHash+ }+ }+ public enum Failure: Error { case denied, staleEvidence, malformed, unavailable }+ private var accepting = true+ private var unshieldedDiagnostic: LockedUseUnshieldedDiagnostic?+ private let requiresWatchdog: Bool+ private let bootSessionID: String+ private var recovering = false+ private var ownerContext: Context?+ private var guardianContext: Context?+ private var watchdogContext: Context?+ private var watchdogChallenge: Data?+ private var watchdogProtected = false+ private var watchdogLastReport: TimeInterval = 0+ private var guardianGone = false+ private var agentDrained = false+ private var machine = LockedUseStateMachine()+ private var registry = LockedUsePermitRegistry()+ private let prerequisites: LockedUseStateMachine.Prerequisites+ private var leaseID: UUID?+ private var guardianChallenge: Data?+ private var guardianID: UUID?+ private var releaseSent = false+ private var pluginID: UUID?+ private var issued: LockedUsePermitRegistry.Permit?+ private var lastReport: TimeInterval = 0+ private var guardEvidence: LockedUseStateMachine.Guards?+ private var observedSession: LockedUseSession?+ private var everGranted = false+ private var observedUnlocked = false+ private var connectionOwner: LockedUseStateMachine.Owner?+ private var receiptTime: TimeInterval = 0+ private var unlockWorkDrained = false+ private var agentEffects: [String] = []+ private var guardianEffects: [String] = []+ private let validationMode: Bool+ private var recoveryProbe = false+ private var recoveryProbePrepared = false+ public var phase: LockedUseStateMachine.Phase { unshieldedDiagnostic?.phase ?? machine.phase }+ public var stopReason: LockedUseStateMachine.StopReason? { machine.stopReason }+ public var owner: LockedUseStateMachine.Owner? { machine.owner ?? connectionOwner }++ public init(enabled: Bool, backendValidated: Bool, requiresWatchdog: Bool = false, recovery: LockedUseRecoveryRecord? = nil, bootSessionID: String = UUID().uuidString, validationMode: Bool = false) {+ self.validationMode = validationMode+ machine = .init(validationWait: validationMode)+ prerequisites = .init(enabled: enabled, backendValidated: backendValidated, clientAuthorized: true)+ self.requiresWatchdog = requiresWatchdog+ self.bootSessionID = bootSessionID+ if let recovery {+ recovering = true+ ownerContext = recovery.owner; guardianContext = recovery.guardian; watchdogContext = recovery.watchdog+ connectionOwner = .init(connectionID: recovery.owner.id, userID: recovery.owner.userID, auditSessionID: recovery.owner.auditSessionID)+ machine.restoreForRelock(owner: connectionOwner!, fullyReleased: recovery.fullyReleased)+ leaseID = recovery.leaseID; guardianID = recovery.guardian?.id+ watchdogChallenge = recovery.watchdogChallenge+ everGranted = recovery.everGranted; observedUnlocked = recovery.observedUnlocked+ agentDrained = recovery.agentDrained+ guardianGone = recovery.guardian == nil+ unlockWorkDrained = guardianGone && (!recovery.everGranted || recovery.observedUnlocked)+ agentEffects = ["stopActions"]; guardianEffects = ["cancelUnlock", "requestRelock"]+ }+ }++ public var recordedGuardian: Context? { guardianContext }+ public var recordedWatchdog: Context? { watchdogContext }+ public var recordedOwner: Context? { ownerContext }+ public var isFullyReleased: Bool { guardianContext == nil && watchdogContext == nil }+ /// Metadata only, for distinguishing unhealthy evidence from stale IPC.+ public func protectionDiagnostics(now: TimeInterval) -> (guardianAge: TimeInterval, watchdogAge: TimeInterval, watchdogProtected: Bool) {+ (max(0, now - lastReport), max(0, now - watchdogLastReport), watchdogProtected)+ }++ public func recoveryRecord(clientToken: Data) -> LockedUseRecoveryRecord? {+ guard let leaseID, let ownerContext, phase != .idle || !isFullyReleased else { return nil }+ return .init(leaseID: leaseID, owner: ownerContext, originalClientToken: clientToken,+ guardian: guardianContext, watchdog: watchdogContext, watchdogChallenge: watchdogChallenge,+ everGranted: everGranted, observedUnlocked: observedUnlocked, agentDrained: agentDrained, fullyReleased: isFullyReleased, bootSessionID: bootSessionID)+ }++ public mutating func handle(_ message: LockedUseIPCMessage, context: Context,+ now: TimeInterval) throws -> LockedUseIPCReply {+ _ = try message.validated()+ try tick(now: now)+ if message.operation == .beginUnshieldedDiagnostic {+ guard validationMode, accepting, prerequisites.enabled, machine.phase == .idle,+ isFullyReleased, unshieldedDiagnostic == nil, let session = message.session else { throw Failure.denied }+ unshieldedDiagnostic = try .init(owner: context, session: session, now: now)+ return unshieldedDiagnostic!.reply(message, context: context)+ }+ if var diagnostic = unshieldedDiagnostic {+ if message.operation != .disable {+ defer { unshieldedDiagnostic = diagnostic.finished ? nil : diagnostic }+ return try diagnostic.handle(message, context: context, now: now)+ }+ guard diagnostic.phase == .awaitingManualUnlock else { throw Failure.denied }+ unshieldedDiagnostic = nil+ }+ switch message.operation {+ case .beginUnshieldedDiagnostic, .endUnshieldedDiagnostic:+ throw Failure.denied+ case .status:+ // Only the owner may acknowledge a manual unlock, using a native+ // session observation matching its kernel connection identity.+ if (isOwner(context) || context.role == .observer && sameSession(context)), phase == .awaitingManualUnlock, let session = message.session {+ try check(session: session, context: context)+ try apply(machine.observe(session: session, now: now))+ }+ return reply(message, context: context)+ case .validationPassed:+ guard isOwner(context), message.leaseID == leaseID, phase == .active else { throw Failure.denied }+ try freshGuards(now: now)+ return reply(message, context: context)+ case .validationManual:+ guard context.role == .agent, sameSession(context), isFullyReleased,+ phase == .idle || phase == .awaitingManualUnlock,+ let session = message.session, session.state == .unlocked else { throw Failure.denied }+ try check(session: session, context: context)+ if phase == .awaitingManualUnlock { try apply(machine.observe(session: session, now: now)) }+ return reply(message, context: context)+ case .disable:+ guard context.role == .observer, context.userID == 0,+ guardianContext == nil, watchdogContext == nil,+ phase == .idle || phase == .awaitingManualUnlock else { throw Failure.denied }+ accepting = false+ return reply(message, context: context)+ case .begin, .beginRecoveryProbe:+ if message.operation == .beginRecoveryProbe, !validationMode { throw Failure.denied }+ guard accepting, guardianID == nil, watchdogContext == nil, context.role == .agent, let session = message.session else { throw Failure.denied }+ try check(session: session, context: context)+ let owner = LockedUseStateMachine.Owner(connectionID: context.id,+ userID: context.userID, auditSessionID: context.auditSessionID)+ let effects = try machine.begin(owner: owner, session: session, prerequisites: prerequisites, now: now)+ // A new fully released idle lease owns a fresh permit epoch. Old+ // lease ids/nonces are never accepted by the new state machine.+ registry = LockedUsePermitRegistry()+ connectionOwner = owner+ ownerContext = context; guardianContext = nil; watchdogContext = nil+ watchdogChallenge = nil; watchdogProtected = false; guardianGone = false; agentDrained = false; recovering = false+ leaseID = UUID(); guardianChallenge = try randomToken()+ guardianID = nil; releaseSent = false; pluginID = nil; issued = nil+ guardEvidence = nil; observedSession = session+ everGranted = false; observedUnlocked = false+ unlockWorkDrained = true+ recoveryProbe = message.operation == .beginRecoveryProbe+ recoveryProbePrepared = false+ agentEffects.removeAll(); guardianEffects.removeAll()+ try apply(effects)+ return reply(message, context: context, token: guardianChallenge)+ case .guardianHello:+ guard context.role == .guardian, sameSession(context), guardianID == nil,+ phase == .preparing, message.leaseID == leaseID,+ let token = message.token, let challenge = guardianChallenge,+ equal(token, challenge) else { throw Failure.denied }+ guardianID = context.id; guardianContext = context; guardianChallenge = nil+ if requiresWatchdog { watchdogChallenge = try randomToken() }+ return reply(message, context: context, token: watchdogChallenge)+ case .guardianReport:+ guard isGuardian(context), message.leaseID == leaseID,+ let session = message.session, let guards = message.guards else { throw Failure.denied }+ try check(session: session, context: context)+ observedSession = session; guardEvidence = guards; lastReport = now+ if let pending = message.unlockWorkPending { unlockWorkDrained = !pending }+ if everGranted, session.state == .unlocked { observedUnlocked = true }+ if message.stopReason == .physicalInput { try apply(machine.localInput()) }+ else if message.stopReason != nil, let owner {+ try apply(machine.end(owner: owner, reason: .guardLost))+ }+ if phase == .preparing {+ if !requiresWatchdog || watchdogContext != nil && watchdogProtected && now - watchdogLastReport < 1.5 {+ if recoveryProbe {+ guard guards.healthy, let owner else { throw Failure.denied }+ recoveryProbePrepared = true+ try apply(machine.end(owner: owner, reason: .operationFailed))+ } else { try apply(machine.guardsPrepared(guards, now: now, deferPermitUntilClaim: true)) }+ }+ }+ else { try apply(machine.heartbeat(guards, now: now)) }+ if phase == .relocking, agentDrained, unlockWorkDrained, !everGranted || observedUnlocked, let owner {+ try machine.confirmQuiescence(owner: owner)+ }+ try apply(machine.observe(session: session, now: now))+ return reply(message, context: context)+ case .guardianReleased:+ guard isGuardian(context), message.leaseID == leaseID, releaseSent,+ phase == .idle || phase == .awaitingManualUnlock else { throw Failure.denied }+ guardianID = nil; guardianContext = nil+ return reply(message, context: context)+ case .ownerRecoveryHello:+ guard isOwner(context), message.leaseID == leaseID, let session = message.session else { throw Failure.denied }+ try check(session: session, context: context)+ if guardianContext == nil { observedSession = session }+ return reply(message, context: context)+ case .guardianRecoveryHello:+ guard isGuardian(context), message.leaseID == leaseID else { throw Failure.denied }+ if everGranted, message.hasObservedUnlock == true { observedUnlocked = true }+ return reply(message, context: context)+ case .watchdogHello:+ guard context.role == .guardian, sameSession(context), message.leaseID == leaseID,+ watchdogContext == nil, let token = message.token, let expected = watchdogChallenge,+ equal(token, expected), phase == .preparing || recovering && phase == .relocking else { throw Failure.denied }+ watchdogContext = context; watchdogChallenge = nil; watchdogLastReport = now+ return reply(message, context: context)+ case .watchdogRecoveryHello:+ guard isWatchdog(context), message.leaseID == leaseID else { throw Failure.denied }+ if everGranted, message.hasObservedUnlock == true { observedUnlocked = true }+ return reply(message, context: context)+ case .watchdogReport:+ guard isWatchdog(context), message.leaseID == leaseID, let session = message.session else { throw Failure.denied }+ try check(session: session, context: context)+ watchdogLastReport = now+ watchdogProtected = message.guards?.healthy == true && message.stopReason == nil+ if !watchdogProtected, ![.idle, .relocking, .awaitingManualUnlock].contains(phase), let owner {+ try apply(machine.end(owner: owner, reason: .guardLost))+ }+ if everGranted, session.state == .unlocked || message.hasObservedUnlock == true { observedUnlocked = true }+ if guardianGone {+ observedSession = session; unlockWorkDrained = true+ if phase == .relocking, agentDrained, !everGranted || observedUnlocked, let owner {+ try machine.confirmQuiescence(owner: owner)+ }+ try apply(machine.observe(session: session, now: now))+ }+ return reply(message, context: context)+ case .watchdogReleased:+ guard isWatchdog(context), message.leaseID == leaseID, releaseSent,+ phase == .idle || phase == .awaitingManualUnlock else { throw Failure.denied }+ watchdogContext = nil+ if guardianGone { guardianID = nil; guardianContext = nil }+ return reply(message, context: context)+ case .pluginClaim:+ guard context.role == .plugin, sameAuditSession(context), phase == .authorizing,+ pluginID == nil, observedSession?.state == .locked else { throw Failure.denied }+ try freshGuards(now: now)+ if issued == nil { try apply(machine.authorizationRequested(now: now)) }+ guard let issued else { throw Failure.denied }+ pluginID = context.id+ return reply(message, context: context, token: issued.nonce)+ case .pluginConsume:+ guard context.role == .plugin, context.id == pluginID, sameAuditSession(context),+ message.leaseID == leaseID, let token = message.token,+ let issued, let owner else { throw Failure.denied }+ try freshGuards(now: now)+ _ = try registry.consume(attemptID: issued.attemptID, session: issued.session,+ nonce: token, guardsHealthy: true, now: now)+ try machine.consumePermit(id: issued.attemptID, owner: owner, now: now)+ everGranted = true+ // Authorization granted is still not an active GUI lease.+ return reply(message, context: context, authorized: true)+ case .pluginFinished:+ guard context.role == .plugin, context.id == pluginID else { throw Failure.denied }+ if message.stopReason != nil, let owner { try apply(machine.end(owner: owner, reason: .operationFailed)) }+ return reply(message, context: context)+ case .action:+ guard isOwner(context), message.leaseID == leaseID,+ let owner, let session = message.session else { throw Failure.denied }+ try check(session: session, context: context)+ try freshGuards(now: now)+ try apply(machine.authorizeAction(owner: owner, session: session, now: now))+ return reply(message, context: context)+ case .end:+ guard isOwner(context), let owner else { throw Failure.denied }+ try apply(machine.end(owner: owner, reason: message.stopReason ?? .turnEnded))+ return reply(message, context: context)+ case .quiesced:+ guard isOwner(context), let owner, message.leaseID == leaseID else { throw Failure.denied }+ // A consumed allow may still be queued in loginwindow. An old lock+ // screen is insufficient; require that unlock actually occurred+ // before accepting the action/transaction drain acknowledgement.+ guard unlockWorkDrained, !everGranted || observedUnlocked else { return reply(message, context: context) }+ agentDrained = true+ if phase == .idle || phase == .awaitingManualUnlock { return reply(message, context: context) }+ try machine.confirmQuiescence(owner: owner)+ if let session = observedSession { try apply(machine.observe(session: session, now: now)) }+ return reply(message, context: context)+ }+ }++ /// A changed authentication policy disables this service epoch. Keep the+ /// cleanup channels alive so old queued unlock work can safely drain.+ public mutating func invalidateInstallation() throws {+ accepting = false+ unshieldedDiagnostic?.cancel()+ if let owner, ![.idle, .relocking, .awaitingManualUnlock].contains(phase) {+ try apply(machine.end(owner: owner, reason: .operationFailed))+ }+ }++ public mutating func tick(now: TimeInterval) throws {+ try unshieldedDiagnostic?.tick(now: now)+ try registry.expire(now: now)+ receiptTime = now+ try apply(machine.tick(now: now))+ if requiresWatchdog, watchdogContext != nil, now - watchdogLastReport >= 1.5,+ ![.idle, .relocking, .awaitingManualUnlock].contains(phase), let owner {+ try apply(machine.end(owner: owner, reason: .guardLost))+ }+ }++ public mutating func disconnected(_ context: Context) throws {+ if context.id == unshieldedDiagnostic?.owner.id { unshieldedDiagnostic?.cancel() }+ registry.revoke(connectionID: context.id)+ if isOwner(context), let owner { try apply(machine.end(owner: owner, reason: .disconnected)) }+ else if isGuardian(context) || isWatchdog(context) || (context.id == pluginID && !everGranted), let owner {+ try apply(machine.end(owner: owner, reason: .guardLost))+ }+ }++ public mutating func guardianProcessExited() throws {+ guardianGone = true+ unlockWorkDrained = true+ if let owner, ![.idle, .awaitingManualUnlock].contains(phase) {+ try apply(machine.end(owner: owner, reason: .guardLost))+ }+ }++ /// Called only after the daemon observes ESRCH for the kernel-verified+ /// owner process. Socket closure alone cannot prove GUI dispatch drained.+ public mutating func ownerProcessExited() throws {+ guard phase == .relocking, let owner, unlockWorkDrained,+ !everGranted || observedUnlocked else { return }+ agentDrained = true+ try machine.confirmQuiescence(owner: owner)+ if let session = observedSession { try apply(machine.observe(session: session, now: receiptTime)) }+ }++ private func check(session: LockedUseSession, context: Context) throws {+ guard context.userID > 0, context.auditSessionID > 0,+ session.userID == context.userID, session.auditSessionID == context.auditSessionID else { throw Failure.denied }+ }+ private func isOwner(_ context: Context) -> Bool {+ context.role == .agent && context.id == owner?.connectionID && sameSession(context)+ }+ private func sameSession(_ context: Context) -> Bool {+ context.userID == owner?.userID && sameAuditSession(context)+ }+ private func sameAuditSession(_ context: Context) -> Bool {+ context.auditSessionID > 0 && context.auditSessionID == owner?.auditSessionID+ }+ private func isWatchdog(_ context: Context) -> Bool {+ context.role == .guardian && context.id == watchdogContext?.id && sameSession(context)+ }+ private func isGuardian(_ context: Context) -> Bool {+ context.role == .guardian && context.id == guardianID && sameSession(context)+ }+ private func freshGuards(now: TimeInterval) throws {+ guard now >= lastReport, now - lastReport < 1,+ guardEvidence?.healthy == true, observedSession?.state != .unavailable,+ !requiresWatchdog || watchdogContext != nil && watchdogProtected && now - watchdogLastReport < 1.5 else { throw Failure.staleEvidence }+ }+ private mutating func apply(_ effects: [LockedUseStateMachine.Effect]) throws {+ for effect in effects {+ switch effect {+ case .prepareGuards: agentEffects.append("prepareGuards")+ case let .issuePermit(permit):+ issued = try registry.issue(attemptID: permit.id, connectionID: permit.owner.connectionID,+ session: .init(userID: permit.owner.userID, auditSessionID: permit.owner.auditSessionID),+ guardsHealthy: true, now: receiptTime)+ case .requestUnlock:+ unlockWorkDrained = false+ guardianEffects.append("requestUnlock")+ case .stopActions: agentEffects.append("stopActions")+ case .revokePermit:+ if let issued { registry.revoke(attemptID: issued.attemptID) }+ issued = nil+ case .cancelUnlock: guardianEffects.append("cancelUnlock")+ case .requestRelock: guardianEffects.append("requestRelock")+ case .releaseGuards: guardianEffects.append("releaseGuards")+ }+ }+ }+ private mutating func reply(_ message: LockedUseIPCMessage, context: Context,+ token: Data? = nil, authorized: Bool = false) -> LockedUseIPCReply {+ var effects: [String] = []+ if isOwner(context) { effects = agentEffects; agentEffects.removeAll() }+ if isGuardian(context) {+ effects = guardianEffects; guardianEffects.removeAll()+ if effects.contains("releaseGuards") { releaseSent = true }+ }+ if isWatchdog(context), releaseSent || guardianGone && guardianEffects.contains("releaseGuards") {+ if guardianGone { guardianEffects.removeAll { $0 == "releaseGuards" }; releaseSent = true }+ effects.append("releaseWatchdog")+ }+ let result: LockedUseIPCReply.Result = effects.contains("releaseGuards") ? .release+ : authorized ? .authorized : phase == .active && isOwner(context) ? .active : phase == .relocking ? .relock+ : phase == .idle ? .ok : .waiting+ return .init(id: message.id, result: result, phase: phase,+ 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))+ }+ private func randomToken() throws -> Data {+ var bytes = [UInt8](repeating: 0, count: 32)+ guard SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) == errSecSuccess else { throw Failure.unavailable }+ return Data(bytes)+ }+ private func equal(_ lhs: Data, _ rhs: Data) -> Bool {+ guard lhs.count == 32, rhs.count == 32 else { return false }+ return zip(lhs, rhs).reduce(UInt8(0)) { $0 | ($1.0 ^ $1.1) } == 0+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseClickAllowance.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseClickAllowance.swiftnew file mode 100644index 0000000..9920815--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseClickAllowance.swift@@ -0,0 +1,41 @@+import Foundation++/// Inherited-pipe capability for a single loginwindow click, never a PID-only+/// exemption. Hardware takeover is monitored separately and revokes this gate.+public struct LockedUseClickAllowance: Sendable {+ public enum Button: Sendable { case down, up }+ public enum Rejection: String, Sendable { case inactive, timing, capability, source, target, sequence }+ public private(set) var rejection: Rejection?+ private let tag: Int64+ private let sender: Int32+ private let deadline: TimeInterval+ private let began: TimeInterval+ private var down: (target: Int32, window: Int64, x: Double, y: Double, at: TimeInterval)?+ private var revoked = false++ public init(tag: Int64, sender: Int32, now: TimeInterval) {+ self.tag = tag; self.sender = sender; deadline = now + 5; began = now+ revoked = tag == 0 || sender <= 0 || !now.isFinite+ }+ public mutating func revoke() { revoked = true; down = nil }+ public mutating func accept(button: Button, tag candidate: Int64, sender candidateSender: Int32,+ target: Int32, window: Int64, x: Double, y: Double, now: TimeInterval, locked: Bool) -> Bool {+ rejection = nil+ guard !revoked else { rejection = .inactive; return false }+ guard locked, now.isFinite, now >= began, now < deadline else { rejection = .timing; revoke(); return false }+ guard candidate == tag else { rejection = .capability; return false }+ guard candidateSender == sender else { rejection = .source; return false }+ guard target > 0, window > 0, x.isFinite, y.isFinite else { rejection = .target; return false }+ switch button {+ case .down:+ guard down == nil else { rejection = .sequence; revoke(); return false }+ down = (target, window, x, y, now)+ return true+ case .up:+ guard let down, down.target == target, down.window == window, down.x == x, down.y == y,+ now >= down.at, now - down.at < 0.25 else { rejection = .sequence; revoke(); return false }+ revoke()+ return true+ }+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseClientApprovals.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseClientApprovals.swiftnew file mode 100644index 0000000..6f9361d--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseClientApprovals.swift@@ -0,0 +1,99 @@+import Darwin+import Foundation+import LockedUseNative++/// Administrator-controlled approval records. These records authorize a+/// signing identity; they never declare the unlock backend validated or enable+/// a lease. No password, username, path, or environment override is stored.+public struct LockedUseClientApprovals: Codable, Sendable {+ public enum Role: String, Codable, Sendable { case client, agent, guardian }+ public struct Approval: Codable, Equatable, Sendable {+ public let id: UUID+ public let userID: UInt32+ public let role: Role+ public let signingIdentifier: String+ public let teamIdentifier: String++ public init(id: UUID = UUID(), userID: UInt32, role: Role,+ signingIdentifier: String, teamIdentifier: String) throws {+ self.id = id; self.userID = userID; self.role = role+ self.signingIdentifier = signingIdentifier; self.teamIdentifier = teamIdentifier+ try validate()+ }++ public func requirement() throws -> String {+ // validate() restricts both interpolated values to a safe alphabet.+ try validate()+ return "identifier \"\(signingIdentifier)\" and anchor apple generic and certificate leaf[subject.OU] = \"\(teamIdentifier)\""+ }++ fileprivate func validate() throws {+ func alphanumeric(_ byte: UInt8) -> Bool {+ (48...57).contains(byte) || (65...90).contains(byte) || (97...122).contains(byte)+ }+ guard userID > 0, userID < UInt32.max,+ (2...255).contains(signingIdentifier.utf8.count),+ signingIdentifier.utf8.first.map(alphanumeric) == true,+ signingIdentifier.utf8.allSatisfy({ alphanumeric($0) || $0 == 45 || $0 == 46 }),+ teamIdentifier.utf8.count == 10,+ teamIdentifier.utf8.allSatisfy({ (48...57).contains($0) || (65...90).contains($0) }) else {+ throw Failure.invalidRecord+ }+ }+ }+ public enum Failure: Error { case invalidRecord, insecureFile, inaccessible(Int32), unapproved }+ public let schemaVersion: Int+ public let approvals: [Approval]++ public init(approvals: [Approval]) throws {+ self.schemaVersion = 1+ self.approvals = approvals+ try validate()+ }++ public static func loadInstalled() throws -> LockedUseClientApprovals {+ try readSecureFile(components: ["Library", "Application Support", "OpenComputerUse", "LockedUse", "clients.json"], owner: 0)+ }++ public func verifiedPeer(socket descriptor: Int32, role: Role) throws -> LockedUsePeerIdentity {+ try validate()+ // Every candidate uses a root-approved signing requirement. The payload+ // cannot select a role, UID or requirement for the Broker to trust.+ for record in approvals where record.role == role {+ if let peer = try? LockedUsePeerIdentity.verified(socket: descriptor, requirement: record.requirement()),+ peer.userID == record.userID, peer.auditSessionID > 0,+ peer.hardenedRuntime, !peer.permitsCodeInjection,+ peer.signingIdentifier == record.signingIdentifier, peer.teamIdentifier == record.teamIdentifier {+ return peer+ }+ }+ throw Failure.unapproved+ }++ private func validate() throws {+ guard schemaVersion == 1, approvals.count <= 64,+ Set(approvals.map(\.id)).count == approvals.count else { throw Failure.invalidRecord }+ var identities = Set<String>()+ for approval in approvals {+ try approval.validate()+ guard identities.insert("\(approval.userID):\(approval.role):\(approval.teamIdentifier):\(approval.signingIdentifier)").inserted else {+ throw Failure.invalidRecord+ }+ }+ }++ static func decodeValidated(_ data: Data) throws -> LockedUseClientApprovals {+ guard data.count <= 128 * 1024 else { throw Failure.insecureFile }+ let decoded = try JSONDecoder().decode(Self.self, from: data)+ try decoded.validate()+ return decoded+ }++ /// Walk with openat/O_NOFOLLOW; lstat followed by open would introduce a+ /// symlink race. All enclosing directories must have the trusted owner and+ /// no group/other write permission. Tests inject an alternate trusted owner;+ /// the installed production entry point always uses root (UID zero).+ static func readSecureFile(components: [String], owner: UInt32) throws -> LockedUseClientApprovals {+ try decodeValidated(LockedUseSecureStore.read(components: components, owner: owner))+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseComponentValidation.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseComponentValidation.swiftnew file mode 100644index 0000000..f080991--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseComponentValidation.swift@@ -0,0 +1,47 @@+import Darwin+import Foundation+import Security++/// Validation is tied to the OS build and each installed executable's signed+/// code hash. Replacing a component or updating macOS invalidates the evidence.+public enum LockedUseComponentValidation {+ public struct Evidence: Codable, Equatable, Sendable {+ public let osBuild: String+ public let brokerHash: String+ public let guardianHash: String+ public let pluginHash: String+ }+ public static func bootSessionID() throws -> String {+ let value = try kernelString("kern.bootsessionuuid")+ guard UUID(uuidString: value) != nil else { throw LockedUseClientApprovals.Failure.unapproved }+ return value+ }+ private static func kernelString(_ name: String) throws -> String {+ var size = 0+ guard sysctlbyname(name, nil, &size, nil, 0) == 0, size > 1, size <= 128 else { throw LockedUseClientApprovals.Failure.unapproved }+ var bytes = [CChar](repeating: 0, count: size)+ guard sysctlbyname(name, &bytes, &size, nil, 0) == 0 else { throw LockedUseClientApprovals.Failure.unapproved }+ return String(decoding: bytes.prefix(while: { $0 != 0 }).map { UInt8(bitPattern: $0) }, as: UTF8.self)+ }+ public static func current(team: String) throws -> Evidence {+ guard team.utf8.count == 10, team.utf8.allSatisfy({ (48...57).contains($0) || (65...90).contains($0) }) else { throw LockedUseClientApprovals.Failure.unapproved }+ let osBuild = try kernelString("kern.osversion")+ let base = "/Library/Application Support/OpenComputerUse/LockedUse/"+ return try .init(osBuild: osBuild,+ brokerHash: hash(path: base + "OCULockService", id: "dev.opencomputeruse.locked-use.broker", team: team),+ guardianHash: hash(path: base + "OCU Guardian.app", id: "dev.opencomputeruse.locked-use.guardian.dev", team: team),+ pluginHash: hash(path: "/Library/Security/SecurityAgentPlugins/OCULockAuth.bundle", id: "dev.opencomputeruse.locked-use.authorization", team: team))+ }+ private static func hash(path: String, id: String, team: String) throws -> String {+ var code: SecStaticCode?+ guard SecStaticCodeCreateWithPath(URL(fileURLWithPath: path) as CFURL, [], &code) == errSecSuccess, let code else { throw LockedUseClientApprovals.Failure.unapproved }+ var requirement: SecRequirement?+ let text = "identifier \"\(id)\" and anchor apple generic and certificate leaf[subject.OU] = \"\(team)\""+ guard SecRequirementCreateWithString(text as CFString, [], &requirement) == errSecSuccess,+ SecStaticCodeCheckValidity(code, SecCSFlags(rawValue: kSecCSStrictValidate | kSecCSCheckAllArchitectures), requirement) == errSecSuccess else { throw LockedUseClientApprovals.Failure.unapproved }+ var info: CFDictionary?+ guard SecCodeCopySigningInformation(code, SecCSFlags(rawValue: kSecCSSigningInformation), &info) == errSecSuccess,+ let info = info as? [String: Any], let hash = info[kSecCodeInfoUnique as String] as? Data else { throw LockedUseClientApprovals.Failure.unapproved }+ return hash.map { String(format: "%02x", $0) }.joined()+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseDiagnostics.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseDiagnostics.swiftnew file mode 100644index 0000000..729e69d--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseDiagnostics.swift@@ -0,0 +1,152 @@+import ApplicationServices+import CoreGraphics+import Darwin+import Foundation+import Security++public struct LockedUseSession: Equatable, Codable, Sendable {+ public enum State: String, Codable, Sendable { case locked, unlocked, unavailable }+ public let state: State+ public let userID: UInt32?+ public let auditSessionID: UInt32?++ public init(state: State, userID: UInt32?, auditSessionID: UInt32?) {+ self.state = state+ self.userID = userID+ self.auditSessionID = auditSessionID+ }++ public static func current() -> LockedUseSession {+ var sessionID = SecuritySessionId()+ var attributes = SessionAttributeBits()+ guard SessionGetInfo(callerSecuritySession, &sessionID, &attributes) == errSecSuccess,+ attributes.contains(.sessionHasGraphicAccess) else {+ return .init(state: .unavailable, userID: nil, auditSessionID: nil)+ }+ return from(dictionary: CGSessionCopyCurrentDictionary() as? [String: Any], effectiveUserID: geteuid(), securitySessionID: sessionID)+ }++ static func from(dictionary: [String: Any]?, effectiveUserID: UInt32, securitySessionID: UInt32?) -> LockedUseSession {+ guard let dictionary,+ boolean(dictionary[kCGSessionOnConsoleKey as String]) == true,+ boolean(dictionary[kCGSessionLoginDoneKey as String]) == true,+ let uid = unsignedNumber(dictionary[kCGSessionUserIDKey as String]),+ let auditID = securitySessionID, auditID != 0,+ uid == effectiveUserID, uid != 0 else {+ return .init(state: .unavailable, userID: nil, auditSessionID: nil)+ }+ if let observedAuditID = dictionary["kCGSSessionAuditIDKey"], unsignedNumber(observedAuditID) != auditID {+ return .init(state: .unavailable, userID: uid, auditSessionID: nil)+ }+ // SessionGetInfo provides the stable audit-session identity. The documented+ // kCGSessionConsoleSetKey is absent on some current systems; do not invent+ // a default console ID or reject an otherwise completed GUI login.+ // This WindowServer key is undocumented. Its absence in a completed GUI+ // login is the usual unlocked representation; malformed values fail closed.+ let locked: Bool+ if let value = dictionary["CGSSessionScreenIsLocked"] {+ guard let number = value as? NSNumber,+ CFGetTypeID(number) == CFBooleanGetTypeID() else {+ return .init(state: .unavailable, userID: uid, auditSessionID: auditID)+ }+ locked = number.boolValue+ } else {+ locked = false+ }+ return .init(state: locked ? .locked : .unlocked, userID: uid, auditSessionID: auditID)+ }++ private static func boolean(_ value: Any?) -> Bool? {+ guard let number = value as? NSNumber, CFGetTypeID(number) == CFBooleanGetTypeID() else { return nil }+ return number.boolValue+ }++ private static func unsignedNumber(_ value: Any?) -> UInt32? {+ guard let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID() else { return nil }+ let value = number.doubleValue+ guard value.isFinite, value >= 0, value <= Double(UInt32.max), value.rounded(.towardZero) == value else { return nil }+ return UInt32(value)+ }+}++public struct LockedUseDiagnostics: Codable, Sendable {+ public let schemaVersion: Int+ public let stage: String+ public let enabled: Bool+ public let available: Bool+ public let clientApproved: Bool+ public let authenticationPolicyIntact: Bool+ public let session: LockedUseSession+ public let accessibility: Bool+ public let screenRecording: Bool+ public let inputMonitoring: Bool+ public let pluginInstalled: Bool+ public let brokerInstalled: Bool+ public let otherAuthorizationPlugins: [String]+ public let blockers: [String]++ /// Never enables the experimental backend from environment variables, files+ /// written by the user, or the presence of another vendor's authorization plugin.+ public static func current() -> LockedUseDiagnostics {+ let pluginsPath = "/Library/Security/SecurityAgentPlugins"+ let entries = (try? FileManager.default.contentsOfDirectory(atPath: pluginsPath)) ?? []+ let ownPlugin = "OCULockAuth.bundle"+ let others = entries.filter { $0.hasSuffix(".bundle") && $0 != ownPlugin && $0 != "OCULockProbe.bundle" }.sorted()+ let configuration = try? LockedUseBrokerConfiguration.loadInstalled()+ let policyIntact = (try? LockedUseAuthorizationRules.installedRulesObserved()) == true+ let identity = try? LockedUseSigningIdentity.current()+ let approvals = try? LockedUseClientApprovals.loadInstalled()+ let approved = approvals?.approvals.contains { record in+ record.role == .agent && record.userID == identity?.userID+ && record.signingIdentifier == identity?.signingIdentifier+ && record.teamIdentifier == identity?.teamIdentifier+ } ?? false+ var available = false+ 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)+ }+ return .init(+ schemaVersion: 1, stage: available ? "validated" : configuration == nil ? "experimental-preflight" : "installed-awaiting-validation", 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"),+ 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."+ ]+ )+ }++ 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"+ + "Other authorization plugins: \(otherAuthorizationPlugins.isEmpty ? "none detected" : otherAuthorizationPlugins.joined(separator: ", "))\n"+ + blockers.joined(separator: "\n")+ }++ public func jsonText() throws -> String {+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]+ return String(decoding: try encoder.encode(self), as: UTF8.self)+ }+}++/// Used by fresh snapshots and cached real-app snapshots. Fixture state is not a+/// desktop and remains usable in headless CI. Inventory never triggers unlocking.+func requireUsableComputerUseSession(_ session: LockedUseSession = .current()) throws {+ switch session.state {+ case .unlocked:+ try LockedUseActionScope.validate()+ return+ case .locked:+ throw ComputerUseError.stateUnavailable("The Mac is locked and this GUI request has no active Locked Use lease. Enable and validate Locked Use in the signed app, or unlock normally; run `ocu locked-use status --json` for diagnostics.")+ case .unavailable:+ throw ComputerUseError.stateUnavailable("No completed GUI session for the current console user is available. Computer Use cannot operate a login, switched-user, or unknown session.")+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseEventEncoding.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseEventEncoding.swiftnew file mode 100644index 0000000..f58ba24--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseEventEncoding.swift@@ -0,0 +1,10 @@+import CoreGraphics++/// Encode the already verified target window's local point. This private SPI+/// describes a mouse event; it neither initiates nor grants authentication.+public func encodeLockedUseWindowLocation(_ event: CGEvent, point: CGPoint) throws {+ guard point.x.isFinite, point.y.isFinite else {+ throw ComputerUseError.message("Invalid Locked Use window location")+ }+ try SkyLightSPI.shared.setWindowLocation(event, point: point)+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseGuardianBootstrap.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseGuardianBootstrap.swiftnew file mode 100644index 0000000..5190ac7--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseGuardianBootstrap.swift@@ -0,0 +1,17 @@+import Foundation++/// Passed only through the launcher-owned inherited pipe, never argv/env.+/// Kernel signing/audit validation still precedes challenge consumption.+public struct LockedUseGuardianBootstrap: Codable, Sendable {+ public let leaseID: UUID+ public let token: Data+ public let clickTag: Int64?+ public let returnTag: Int64?+ public let startupDeadline: TimeInterval?+ public init(leaseID: UUID, token: Data, clickTag: Int64? = nil, returnTag: Int64? = nil, startupDeadline: TimeInterval? = nil) throws {+ guard token.count == 32 else { throw LockedUseIPCFrame.Failure.malformed }+ self.leaseID = leaseID; self.token = token+ self.clickTag = clickTag; self.returnTag = returnTag+ self.startupDeadline = startupDeadline+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseGuardianPolicy.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseGuardianPolicy.swiftnew file mode 100644index 0000000..8066d34--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseGuardianPolicy.swift@@ -0,0 +1,111 @@+import Foundation++/// Independent guardian policy. No caller command can stand in for observing+/// the original audit session locked. OS adapters provide evidence, not flags+/// copied from a Computer Use request.+public struct LockedUseGuardianPolicy: Sendable {+ public enum Phase: String, Codable, Sendable { case preparing, shielding, relocking, finished }+ public enum Reason: String, Codable, Sendable {+ case localInput, guardianFailure, parentDisconnected, heartbeatExpired+ case displayChanged, sessionChanged, leaseExpired, stopRequested+ }+ public enum Effect: Equatable, Sendable { case requestRelock, releaseShield }+ public private(set) var phase: Phase = .preparing+ public private(set) var reason: Reason?+ public let session: LockedUseSession+ private let deadline: TimeInterval+ private var lastHeartbeat: TimeInterval+ private var lastNow: TimeInterval+ private var lastRelock: TimeInterval = -.infinity+ private var quiesced = false+ private var lockedAfterDrain = false+ private var localRecoveryRequested = false+ public var localRecoveryReady: Bool { quiesced && lockedAfterDrain && localRecoveryRequested }+ public mutating func requestLocalRecovery() { localRecoveryRequested = true }+ private var topology: String?++ public init(session: LockedUseSession, now: TimeInterval, lifetime: TimeInterval = 300) throws {+ guard now.isFinite, now >= 0, lifetime.isFinite, lifetime > 0, lifetime <= 300,+ session.state != .unavailable, let uid = session.userID, uid > 0,+ let auditID = session.auditSessionID, auditID > 0 else {+ throw LockedUseStateMachine.Failure.invalidSession+ }+ self.session = session+ self.deadline = now + lifetime+ self.lastHeartbeat = now+ self.lastNow = now+ }++ public mutating func prepared(topology: String, now: TimeInterval) throws {+ try clock(now)+ guard phase == .preparing, !topology.isEmpty, now < deadline else {+ throw LockedUseStateMachine.Failure.invalidTransition+ }+ self.topology = topology+ // Startup is bounded separately; the live heartbeat begins only after+ // the child and its protection surface have actually registered.+ lastHeartbeat = now+ phase = .shielding+ }++ /// A heartbeat after expiry is never allowed to restore health.+ public mutating func heartbeat(now: TimeInterval) throws -> [Effect] {+ try clock(now)+ guard phase == .preparing || phase == .shielding else { return [] }+ if now - lastHeartbeat >= 1.5 { return stop(.heartbeatExpired, now: now) }+ if now >= deadline { return stop(.leaseExpired, now: now) }+ lastHeartbeat = now+ return []+ }++ public mutating func stop(_ reason: Reason, now: TimeInterval) -> [Effect] {+ guard phase != .finished else { return [] }+ if phase != .relocking {+ self.reason = reason+ phase = .relocking+ }+ guard !localRecoveryReady, now.isFinite, now >= lastNow, now - lastRelock >= 0.5 else { return [] }+ lastNow = now+ lastRelock = now+ return [.requestRelock]+ }++ public mutating func confirmQuiescence() { quiesced = true }+ public mutating func requireQuiescence() { quiesced = false; lockedAfterDrain = false }++ public mutating func poll(session current: LockedUseSession, topology currentTopology: String,+ guardsHealthy: Bool, lockPresentationReady: Bool = false, now: TimeInterval) throws -> [Effect] {+ try clock(now)+ guard phase != .finished else { return [] }+ let sameSession = current.userID == session.userID && current.auditSessionID == session.auditSessionID+ if phase == .relocking {+ if sameSession, current.state == .unlocked, localRecoveryReady {+ phase = .finished+ return [.releaseShield]+ }+ if sameSession, current.state == .locked {+ if quiesced { lockedAfterDrain = true }+ if quiesced, lockPresentationReady {+ phase = .finished+ return [.releaseShield]+ }+ // Waiting for the action drain is not another lock request.+ // Repeated SPI calls can dismiss the password UI while the+ // user is trying to recover from a failed authorization.+ return []+ }+ return stop(reason ?? .guardianFailure, now: now)+ }+ guard sameSession, current.state != .unavailable else { return stop(.sessionChanged, now: now) }+ guard guardsHealthy else { return stop(.guardianFailure, now: now) }+ if let topology, topology != currentTopology { return stop(.displayChanged, now: now) }+ if now - lastHeartbeat >= 1.5 { return stop(.heartbeatExpired, now: now) }+ if now >= deadline { return stop(.leaseExpired, now: now) }+ return []+ }++ private mutating func clock(_ now: TimeInterval) throws {+ guard now.isFinite, now >= lastNow else { throw LockedUseStateMachine.Failure.invalidClock }+ lastNow = now+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseIPC.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseIPC.swiftnew file mode 100644index 0000000..2eaaeed--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseIPC.swift@@ -0,0 +1,116 @@+import Foundation++/// Local Broker protocol. Endpoint selection and kernel peer validation supply+/// the role/connection identity; neither is accepted from this message body.+public struct LockedUseIPCMessage: Codable, Sendable {+ public enum Operation: String, Codable, Sendable {+ case status, disable, validationPassed, validationManual, begin, beginRecoveryProbe, guardianHello, guardianReport, guardianReleased, watchdogHello, watchdogRecoveryHello, watchdogReport, watchdogReleased, ownerRecoveryHello, guardianRecoveryHello, action, end, quiesced+ case pluginClaim, pluginConsume, pluginFinished, beginUnshieldedDiagnostic, endUnshieldedDiagnostic+ }+ public let version: Int+ public let id: UUID+ public let operation: Operation+ public let leaseID: UUID?+ public let token: Data?+ public let session: LockedUseSession?+ public let guards: LockedUseStateMachine.Guards?+ public let stopReason: LockedUseStateMachine.StopReason?+ public let unlockWorkPending: Bool?+ public let hasObservedUnlock: Bool?++ public init(id: UUID = UUID(), operation: Operation, leaseID: UUID? = nil,+ token: Data? = nil, session: LockedUseSession? = nil,+ guards: LockedUseStateMachine.Guards? = nil,+ stopReason: LockedUseStateMachine.StopReason? = nil, unlockWorkPending: Bool? = nil, hasObservedUnlock: Bool? = nil) {+ version = 1; self.id = id; self.operation = operation+ self.leaseID = leaseID; self.token = token; self.session = session+ self.guards = guards; self.stopReason = stopReason+ self.unlockWorkPending = unlockWorkPending+ self.hasObservedUnlock = hasObservedUnlock+ }++ public func validated() throws -> Self {+ guard version == 1, token == nil || token?.count == 32 else { throw LockedUseIPCFrame.Failure.malformed }+ return self+ }+}++public struct LockedUseIPCReply: Codable, Sendable {+ public enum Result: String, Codable, Sendable { case ok, denied, waiting, authorized, active, relock, release }+ public let version: Int+ public let id: UUID+ public let result: Result+ public let phase: LockedUseStateMachine.Phase+ public let leaseID: UUID?+ public let token: Data?+ public let effects: [String]+ public let detail: String?+ public let guardsReleased: Bool?+ public let recoveryProbePrepared: Bool?+ public let startupDeadline: TimeInterval?+ public let validationConfirmation: Bool?++ public init(id: UUID, result: Result, phase: LockedUseStateMachine.Phase,+ leaseID: UUID? = nil, token: Data? = nil, effects: [String] = [], detail: String? = nil, guardsReleased: Bool? = nil, recoveryProbePrepared: Bool? = nil, startupDeadline: TimeInterval? = nil, validationConfirmation: Bool? = nil) {+ version = 1; self.id = id; self.result = result; self.phase = phase+ self.leaseID = leaseID; self.token = token; self.effects = effects; self.detail = detail+ self.guardsReleased = guardsReleased+ self.recoveryProbePrepared = recoveryProbePrepared+ self.startupDeadline = startupDeadline+ self.validationConfirmation = validationConfirmation+ }+}++/// Bounded length-prefix framing; never use readLine/getline in a privileged+/// server. Zero/oversized frames and EOF mid-frame permanently poison a stream.+public struct LockedUseIPCFrame: Sendable {+ public enum Failure: Error { case malformed, oversized, truncated, poisoned }+ public static let maximumPayload = 16 * 1024+ private var buffered = Data()+ private var failed = false++ public init() {}++ public static func encode<T: Encodable>(_ value: T) throws -> Data {+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.sortedKeys]+ let payload = try encoder.encode(value)+ guard !payload.isEmpty, payload.count <= maximumPayload else { throw Failure.oversized }+ let length = UInt32(payload.count)+ return Data([UInt8(length >> 24), UInt8((length >> 16) & 255),+ UInt8((length >> 8) & 255), UInt8(length & 255)]) + payload+ }++ /// The socket adapter reads at most 4096 bytes per event. A peer sending a+ /// batch cannot force unbounded buffering or one run-loop's worth of work.+ public mutating func append(_ chunk: Data) throws -> [Data] {+ guard !failed else { throw Failure.poisoned }+ do {+ guard chunk.count <= 4096, buffered.count + chunk.count <= Self.maximumPayload + 4096 + 4 else {+ throw Failure.oversized+ }+ buffered.append(chunk)+ var frames: [Data] = []+ while buffered.count >= 4 {+ let length = buffered.prefix(4).reduce(UInt32(0)) { ($0 << 8) | UInt32($1) }+ guard length > 0 else { throw Failure.malformed }+ guard length <= Self.maximumPayload else { throw Failure.oversized }+ guard buffered.count >= Int(length) + 4 else { break }+ guard frames.count < 16 else { throw Failure.oversized }+ frames.append(Data(buffered.dropFirst(4).prefix(Int(length))))+ buffered.removeFirst(Int(length) + 4)+ }+ return frames+ } catch {+ failed = true+ buffered.removeAll(keepingCapacity: false)+ throw error+ }+ }++ public mutating func finish() throws {+ guard !failed else { throw Failure.poisoned }+ failed = true+ guard buffered.isEmpty else { buffered.removeAll(); throw Failure.truncated }+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseIPCSocket.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseIPCSocket.swiftnew file mode 100644index 0000000..a39c918--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseIPCSocket.swift@@ -0,0 +1,171 @@+import Darwin+import Foundation+import LockedUseNative++public enum LockedUseIPCEndpoint: String, Sendable {+ case agent, guardian, plugin, observer, admin+ public var path: String {+ "/Library/Application Support/OpenComputerUse/LockedUse/run/\(rawValue).sock"+ }+}++/// Owns one connection. Each synchronous request is serialized and bounded by+/// socket deadlines. A protocol failure permanently closes the connection.+/// GUI adapters must call this outside their AppKit/input event callback.+public final class LockedUseIPCClient: @unchecked Sendable {+ private let mutex = NSLock()+ private var descriptor: Int32+ private var decoder = LockedUseIPCFrame()+ private let brokerRequirement: String+ public let broker: LockedUsePeerIdentity++ public init(endpoint: LockedUseIPCEndpoint, brokerRequirement: String, clientSocket: Int32? = nil) throws {+ let fd = try LockedUseIPCSocket.connect(path: endpoint.path)+ do {+ let peer = try LockedUsePeerIdentity.verified(socket: fd, requirement: brokerRequirement)+ guard peer.userID == 0, peer.hardenedRuntime, !peer.permitsCodeInjection else {+ throw LockedUseClientApprovals.Failure.unapproved+ }+ if endpoint == .agent {+ guard let clientSocket else { throw LockedUseClientApprovals.Failure.unapproved }+ try LockedUseIPCSocket.wait(descriptor: fd, events: Int16(POLLOUT), deadline: ProcessInfo.processInfo.systemUptime + 2)+ guard ocu_send_peer_socket(fd, clientSocket) == 0 else {+ throw POSIXError(.init(rawValue: errno) ?? .EIO)+ }+ }+ broker = peer+ self.brokerRequirement = brokerRequirement+ descriptor = fd+ } catch { Darwin.close(fd); throw error }+ }++ public func request(_ message: LockedUseIPCMessage) throws -> LockedUseIPCReply {+ mutex.lock(); defer { mutex.unlock() }+ guard descriptor >= 0 else { throw LockedUseIPCFrame.Failure.poisoned }+ do {+ let current = try LockedUsePeerIdentity.verified(socket: descriptor, requirement: brokerRequirement)+ guard current.auditToken == broker.auditToken,+ current.codeDirectoryHash == broker.codeDirectoryHash,+ current.userID == 0, current.hardenedRuntime, !current.permitsCodeInjection else {+ throw LockedUseClientApprovals.Failure.unapproved+ }+ _ = try message.validated()+ let deadline = ProcessInfo.processInfo.systemUptime + 2+ try LockedUseIPCSocket.writeAll(try LockedUseIPCFrame.encode(message), descriptor: descriptor, deadline: deadline)+ var bytes = [UInt8](repeating: 0, count: 4096)+ while true {+ try LockedUseIPCSocket.wait(descriptor: descriptor, events: Int16(POLLIN), deadline: deadline)+ let count = Darwin.read(descriptor, &bytes, bytes.count)+ if count < 0, [EINTR, EAGAIN, EWOULDBLOCK].contains(errno) { continue }+ guard count > 0 else {+ if count == 0 { try decoder.finish() }+ throw POSIXError(.init(rawValue: count == 0 ? ECONNRESET : errno) ?? .EIO)+ }+ let frames = try decoder.append(Data(bytes.prefix(count)))+ guard frames.count <= 1 else { throw LockedUseIPCFrame.Failure.malformed }+ if let frame = frames.first {+ 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 }+ return reply+ }+ }+ } catch {+ shutdown(descriptor, SHUT_RDWR)+ Darwin.close(descriptor); descriptor = -1+ throw error+ }+ }++ public func close() {+ mutex.lock(); defer { mutex.unlock() }+ if descriptor >= 0 {+ shutdown(descriptor, SHUT_RDWR)+ Darwin.close(descriptor); descriptor = -1+ }+ }+ deinit { if descriptor >= 0 { Darwin.close(descriptor) } }+}++public enum LockedUseIPCSocket {+ public static func address(path: String) throws -> sockaddr_un {+ var address = sockaddr_un()+ address.sun_family = sa_family_t(AF_UNIX)+ let bytes = Array(path.utf8)+ let capacity = MemoryLayout.size(ofValue: address.sun_path)+ guard !bytes.isEmpty, !bytes.contains(0), bytes.count < capacity else {+ throw LockedUseIPCFrame.Failure.malformed+ }+ withUnsafeMutableBytes(of: &address.sun_path) { buffer in+ for (index, byte) in bytes.enumerated() { buffer[index] = byte }+ }+ address.sun_len = UInt8(MemoryLayout<sockaddr_un>.size)+ return address+ }++ static func connect(path: String) throws -> Int32 {+ let fd = socket(AF_UNIX, SOCK_STREAM, 0)+ guard fd >= 0 else { throw POSIXError(.init(rawValue: errno) ?? .EIO) }+ do {+ try configure(fd)+ guard fcntl(fd, F_SETFL, O_NONBLOCK) == 0 else { throw POSIXError(.init(rawValue: errno) ?? .EIO) }+ var address = try address(path: path)+ let result = withUnsafePointer(to: &address) { pointer in+ pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) {+ Darwin.connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size))+ }+ }+ if result != 0 {+ guard errno == EINPROGRESS else { throw POSIXError(.init(rawValue: errno) ?? .EIO) }+ try wait(descriptor: fd, events: Int16(POLLOUT), deadline: ProcessInfo.processInfo.systemUptime + 2)+ var failure: Int32 = 0+ var size = socklen_t(MemoryLayout.size(ofValue: failure))+ guard getsockopt(fd, SOL_SOCKET, SO_ERROR, &failure, &size) == 0, failure == 0 else {+ throw POSIXError(.init(rawValue: failure == 0 ? errno : failure) ?? .EIO)+ }+ }+ return fd+ } catch { Darwin.close(fd); throw error }+ }++ public static func configure(_ descriptor: Int32) throws {+ guard fcntl(descriptor, F_SETFD, FD_CLOEXEC) == 0 else { throw POSIXError(.init(rawValue: errno) ?? .EIO) }+ var value: Int32 = 1+ guard setsockopt(descriptor, SOL_SOCKET, SO_NOSIGPIPE, &value, socklen_t(MemoryLayout.size(ofValue: value))) == 0 else {+ throw POSIXError(.init(rawValue: errno) ?? .EIO)+ }+ var timeout = timeval(tv_sec: 2, tv_usec: 0)+ for option in [SO_RCVTIMEO, SO_SNDTIMEO] {+ guard setsockopt(descriptor, SOL_SOCKET, option, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout))) == 0 else {+ throw POSIXError(.init(rawValue: errno) ?? .EIO)+ }+ }+ }++ public static func wait(descriptor: Int32, events: Int16, deadline: TimeInterval) throws {+ while true {+ let remaining = deadline - ProcessInfo.processInfo.systemUptime+ guard remaining > 0, remaining <= 60 else { throw POSIXError(.ETIMEDOUT) }+ var entry = pollfd(fd: descriptor, events: events, revents: 0)+ let result = Darwin.poll(&entry, 1, Int32(ceil(remaining * 1000)))+ if result < 0, errno == EINTR { continue }+ guard result > 0 else { throw POSIXError(result == 0 ? .ETIMEDOUT : .init(rawValue: errno) ?? .EIO) }+ guard entry.revents & Int16(POLLNVAL) == 0 else { throw POSIXError(.EBADF) }+ return+ }+ }++ public static func writeAll(_ data: Data, descriptor: Int32, deadline: TimeInterval = ProcessInfo.processInfo.systemUptime + 2) throws {+ try data.withUnsafeBytes { buffer in+ guard let base = buffer.baseAddress else { return }+ var offset = 0+ while offset < buffer.count {+ try wait(descriptor: descriptor, events: Int16(POLLOUT), deadline: deadline)+ let count = Darwin.write(descriptor, base.advanced(by: offset), buffer.count - offset)+ if count < 0, [EINTR, EAGAIN, EWOULDBLOCK].contains(errno) { continue }+ guard count > 0 else { throw POSIXError(.init(rawValue: errno) ?? .EIO) }+ offset += count+ }+ }+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseKeychainProbe.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseKeychainProbe.swiftnew file mode 100644index 0000000..36f0d7d--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseKeychainProbe.swift@@ -0,0 +1,65 @@+import Foundation+import Security+import LocalAuthentication++/// Isolated validation items only. Never enumerate, inspect, export or modify+/// an existing application's Keychain records. Never allow authentication UI.+public final class LockedUseKeychainProbe {+ public enum Failure: Error { case operation(OSStatus), verification }+ private let account = UUID().uuidString+ private let service = "dev.opencomputeruse.locked-use.validation"+ private var secret = Data()+ private var created: [Bool] = []+ public let includesDataProtection: Bool++ public init(includeDataProtection: Bool = true) throws {+ includesDataProtection = includeDataProtection+ var bytes = [UInt8](repeating: 0, count: 32)+ guard SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) == errSecSuccess else { throw Failure.verification }+ secret = Data(bytes)+ do {+ for protection in (includeDataProtection ? [false, true] : [false]) {+ var attributes = query(dataProtection: protection)+ attributes[kSecValueData as String] = secret+ if protection { attributes[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly }+ let status = SecItemAdd(attributes as CFDictionary, nil)+ guard status == errSecSuccess else { throw Failure.operation(status) }+ created.append(protection)+ }+ try verify()+ } catch { cleanup(); throw error }+ }++ public func verify() throws {+ guard created.count == (includesDataProtection ? 2 : 1) else { throw Failure.verification }+ for protection in created {+ var attributes = query(dataProtection: protection)+ attributes[kSecReturnData as String] = true+ attributes[kSecMatchLimit as String] = kSecMatchLimitOne+ var value: CFTypeRef?+ let status = SecItemCopyMatching(attributes as CFDictionary, &value)+ guard status == errSecSuccess else { throw Failure.operation(status) }+ guard let data = value as? Data, data.count == secret.count,+ zip(data, secret).reduce(UInt8(0), { $0 | ($1.0 ^ $1.1) }) == 0 else { throw Failure.verification }+ }+ }++ /// Cleanup can fail while the OS denies locked Keychain operations. The+ /// caller retains this object and retries after a normal manual unlock.+ @discardableResult public func cleanup() -> Bool {+ created = created.filter {+ let result = SecItemDelete(query(dataProtection: $0) as CFDictionary)+ return result != errSecSuccess && result != errSecItemNotFound+ }+ if created.isEmpty { secret.resetBytes(in: 0..<secret.count); return true }+ return false+ }+ private func query(dataProtection: Bool) -> [String: Any] {+ let context = LAContext()+ context.interactionNotAllowed = true+ return [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service,+ kSecAttrAccount as String: account, kSecUseDataProtectionKeychain as String: dataProtection,+ kSecUseAuthenticationContext as String: context]+ }+ deinit { cleanup() }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUsePeerIdentity.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUsePeerIdentity.swiftnew file mode 100644index 0000000..313a6cd--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUsePeerIdentity.swift@@ -0,0 +1,71 @@+import Darwin+import Foundation+import LockedUseNative+import Security++/// Identity extracted from the connected socket, validated against a designated+/// signing requirement. Same UID, a PID, or a claimed bundle ID is insufficient.+public struct LockedUsePeerIdentity: Sendable {+ public let auditToken: Data+ public let userID: UInt32+ public let auditUserID: UInt32+ public let auditSessionID: UInt32+ public let processID: Int32+ public let signingIdentifier: String+ public let teamIdentifier: String?+ public let codeDirectoryHash: Data+ public let designatedRequirement: String+ public let hardenedRuntime: Bool+ public let permitsCodeInjection: Bool++ public enum Failure: Error { case peerUnavailable(Int32), signingUnavailable(OSStatus), invalidSignature(OSStatus), malformedIdentity }++ /// 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 {+ 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) }+ var guest: SecCode?+ let attributes = [kSecGuestAttributeAudit as String: token] as CFDictionary+ let guestStatus = SecCodeCopyGuestWithAttributes(nil, attributes, [], &guest)+ guard guestStatus == errSecSuccess, let guest else { throw Failure.signingUnavailable(guestStatus) }+ var expected: SecRequirement?+ let requirementStatus = SecRequirementCreateWithString(requirement as CFString, [], &expected)+ guard requirementStatus == errSecSuccess, let expected else { throw Failure.signingUnavailable(requirementStatus) }+ let validity = SecCodeCheckValidity(guest, [], expected)+ guard validity == errSecSuccess else { throw Failure.invalidSignature(validity) }+ var staticCode: SecStaticCode?+ let staticStatus = SecCodeCopyStaticCode(guest, [], &staticCode)+ guard staticStatus == errSecSuccess, let staticCode else { throw Failure.signingUnavailable(staticStatus) }+ var info: CFDictionary?+ let infoStatus = SecCodeCopySigningInformation(staticCode, SecCSFlags(rawValue: kSecCSSigningInformation | kSecCSRequirementInformation), &info)+ guard infoStatus == errSecSuccess, let info = info as? [String: Any],+ let identifier = info[kSecCodeInfoIdentifier as String] as? String,+ let hash = info[kSecCodeInfoUnique as String] as? Data,+ let designated = info[kSecCodeInfoDesignatedRequirement as String],+ CFGetTypeID(designated as CFTypeRef) == SecRequirementGetTypeID() else {+ throw Failure.signingUnavailable(infoStatus)+ }+ // Values above originate from Security.framework, never client metadata.+ let designatedRef = designated as! SecRequirement+ var requirementText: CFString?+ let textStatus = SecRequirementCopyString(designatedRef, [], &requirementText)+ guard textStatus == errSecSuccess, let text = requirementText as String?,+ native.process_id > 0 else { throw Failure.malformedIdentity }+ let flags = (info[kSecCodeInfoFlags as String] as? NSNumber)?.uint32Value ?? 0+ let entitlements = info[kSecCodeInfoEntitlementsDict as String] as? [String: Any] ?? [:]+ let dangerous = ["com.apple.security.get-task-allow", "get-task-allow",+ "com.apple.security.cs.disable-library-validation", "com.apple.security.cs.allow-dyld-environment-variables",+ "com.apple.security.cs.allow-unsigned-executable-memory"]+ let injection = dangerous.contains { (entitlements[$0] as? NSNumber)?.boolValue == true }+ // Verify the live code once more after extracting on-disk metadata.+ let rechecked = SecCodeCheckValidity(guest, [], expected)+ guard rechecked == errSecSuccess else { throw Failure.invalidSignature(rechecked) }+ return .init(auditToken: token, userID: native.effective_user_id, auditUserID: native.audit_user_id, auditSessionID: native.audit_session_id,+ processID: native.process_id, signingIdentifier: identifier,+ teamIdentifier: info[kSecCodeInfoTeamIdentifier as String] as? String,+ codeDirectoryHash: hash, designatedRequirement: text,+ hardenedRuntime: flags & SecCodeSignatureFlags.runtime.rawValue != 0, permitsCodeInjection: injection)+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUsePermitRegistry.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUsePermitRegistry.swiftnew file mode 100644index 0000000..4b07d38--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUsePermitRegistry.swift@@ -0,0 +1,88 @@+import Foundation+import Security++/// Broker-side one-shot capability registry. The plugin supplies the kernel+/// verified session; clients cannot choose a UID/session in an IPC body.+/// This registry is deliberately independent of authorization return values.+public struct LockedUsePermitRegistry: Sendable {+ public struct Session: Equatable, Codable, Sendable {+ public let userID: UInt32+ public let auditSessionID: UInt32+ public init(userID: UInt32, auditSessionID: UInt32) {+ self.userID = userID; self.auditSessionID = auditSessionID+ }+ }+ public struct Permit: Equatable, Sendable {+ public let nonce: Data+ public let attemptID: UUID+ public let connectionID: UUID+ public let session: Session+ public let deadline: TimeInterval+ }+ public enum Failure: Error { case invalidClock, invalidPermit, unavailable, duplicateAttempt }+ private var permits: [UUID: Permit] = [:]+ private var retired: Set<UUID> = []+ private var lastNow: TimeInterval = 0+ public init() {}++ public mutating func issue(attemptID: UUID, connectionID: UUID, session: Session,+ guardsHealthy: Bool, now: TimeInterval) throws -> Permit {+ var bytes = [UInt8](repeating: 0, count: 32)+ guard SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) == errSecSuccess else { throw Failure.unavailable }+ return try issue(attemptID: attemptID, connectionID: connectionID, session: session,+ guardsHealthy: guardsHealthy, now: now, nonce: Data(bytes))+ }++ mutating func issue(attemptID: UUID, connectionID: UUID, session: Session,+ guardsHealthy: Bool, now: TimeInterval, nonce: Data) throws -> Permit {+ try clock(now)+ guard guardsHealthy, session.userID > 0, session.auditSessionID > 0,+ nonce.count == 32, permits.count < 32, retired.count < 4096 else { throw Failure.unavailable }+ guard permits[attemptID] == nil, !retired.contains(attemptID),+ !permits.values.contains(where: { $0.session == session }) else { throw Failure.duplicateAttempt }+ let permit = Permit(nonce: nonce, attemptID: attemptID, connectionID: connectionID,+ session: session, deadline: now + LockedUseStateMachine.permitLifetime)+ permits[attemptID] = permit+ return permit+ }++ /// Authentication of the plugin's Apple SecurityAgent 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 {+ try clock(now)+ guard let permit = permits[attemptID] else { throw Failure.invalidPermit }+ if now >= permit.deadline || !guardsHealthy {+ retire(attemptID)+ throw Failure.invalidPermit+ }+ guard permit.session == session, constantTimeEqual(nonce, permit.nonce) else { throw Failure.invalidPermit }+ retire(attemptID)+ return permit+ }++ public mutating func revoke(connectionID: UUID) {+ for permit in Array(permits.values) where permit.connectionID == connectionID { retire(permit.attemptID) }+ }+ public mutating func revoke(attemptID: UUID) {+ if permits[attemptID] != nil { retire(attemptID) }+ }+ public mutating func expire(now: TimeInterval) throws {+ try clock(now)+ for permit in Array(permits.values) where now >= permit.deadline { retire(permit.attemptID) }+ }+ public var pendingCount: Int { permits.count }++ private mutating func retire(_ id: UUID) {+ permits.removeValue(forKey: id)+ retired.insert(id)+ }+ private mutating func clock(_ now: TimeInterval) throws {+ guard now.isFinite, now >= lastNow else { throw Failure.invalidClock }+ lastNow = now+ }+ private func constantTimeEqual(_ lhs: Data, _ rhs: Data) -> Bool {+ guard lhs.count == 32, rhs.count == 32 else { return false }+ return zip(lhs, rhs).reduce(UInt8(0)) { $0 | ($1.0 ^ $1.1) } == 0+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUsePolicyMonitor.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUsePolicyMonitor.swiftnew file mode 100644index 0000000..eba326d--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUsePolicyMonitor.swift@@ -0,0 +1,47 @@+import Dispatch+import Foundation++/// AuthorizationRightGet talks to authd. Never run it on the queue that must+/// answer a mechanism currently waiting for this Broker or drain a GUI lease.+/// A slow check makes permits unavailable, without blocking recovery messages.+public final class LockedUsePolicyMonitor: @unchecked Sendable {+ public enum Status: Equatable, Sendable { case pending, valid, invalid, stale }+ private let mutex = NSLock()+ private let queue = DispatchQueue(label: "ocu.locked-use.policy-observation")+ private let observe: @Sendable () throws -> Bool+ private var started: TimeInterval?+ private var checked: TimeInterval?+ private var result = false+ private var running = false+ private var invalidated = false+ public static let maximumAge: TimeInterval = 2++ public init(observe: @escaping @Sendable () throws -> Bool) { self.observe = observe }++ public func refresh(now: TimeInterval = ProcessInfo.processInfo.systemUptime) {+ mutex.lock()+ guard !running else { mutex.unlock(); return }+ running = true+ if started == nil { started = now }+ mutex.unlock()+ queue.async { [self] in+ let observationStarted = ProcessInfo.processInfo.systemUptime+ let value = (try? observe()) == true+ mutex.lock()+ invalidated = invalidated || !value+ result = value; checked = observationStarted; running = false+ mutex.unlock()+ }+ }++ public func status(now: TimeInterval = ProcessInfo.processInfo.systemUptime) -> Status {+ mutex.lock(); defer { mutex.unlock() }+ if invalidated { return .invalid }+ if let checked {+ guard now.isFinite, now >= checked, now - checked < Self.maximumAge else { return .stale }+ return result ? .valid : .invalid+ }+ guard let started, now.isFinite, now >= started, now - started < Self.maximumAge else { return .stale }+ return .pending+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUsePrivateRecord.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUsePrivateRecord.swiftnew file mode 100644index 0000000..9532fe7--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUsePrivateRecord.swift@@ -0,0 +1,43 @@+import Darwin+import Foundation+import LockedUseNative++/// Private from creation through atomic publication, independent of launchd's+/// umask. Never publish a readable capability-bearing journal then chmod it.+public enum LockedUsePrivateRecord {+ public static func writeInstalled(_ data: Data, name: String) throws {+ guard geteuid() == 0, ["lease-recovery.json", "validation-report.json"].contains(name) else {+ throw LockedUseClientApprovals.Failure.insecureFile+ }+ try write(data, directory: URL(fileURLWithPath: "/Library/Application Support/OpenComputerUse/LockedUse"), name: name, owner: 0)+ }++ static func write(_ data: Data, directory: URL, name: String, owner: UInt32) throws {+ guard !data.isEmpty, data.count <= 128 * 1024, !name.contains("/"), name != ".", name != ".." else {+ throw LockedUseClientApprovals.Failure.insecureFile+ }+ let parent = open(directory.path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ guard parent >= 0 else { throw LockedUseClientApprovals.Failure.inaccessible(errno) }+ defer { Darwin.close(parent) }+ var info = stat()+ guard fstat(parent, &info) == 0, info.st_uid == owner, info.st_mode & 0o022 == 0,+ ocu_has_mutating_acl(parent) == 0 else { throw LockedUseClientApprovals.Failure.insecureFile }+ let temporary = ".private-" + UUID().uuidString+ let fd = openat(parent, temporary, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600)+ guard fd >= 0 else { throw LockedUseClientApprovals.Failure.inaccessible(errno) }+ defer { Darwin.close(fd); _ = unlinkat(parent, temporary, 0) }+ guard ocu_remove_extended_acl(fd) == 0, fchmod(fd, 0o600) == 0 else { throw LockedUseClientApprovals.Failure.insecureFile }+ try data.withUnsafeBytes { buffer in+ var offset = 0+ while offset < data.count {+ let count = Darwin.write(fd, buffer.baseAddress!.advanced(by: offset), data.count - offset)+ if count < 0, errno == EINTR { continue }+ guard count > 0 else { throw LockedUseClientApprovals.Failure.inaccessible(errno) }+ offset += count+ }+ }+ guard fsync(fd) == 0, renameat(parent, temporary, parent, name) == 0, fsync(parent) == 0 else {+ throw LockedUseClientApprovals.Failure.inaccessible(errno)+ }+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseRecoveryDeadline.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseRecoveryDeadline.swiftnew file mode 100644index 0000000..c08df3a--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseRecoveryDeadline.swift@@ -0,0 +1,47 @@+import Dispatch+import Foundation++/// Independent of the RPC queue and its socket/signature deadlines. Repeated+/// failures can shorten this deadline, never postpone it. The owner decides+/// how to stop its own process; this helper never kills another process.+public final class LockedUseRecoveryDeadline: @unchecked Sendable {+ private let lock = NSLock()+ private let queue = DispatchQueue(label: "ocu.locked-use.recovery-deadline")+ private var timer: DispatchSourceTimer?+ private var deadline: UInt64?+ private var generation: UInt64 = 0+ private let expired: @Sendable () -> Void++ public init(expired: @escaping @Sendable () -> Void) { self.expired = expired }++ public func arm(after seconds: TimeInterval) {+ precondition(seconds.isFinite && seconds > 0)+ let next = DispatchTime.now() + seconds+ lock.lock(); defer { lock.unlock() }+ if let deadline, deadline <= next.uptimeNanoseconds { return }+ timer?.cancel()+ generation &+= 1+ let expected = generation+ deadline = next.uptimeNanoseconds+ let source = DispatchSource.makeTimerSource(queue: queue)+ source.schedule(deadline: next, leeway: .milliseconds(10))+ source.setEventHandler { [weak self] in+ guard let self else { return }+ self.lock.lock()+ guard self.generation == expected, self.deadline != nil else { self.lock.unlock(); return }+ self.timer?.cancel(); self.timer = nil; self.deadline = nil+ self.lock.unlock()+ self.expired()+ }+ timer = source+ source.resume()+ }++ public func cancel() {+ lock.lock(); defer { lock.unlock() }+ generation &+= 1+ timer?.cancel(); timer = nil; deadline = nil+ }++ deinit { timer?.cancel() }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseRecoveryRecord.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseRecoveryRecord.swiftnew file mode 100644index 0000000..61e46ae--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseRecoveryRecord.swift@@ -0,0 +1,61 @@+import Foundation+import Darwin++/// A durable revocation fence, never a reusable authorization permit. Recovery+/// can only drain/relock the old epoch and then require a normal manual unlock.+public struct LockedUseRecoveryRecord: Codable, Sendable {+ public let schemaVersion: Int+ public let bootSessionID: String+ public let leaseID: UUID+ public let owner: LockedUseBrokerCoordinator.Context+ public let originalClientToken: Data+ public let guardian: LockedUseBrokerCoordinator.Context?+ public let watchdog: LockedUseBrokerCoordinator.Context?+ public let watchdogChallenge: Data?+ public let everGranted: Bool+ public let observedUnlocked: Bool+ public let agentDrained: Bool+ public let fullyReleased: Bool++ public init(leaseID: UUID, owner: LockedUseBrokerCoordinator.Context, originalClientToken: Data,+ guardian: LockedUseBrokerCoordinator.Context?, watchdog: LockedUseBrokerCoordinator.Context?,+ watchdogChallenge: Data?, everGranted: Bool, observedUnlocked: Bool,+ agentDrained: Bool, fullyReleased: Bool, bootSessionID: String = UUID().uuidString) {+ schemaVersion = 1; self.bootSessionID = bootSessionID; self.leaseID = leaseID; self.owner = owner; self.originalClientToken = originalClientToken+ self.guardian = guardian; self.watchdog = watchdog; self.watchdogChallenge = watchdogChallenge+ self.everGranted = everGranted; self.observedUnlocked = observedUnlocked+ self.agentDrained = agentDrained; self.fullyReleased = fullyReleased+ }++ public func validated() throws -> Self {+ func valid(_ context: LockedUseBrokerCoordinator.Context) -> Bool {+ context.userID > 0 && context.auditSessionID > 0 && context.processID > 0+ && context.auditToken.count == 32 && !context.codeHash.isEmpty && context.codeHash.count <= 64+ }+ guard schemaVersion == 1, UUID(uuidString: bootSessionID) != nil, valid(owner), owner.role == .agent,+ originalClientToken.count == 32,+ guardian.map({ valid($0) && $0.role == .guardian && $0.userID == owner.userID && $0.auditSessionID == owner.auditSessionID }) ?? true,+ watchdog.map({ valid($0) && $0.role == .guardian && $0.userID == owner.userID && $0.auditSessionID == owner.auditSessionID }) ?? true,+ watchdogChallenge == nil || watchdogChallenge?.count == 32,+ guardian?.id != owner.id, watchdog?.id != owner.id,+ guardian == nil || watchdog == nil || guardian?.id != watchdog?.id,+ !fullyReleased || guardian == nil && watchdog == nil,+ !fullyReleased || !everGranted || observedUnlocked && agentDrained else { throw LockedUseBrokerCoordinator.Failure.malformed }+ return self+ }++ /// Administrative reconciliation, never validation evidence. The caller+ /// must obtain an authenticated live Broker status and kernel ESRCH for+ /// every recorded guard before stopping the service under its instance lock.+ public func canRetireStoppedGuards(phase: LockedUseStateMachine.Phase, allGuardsExited: Bool) -> Bool {+ phase == .idle && !fullyReleased && (guardian != nil || watchdog != nil)+ && agentDrained && (!everGranted || observedUnlocked) && allGuardsExited+ }++ public static func loadInstalled() throws -> Self? {+ do {+ let data = try LockedUseSecureStore.read(components: ["Library", "Application Support", "OpenComputerUse", "LockedUse", "lease-recovery.json"], privateFile: true)+ return try JSONDecoder().decode(Self.self, from: data).validated()+ } catch LockedUseClientApprovals.Failure.inaccessible(let code) where code == ENOENT { return nil }+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseReleaseBarrier.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseReleaseBarrier.swiftnew file mode 100644index 0000000..f0413c8--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseReleaseBarrier.swift@@ -0,0 +1,22 @@+import Foundation++/// Continuous presentation evidence is independent of the session lock flag.+public struct LockedUseReleaseBarrier: Sendable {+ private var since: TimeInterval?+ private var fingerprint: String?+ private var lastNow: TimeInterval?+ public init() {}+ public mutating func observe(locked: Bool, presentation: String?, now: TimeInterval) -> Bool {+ guard now.isFinite, lastNow.map({ now >= $0 && now - $0 <= 0.5 }) ?? true else {+ since = nil; fingerprint = nil; lastNow = now.isFinite ? now : nil+ return false+ }+ lastNow = now+ guard locked, let presentation, !presentation.isEmpty else {+ since = nil; fingerprint = nil+ return false+ }+ if fingerprint != presentation { fingerprint = presentation; since = now }+ return now - (since ?? now) >= 1+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseReturnAllowance.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseReturnAllowance.swiftnew file mode 100644index 0000000..2151379--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseReturnAllowance.swift@@ -0,0 +1,40 @@+import Foundation++/// A separate inherited capability for exactly one unmodified Return pair.+/// Never grants general keyboard access or exempts events by PID alone.+public struct LockedUseReturnAllowance: Sendable {+ public enum Rejection: String, Sendable { case inactive, timing, capability, source, target, key, sequence }+ public private(set) var rejection: Rejection?+ private let tag: Int64+ private let sender: Int32+ private let session: LockedUseSession+ private let began: TimeInterval+ private var down: (target: Int32, at: TimeInterval)?+ private var revoked = false+ public init(tag: Int64, sender: Int32, session: LockedUseSession, now: TimeInterval) {+ self.tag = tag; self.sender = sender; self.session = session; began = now+ revoked = tag == 0 || sender <= 0 || session.state != .locked || !now.isFinite+ }+ public mutating func revoke() { revoked = true; down = nil }+ public mutating func accept(isDown: Bool, tag candidate: Int64, sender source: Int32,+ target: Int32, keyCode: Int64, repeated: Bool, modified: Bool,+ session observed: LockedUseSession, now: TimeInterval) -> Bool {+ rejection = nil+ guard !revoked else { rejection = .inactive; return false }+ guard observed == session, now.isFinite, now >= began, now < began + 5 else {+ rejection = .timing; revoke(); return false+ }+ guard candidate == tag else { rejection = .capability; return false }+ guard source == sender else { rejection = .source; return false }+ guard target > 0 else { rejection = .target; return false }+ guard keyCode == 36, !repeated, !modified else { rejection = .key; revoke(); return false }+ if isDown {+ guard down == nil else { rejection = .sequence; revoke(); return false }+ down = (target, now); return true+ }+ guard let down, down.target == target, now >= down.at, now - down.at < 0.25 else {+ rejection = .sequence; revoke(); return false+ }+ revoke(); return true+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseSecureStore.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseSecureStore.swiftnew file mode 100644index 0000000..6e5a4ba--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseSecureStore.swift@@ -0,0 +1,50 @@+import Darwin+import Foundation+import LockedUseNative++/// Fixed-location installer data. Production callers always use owner zero;+/// injected owners are internal and only used by filesystem regression tests.+enum LockedUseSecureStore {+ static func read(components: [String], owner: UInt32 = 0, privateFile: Bool = false) throws -> Data {+ guard !components.isEmpty, components.allSatisfy({ !$0.isEmpty && $0 != "." && $0 != ".." && !$0.contains("/") }) else {+ throw LockedUseClientApprovals.Failure.insecureFile+ }+ var directory = open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC)+ guard directory >= 0 else { throw LockedUseClientApprovals.Failure.inaccessible(errno) }+ defer { close(directory) }+ for component in components.dropLast() {+ let next = openat(directory, component, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ guard next >= 0 else { throw LockedUseClientApprovals.Failure.inaccessible(errno) }+ var info = stat()+ guard fstat(next, &info) == 0, info.st_uid == owner, info.st_mode & 0o022 == 0,+ ocu_has_mutating_acl(next) == 0 else {+ close(next); throw LockedUseClientApprovals.Failure.insecureFile+ }+ close(directory)+ directory = next+ }+ let fd = openat(directory, components.last!, O_RDONLY | O_NONBLOCK | O_NOFOLLOW | O_CLOEXEC)+ guard fd >= 0 else { throw LockedUseClientApprovals.Failure.inaccessible(errno) }+ defer { close(fd) }+ var info = stat()+ guard fstat(fd, &info) == 0, info.st_uid == owner, info.st_mode & 0o022 == 0,+ ocu_has_mutating_acl(fd) == 0,+ !privateFile || (info.st_mode & 0o077 == 0 && ocu_has_any_acl(fd) == 0),+ info.st_mode & S_IFMT == S_IFREG, info.st_size >= 0, info.st_size <= 128 * 1024 else {+ throw LockedUseClientApprovals.Failure.insecureFile+ }+ var data = Data()+ var buffer = [UInt8](repeating: 0, count: 4096)+ while true {+ let count = Darwin.read(fd, &buffer, buffer.count)+ if count == 0 { break }+ if count < 0 {+ if errno == EINTR { continue }+ throw LockedUseClientApprovals.Failure.inaccessible(errno)+ }+ data.append(contentsOf: buffer.prefix(count))+ guard data.count <= 128 * 1024 else { throw LockedUseClientApprovals.Failure.insecureFile }+ }+ return data+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseShieldCoverage.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseShieldCoverage.swiftnew file mode 100644index 0000000..5e266f6--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseShieldCoverage.swift@@ -0,0 +1,22 @@+import Foundation++/// Compare only Quartz global bounds from WindowServer and CGDisplayBounds.+/// Larger opaque surfaces are valid; an uncovered edge is never tolerated.+public enum LockedUseShieldCoverage {+ /// Extra opaque area survives the loginwindow zoom transition. Health+ /// still requires actual WindowServer bounds to contain the full display.+ public static func surfaceFrame(for display: CGRect) -> CGRect {+ display.insetBy(dx: -display.width / 4, dy: -display.height / 4)+ }++ public static func covers(_ surface: CGRect, display: CGRect) -> Bool {+ func valid(_ rect: CGRect) -> Bool {+ !rect.isNull && !rect.isInfinite && [rect.origin.x, rect.origin.y, rect.size.width, rect.size.height,+ rect.maxX, rect.maxY].allSatisfy(\.isFinite)+ && rect.size.width > 0 && rect.size.height > 0+ }+ guard valid(surface), valid(display) else { return false }+ return surface.minX <= display.minX && surface.minY <= display.minY+ && surface.maxX >= display.maxX && surface.maxY >= display.maxY+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseShieldStatus.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseShieldStatus.swiftnew file mode 100644index 0000000..f11dd29--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseShieldStatus.swift@@ -0,0 +1,19 @@+import Foundation++/// Display-only state shared by both shields; never authorizes GUI actions.+public struct LockedUseShieldStatus: Sendable {+ public static let message = "Open Computer Use is Using Your Mac\nPress any key or click to unlock"+ private var stopping = false+ private var lastMessage: String?+ public init() {}++ /// The protected presentation remains fixed across authentication and+ /// operation. Exit latches, freezing the last rendered frame during drain.+ public mutating func update(now: TimeInterval, startupDeadline: TimeInterval?,+ unlocked: Bool, stopping: Bool) -> String? {+ self.stopping = self.stopping || stopping+ guard !self.stopping, lastMessage == nil else { return nil }+ lastMessage = Self.message+ return Self.message+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseSigningIdentity.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseSigningIdentity.swiftnew file mode 100644index 0000000..601b388--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseSigningIdentity.swift@@ -0,0 +1,27 @@+import Darwin+import Foundation++public enum LockedUseSigningIdentity {+ /// Read the running signed code through a kernel audit-token socketpair.+ /// Environment variables, claimed bundle identifiers and mutable paths+ /// cannot select the Broker's signing team.+ public static func current() throws -> LockedUsePeerIdentity {+ var descriptors: [Int32] = [-1, -1]+ guard socketpair(AF_UNIX, SOCK_STREAM, 0, &descriptors) == 0 else {+ throw LockedUseClientApprovals.Failure.unapproved+ }+ defer { Darwin.close(descriptors[0]); Darwin.close(descriptors[1]) }+ let peer = try LockedUsePeerIdentity.verified(socket: descriptors[0], requirement: "anchor apple generic")+ guard peer.processID == getpid(), peer.userID == geteuid(), peer.hardenedRuntime,+ !peer.permitsCodeInjection, let team = peer.teamIdentifier,+ team.utf8.count == 10, team.utf8.allSatisfy({ (48...57).contains($0) || (65...90).contains($0) }) else {+ throw LockedUseClientApprovals.Failure.unapproved+ }+ return peer+ }++ public static func brokerRequirement() throws -> String {+ let peer = try current()+ return "identifier \"dev.opencomputeruse.locked-use.broker\" and anchor apple generic and certificate leaf[subject.OU] = \"\(peer.teamIdentifier!)\""+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseStateMachine.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseStateMachine.swiftnew file mode 100644index 0000000..72a4fc7--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseStateMachine.swift@@ -0,0 +1,306 @@+import Foundation++/// Pure policy for the macOS experiment. Effects are commands, never evidence+/// that the operating system has actually unlocked or locked the desktop.+/// A future Broker must serialize events and execute these effects independently+/// of tool execution; callbacks must not wait for an in-flight GUI action.+public struct LockedUseStateMachine: Sendable {+ public enum Phase: String, Codable, Sendable {+ case idle, preparing, authorizing, unlocking, active, relocking, awaitingManualUnlock+ }++ public enum StopReason: String, Codable, Sendable {+ case turnEnded, disconnected, idleTimeout, leaseExpired, physicalInput+ case guardLost, unlockTimeout, sessionChanged, operationFailed+ }++ public enum Effect: Equatable, Sendable {+ case prepareGuards+ case issuePermit(Permit)+ case requestUnlock+ case stopActions+ case revokePermit+ case cancelUnlock+ case requestRelock+ case releaseGuards+ }++ public struct Owner: Equatable, Sendable {+ /// Issued by verified IPC, not taken from request metadata or environment.+ public let connectionID: UUID+ public let userID: UInt32+ public let auditSessionID: UInt32++ public init(connectionID: UUID, userID: UInt32, auditSessionID: UInt32) {+ self.connectionID = connectionID+ self.userID = userID+ self.auditSessionID = auditSessionID+ }+ }++ public struct Permit: Equatable, Sendable {+ public let id: UUID+ public let owner: Owner+ public let deadline: TimeInterval+ }++ public struct Guards: Equatable, Codable, Sendable {+ public let allDisplaysCovered: Bool+ public let inputTapHealthy: Bool+ public let watchdogHealthy: Bool+ public let displayGeneration: UInt64++ public init(allDisplaysCovered: Bool, inputTapHealthy: Bool, watchdogHealthy: Bool, displayGeneration: UInt64) {+ self.allDisplaysCovered = allDisplaysCovered+ self.inputTapHealthy = inputTapHealthy+ self.watchdogHealthy = watchdogHealthy+ self.displayGeneration = displayGeneration+ }++ public var healthy: Bool { allDisplaysCovered && inputTapHealthy && watchdogHealthy }+ }++ public struct Prerequisites: Sendable {+ public let enabled: Bool+ public let backendValidated: Bool+ public let clientAuthorized: Bool++ public init(enabled: Bool, backendValidated: Bool, clientAuthorized: Bool) {+ self.enabled = enabled+ self.backendValidated = backendValidated+ self.clientAuthorized = clientAuthorized+ }+ }++ public enum Failure: String, Error, LocalizedError, Sendable {+ case disabled, backendUnvalidated, clientUnauthorized, invalidSession+ case busy, manualUnlockRequired, invalidTransition, invalidClock, invalidPermit, guardsUnhealthy++ public var errorDescription: String? { "Locked Use: \(rawValue)" }+ }++ public private(set) var phase: Phase = .idle+ public private(set) var owner: Owner?+ public private(set) var permit: Permit?+ public private(set) var stopReason: StopReason?+ private var guards: Guards?+ private var permitConsumed = false+ private var startedAt: TimeInterval = 0+ private var lastActivityAt: TimeInterval = 0+ private var lastHeartbeatAt: TimeInterval = 0+ private var lastEventAt: TimeInterval = 0+ private var requiresManualUnlock = false+ private var quiesced = false++ public static let idleTimeout: TimeInterval = 30+ public static let permitLifetime: TimeInterval = 5+ public static let unlockTimeout: TimeInterval = 8+ public static let validationUnlockTimeout: TimeInterval = 20+ private let startupTimeout: TimeInterval+ public var startupDeadline: TimeInterval? {+ [.preparing, .authorizing, .unlocking].contains(phase) ? startedAt + startupTimeout : nil+ }+ public static let heartbeatTimeout: TimeInterval = 3+ public static let maximumLease: TimeInterval = 300++ public init(validationWait: Bool = false) {+ startupTimeout = validationWait ? Self.validationUnlockTimeout : Self.unlockTimeout+ }++ public mutating func restoreForRelock(owner: Owner, fullyReleased: Bool) {+ reset()+ self.owner = owner+ phase = fullyReleased ? .awaitingManualUnlock : .relocking+ requiresManualUnlock = true+ stopReason = .disconnected+ }++ /// `now` must be monotonic uptime. Wall-clock timestamps cannot extend leases.+ public mutating func begin(owner candidate: Owner, session: LockedUseSession, prerequisites: Prerequisites, now: TimeInterval) throws -> [Effect] {+ try checkClock(now)+ guard phase != .awaitingManualUnlock else { throw Failure.manualUnlockRequired }+ guard phase == .idle else { throw Failure.busy }+ guard prerequisites.enabled else { throw Failure.disabled }+ guard prerequisites.backendValidated else { throw Failure.backendUnvalidated }+ guard prerequisites.clientAuthorized else { throw Failure.clientUnauthorized }+ guard session.state == .locked, matches(session, owner: candidate) else { throw Failure.invalidSession }+ owner = candidate+ phase = .preparing+ startedAt = now+ lastActivityAt = now+ lastHeartbeatAt = now+ stopReason = nil+ requiresManualUnlock = false+ return [.prepareGuards]+ }++ public mutating func guardsPrepared(_ evidence: Guards, now: TimeInterval, deferPermitUntilClaim: Bool = false) throws -> [Effect] {+ try checkClock(now)+ guard phase == .preparing, let owner else { throw Failure.invalidTransition }+ guard now - startedAt < Self.unlockTimeout else { return stop(.unlockTimeout) }+ guard evidence.healthy else { return stop(.guardLost) }+ guards = evidence+ lastHeartbeatAt = now+ phase = .authorizing+ if deferPermitUntilClaim { return [.requestUnlock] }+ let issued = Permit(id: UUID(), owner: owner, deadline: now + Self.permitLifetime)+ permit = issued+ return [.issuePermit(issued), .requestUnlock]+ }++ /// Only an authenticated mechanism claim can convert protected waiting into+ /// a permit. The overall startup deadline is never restarted or extended.+ public mutating func authorizationRequested(now: TimeInterval) throws -> [Effect] {+ try checkClock(now)+ guard phase == .authorizing, permit == nil, !permitConsumed, let owner,+ guards?.healthy == true, now - lastHeartbeatAt < Self.heartbeatTimeout,+ now - startedAt < startupTimeout else { throw Failure.invalidTransition }+ let issued = Permit(id: UUID(), owner: owner, deadline: min(now + Self.permitLifetime, startedAt + startupTimeout))+ permit = issued+ return [.issuePermit(issued)]+ }++ /// Called only by the authenticated Broker when the plugin consumes a permit.+ /// Evaluation of an authorization right alone cannot activate the session.+ public mutating func consumePermit(id: UUID, owner candidate: Owner, now: TimeInterval) throws {+ try checkClock(now)+ guard phase == .authorizing, let permit, !permitConsumed,+ permit.id == id, permit.owner == candidate, now < permit.deadline else {+ throw Failure.invalidPermit+ }+ permitConsumed = true+ phase = .unlocking+ }++ public mutating func observe(session: LockedUseSession, now: TimeInterval) throws -> [Effect] {+ try checkClock(now)+ if phase == .awaitingManualUnlock {+ // The backend may send this event only after observing a normal user+ // unlock with no OCU permit. Merely starting a new tool is insufficient.+ if session.state == .unlocked, let owner, matches(session, owner: owner) {+ reset()+ }+ return []+ }+ guard phase != .idle, let owner else { return [] }+ // Unknown / different sessions never count as relock confirmation.+ guard matches(session, owner: owner), session.state != .unavailable else {+ return phase == .relocking ? [] : stop(.sessionChanged)+ }+ if phase == .relocking, session.state == .locked {+ // A lock observation during a still-pending unlock attempt may be+ // the original lock screen. Keep shielding until the Broker has+ // drained/cancelled that attempt and stopped action dispatch.+ guard quiesced else { return [] }+ let effects: [Effect] = [.releaseGuards]+ if requiresManualUnlock {+ phase = .awaitingManualUnlock+ permit = nil+ guards = nil+ } else {+ reset()+ }+ return effects+ }+ if phase == .unlocking, session.state == .unlocked {+ guard now - startedAt < startupTimeout,+ now - lastHeartbeatAt < Self.heartbeatTimeout,+ guards?.healthy == true, permitConsumed else {+ return stop(.unlockTimeout)+ }+ phase = .active+ lastActivityAt = now+ return [.revokePermit]+ }+ if phase == .active, session.state != .unlocked { return stop(.sessionChanged) }+ if [.preparing, .authorizing].contains(phase), session.state == .unlocked {+ return stop(.sessionChanged)+ }+ return []+ }++ public mutating func heartbeat(_ evidence: Guards, now: TimeInterval) throws -> [Effect] {+ try checkClock(now)+ guard [.preparing, .authorizing, .unlocking, .active].contains(phase) else { return [] }+ guard evidence.healthy else { return stop(.guardLost) }+ if let guards, evidence.displayGeneration != guards.displayGeneration {+ return stop(.guardLost)+ }+ // A late heartbeat cannot resurrect a dead watchdog / expired lease.+ let expired = try tick(now: now)+ guard expired.isEmpty else { return expired }+ lastHeartbeatAt = now+ return []+ }++ /// Check immediately before each action; an old AX snapshot is not a lease.+ public mutating func authorizeAction(owner candidate: Owner, session: LockedUseSession, now: TimeInterval) throws -> [Effect] {+ try checkClock(now)+ guard phase == .active, owner == candidate else { throw Failure.invalidTransition }+ let expired = try tick(now: now)+ guard expired.isEmpty else { return expired }+ guard session.state == .unlocked, matches(session, owner: candidate) else { return stop(.sessionChanged) }+ lastActivityAt = now+ return []+ }++ public mutating func end(owner candidate: Owner, reason: StopReason) throws -> [Effect] {+ guard owner == candidate else { throw Failure.clientUnauthorized }+ return stop(reason)+ }++ /// Called out of band. The triggering event is swallowed before it reaches apps.+ public mutating func localInput() -> [Effect] { stop(.physicalInput) }++ public mutating func tick(now: TimeInterval) throws -> [Effect] {+ try checkClock(now)+ guard [.preparing, .authorizing, .unlocking, .active].contains(phase) else { return [] }+ if phase != .preparing, now - lastHeartbeatAt >= Self.heartbeatTimeout { return stop(.guardLost) }+ if now - startedAt >= Self.maximumLease { return stop(.leaseExpired) }+ if phase == .active, now - lastActivityAt >= Self.idleTimeout { return stop(.idleTimeout) }+ if phase == .preparing, now - startedAt >= Self.unlockTimeout { return stop(.unlockTimeout) }+ if phase != .active, now - startedAt >= startupTimeout { return stop(.unlockTimeout) }+ if phase == .authorizing, let permit, now >= permit.deadline { return stop(.unlockTimeout) }+ return []+ }++ /// Authenticated Broker acknowledgement: permit revocation is committed,+ /// no unlock request can still complete, and action dispatch is drained.+ /// Merely sending cancel / stop effects does not satisfy this barrier.+ public mutating func confirmQuiescence(owner candidate: Owner) throws {+ guard phase == .relocking, owner == candidate else { throw Failure.invalidTransition }+ quiesced = true+ }++ /// If relock failed, retain shielding and retry; never release on a timer.+ public func retryRelock() -> [Effect] { phase == .relocking ? [.requestRelock] : [] }++ private mutating func stop(_ reason: StopReason) -> [Effect] {+ guard [.preparing, .authorizing, .unlocking, .active].contains(phase) else { return [] }+ phase = .relocking+ quiesced = false+ stopReason = reason+ requiresManualUnlock = ![.turnEnded, .disconnected, .idleTimeout, .leaseExpired].contains(reason)+ return [.stopActions, .revokePermit, .cancelUnlock, .requestRelock]+ }++ private func matches(_ session: LockedUseSession, owner: Owner) -> Bool {+ session.userID == owner.userID && session.auditSessionID == owner.auditSessionID+ }++ private mutating func checkClock(_ now: TimeInterval) throws {+ guard now.isFinite, now >= lastEventAt else { throw Failure.invalidClock }+ lastEventAt = now+ }++ private mutating func reset() {+ phase = .idle+ owner = nil+ permit = nil+ guards = nil+ permitConsumed = false+ stopReason = nil+ requiresManualUnlock = false+ quiesced = false+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseUnlockCancellation.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseUnlockCancellation.swiftnew file mode 100644index 0000000..e08a319--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseUnlockCancellation.swift@@ -0,0 +1,20 @@+import Foundation++/// Cancellation fences future native writes even if a readonly signature/AX+/// lookup is stuck. An already dispatched write remains pending until return.+public final class LockedUseUnlockCancellation: @unchecked Sendable {+ private let mutex = NSLock()+ private var cancelled = false+ private var activeProbe = false+ public init() {}+ public func cancel() { mutex.lock(); cancelled = true; mutex.unlock() }+ public func allowsRequest() -> Bool { mutex.lock(); defer { mutex.unlock() }; return !cancelled }+ public var quiesced: Bool { mutex.lock(); defer { mutex.unlock() }; return cancelled && !activeProbe }+ public func performProbe<T>(_ operation: () -> T) -> T? {+ mutex.lock()+ guard !cancelled && !activeProbe else { mutex.unlock(); return nil }+ activeProbe = true; mutex.unlock()+ defer { mutex.lock(); activeProbe = false; mutex.unlock() }+ return operation()+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseUnshieldedDiagnostic.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseUnshieldedDiagnostic.swiftnew file mode 100644index 0000000..db688b0--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseUnshieldedDiagnostic.swift@@ -0,0 +1,73 @@+import Foundation+import Security++/// Explicit validation-only experiment. It has no GUI action authorization,+/// guard readiness claims, production evidence, or restart/resume capability.+public struct LockedUseUnshieldedDiagnostic: Sendable {+ public private(set) var phase: LockedUseStateMachine.Phase = .authorizing+ public let leaseID = UUID()+ public let deadline: TimeInterval+ public let owner: LockedUseBrokerCoordinator.Context+ private let session: LockedUseSession+ private var lastNow: TimeInterval+ private var pluginID: UUID?+ private var nonce: Data?+ private var permitDeadline: TimeInterval = 0+ private var consumed = false+ public private(set) var finished = false++ public init(owner: LockedUseBrokerCoordinator.Context, session: LockedUseSession, now: TimeInterval) throws {+ guard owner.role == .guardian, session.state == .locked,+ session.userID == owner.userID, session.auditSessionID == owner.auditSessionID,+ now.isFinite else { throw LockedUseBrokerCoordinator.Failure.denied }+ self.owner = owner; self.session = session; lastNow = now+ deadline = now + 20+ }+ public mutating func tick(now: TimeInterval) throws {+ guard now.isFinite, now >= lastNow else { throw LockedUseBrokerCoordinator.Failure.staleEvidence }+ lastNow = now+ if now >= deadline || nonce != nil && now >= permitDeadline {+ nonce = nil; phase = .awaitingManualUnlock+ }+ }+ public mutating func cancel() { nonce = nil; phase = .awaitingManualUnlock }+ public mutating func handle(_ message: LockedUseIPCMessage, context: LockedUseBrokerCoordinator.Context, now: TimeInterval) throws -> LockedUseIPCReply {+ try tick(now: now)+ switch message.operation {+ case .status:+ if context.id == owner.id {+ guard let observed = message.session, observed.userID == session.userID,+ observed.auditSessionID == session.auditSessionID else { throw LockedUseBrokerCoordinator.Failure.denied }+ }+ case .pluginClaim:+ guard context.role == .plugin, context.auditSessionID == owner.auditSessionID,+ phase == .authorizing, pluginID == nil else { throw LockedUseBrokerCoordinator.Failure.denied }+ var bytes = [UInt8](repeating: 0, count: 32)+ guard SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) == errSecSuccess else { throw LockedUseBrokerCoordinator.Failure.unavailable }+ nonce = Data(bytes); pluginID = context.id; permitDeadline = min(now + 5, deadline)+ return reply(message, context: context, token: nonce)+ case .pluginConsume:+ guard context.role == .plugin, context.auditSessionID == owner.auditSessionID,+ context.id == pluginID, phase == .authorizing, now < permitDeadline,+ message.leaseID == leaseID, let expected = nonce, let token = message.token,+ token.count == expected.count,+ zip(token, expected).reduce(UInt8(0), { $0 | ($1.0 ^ $1.1) }) == 0 else { throw LockedUseBrokerCoordinator.Failure.denied }+ nonce = nil; consumed = true; phase = .unlocking+ case .pluginFinished:+ guard context.role == .plugin, context.id == pluginID else { throw LockedUseBrokerCoordinator.Failure.denied }+ if message.stopReason != nil { cancel() }+ case .endUnshieldedDiagnostic:+ guard context.id == owner.id, message.leaseID == leaseID,+ let observed = message.session, observed.state == .locked,+ observed.userID == session.userID, observed.auditSessionID == session.auditSessionID else { throw LockedUseBrokerCoordinator.Failure.denied }+ nonce = nil; finished = true; phase = .idle+ default: throw LockedUseBrokerCoordinator.Failure.denied+ }+ return reply(message, context: context)+ }+ public func reply(_ message: LockedUseIPCMessage, context: LockedUseBrokerCoordinator.Context, token: Data? = nil) -> LockedUseIPCReply {+ .init(id: message.id, result: consumed && phase == .unlocking ? .authorized : .waiting, phase: phase,+ leaseID: context.id == owner.id || context.id == pluginID ? leaseID : nil,+ token: token, detail: "unshieldedDiagnostic", startupDeadline: deadline)+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseValidationReport.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseValidationReport.swiftnew file mode 100644index 0000000..4519e29--- /dev/null+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/LockedUseValidationReport.swift@@ -0,0 +1,27 @@+import Foundation++/// Written only by the authenticated root Broker, after the signed native+/// agent has completed its fixed AX/SCK/Keychain fixture validation. Manual+/// physical-screen, input and fault checks still require administrator review.+public struct LockedUseValidationReport: Codable, Sendable {+ public let schemaVersion: Int+ public let leaseID: UUID+ public let evidence: LockedUseComponentValidation.Evidence+ public let ownerToken: Data+ public let guiAndKeychainPassed: Bool+ public var lockedAndReleased: Bool+ public var afterManualUnlockPassed: Bool++ public init(leaseID: UUID, evidence: LockedUseComponentValidation.Evidence, ownerToken: Data) {+ schemaVersion = 1; self.leaseID = leaseID; self.evidence = evidence; self.ownerToken = ownerToken+ guiAndKeychainPassed = true; lockedAndReleased = false; afterManualUnlockPassed = false+ }+ public func canPromote(current: LockedUseComponentValidation.Evidence) -> Bool {+ schemaVersion == 1 && ownerToken.count == 32 && evidence == current+ && guiAndKeychainPassed && lockedAndReleased && afterManualUnlockPassed+ }+ public static func loadInstalled() throws -> Self {+ let bytes = try LockedUseSecureStore.read(components: ["Library", "Application Support", "OpenComputerUse", "LockedUse", "validation-report.json"], privateFile: true)+ return try JSONDecoder().decode(Self.self, from: bytes)+ }+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/OpenComputerUseCLI.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/OpenComputerUseCLI.swiftindex a64bd0e..f8c83db 100644--- a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/OpenComputerUseCLI.swift+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/OpenComputerUseCLI.swift@@ -4,6 +4,8 @@ public enum OpenComputerUseCLICommand: Equatable {case launchOnboardingcase mcpcase doctor(json: Bool = false)+ case lockedUseStatus(json: Bool)+ case lockedUseManagement(action: String, validation: Bool)case listAppscase snapshot(app: String, textLimit: SnapshotTextLimit = .defaults, treeLimits: AccessibilityTreeLimits = .defaults)case call(OpenComputerUseCallInvocation)@@ -32,9 +34,9 @@ public func shouldUseMacOSAppAgentProxy(switch command {case .launchOnboarding:return !runningFromLaunchServicesAppInstance- case .mcp, .doctor, .listApps, .snapshot, .call:+ case .mcp, .doctor, .lockedUseStatus, .listApps, .snapshot, .call:return true- case .turnEnded, .help, .version:+ case .lockedUseManagement, .turnEnded, .help, .version:return false}}@@ -81,6 +83,8 @@ public func parseOpenComputerUseCLI(arguments: [String]) throws -> OpenComputerUreturn .doctor(json: true)}return try parseSimpleCommand(name: "doctor", arguments: Array(arguments.dropFirst()), result: .doctor())+ case "locked-use":+ return try parseLockedUse(arguments: Array(arguments.dropFirst()))case "list-apps":return try parseSimpleCommand(name: "list-apps", arguments: Array(arguments.dropFirst()), result: .listApps)case "call":@@ -111,6 +115,7 @@ public func openComputerUseHelpText(command: String? = nil) -> String {Commands:mcp Start the stdio MCP server.doctor Print permission status and launch onboarding if needed.+ locked-use status Print experimental macOS Locked Use readiness.list-apps Print running or recently used apps.snapshot <app> Print the current accessibility snapshot for an app.call <tool> Call one tool, or run a JSON array of tool calls.@@ -143,6 +148,23 @@ public func openComputerUseHelpText(command: String? = nil) -> String {--json prints a permission snapshot without launching onboarding (macOS only).Read allGranted to determine readiness; missing permissions still exit successfully."""+ case "locked-use":+ return """+ Usage:+ 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 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.+ recover restores an interrupted installation only after safe drainage.+ """case "list-apps":return """Usage:@@ -473,3 +495,17 @@ private func formatOpenComputerUseDelay(_ delay: TimeInterval) -> String {return "\(delay)s"}++private func parseLockedUse(arguments: [String]) throws -> OpenComputerUseCLICommand {+ if arguments == ["--help"] || arguments == ["-h"] || arguments == ["status", "--help"] {+ return .help(command: "locked-use")+ }+ 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)+ }+ throw OpenComputerUseCLIError(message: "Expected locked-use status, enable, disable, recover, certify, or settings", helpCommand: "locked-use")+}diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/SkyClickSimulation.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/SkyClickSimulation.swiftindex 51b52cb..08e41af 100644--- a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/SkyClickSimulation.swift+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/SkyClickSimulation.swift@@ -111,6 +111,7 @@ enum SkyClickDispatcher {clickCount: Int,spi: SkyLightSPI = .shared) throws {+ try requireUsableComputerUseSession()guard spi.capability.isAvailable else {throw ComputerUseError.message("click_method 'sky_click' is unavailable: \(spi.capability.unavailableReason)"@@ -148,6 +149,7 @@ enum SkyClickDispatcher {do {for step in recipe {+ try requireUsableComputerUseSession()let screenPoint = step.pointKind == .target ? target.screenPoint : primerScreenPointlet windowPoint = step.pointKind == .target ? target.windowPoint : primerWindowPointguard let event = CGEvent(diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/SkyKeyboardSimulation.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/SkyKeyboardSimulation.swiftindex 8e940c3..7264c40 100644--- a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/SkyKeyboardSimulation.swift+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/SkyKeyboardSimulation.swift@@ -123,6 +123,7 @@ enum SkyKeyboardDispatcher {try deliver(to: target, spi: spi) {if let equivalent = skyMenuKeyEquivalent(for: parsed),let item = menuItem(matching: equivalent, pid: target.pid) {+ try requireUsableComputerUseSession()let result = AXUIElementPerformAction(item, kAXPressAction as CFString)guard result == .success else {throw ComputerUseError.message(@@ -142,6 +143,7 @@ enum SkyKeyboardDispatcher {spi: SkyLightSPI,_ body: () throws -> Void) throws {+ try requireUsableComputerUseSession()guard spi.capability.isAvailable else {throw ComputerUseError.message("key_method 'sky_key' is unavailable: \(spi.capability.unavailableReason)"diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/SkyLightSPI.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/SkyLightSPI.swiftindex 6786031..7294ecf 100644--- a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/SkyLightSPI.swift+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/SkyLightSPI.swift@@ -268,6 +268,7 @@ final class SkyLightSPI: WindowOcclusionControlling, @unchecked Sendable {}func postToPid(_ event: CGEvent, pid: pid_t) throws {+ try requireUsableComputerUseSession()guard let postToPidFunction else {throw unavailableError()}diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseApprovalTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseApprovalTests.swiftnew file mode 100644index 0000000..00ccd6a--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseApprovalTests.swift@@ -0,0 +1,56 @@+import Darwin+import XCTest+import LockedUseNative+@testable import OpenComputerUseKit++final class LockedUseApprovalTests: XCTestCase {+ func testExtendedACLWriteGrantIsRejectedEvenWithPrivateModeBits() throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent("ocu-approval-test-\(UUID())")+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])+ defer { try? FileManager.default.removeItem(at: directory) }+ let path = directory.appendingPathComponent("approval.json").path+ XCTAssertTrue(FileManager.default.createFile(atPath: path, contents: Data(), attributes: [.posixPermissions: 0o600]))+ let fd = open(path, O_RDONLY | O_NOFOLLOW)+ XCTAssertGreaterThanOrEqual(fd, 0)+ defer { close(fd) }+ XCTAssertEqual(ocu_has_mutating_acl(fd), 0)+ let process = Process()+ process.executableURL = URL(fileURLWithPath: "/bin/chmod")+ process.arguments = ["+a", "everyone allow write", path]+ try process.run()+ process.waitUntilExit()+ XCTAssertEqual(process.terminationStatus, 0)+ XCTAssertEqual(ocu_has_mutating_acl(fd), 1)+ XCTAssertEqual(ocu_has_mutating_acl(-1), -1)+ }+ func testRecordsCannotInjectCodeSigningRequirement() throws {+ for identifier in ["client\" or true", "../client", "client\\n", "client\n", "", "client/agent"] {+ XCTAssertThrowsError(try LockedUseClientApprovals.Approval(userID: 501, role: .client,+ signingIdentifier: identifier, teamIdentifier: "ABCDE12345"))+ }+ XCTAssertThrowsError(try LockedUseClientApprovals.Approval(userID: 0, role: .client,+ signingIdentifier: "dev.ocu.client", teamIdentifier: "ABCDE12345"))+ XCTAssertThrowsError(try LockedUseClientApprovals.Approval(userID: 501, role: .client,+ signingIdentifier: "dev.ocu.client", teamIdentifier: "ADHOC"))+ }++ func testDecodedRecordsAreValidatedAgainAndDuplicatesRejected() throws {+ let record = try LockedUseClientApprovals.Approval(userID: 501, role: .client,+ signingIdentifier: "dev.ocu.client", teamIdentifier: "ABCDE12345")+ XCTAssertThrowsError(try LockedUseClientApprovals(approvals: [record, record]))+ let valid = try LockedUseClientApprovals(approvals: [record])+ var object = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(valid)) as? [String: Any])+ object["schemaVersion"] = 999+ XCTAssertThrowsError(try LockedUseClientApprovals.decodeValidated(JSONSerialization.data(withJSONObject: object)))+ object["schemaVersion"] = 1+ var records = try XCTUnwrap(object["approvals"] as? [[String: Any]])+ records[0]["signingIdentifier"] = "anything\" or true"+ object["approvals"] = records+ XCTAssertThrowsError(try LockedUseClientApprovals.decodeValidated(JSONSerialization.data(withJSONObject: object)))+ }++ func testCallerCannotSupplyAlternativeConfigPathOrUserOwnedInstalledApproval() {+ XCTAssertThrowsError(try LockedUseClientApprovals.readSecureFile(components: ["Library", "..", "clients.json"], owner: 0))+ XCTAssertThrowsError(try LockedUseClientApprovals.readSecureFile(components: ["Library", "Application Support", "clients.json"], owner: geteuid()))+ }+}diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseAuthorizationRulesTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseAuthorizationRulesTests.swiftnew file mode 100644index 0000000..ae2a081--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseAuthorizationRulesTests.swift@@ -0,0 +1,83 @@+import Foundation+@testable import OpenComputerUseKit+import XCTest++final class LockedUseAuthorizationRulesTests: XCTestCase {+ private func data(_ object: [String: Any]) throws -> Data {+ try PropertyListSerialization.data(fromPropertyList: object, format: .xml, options: 0)+ }+ private func object(_ data: Data) throws -> [String: Any] {+ try XCTUnwrap(PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any])+ }++ 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])+ let plan = try LockedUseAuthorizationRules.planInstallation(current: before)+ let installed = try object(plan.installed)+ XCTAssertEqual(installed["rule"] as? [String], [LockedUseAuthorizationRules.remoteRight, "use-login-window-ui"])+ XCTAssertEqual(installed["comment"] as? String, "existing comment")+ XCTAssertEqual(installed["shared"] as? Bool, false)+ XCTAssertTrue(try LockedUseAuthorizationRules.installationStillApplicable(current: before, plan: plan))+ XCTAssertTrue(try LockedUseAuthorizationRules.installationObserved(current: plan.installed, plan: plan))+ let restored = try object(LockedUseAuthorizationRules.planUninstallation(current: plan.installed, plan: plan))+ XCTAssertEqual(restored["rule"] as? [String], ["use-login-window-ui"])+ XCTAssertNil(restored["k-of-n"])+ }++ func testPlatformSSOAndExistingOrderArePreserved() throws {+ let before = try data(["class": "rule", "k-of-n": 1, "rule": ["psso-screensaver", "enterprise-fallback"]])+ let plan = try LockedUseAuthorizationRules.planInstallation(current: before)+ XCTAssertEqual(try object(plan.installed)["rule"] as? [String],+ [LockedUseAuthorizationRules.remoteRight, "psso-screensaver", "enterprise-fallback"])+ }++ func testExternalChangesRefuseRestoreAndInstallation() throws {+ let before = try data(["class": "rule", "rule": ["use-login-window-ui"]])+ let plan = try LockedUseAuthorizationRules.planInstallation(current: before)+ var changed = try object(plan.installed)+ changed["rule"] = [LockedUseAuthorizationRules.remoteRight, "psso-screensaver"]+ XCTAssertThrowsError(try LockedUseAuthorizationRules.planUninstallation(current: data(changed), plan: plan))+ XCTAssertFalse(try LockedUseAuthorizationRules.installationStillApplicable(current: data(changed), plan: plan))+ }++ func testMalformedOrDifferentThresholdNeverWeakensPolicy() throws {+ let inputs: [[String: Any]] = [+ ["class": "user", "rule": ["use-login-window-ui"]],+ ["class": "rule", "rule": ["a", "b"], "k-of-n": 2],+ ["class": "rule", "rule": ["a"], "k-of-n": true],+ ["class": "rule", "rule": []],+ ["class": "rule", "rule": ["a", "a"]],+ ["class": "rule", "rule": [""]],+ ["class": "rule", "rule": ["a"], "k-of-n": "1"],+ ]+ for input in inputs { XCTAssertThrowsError(try LockedUseAuthorizationRules.planInstallation(current: data(input))) }+ XCTAssertThrowsError(try LockedUseAuthorizationRules.planInstallation(current: Data()))+ }++ func testOwnReferenceIsNeverDuplicatedOrSilentlyClaimed() throws {+ let current = try data(["class": "rule", "rule": [LockedUseAuthorizationRules.remoteRight, "use-login-window-ui"]])+ XCTAssertThrowsError(try LockedUseAuthorizationRules.planInstallation(current: current))+ }++ func testTamperedPersistedPlanIsRejected() throws {+ let before = try data(["class": "rule", "rule": ["use-login-window-ui"]])+ let plan = try LockedUseAuthorizationRules.planInstallation(current: before)+ let encoded = try JSONEncoder().encode(plan)+ var json = try XCTUnwrap(JSONSerialization.jsonObject(with: encoded) as? [String: Any])+ json["installed"] = try data(["class": "rule", "rule": ["allow"]]).base64EncodedString()+ let changed = try JSONDecoder().decode(LockedUseAuthorizationRules.Plan.self,+ from: JSONSerialization.data(withJSONObject: json))+ XCTAssertThrowsError(try LockedUseAuthorizationRules.planUninstallation(current: plan.installed, plan: changed))+ }++ func testAuthDatabaseTimestampsDoNotInvalidateSemanticComparison() throws {+ let before = try data(["class": "rule", "rule": ["use-login-window-ui"]])+ let plan = try LockedUseAuthorizationRules.planInstallation(current: before)+ var observed = try object(plan.installed)+ observed["created"] = 10.5+ observed["modified"] = 999.5+ XCTAssertTrue(try LockedUseAuthorizationRules.installationObserved(current: data(observed), plan: plan))+ XCTAssertNoThrow(try LockedUseAuthorizationRules.planUninstallation(current: data(observed), plan: plan))+ }+}diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseBrokerCoordinatorTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseBrokerCoordinatorTests.swiftnew file mode 100644index 0000000..36d269a--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseBrokerCoordinatorTests.swift@@ -0,0 +1,154 @@+import Foundation+@testable import OpenComputerUseKit+import XCTest++final class LockedUseBrokerCoordinatorTests: XCTestCase {+ private let agent = LockedUseBrokerCoordinator.Context(id: UUID(), role: .agent, userID: 501, auditSessionID: 42)+ private let guardian = LockedUseBrokerCoordinator.Context(id: UUID(), role: .guardian, userID: 501, auditSessionID: 42)+ private let plugin = LockedUseBrokerCoordinator.Context(id: UUID(), role: .plugin, userID: 88, auditSessionID: 42)+ private let locked = LockedUseSession(state: .locked, userID: 501, auditSessionID: 42)+ private let unlocked = LockedUseSession(state: .unlocked, userID: 501, auditSessionID: 42)+ private let healthy = LockedUseStateMachine.Guards(allDisplaysCovered: true, inputTapHealthy: true, watchdogHealthy: true, displayGeneration: 1)++ private func prepare(_ broker: inout LockedUseBrokerCoordinator) throws -> UUID {+ let begin = try broker.handle(.init(operation: .begin, session: locked), context: agent, now: 1)+ let lease = try XCTUnwrap(begin.leaseID)+ XCTAssertEqual(begin.effects, ["prepareGuards"])+ _ = try broker.handle(.init(operation: .guardianHello, leaseID: lease, token: begin.token), context: guardian, now: 1.1)+ let ready = try broker.handle(.init(operation: .guardianReport, leaseID: lease, session: locked, guards: healthy), context: guardian, now: 1.2)+ XCTAssertEqual(ready.effects, ["requestUnlock"])+ return lease+ }++ private func grant(_ broker: inout LockedUseBrokerCoordinator, lease: UUID) throws {+ let claim = try broker.handle(.init(operation: .pluginClaim), context: plugin, now: 1.3)+ let consumed = try broker.handle(.init(operation: .pluginConsume, leaseID: lease, token: claim.token), context: plugin, now: 1.4)+ XCTAssertEqual(consumed.result, .authorized)+ XCTAssertEqual(consumed.phase, .unlocking)+ XCTAssertThrowsError(try broker.handle(.init(operation: .pluginConsume, leaseID: lease, token: claim.token), context: plugin, now: 1.4))+ }++ func testPermitConsumptionDoesNotAuthorizeGUIUntilObservedUnlock() throws {+ var broker = LockedUseBrokerCoordinator(enabled: true, backendValidated: true)+ let lease = try prepare(&broker)+ try grant(&broker, lease: lease)+ XCTAssertThrowsError(try broker.handle(.init(operation: .action, leaseID: lease, session: unlocked), context: agent, now: 1.5))+ _ = try broker.handle(.init(operation: .guardianReport, leaseID: lease, session: unlocked, guards: healthy, unlockWorkPending: false), context: guardian, now: 1.6)+ let action = try broker.handle(.init(operation: .action, leaseID: lease, session: unlocked), context: agent, now: 1.7)+ XCTAssertEqual(action.result, .active)+ let foreign = LockedUseBrokerCoordinator.Context(id: UUID(), role: .agent, userID: 501, auditSessionID: 42)+ XCTAssertThrowsError(try broker.handle(.init(operation: .action, leaseID: lease, session: unlocked), context: foreign, now: 1.8))+ let status = try broker.handle(.init(operation: .status), context: foreign, now: 1.9)+ XCTAssertNotEqual(status.result, .active)+ XCTAssertNil(status.leaseID)+ }++ func testConfirmationExperimentRequiresValidationProfileAndGuardianIdentity() 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)+ let status = try broker.handle(.init(operation: .status), context: agent, now: 1.2)+ XCTAssertEqual(status.validationConfirmation, false)+ }+ let old = LockedUseIPCReply(id: UUID(), result: .waiting, phase: .authorizing)+ XCTAssertNil(try JSONDecoder().decode(LockedUseIPCReply.self, from: JSONEncoder().encode(old)).validationConfirmation)+ }++ func testConsumedAllowAndOriginalLockCannotReleaseGuards() throws {+ var broker = LockedUseBrokerCoordinator(enabled: true, backendValidated: true)+ let lease = try prepare(&broker)+ try grant(&broker, lease: lease)+ _ = try broker.handle(.init(operation: .end), context: agent, now: 1.5)+ _ = try broker.handle(.init(operation: .quiesced, leaseID: lease), context: agent, now: 1.6)+ let report = try broker.handle(.init(operation: .guardianReport, leaseID: lease, session: locked, guards: healthy), context: guardian, now: 1.7)+ XCTAssertEqual(report.phase, .relocking)+ XCTAssertFalse(report.effects.contains("releaseGuards"))+ }++ func testLateUnlockIsRelockedBeforeReleaseAfterCancellation() throws {+ var broker = LockedUseBrokerCoordinator(enabled: true, backendValidated: true)+ let lease = try prepare(&broker)+ try grant(&broker, lease: lease)+ _ = try broker.handle(.init(operation: .end), context: agent, now: 1.5)+ _ = try broker.handle(.init(operation: .guardianReport, leaseID: lease, session: unlocked, guards: healthy, unlockWorkPending: false), context: guardian, now: 1.6)+ _ = try broker.handle(.init(operation: .quiesced, leaseID: lease), context: agent, now: 1.7)+ let report = try broker.handle(.init(operation: .guardianReport, leaseID: lease, session: locked, guards: healthy), context: guardian, now: 1.8)+ XCTAssertEqual(report.result, .release)+ XCTAssertTrue(report.effects.contains("releaseGuards"))+ }++ func testRoleSessionChallengeAndStaleEvidenceAreRejected() throws {+ var broker = LockedUseBrokerCoordinator(enabled: true, backendValidated: true)+ let begin = try broker.handle(.init(operation: .begin, session: locked), context: agent, now: 1)+ let lease = try XCTUnwrap(begin.leaseID)+ XCTAssertThrowsError(try broker.handle(.init(operation: .guardianHello, leaseID: lease, token: Data(repeating: 0, count: 32)), context: guardian, now: 1.1))+ XCTAssertThrowsError(try broker.handle(.init(operation: .guardianHello, leaseID: lease, token: begin.token), context: agent, now: 1.1))+ _ = try broker.handle(.init(operation: .guardianHello, leaseID: lease, token: begin.token), context: guardian, now: 1.2)+ _ = try broker.handle(.init(operation: .guardianReport, leaseID: lease, session: locked, guards: healthy), context: guardian, now: 1.3)+ let wrongSession = LockedUseBrokerCoordinator.Context(id: UUID(), role: .plugin, userID: 88, auditSessionID: 43)+ XCTAssertThrowsError(try broker.handle(.init(operation: .pluginClaim), context: wrongSession, now: 1.4))+ XCTAssertThrowsError(try broker.handle(.init(operation: .pluginClaim), context: plugin, now: 2.4))+ }++ func testDisconnectRevokesPendingPermit() throws {+ var broker = LockedUseBrokerCoordinator(enabled: true, backendValidated: true)+ _ = try prepare(&broker)+ try broker.disconnected(agent)+ XCTAssertEqual(broker.phase, .relocking)+ XCTAssertThrowsError(try broker.handle(.init(operation: .pluginClaim), context: plugin, now: 1.4))+ }++ func testNextLeaseWaitsForGuardianReleaseAcknowledgment() 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.handle(.init(operation: .end), context: agent, now: 1.6)+ _ = try broker.handle(.init(operation: .quiesced, leaseID: lease), context: agent, now: 1.7)+ let release = try broker.handle(.init(operation: .guardianReport, leaseID: lease, session: locked, guards: healthy, unlockWorkPending: false), context: guardian, now: 1.8)+ XCTAssertEqual(release.phase, .idle)+ XCTAssertThrowsError(try broker.handle(.init(operation: .begin, session: locked), context: agent, now: 1.9))+ XCTAssertThrowsError(try broker.handle(.init(operation: .guardianReleased, leaseID: lease), context: agent, now: 2))+ _ = try broker.handle(.init(operation: .guardianReleased, leaseID: lease), context: guardian, now: 2.1)+ XCTAssertNoThrow(try broker.handle(.init(operation: .begin, session: locked), context: agent, now: 2.2))+ }++ func testOnlyAdministratorCanFreezeNewLeasesBeforeUninstall() throws {+ var broker = LockedUseBrokerCoordinator(enabled: true, backendValidated: true)+ XCTAssertThrowsError(try broker.handle(.init(operation: .disable), context: agent, now: 1))+ let admin = LockedUseBrokerCoordinator.Context(id: UUID(), role: .observer, userID: 0, auditSessionID: 1)+ let reply = try broker.handle(.init(operation: .disable), context: admin, now: 1.1)+ XCTAssertEqual(reply.result, .ok)+ XCTAssertThrowsError(try broker.handle(.init(operation: .begin, session: locked), context: agent, now: 1.2))+ var active = LockedUseBrokerCoordinator(enabled: true, backendValidated: true)+ _ = try prepare(&active)+ XCTAssertThrowsError(try active.handle(.init(operation: .disable), context: admin, now: 1.3))+ XCTAssertEqual(active.phase, .authorizing)+ }++ func testChangedInstallationRevokesPermitButKeepsDrainageAvailable() throws {+ var broker = LockedUseBrokerCoordinator(enabled: true, backendValidated: true)+ let lease = try prepare(&broker)+ let claim = try broker.handle(.init(operation: .pluginClaim), context: plugin, now: 1.3)+ try broker.invalidateInstallation()+ XCTAssertEqual(broker.phase, .relocking)+ XCTAssertThrowsError(try broker.handle(.init(operation: .pluginConsume, leaseID: lease, token: claim.token), context: plugin, now: 1.4))+ _ = try broker.handle(.init(operation: .guardianReport, leaseID: lease, session: locked, guards: healthy, unlockWorkPending: false), context: guardian, now: 1.5)+ _ = try broker.handle(.init(operation: .quiesced, leaseID: lease), context: agent, now: 1.6)+ _ = try broker.handle(.init(operation: .guardianReport, leaseID: lease, session: locked, guards: healthy, unlockWorkPending: false), context: guardian, now: 1.7)+ _ = try broker.handle(.init(operation: .guardianReleased, leaseID: lease), context: guardian, now: 1.8)+ XCTAssertThrowsError(try broker.handle(.init(operation: .begin, session: locked), context: agent, now: 1.9))+ }++ func testUnvalidatedBackendAndForgedSessionCannotBegin() throws {+ var disabled = LockedUseBrokerCoordinator(enabled: true, backendValidated: false)+ XCTAssertThrowsError(try disabled.handle(.init(operation: .begin, session: locked), context: agent, now: 1))+ var broker = LockedUseBrokerCoordinator(enabled: true, backendValidated: true)+ let wrong = LockedUseSession(state: .locked, userID: 502, auditSessionID: 42)+ XCTAssertThrowsError(try broker.handle(.init(operation: .begin, session: wrong), context: agent, now: 1))+ XCTAssertThrowsError(try broker.handle(.init(operation: .begin, session: locked), context: guardian, now: 1))+ }+}diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseClickAllowanceTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseClickAllowanceTests.swiftnew file mode 100644index 0000000..370547d--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseClickAllowanceTests.swift@@ -0,0 +1,51 @@+import XCTest+@testable import OpenComputerUseKit++final class LockedUseClickAllowanceTests: XCTestCase {+ private func accept(_ gate: inout LockedUseClickAllowance, _ button: LockedUseClickAllowance.Button,+ tag: Int64 = 123, sender: Int32 = 42, target: Int32 = 84, window: Int64 = 9,+ x: Double = 10, now: TimeInterval = 11, locked: Bool = true) -> Bool {+ gate.accept(button: button, tag: tag, sender: sender, target: target, window: window,+ x: x, y: 20, now: now, locked: locked)+ }+ func testOneMatchedPairOnly() {+ var gate = LockedUseClickAllowance(tag: 123, sender: 42, now: 10)+ XCTAssertTrue(accept(&gate, .down))+ XCTAssertTrue(accept(&gate, .up, now: 11.01))+ XCTAssertFalse(accept(&gate, .down, now: 11.02))+ }+ func testPIDAloneAndInvalidGeometryCannotPass() {+ for invalid in [0, 1, 2, 3, 4, 5] {+ var gate = LockedUseClickAllowance(tag: 123, sender: 42, now: 10)+ XCTAssertFalse(accept(&gate, .down, tag: invalid == 0 ? 999 : 123,+ sender: invalid == 1 ? 99 : 42, target: invalid == 2 ? 0 : 84,+ window: invalid == 3 ? 0 : 9, x: invalid == 4 ? .nan : 10,+ locked: invalid != 5))+ }+ }+ func testTakeoverAndExpiryCannotRearm() {+ var gate = LockedUseClickAllowance(tag: 123, sender: 42, now: 10)+ XCTAssertFalse(accept(&gate, .down, now: 9))+ XCTAssertFalse(accept(&gate, .down, now: 15))+ gate.revoke()+ XCTAssertFalse(accept(&gate, .down))+ var expired = LockedUseClickAllowance(tag: 123, sender: 42, now: 10)+ XCTAssertFalse(accept(&expired, .down, now: 15))+ XCTAssertFalse(accept(&expired, .down, now: 11))+ }+ func testMismatchDuplicateAndLateUpRevokePair() {+ for invalid in [0, 1, 2, 3] {+ var gate = LockedUseClickAllowance(tag: 123, sender: 42, now: 10)+ XCTAssertTrue(accept(&gate, .down))+ if invalid == 0 { XCTAssertFalse(accept(&gate, .down)) }+ else {+ XCTAssertFalse(accept(&gate, .up, window: invalid == 1 ? 10 : 9,+ x: invalid == 2 ? 11 : 10, now: invalid == 3 ? 11.25 : 11.01))+ }+ XCTAssertFalse(accept(&gate, .up, now: 11.02))+ }+ var gate = LockedUseClickAllowance(tag: 123, sender: 42, now: 10)+ XCTAssertFalse(accept(&gate, .up))+ XCTAssertFalse(accept(&gate, .down))+ }+}diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseDispatchTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseDispatchTests.swiftnew file mode 100644index 0000000..11a8daf--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseDispatchTests.swift@@ -0,0 +1,40 @@+import CoreGraphics+import XCTest+@testable import OpenComputerUseKit++final class LockedUseDispatchTests: XCTestCase {+ private enum Revoked: Error { case lease }++ func testLeasedCapturePolicyIsClearedOnThrow() {+ XCTAssertFalse(LockedUseActionScope.requiresScreenCaptureKit)+ XCTAssertThrowsError(try LockedUseActionScope.withValidator({}, body: {+ XCTAssertTrue(LockedUseActionScope.requiresScreenCaptureKit)+ throw Revoked.lease+ }))+ XCTAssertFalse(LockedUseActionScope.requiresScreenCaptureKit)+ }++ func testRevokedLeaseStopsInputAndQueryBeforeResolvingTarget() throws {+ guard LockedUseSession.current().state == .unlocked else {+ throw XCTSkip("Requires a completed unlocked console session; no input is emitted")+ }+ // These targets deliberately do not exist. A revoked lease must be+ // reported before capability, process or window checks can run.+ let click = SkyClickTarget(screenPoint: .zero, windowPoint: .zero,+ windowBounds: .zero, windowID: 0, pid: -1)+ let keyboard = SkyKeyboardTarget(windowID: 0, pid: -1)+ let actions: [() throws -> Void] = [+ { try SkyClickDispatcher.click(target: click, clickCount: 1) },+ { try SkyKeyboardDispatcher.typeText(target: keyboard, text: "probe") },+ { try SkyKeyboardDispatcher.pressKey(target: keyboard, key: "cmd+a") },+ { _ = try ComputerUseService().query(app: "NoSuchRevokedLeaseApp", text: "Send") }+ ]+ for action in actions {+ try LockedUseActionScope.withValidator({ throw Revoked.lease }, body: {+ XCTAssertThrowsError(try action()) { error in+ XCTAssertTrue(error is Revoked)+ }+ })+ }+ }+}diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseGuardianTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseGuardianTests.swiftnew file mode 100644index 0000000..89f5da6--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseGuardianTests.swift@@ -0,0 +1,137 @@+import XCTest+@testable import OpenComputerUseKit++final class LockedUseGuardianTests: XCTestCase {+ private let unlocked = LockedUseSession(state: .unlocked, userID: 501, auditSessionID: 10)+ private let locked = LockedUseSession(state: .locked, userID: 501, auditSessionID: 10)++ private func shielding() throws -> LockedUseGuardianPolicy {+ var policy = try LockedUseGuardianPolicy(session: unlocked, now: 100)+ try policy.prepared(topology: "display-1", now: 100)+ return policy+ }++ func testNeverReleaseBeforeQuiescenceAndSameSessionLock() throws {+ var policy = try shielding()+ XCTAssertEqual(policy.stop(.localInput, now: 100), [.requestRelock])+ XCTAssertEqual(try policy.poll(session: locked, topology: "", guardsHealthy: false, now: 100.1), [])+ XCTAssertEqual(policy.phase, .relocking)+ policy.confirmQuiescence()+ XCTAssertEqual(try policy.poll(session: locked, topology: "", guardsHealthy: false, now: 100.2), [])+ let other = LockedUseSession(state: .locked, userID: 502, auditSessionID: 11)+ XCTAssertEqual(try policy.poll(session: other, topology: "", guardsHealthy: false, now: 100.5), [.requestRelock])+ XCTAssertEqual(try policy.poll(session: .init(state: .unavailable, userID: nil, auditSessionID: nil),+ topology: "", guardsHealthy: false, now: 101), [.requestRelock])+ XCTAssertEqual(try policy.poll(session: locked, topology: "", guardsHealthy: false, lockPresentationReady: true, now: 101.1), [.releaseShield])+ XCTAssertEqual(policy.phase, .finished)+ XCTAssertEqual(policy.stop(.localInput, now: 102), [])+ }++ func testExpiredHeartbeatCannotReviveGuardian() throws {+ var policy = try shielding()+ XCTAssertEqual(try policy.heartbeat(now: 101.5), [.requestRelock])+ XCTAssertEqual(policy.reason, .heartbeatExpired)+ XCTAssertEqual(try policy.heartbeat(now: 101.6), [])+ XCTAssertEqual(policy.phase, .relocking)+ }++ func testDelayedChildPreparationStartsHeartbeatOnlyAfterHealthyRegistration() throws {+ var policy = try LockedUseGuardianPolicy(session: locked, now: 100)+ try policy.prepared(topology: "display-1", now: 103)+ XCTAssertEqual(try policy.heartbeat(now: 103.1), [])+ XCTAssertEqual(try policy.poll(session: locked, topology: "display-1", guardsHealthy: true, now: 104), [])+ XCTAssertEqual(try policy.poll(session: locked, topology: "display-1", guardsHealthy: true, now: 104.6), [.requestRelock])+ }++ func testLockedDrainWaitDoesNotRepeatedlyDismissLoginAndStillRelocksAnUnlock() throws {+ var policy = try shielding()+ XCTAssertEqual(policy.stop(.parentDisconnected, now: 100), [.requestRelock])+ for step in 1...20 {+ XCTAssertEqual(try policy.poll(session: locked, topology: "", guardsHealthy: false,+ now: 100 + Double(step)), [])+ }+ XCTAssertEqual(policy.phase, .relocking)+ XCTAssertEqual(try policy.poll(session: unlocked, topology: "", guardsHealthy: false,+ now: 121), [.requestRelock])+ policy.confirmQuiescence()+ XCTAssertEqual(try policy.poll(session: locked, topology: "", guardsHealthy: false, lockPresentationReady: true,+ now: 122), [.releaseShield])+ }++ func testNewInFlightActionInvalidatesPreviousQuiescence() throws {+ var policy = try shielding()+ policy.confirmQuiescence()+ policy.requireQuiescence()+ _ = policy.stop(.localInput, now: 100)+ XCTAssertEqual(try policy.poll(session: locked, topology: "", guardsHealthy: false, now: 100.1), [])+ policy.confirmQuiescence()+ XCTAssertEqual(try policy.poll(session: locked, topology: "", guardsHealthy: false, lockPresentationReady: true, now: 100.2), [.releaseShield])+ }++ func testLeaseExpiresDespiteContinuedHeartbeats() throws {+ var policy = try LockedUseGuardianPolicy(session: unlocked, now: 100, lifetime: 2)+ try policy.prepared(topology: "display-1", now: 100)+ XCTAssertEqual(try policy.heartbeat(now: 101), [])+ XCTAssertEqual(try policy.heartbeat(now: 102), [.requestRelock])+ XCTAssertEqual(policy.reason, .leaseExpired)+ }++ func testDisplayChangeAndGuardFailureStopBeforeMoreWork() throws {+ var policy = try shielding()+ XCTAssertEqual(try policy.poll(session: unlocked, topology: "display-1|display-2", guardsHealthy: true, now: 100.1), [.requestRelock])+ XCTAssertEqual(policy.reason, .displayChanged)+ var broken = try shielding()+ XCTAssertEqual(try broken.poll(session: unlocked, topology: "display-1", guardsHealthy: false, now: 100.1), [.requestRelock])+ XCTAssertEqual(broken.reason, .guardianFailure)+ }++ func testDisconnectRetainsShieldAndRetriesWithoutReleaseDeadline() throws {+ var policy = try shielding()+ policy.confirmQuiescence()+ XCTAssertEqual(policy.stop(.parentDisconnected, now: 100), [.requestRelock])+ XCTAssertEqual(try policy.poll(session: unlocked, topology: "display-1", guardsHealthy: true, now: 100.1), [])+ XCTAssertEqual(try policy.poll(session: unlocked, topology: "display-1", guardsHealthy: true, now: 10000), [.requestRelock])+ XCTAssertEqual(policy.phase, .relocking)+ }++ func testActualLocalRecoveryAfterDrainAndLockNeverRelocksTheUser() throws {+ var policy = try shielding()+ _ = policy.stop(.stopRequested, now: 100)+ policy.requestLocalRecovery()+ // Physical input alone is insufficient, and drain alone isn't a lock.+ XCTAssertEqual(try policy.poll(session: unlocked, topology: "", guardsHealthy: true, now: 100.1), [])+ policy.confirmQuiescence()+ XCTAssertEqual(try policy.poll(session: unlocked, topology: "", guardsHealthy: true, now: 100.2), [])+ XCTAssertFalse(policy.localRecoveryReady)+ XCTAssertEqual(try policy.poll(session: locked, topology: "", guardsHealthy: true, now: 100.3), [])+ XCTAssertTrue(policy.localRecoveryReady)+ XCTAssertEqual(policy.stop(.localInput, now: 101), [])+ XCTAssertEqual(try policy.poll(session: unlocked, topology: "", guardsHealthy: true, now: 101.1), [.releaseShield])+ }+ func testLockAndDrainWithoutHardwareIntentCannotReleaseAnUnlock() throws {+ var policy = try shielding()+ _ = policy.stop(.stopRequested, now: 100)+ policy.confirmQuiescence()+ _ = try policy.poll(session: locked, topology: "", guardsHealthy: true, now: 100.1)+ XCTAssertFalse(policy.localRecoveryReady)+ XCTAssertEqual(try policy.poll(session: unlocked, topology: "", guardsHealthy: true, now: 101), [.requestRelock])+ }+ func testNewWorkInvalidatesTheManualRecoveryFence() throws {+ var policy = try shielding()+ _ = policy.stop(.stopRequested, now: 100)+ policy.confirmQuiescence(); policy.requestLocalRecovery()+ _ = try policy.poll(session: locked, topology: "", guardsHealthy: true, now: 100.1)+ XCTAssertTrue(policy.localRecoveryReady)+ policy.requireQuiescence()+ XCTAssertFalse(policy.localRecoveryReady)+ XCTAssertEqual(try policy.poll(session: unlocked, topology: "", guardsHealthy: true, now: 101), [.requestRelock])+ }++ func testInvalidIdentityAndClockAreRejected() throws {+ XCTAssertThrowsError(try LockedUseGuardianPolicy(session: .init(state: .unavailable, userID: nil, auditSessionID: nil), now: 100))+ XCTAssertThrowsError(try LockedUseGuardianPolicy(session: unlocked, now: 100, lifetime: .infinity))+ var policy = try shielding()+ XCTAssertThrowsError(try policy.heartbeat(now: 99))+ XCTAssertThrowsError(try policy.poll(session: unlocked, topology: "display-1", guardsHealthy: true, now: .nan))+ }+}diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseIPCTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseIPCTests.swiftnew file mode 100644index 0000000..cdeccda--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseIPCTests.swift@@ -0,0 +1,79 @@+import Foundation+import Darwin+import LockedUseNative+@testable import OpenComputerUseKit+import XCTest++final class LockedUseIPCTests: XCTestCase {+ func testTransferredSocketRetainsKernelPeerAndIsCloseOnExec() throws {+ var channel: [Int32] = [-1, -1], peer: [Int32] = [-1, -1]+ XCTAssertEqual(socketpair(AF_UNIX, SOCK_STREAM, 0, &channel), 0)+ XCTAssertEqual(socketpair(AF_UNIX, SOCK_STREAM, 0, &peer), 0)+ defer { for fd in channel + peer { Darwin.close(fd) } }+ XCTAssertEqual(ocu_send_peer_socket(channel[0], peer[0]), 0)+ let copied = ocu_receive_peer_socket(channel[1])+ XCTAssertGreaterThanOrEqual(copied, 0)+ defer { Darwin.close(copied) }+ XCTAssertNotEqual(fcntl(copied, F_GETFD) & FD_CLOEXEC, 0)+ var identity = OCUPeerIdentity()+ XCTAssertEqual(ocu_copy_peer_identity(copied, &identity), 0)+ XCTAssertEqual(identity.effective_user_id, geteuid())+ XCTAssertEqual(identity.process_id, getpid())+ }++ func testMissingDescriptorAndNonSocketDoNotSupplyPeerIdentity() throws {+ var channel: [Int32] = [-1, -1]+ XCTAssertEqual(socketpair(AF_UNIX, SOCK_STREAM, 0, &channel), 0)+ defer { for fd in channel { Darwin.close(fd) } }+ var marker: UInt8 = 0x4f+ XCTAssertEqual(Darwin.write(channel[0], &marker, 1), 1)+ XCTAssertEqual(ocu_receive_peer_socket(channel[1]), -1)+ var pipeFDs: [Int32] = [-1, -1]+ XCTAssertEqual(pipe(&pipeFDs), 0)+ defer { for fd in pipeFDs { Darwin.close(fd) } }+ XCTAssertEqual(ocu_send_peer_socket(channel[0], pipeFDs[0]), 0)+ let copied = ocu_receive_peer_socket(channel[1])+ defer { Darwin.close(copied) }+ var identity = OCUPeerIdentity()+ XCTAssertEqual(ocu_copy_peer_identity(copied, &identity), -1)+ }++ func testExpiredRPCDeadlineFailsWithoutWaiting() throws {+ var channel: [Int32] = [-1, -1]+ XCTAssertEqual(socketpair(AF_UNIX, SOCK_STREAM, 0, &channel), 0)+ defer { for fd in channel { Darwin.close(fd) } }+ XCTAssertThrowsError(try LockedUseIPCSocket.wait(descriptor: channel[0], events: Int16(POLLIN), deadline: ProcessInfo.processInfo.systemUptime - 1))+ }++ func testFragmentedFramesAndCoalescedMessagesRoundTrip() throws {+ let message = LockedUseIPCMessage(operation: .status)+ let encoded = try LockedUseIPCFrame.encode(message)+ var decoder = LockedUseIPCFrame()+ var frames: [Data] = []+ for byte in encoded { frames += try decoder.append(Data([byte])) }+ XCTAssertEqual(frames.count, 1)+ let decoded = try JSONDecoder().decode(LockedUseIPCMessage.self, from: frames[0]).validated()+ XCTAssertEqual(decoded.id, message.id)+ frames = try decoder.append(encoded + encoded)+ XCTAssertEqual(frames.count, 2)+ XCTAssertNoThrow(try decoder.finish())+ }++ func testInvalidLengthsFloodAndTruncatedEOFPoisonStream() throws {+ for input in [Data([0, 0, 0, 0]), Data([0, 1, 0, 0]), Data(repeating: 1, count: 4097)] {+ var decoder = LockedUseIPCFrame()+ XCTAssertThrowsError(try decoder.append(input))+ XCTAssertThrowsError(try decoder.append(Data()))+ }+ var decoder = LockedUseIPCFrame()+ _ = try decoder.append(Data([0, 0, 0, 5, 1]))+ XCTAssertThrowsError(try decoder.finish())+ XCTAssertThrowsError(try decoder.append(Data([2, 3, 4, 5])))+ }++ func testProtocolVersionAndNonceLengthAreNotImplicitlyTrusted() throws {+ XCTAssertThrowsError(try LockedUseIPCMessage(operation: .pluginConsume, token: Data([1])).validated())+ let bad = Data("{\"version\":2,\"id\":\"00000000-0000-0000-0000-000000000001\",\"operation\":\"begin\"}".utf8)+ XCTAssertThrowsError(try JSONDecoder().decode(LockedUseIPCMessage.self, from: bad).validated())+ }+}diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUsePeerTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUsePeerTests.swiftnew file mode 100644index 0000000..0633e77--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUsePeerTests.swift@@ -0,0 +1,34 @@+import Darwin+import LockedUseNative+import Security+import XCTest+@testable import OpenComputerUseKit++final class LockedUsePeerTests: XCTestCase {+ func testKernelTokenIdentifiesConnectionWithoutRequestMetadata() throws {+ var sockets: [Int32] = [-1, -1]+ XCTAssertEqual(socketpair(AF_UNIX, SOCK_STREAM, 0, &sockets), 0)+ defer { close(sockets[0]); close(sockets[1]) }+ var peer = OCUPeerIdentity()+ XCTAssertEqual(ocu_copy_peer_identity(sockets[0], &peer), 0)+ XCTAssertEqual(peer.effective_user_id, geteuid())+ XCTAssertEqual(peer.process_id, getpid())+ var sessionID = SecuritySessionId()+ var attributes = SessionAttributeBits()+ XCTAssertEqual(SessionGetInfo(callerSecuritySession, &sessionID, &attributes), errSecSuccess)+ XCTAssertEqual(peer.audit_session_id, sessionID)+ }++ func testUnconnectedDescriptorCannotInventIdentity() {+ XCTAssertThrowsError(try LockedUsePeerIdentity.verified(socket: -1, requirement: "true")) { error in+ guard case LockedUsePeerIdentity.Failure.peerUnavailable = error else { return XCTFail("Unexpected error \(error)") }+ }+ }++ func testSameUserDoesNotSatisfyWrongCodeSignature() {+ var sockets: [Int32] = [-1, -1]+ XCTAssertEqual(socketpair(AF_UNIX, SOCK_STREAM, 0, &sockets), 0)+ defer { close(sockets[0]); close(sockets[1]) }+ XCTAssertThrowsError(try LockedUsePeerIdentity.verified(socket: sockets[0], requirement: "identifier \"dev.unapproved.client\""))+ }+}diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUsePermitTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUsePermitTests.swiftnew file mode 100644index 0000000..4656a05--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUsePermitTests.swift@@ -0,0 +1,48 @@+import XCTest+@testable import OpenComputerUseKit++final class LockedUsePermitTests: XCTestCase {+ private let session = LockedUsePermitRegistry.Session(userID: 501, auditSessionID: 10)+ private let nonce = Data(repeating: 17, count: 32)++ func testExactlyOnceAndWrongSessionOrNonceCannotConsume() throws {+ var registry = LockedUsePermitRegistry()+ let id = UUID(), connection = UUID()+ let permit = try registry.issue(attemptID: id, connectionID: connection, session: session, guardsHealthy: true, now: 100, nonce: nonce)+ XCTAssertThrowsError(try registry.consume(attemptID: id, session: .init(userID: 502, auditSessionID: 10), nonce: nonce, guardsHealthy: true, now: 100))+ XCTAssertThrowsError(try registry.consume(attemptID: id, session: session, nonce: Data(repeating: 0, count: 32), guardsHealthy: true, now: 100))+ XCTAssertEqual(try registry.consume(attemptID: id, session: session, nonce: nonce, guardsHealthy: true, now: 100), permit)+ XCTAssertThrowsError(try registry.consume(attemptID: id, session: session, nonce: nonce, guardsHealthy: true, now: 100))+ XCTAssertThrowsError(try registry.issue(attemptID: id, connectionID: connection, session: session, guardsHealthy: true, now: 100, nonce: nonce))+ }++ func testExpiryAndLostGuardBurnAttempt() throws {+ for (healthy, time) in [(true, 105.0), (false, 101.0)] {+ var registry = LockedUsePermitRegistry()+ let id = UUID(), connection = UUID()+ _ = try registry.issue(attemptID: id, connectionID: connection, session: session, guardsHealthy: true, now: 100, nonce: nonce)+ XCTAssertThrowsError(try registry.consume(attemptID: id, session: session, nonce: nonce, guardsHealthy: healthy, now: time))+ XCTAssertEqual(registry.pendingCount, 0)+ XCTAssertThrowsError(try registry.issue(attemptID: id, connectionID: connection, session: session, guardsHealthy: true, now: time, nonce: nonce))+ }+ }++ func testDisconnectRevokesOnlyOwnConnectionAndSessionCannotHaveTwoPermits() throws {+ var registry = LockedUsePermitRegistry()+ let id = UUID(), connection = UUID()+ _ = try registry.issue(attemptID: id, connectionID: connection, session: session, guardsHealthy: true, now: 100, nonce: nonce)+ XCTAssertThrowsError(try registry.issue(attemptID: UUID(), connectionID: UUID(), session: session, guardsHealthy: true, now: 100, nonce: nonce))+ registry.revoke(connectionID: UUID())+ XCTAssertEqual(registry.pendingCount, 1)+ registry.revoke(connectionID: connection)+ XCTAssertEqual(registry.pendingCount, 0)+ XCTAssertThrowsError(try registry.consume(attemptID: id, session: session, nonce: nonce, guardsHealthy: true, now: 100))+ }++ func testInvalidClockAndMissingGuardsNeverIssue() throws {+ var registry = LockedUsePermitRegistry()+ XCTAssertThrowsError(try registry.issue(attemptID: UUID(), connectionID: UUID(), session: session, guardsHealthy: false, now: 100, nonce: nonce))+ XCTAssertThrowsError(try registry.issue(attemptID: UUID(), connectionID: UUID(), session: session, guardsHealthy: true, now: 99, nonce: nonce))+ XCTAssertThrowsError(try registry.expire(now: .infinity))+ }+}diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUsePolicyMonitorTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUsePolicyMonitorTests.swiftnew file mode 100644index 0000000..359f158--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUsePolicyMonitorTests.swift@@ -0,0 +1,27 @@+import XCTest+@testable import OpenComputerUseKit++final class LockedUsePolicyMonitorTests: XCTestCase {+ func testWedgedAuthorizationServerDoesNotBlockRecoveryQueueAndExpiresPermits() {+ let entered = expectation(description: "policy read entered")+ let release = DispatchSemaphore(value: 0)+ let monitor = LockedUsePolicyMonitor { entered.fulfill(); release.wait(); return true }+ defer { release.signal() }+ let started = ProcessInfo.processInfo.systemUptime+ monitor.refresh(now: started)+ wait(for: [entered], timeout: 1)+ for _ in 0..<100 { monitor.refresh(); XCTAssertEqual(monitor.status(), .pending) }+ XCTAssertLessThan(ProcessInfo.processInfo.systemUptime - started, 1)+ XCTAssertEqual(monitor.status(now: started + LockedUsePolicyMonitor.maximumAge), .stale)+ }++ func testFailedObservationCannotAuthorize() {+ let returned = expectation(description: "check ran")+ let monitor = LockedUsePolicyMonitor { returned.fulfill(); return false }+ monitor.refresh()+ wait(for: [returned], timeout: 1)+ let deadline = ProcessInfo.processInfo.systemUptime + 1+ while monitor.status() == .pending && ProcessInfo.processInfo.systemUptime < deadline { Thread.sleep(forTimeInterval: 0.001) }+ XCTAssertEqual(monitor.status(), .invalid)+ }+}diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUsePrivateRecordTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUsePrivateRecordTests.swiftnew file mode 100644index 0000000..e012556--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUsePrivateRecordTests.swift@@ -0,0 +1,40 @@+import Darwin+import Foundation+import LockedUseNative+@testable import OpenComputerUseKit+import XCTest++final class LockedUsePrivateRecordTests: XCTestCase {+ func testAtomicRecordIsPrivateAndRemovesInheritedReadACL() throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent("ocu-private-record-\(UUID())")+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])+ defer { try? FileManager.default.removeItem(at: directory) }+ let process = Process()+ process.executableURL = URL(fileURLWithPath: "/bin/chmod")+ process.arguments = ["+a", "everyone allow read,file_inherit", directory.path]+ try process.run(); process.waitUntilExit()+ XCTAssertEqual(process.terminationStatus, 0)+ let bytes = Data("isolated-test-record".utf8)+ try LockedUsePrivateRecord.write(bytes, directory: directory, name: "record.json", owner: geteuid())+ let path = directory.appendingPathComponent("record.json").path+ let fd = open(path, O_RDONLY | O_NOFOLLOW)+ XCTAssertGreaterThanOrEqual(fd, 0)+ defer { close(fd) }+ var info = stat()+ XCTAssertEqual(fstat(fd, &info), 0)+ XCTAssertEqual(info.st_mode & 0o777, 0o600)+ XCTAssertEqual(ocu_has_any_acl(fd), 0)+ XCTAssertEqual(try Data(contentsOf: URL(fileURLWithPath: path)), bytes)+ try LockedUsePrivateRecord.write(Data("updated".utf8), directory: directory, name: "record.json", owner: geteuid())+ XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: directory.path), ["record.json"])+ }++ func testWriterRejectsUntrustedDirectoryAndNames() throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent("ocu-private-record-\(UUID())")+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o777])+ defer { try? FileManager.default.removeItem(at: directory) }+ XCTAssertEqual(chmod(directory.path, 0o777), 0)+ XCTAssertThrowsError(try LockedUsePrivateRecord.write(Data([1]), directory: directory, name: "record.json", owner: geteuid()))+ XCTAssertThrowsError(try LockedUsePrivateRecord.write(Data([1]), directory: directory, name: "../outside", owner: geteuid()))+ }+}diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseRecoveryDeadlineTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseRecoveryDeadlineTests.swiftnew file mode 100644index 0000000..fd382a1--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseRecoveryDeadlineTests.swift@@ -0,0 +1,34 @@+import XCTest+@testable import OpenComputerUseKit++final class LockedUseRecoveryDeadlineTests: XCTestCase {+ func testWedgedRPCQueueAndRepeatedRetriesCannotExtendRecoveryDeadline() {+ let expired = expectation(description: "independent recovery")+ let deadline = LockedUseRecoveryDeadline { expired.fulfill() }+ let rpc = DispatchQueue(label: "test.wedged-rpc")+ let release = DispatchSemaphore(value: 0)+ rpc.async { release.wait() }+ defer { release.signal(); deadline.cancel() }+ deadline.arm(after: 0.05)+ for _ in 0..<20 { deadline.arm(after: 5) }+ wait(for: [expired], timeout: 1)+ }++ func testCompletedCleanupCancelsExpiration() {+ let expired = expectation(description: "no expiration after cleanup")+ expired.isInverted = true+ let deadline = LockedUseRecoveryDeadline { expired.fulfill() }+ deadline.arm(after: 0.05)+ deadline.cancel()+ wait(for: [expired], timeout: 0.15)+ }++ func testEarlierFailureShortensAcquisitionDeadline() {+ let expired = expectation(description: "shortened recovery")+ let deadline = LockedUseRecoveryDeadline { expired.fulfill() }+ defer { deadline.cancel() }+ deadline.arm(after: 5)+ deadline.arm(after: 0.05)+ wait(for: [expired], timeout: 1)+ }+}diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseRecoveryTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseRecoveryTests.swiftnew file mode 100644index 0000000..253a110--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseRecoveryTests.swift@@ -0,0 +1,191 @@+import Foundation+@testable import OpenComputerUseKit+import XCTest++final class LockedUseRecoveryTests: XCTestCase {+ private func context(_ role: LockedUseBrokerCoordinator.Role, _ byte: UInt8) -> LockedUseBrokerCoordinator.Context {+ .init(id: UUID(), role: role, userID: 501, auditSessionID: 42,+ auditToken: Data(repeating: byte, count: 32), processID: Int32(100 + byte), codeHash: Data(repeating: byte, count: 20))+ }+ private let locked = LockedUseSession(state: .locked, userID: 501, auditSessionID: 42)+ private let unlocked = LockedUseSession(state: .unlocked, userID: 501, auditSessionID: 42)+ private let guards = LockedUseStateMachine.Guards(allDisplaysCovered: true, inputTapHealthy: true, watchdogHealthy: true, displayGeneration: 1)++ func testAdministrativeRetirementNeedsIdleDrainAndEveryGuardExit() {+ func record(drained: Bool = true, observed: Bool = true) -> LockedUseRecoveryRecord {+ .init(leaseID: UUID(), owner: context(.agent, 1), originalClientToken: Data(repeating: 1, count: 32),+ guardian: context(.guardian, 2), watchdog: context(.guardian, 3), watchdogChallenge: nil,+ everGranted: true, observedUnlocked: observed, agentDrained: drained, fullyReleased: false)+ }+ XCTAssertTrue(record().canRetireStoppedGuards(phase: .idle, allGuardsExited: true))+ for phase in [LockedUseStateMachine.Phase.active, .authorizing, .unlocking, .relocking, .awaitingManualUnlock] {+ XCTAssertFalse(record().canRetireStoppedGuards(phase: phase, allGuardsExited: true))+ }+ XCTAssertFalse(record().canRetireStoppedGuards(phase: .idle, allGuardsExited: false))+ XCTAssertFalse(record(drained: false).canRetireStoppedGuards(phase: .idle, allGuardsExited: true))+ XCTAssertFalse(record(observed: false).canRetireStoppedGuards(phase: .idle, allGuardsExited: true))+ }++ func testWatchdogMustRegisterBeforeProductionPermitIsIssued() throws {+ let owner = context(.agent, 1), guardian = context(.guardian, 2), watchdog = context(.guardian, 3)+ var broker = LockedUseBrokerCoordinator(enabled: true, backendValidated: true, requiresWatchdog: true)+ let begin = try broker.handle(.init(operation: .begin, session: locked), context: owner, now: 1)+ let lease = try XCTUnwrap(begin.leaseID)+ let hello = try broker.handle(.init(operation: .guardianHello, leaseID: lease, token: begin.token), context: guardian, now: 1.1)+ _ = try broker.handle(.init(operation: .guardianReport, leaseID: lease, session: locked, guards: guards), context: guardian, now: 1.2)+ XCTAssertEqual(broker.phase, .preparing)+ XCTAssertThrowsError(try broker.handle(.init(operation: .watchdogHello, leaseID: lease, token: Data(repeating: 0, count: 32)), context: watchdog, now: 1.3))+ _ = try broker.handle(.init(operation: .watchdogHello, leaseID: lease, token: hello.token), context: watchdog, now: 1.4)+ let waiting = try broker.handle(.init(operation: .guardianReport, leaseID: lease, session: locked, guards: guards), context: guardian, now: 1.45)+ XCTAssertEqual(waiting.phase, .preparing)+ _ = try broker.handle(.init(operation: .watchdogReport, leaseID: lease, session: locked, guards: guards), context: watchdog, now: 1.46)+ let ready = try broker.handle(.init(operation: .guardianReport, leaseID: lease, session: locked, guards: guards), context: guardian, now: 1.5)+ XCTAssertEqual(ready.phase, .authorizing)+ XCTAssertTrue(ready.effects.contains("requestUnlock"))+ }++ func testRecoveryNeverReissuesPermitAndNeedsActualUnlockDrainAndRelock() throws {+ let owner = context(.agent, 1), guardian = context(.guardian, 2), watchdog = context(.guardian, 3)+ let lease = UUID()+ let record = try LockedUseRecoveryRecord(leaseID: lease, owner: owner, originalClientToken: Data(repeating: 9, count: 32), guardian: guardian,+ watchdog: watchdog, watchdogChallenge: nil, everGranted: true, observedUnlocked: false, agentDrained: false, fullyReleased: false).validated()+ var broker = LockedUseBrokerCoordinator(enabled: true, backendValidated: true, requiresWatchdog: true, recovery: record)+ XCTAssertEqual(broker.phase, .relocking)+ XCTAssertThrowsError(try broker.handle(.init(operation: .begin, session: locked), context: owner, now: 1))+ let plugin = context(.plugin, 4)+ XCTAssertThrowsError(try broker.handle(.init(operation: .pluginClaim), context: plugin, now: 1.1))+ _ = try broker.handle(.init(operation: .guardianReport, leaseID: lease, session: locked, guards: guards, unlockWorkPending: false), context: guardian, now: 1.2)+ _ = try broker.handle(.init(operation: .quiesced, leaseID: lease), context: owner, now: 1.3)+ XCTAssertEqual(broker.phase, .relocking)+ _ = try broker.handle(.init(operation: .guardianRecoveryHello, leaseID: lease, hasObservedUnlock: true), context: guardian, now: 1.4)+ _ = try broker.handle(.init(operation: .quiesced, leaseID: lease), context: owner, now: 1.5)+ let released = try broker.handle(.init(operation: .guardianReport, leaseID: lease, session: locked, guards: guards, unlockWorkPending: false), context: guardian, now: 1.6)+ XCTAssertEqual(released.phase, .awaitingManualUnlock)+ XCTAssertTrue(released.effects.contains("releaseGuards"))+ _ = try broker.handle(.init(operation: .guardianReleased, leaseID: lease), context: guardian, now: 1.7)+ _ = try broker.handle(.init(operation: .watchdogReleased, leaseID: lease), context: watchdog, now: 1.8)+ XCTAssertTrue(broker.isFullyReleased)+ let observer = context(.observer, 5)+ _ = try broker.handle(.init(operation: .status, session: unlocked), context: observer, now: 1.9)+ XCTAssertEqual(broker.phase, .idle)+ }++ func testGuardianDeathUsesIndependentWatchdogLockEvidenceAndActionDrain() throws {+ let owner = context(.agent, 1), guardian = context(.guardian, 2), watchdog = context(.guardian, 3)+ let lease = UUID()+ let record = try LockedUseRecoveryRecord(leaseID: lease, owner: owner, originalClientToken: Data(repeating: 9, count: 32), guardian: guardian,+ watchdog: watchdog, watchdogChallenge: nil, everGranted: true, observedUnlocked: true, agentDrained: false, fullyReleased: false).validated()+ var broker = LockedUseBrokerCoordinator(enabled: true, backendValidated: true, requiresWatchdog: true, recovery: record)+ try broker.guardianProcessExited()+ let beforeDrain = try broker.handle(.init(operation: .watchdogReport, leaseID: lease, session: locked), context: watchdog, now: 1)+ XCTAssertFalse(beforeDrain.effects.contains("releaseWatchdog"))+ _ = try broker.handle(.init(operation: .quiesced, leaseID: lease), context: owner, now: 1.1)+ let afterDrain = try broker.handle(.init(operation: .watchdogReport, leaseID: lease, session: locked), context: watchdog, now: 1.2)+ XCTAssertEqual(afterDrain.phase, .awaitingManualUnlock)+ XCTAssertTrue(afterDrain.effects.contains("releaseWatchdog"))+ _ = try broker.handle(.init(operation: .watchdogReleased, leaseID: lease), context: watchdog, now: 1.3)+ XCTAssertTrue(broker.isFullyReleased)+ }++ func testRecoveryRecordRejectsUnattestedOrCrossSessionPeers() throws {+ let bare = LockedUseBrokerCoordinator.Context(id: UUID(), role: .agent, userID: 501, auditSessionID: 42)+ let bad = LockedUseRecoveryRecord(leaseID: UUID(), owner: bare, originalClientToken: Data(repeating: 1, count: 32), guardian: nil, watchdog: nil,+ watchdogChallenge: nil, everGranted: false, observedUnlocked: false, agentDrained: false, fullyReleased: true)+ XCTAssertThrowsError(try bad.validated())+ let owner = context(.agent, 1)+ let other = LockedUseBrokerCoordinator.Context(id: UUID(), role: .guardian, userID: 502, auditSessionID: 42,+ auditToken: Data(repeating: 2, count: 32), processID: 102, codeHash: Data(repeating: 2, count: 20))+ let mismatch = LockedUseRecoveryRecord(leaseID: UUID(), owner: owner, originalClientToken: Data(repeating: 1, count: 32), guardian: other, watchdog: nil,+ watchdogChallenge: nil, everGranted: false, observedUnlocked: false, agentDrained: false, fullyReleased: false)+ XCTAssertThrowsError(try mismatch.validated())+ }++ func testRecoveryProbeNeverIssuesPermitAndProductionRejectsIt() throws {+ let owner = context(.agent, 1), guardian = context(.guardian, 2), watchdog = context(.guardian, 3)+ var production = LockedUseBrokerCoordinator(enabled: true, backendValidated: true)+ XCTAssertThrowsError(try production.handle(.init(operation: .beginRecoveryProbe, session: locked), context: owner, now: 1))+ var broker = LockedUseBrokerCoordinator(enabled: true, backendValidated: true,+ requiresWatchdog: true, validationMode: true)+ let begin = try broker.handle(.init(operation: .beginRecoveryProbe, session: locked), context: owner, now: 1)+ let lease = try XCTUnwrap(begin.leaseID)+ let hello = try broker.handle(.init(operation: .guardianHello, leaseID: lease, token: begin.token), context: guardian, now: 1.1)+ _ = try broker.handle(.init(operation: .watchdogHello, leaseID: lease, token: hello.token), context: watchdog, now: 1.2)+ _ = try broker.handle(.init(operation: .watchdogReport, leaseID: lease, session: locked, guards: guards), context: watchdog, now: 1.3)+ let stopping = try broker.handle(.init(operation: .guardianReport, leaseID: lease, session: locked,+ guards: guards, unlockWorkPending: false), context: guardian, now: 1.4)+ XCTAssertEqual(stopping.phase, .relocking)+ XCTAssertEqual(stopping.recoveryProbePrepared, true)+ XCTAssertFalse(stopping.effects.contains("requestUnlock"))+ XCTAssertThrowsError(try broker.handle(.init(operation: .pluginClaim), context: context(.plugin, 4), now: 1.5))+ _ = try broker.handle(.init(operation: .quiesced, leaseID: lease), context: owner, now: 1.6)+ let release = try broker.handle(.init(operation: .guardianReport, leaseID: lease, session: locked,+ guards: guards, unlockWorkPending: false), context: guardian, now: 1.7)+ XCTAssertTrue(release.effects.contains("releaseGuards"))+ XCTAssertEqual(release.guardsReleased, false)+ _ = try broker.handle(.init(operation: .guardianReleased, leaseID: lease), context: guardian, now: 1.8)+ let finished = try broker.handle(.init(operation: .watchdogReleased, leaseID: lease), context: watchdog, now: 1.9)+ XCTAssertEqual(finished.guardsReleased, true)+ }++ func testStartupFailureCannotMasqueradeAsSuccessfulDualGuardRecovery() throws {+ let owner = context(.agent, 1), guardian = context(.guardian, 2)+ var broker = LockedUseBrokerCoordinator(enabled: true, backendValidated: true,+ requiresWatchdog: true, validationMode: true)+ let begin = try broker.handle(.init(operation: .beginRecoveryProbe, session: locked), context: owner, now: 1)+ let lease = try XCTUnwrap(begin.leaseID)+ _ = try broker.handle(.init(operation: .guardianHello, leaseID: lease, token: begin.token), context: guardian, now: 1.1)+ _ = try broker.handle(.init(operation: .end, leaseID: lease), context: owner, now: 1.2)+ _ = try broker.handle(.init(operation: .quiesced, leaseID: lease), context: owner, now: 1.3)+ _ = try broker.handle(.init(operation: .guardianReport, leaseID: lease, session: locked,+ guards: guards, unlockWorkPending: false), context: guardian, now: 1.4)+ let cleanup = try broker.handle(.init(operation: .guardianReleased, leaseID: lease), context: guardian, now: 1.5)+ XCTAssertEqual(cleanup.guardsReleased, true)+ XCTAssertEqual(cleanup.recoveryProbePrepared, false)+ }++ func testPreparingAllowsBoundedChildStartupButCannotGrantEarly() throws {+ let owner = context(.agent, 1)+ var broker = LockedUseBrokerCoordinator(enabled: true, backendValidated: true,+ requiresWatchdog: true, validationMode: true)+ _ = try broker.handle(.init(operation: .beginRecoveryProbe, session: locked), context: owner, now: 1)+ try broker.tick(now: 4.5)+ XCTAssertEqual(broker.phase, .preparing)+ XCTAssertThrowsError(try broker.handle(.init(operation: .pluginClaim), context: context(.plugin, 4), now: 4.6))+ try broker.tick(now: 1 + LockedUseStateMachine.unlockTimeout)+ XCTAssertEqual(broker.phase, .relocking)+ }++ func testFailedAgentExitReleasesGuardsOnlyAfterUnlockWorkIsDrained() throws {+ for everGranted in [false, true] {+ let owner = context(.agent, 1), guardian = context(.guardian, 2), watchdog = context(.guardian, 3)+ let lease = UUID()+ let record = try LockedUseRecoveryRecord(leaseID: lease, owner: owner,+ originalClientToken: Data(repeating: 9, count: 32), guardian: guardian,+ watchdog: watchdog, watchdogChallenge: nil, everGranted: everGranted,+ observedUnlocked: false, agentDrained: false, fullyReleased: false).validated()+ var broker = LockedUseBrokerCoordinator(enabled: true, backendValidated: true,+ requiresWatchdog: true, recovery: record)+ _ = try broker.handle(.init(operation: .guardianReport, leaseID: lease,+ session: locked, guards: guards, unlockWorkPending: true), context: guardian, now: 1)+ try broker.ownerProcessExited()+ XCTAssertEqual(broker.phase, .relocking)+ _ = try broker.handle(.init(operation: .guardianReport, leaseID: lease,+ session: locked, guards: guards, unlockWorkPending: false), context: guardian, now: 1.1)+ try broker.ownerProcessExited()+ var releaseObserved = false+ if everGranted {+ XCTAssertEqual(broker.phase, .relocking, "A queued authorization allow must not expose the desktop")+ _ = try broker.handle(.init(operation: .guardianReport, leaseID: lease,+ session: unlocked, guards: guards, unlockWorkPending: false), context: guardian, now: 1.2)+ try broker.ownerProcessExited()+ let relocked = try broker.handle(.init(operation: .guardianReport, leaseID: lease,+ session: locked, guards: guards, unlockWorkPending: false), context: guardian, now: 1.3)+ releaseObserved = relocked.effects.contains("releaseGuards")+ }+ XCTAssertEqual(broker.phase, .awaitingManualUnlock)+ let release = try broker.handle(.init(operation: .guardianReport, leaseID: lease,+ session: locked, guards: guards, unlockWorkPending: false), context: guardian, now: 1.4)+ XCTAssertTrue(releaseObserved || release.effects.contains("releaseGuards"))+ }+ }+}diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseReleaseBarrierTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseReleaseBarrierTests.swiftnew file mode 100644index 0000000..df6b688--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseReleaseBarrierTests.swift@@ -0,0 +1,24 @@+import XCTest+@testable import OpenComputerUseKit+final class LockedUseReleaseBarrierTests: XCTestCase {+ func testNeedsContinuousLockedCoverageAndFreshSamples() {+ var b = LockedUseReleaseBarrier()+ for n in 0..<10 { XCTAssertFalse(b.observe(locked: true, presentation: "all", now: Double(n)/10)) }+ XCTAssertTrue(b.observe(locked: true, presentation: "all", now: 1))+ XCTAssertFalse(b.observe(locked: false, presentation: "all", now: 1.1))+ XCTAssertFalse(b.observe(locked: true, presentation: "all", now: 1.2))+ XCTAssertFalse(b.observe(locked: true, presentation: nil, now: 1.3))+ XCTAssertFalse(b.observe(locked: true, presentation: "all", now: 1.4))+ XCTAssertFalse(b.observe(locked: true, presentation: "all", now: 5))+ XCTAssertFalse(b.observe(locked: true, presentation: "all", now: 5.1))+ }+ func testTopologyOrClockChangeResetsStability() {+ var b = LockedUseReleaseBarrier()+ _ = b.observe(locked: true, presentation: "a", now: 1)+ _ = b.observe(locked: true, presentation: "a", now: 1.5)+ XCTAssertFalse(b.observe(locked: true, presentation: "b", now: 2))+ XCTAssertFalse(b.observe(locked: true, presentation: "b", now: .nan))+ XCTAssertFalse(b.observe(locked: true, presentation: "b", now: 3))+ XCTAssertFalse(b.observe(locked: true, presentation: "b", now: 2))+ }+}diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseReturnAllowanceTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseReturnAllowanceTests.swiftnew file mode 100644index 0000000..aec8d82--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseReturnAllowanceTests.swift@@ -0,0 +1,59 @@+import XCTest+@testable import OpenComputerUseKit++final class LockedUseReturnAllowanceTests: XCTestCase {+ private let session = LockedUseSession(state: .locked, userID: 501, auditSessionID: 42)+ private func gate() -> LockedUseReturnAllowance { .init(tag: 123, sender: 10, session: session, now: 1) }+ private func send(_ g: inout LockedUseReturnAllowance, down: Bool = true, tag: Int64 = 123,+ sender: Int32 = 10, target: Int32 = 20, code: Int64 = 36, repeated: Bool = false,+ modified: Bool = false, observed: LockedUseSession? = nil, now: Double = 2) -> Bool {+ g.accept(isDown: down, tag: tag, sender: sender, target: target, keyCode: code,+ repeated: repeated, modified: modified, session: observed ?? session, now: now)+ }+ func testExactlyOnePairInEachIndependentFilter() {+ var main = gate(), watchdog = gate()+ for down in [true, false] {+ XCTAssertTrue(send(&main, down: down, now: down ? 2 : 2.01))+ XCTAssertTrue(send(&watchdog, down: down, now: down ? 2 : 2.01))+ }+ XCTAssertFalse(send(&main)); XCTAssertFalse(send(&watchdog))+ }+ func testPIDWithoutCapabilityCannotPass() {+ var g = gate(); XCTAssertFalse(send(&g, tag: 0))+ XCTAssertFalse(send(&g, sender: 11)); XCTAssertFalse(send(&g, target: 0))+ }+ func testOtherKeysModifiersAndRepeatsRevoke() {+ for i in 0..<3 {+ var g = gate()+ XCTAssertFalse(send(&g, code: i == 0 ? 37 : 36, repeated: i == 1, modified: i == 2))+ XCTAssertFalse(send(&g))+ }+ }+ func testSessionChangesAndExpiryRevoke() {+ for observed in [LockedUseSession(state: .unlocked, userID: 501, auditSessionID: 42),+ LockedUseSession(state: .locked, userID: 502, auditSessionID: 42),+ LockedUseSession(state: .locked, userID: 501, auditSessionID: 43)] {+ var g = gate(); XCTAssertFalse(send(&g, observed: observed)); XCTAssertFalse(send(&g))+ }+ for now in [0.0, 6.0, Double.nan] {+ var g = gate(); XCTAssertFalse(send(&g, now: now)); XCTAssertFalse(send(&g))+ }+ }+ func testOrderingTargetAndPairDeadline() {+ for i in 0..<4 {+ var g = gate()+ if i == 0 { XCTAssertFalse(send(&g, down: false)) }+ else {+ XCTAssertTrue(send(&g))+ XCTAssertFalse(send(&g, down: i == 1, target: i == 2 ? 21 : 20, now: i == 3 ? 2.25 : 2.01))+ }+ XCTAssertFalse(send(&g, down: false, now: 2.02))+ }+ }+ func testTakeoverRevokesBothPairsAndOldBootstrapHasNoReturn() throws {+ var g = gate(); g.revoke(); XCTAssertFalse(send(&g))+ let bootstrap = try LockedUseGuardianBootstrap(leaseID: UUID(), token: Data(repeating: 0, count: 32))+ let restored = try JSONDecoder().decode(LockedUseGuardianBootstrap.self, from: JSONEncoder().encode(bootstrap))+ XCTAssertNil(restored.returnTag)+ }+}diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseShieldCoverageTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseShieldCoverageTests.swiftnew file mode 100644index 0000000..be47359--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseShieldCoverageTests.swift@@ -0,0 +1,42 @@+import XCTest+@testable import OpenComputerUseKit++final class LockedUseShieldCoverageTests: XCTestCase {+ func testQuartzDisplayAtNegativeOriginAndOversizedSurface() {+ let display = CGRect(x: -1512, y: 1440, width: 1512, height: 982)+ XCTAssertTrue(LockedUseShieldCoverage.covers(display, display: display))+ XCTAssertTrue(LockedUseShieldCoverage.covers(display.insetBy(dx: -1, dy: -1), display: display))+ XCTAssertFalse(LockedUseShieldCoverage.covers(display.insetBy(dx: 75, dy: 49), display: display))+ for offset in [CGPoint(x: 0.01, y: 0), CGPoint(x: -0.01, y: 0),+ CGPoint(x: 0, y: 0.01), CGPoint(x: 0, y: -0.01)] {+ XCTAssertFalse(LockedUseShieldCoverage.covers(+ display.offsetBy(dx: offset.x, dy: offset.y), display: display))+ }+ }++ func testOverscanStillRequiresRealFullCoverageDuringTransition() {+ for display in [CGRect(x: 0, y: 0, width: 2560, height: 1440),+ CGRect(x: -1512, y: 1440, width: 1512, height: 982)] {+ let surface = LockedUseShieldCoverage.surfaceFrame(for: display)+ XCTAssertEqual(surface.midX, display.midX)+ XCTAssertEqual(surface.midY, display.midY)+ for scale in [1.0, 0.9375, 0.9, 0.75] {+ let actual = CGRect(x: display.midX - surface.width * scale / 2,+ y: display.midY - surface.height * scale / 2,+ width: surface.width * scale, height: surface.height * scale)+ XCTAssertTrue(LockedUseShieldCoverage.covers(actual, display: display))+ }+ XCTAssertFalse(LockedUseShieldCoverage.covers(display.insetBy(dx: 1, dy: 1), display: display))+ }+ }++ func testInvalidGeometryCannotAuthorizeCoverage() {+ let display = CGRect(x: 0, y: 0, width: 100, height: 100)+ for invalid in [CGRect.null, .infinite, .zero,+ CGRect(x: 0, y: 0, width: -100, height: 100),+ CGRect(x: CGFloat.nan, y: 0, width: 100, height: 100)] {+ XCTAssertFalse(LockedUseShieldCoverage.covers(invalid, display: display))+ XCTAssertFalse(LockedUseShieldCoverage.covers(display, display: invalid))+ }+ }+}diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseShieldStatusTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseShieldStatusTests.swiftnew file mode 100644index 0000000..0b08aaa--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseShieldStatusTests.swift@@ -0,0 +1,22 @@+import XCTest+@testable import OpenComputerUseKit++final class LockedUseShieldStatusTests: XCTestCase {+ func testAuthenticationNeverReplacesActiveAndExitFreezesText() {+ var status = LockedUseShieldStatus()+ XCTAssertTrue(status.update(now: 1, startupDeadline: 20, unlocked: false, stopping: false)! == LockedUseShieldStatus.message)+ XCTAssertNil(status.update(now: 2, startupDeadline: 20, unlocked: true, stopping: false))+ for now in 3...23 {+ XCTAssertNil(status.update(now: Double(now), startupDeadline: 20, unlocked: false, stopping: false))+ }+ XCTAssertNil(status.update(now: 24, startupDeadline: 20, unlocked: false, stopping: true))+ XCTAssertNil(status.update(now: 25, startupDeadline: 20, unlocked: true, stopping: false))+ }+ func testBothShieldsUseSameTextAndDeadline() {+ var main = LockedUseShieldStatus(), watchdog = LockedUseShieldStatus()+ for now in 1...5 {+ XCTAssertEqual(main.update(now: Double(now), startupDeadline: 20, unlocked: now >= 3, stopping: now >= 5),+ watchdog.update(now: Double(now), startupDeadline: 20, unlocked: now >= 3, stopping: now >= 5))+ }+ }+}diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseTests.swiftnew file mode 100644index 0000000..a8e0d8b--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseTests.swift@@ -0,0 +1,285 @@+import CoreGraphics+import XCTest+@testable import OpenComputerUseKit++final class LockedUseTests: XCTestCase {+ private let owner = LockedUseStateMachine.Owner(connectionID: UUID(), userID: 501, auditSessionID: 1)+ private let ready = LockedUseStateMachine.Prerequisites(enabled: true, backendValidated: true, clientAuthorized: true)+ private let guards = LockedUseStateMachine.Guards(allDisplaysCovered: true, inputTapHealthy: true, watchdogHealthy: true, displayGeneration: 1)++ private func session(_ state: LockedUseSession.State, uid: UInt32 = 501, console: UInt32 = 1) -> LockedUseSession {+ .init(state: state, userID: uid, auditSessionID: console)+ }++ func testProtectedWaitingHasNoPermitUntilMechanismRequestsAuthorization() throws {+ var machine = LockedUseStateMachine()+ _ = try machine.begin(owner: owner, session: session(.locked), prerequisites: ready, now: 100)+ XCTAssertEqual(try machine.guardsPrepared(guards, now: 100.1, deferPermitUntilClaim: true), [.requestUnlock])+ XCTAssertNil(machine.permit)+ XCTAssertThrowsError(try machine.consumePermit(id: UUID(), owner: owner, now: 100.2))+ for second in 1...6 { _ = try machine.heartbeat(guards, now: 100 + Double(second)) }+ let effects = try machine.authorizationRequested(now: 106.1)+ guard case let .issuePermit(permit) = effects.first else { return XCTFail("permit missing") }+ XCTAssertEqual(permit.deadline, 108, accuracy: 0.001)+ XCTAssertThrowsError(try machine.authorizationRequested(now: 106.2))+ // A late claim must not extend the original eight-second startup cap.+ _ = try machine.heartbeat(guards, now: 107)+ XCTAssertTrue(try machine.tick(now: 108).contains(.cancelUnlock))+ XCTAssertEqual(machine.stopReason, .unlockTimeout)+ }++ func testCancelledProtectedWaitingCannotIssueALatePermit() throws {+ var machine = LockedUseStateMachine()+ _ = try machine.begin(owner: owner, session: session(.locked), prerequisites: ready, now: 100)+ _ = try machine.guardsPrepared(guards, now: 100.1, deferPermitUntilClaim: true)+ _ = machine.localInput()+ XCTAssertThrowsError(try machine.authorizationRequested(now: 100.2))+ XCTAssertNil(machine.permit)+ }++ private func active() throws -> LockedUseStateMachine {+ var machine = LockedUseStateMachine()+ XCTAssertEqual(try machine.begin(owner: owner, session: session(.locked), prerequisites: ready, now: 100), [.prepareGuards])+ let effects = try machine.guardsPrepared(guards, now: 100.1)+ guard case let .issuePermit(permit) = effects.first else { XCTFail("permit missing"); return machine }+ XCTAssertEqual(effects, [.issuePermit(permit), .requestUnlock])+ XCTAssertEqual(machine.phase, .authorizing)+ try machine.consumePermit(id: permit.id, owner: owner, now: 100.2)+ XCTAssertEqual(machine.phase, .unlocking)+ XCTAssertEqual(try machine.observe(session: session(.unlocked), now: 100.3), [.revokePermit])+ XCTAssertEqual(machine.phase, .active)+ return machine+ }++ func testProtectBeforeIssuingPermitAndRequireObservedUnlock() throws {+ var machine = LockedUseStateMachine()+ _ = try machine.begin(owner: owner, session: session(.locked), prerequisites: ready, now: 100)+ XCTAssertNil(machine.permit)+ XCTAssertThrowsError(try machine.authorizeAction(owner: owner, session: session(.unlocked), now: 100))+ _ = try machine.guardsPrepared(guards, now: 100)+ // An unrelated unlock notification before permit consumption grants nothing.+ XCTAssertEqual(try machine.observe(session: session(.unlocked), now: 100), [.stopActions, .revokePermit, .cancelUnlock, .requestRelock])+ XCTAssertEqual(machine.phase, .relocking)+ XCTAssertThrowsError(try machine.authorizeAction(owner: owner, session: session(.unlocked), now: 100))+ }++ func testAuthorizationPrerequisitesFailBeforeAnyEffect() {+ for (prerequisites, expected) in [+ (LockedUseStateMachine.Prerequisites(enabled: false, backendValidated: true, clientAuthorized: true), LockedUseStateMachine.Failure.disabled),+ (.init(enabled: true, backendValidated: false, clientAuthorized: true), .backendUnvalidated),+ (.init(enabled: true, backendValidated: true, clientAuthorized: false), .clientUnauthorized)+ ] {+ var machine = LockedUseStateMachine()+ XCTAssertThrowsError(try machine.begin(owner: owner, session: session(.locked), prerequisites: prerequisites, now: 100)) {+ XCTAssertEqual($0 as? LockedUseStateMachine.Failure, expected)+ }+ XCTAssertEqual(machine.phase, .idle)+ XCTAssertNil(machine.owner)+ XCTAssertNil(machine.permit)+ }+ }++ func testInvalidOrDifferentConsoleCannotStart() {+ for invalid in [session(.unlocked), session(.unavailable), session(.locked, uid: 502), session(.locked, console: 2)] {+ var machine = LockedUseStateMachine()+ XCTAssertThrowsError(try machine.begin(owner: owner, session: invalid, prerequisites: ready, now: 100))+ XCTAssertEqual(machine.phase, .idle)+ }+ }++ func testEveryGuardMustBeHealthyBeforeUnlock() throws {+ for broken in [+ LockedUseStateMachine.Guards(allDisplaysCovered: false, inputTapHealthy: true, watchdogHealthy: true, displayGeneration: 1),+ .init(allDisplaysCovered: true, inputTapHealthy: false, watchdogHealthy: true, displayGeneration: 1),+ .init(allDisplaysCovered: true, inputTapHealthy: true, watchdogHealthy: false, displayGeneration: 1)+ ] {+ var machine = LockedUseStateMachine()+ _ = try machine.begin(owner: owner, session: session(.locked), prerequisites: ready, now: 100)+ XCTAssertEqual(try machine.guardsPrepared(broken, now: 100), [.stopActions, .revokePermit, .cancelUnlock, .requestRelock])+ XCTAssertNil(machine.permit)+ }+ }++ func testPermitCannotBeReplayedOrConsumedByAnotherClient() throws {+ var machine = LockedUseStateMachine()+ _ = try machine.begin(owner: owner, session: session(.locked), prerequisites: ready, now: 100)+ _ = try machine.guardsPrepared(guards, now: 100)+ let permit = try XCTUnwrap(machine.permit)+ let stranger = LockedUseStateMachine.Owner(connectionID: UUID(), userID: 501, auditSessionID: 1)+ XCTAssertThrowsError(try machine.consumePermit(id: permit.id, owner: stranger, now: 100))+ XCTAssertThrowsError(try machine.consumePermit(id: UUID(), owner: owner, now: 100))+ try machine.consumePermit(id: permit.id, owner: owner, now: 100)+ XCTAssertThrowsError(try machine.consumePermit(id: permit.id, owner: owner, now: 100))+ }++ func testExpiredPermitIsNeverConsumed() throws {+ var machine = LockedUseStateMachine()+ _ = try machine.begin(owner: owner, session: session(.locked), prerequisites: ready, now: 100)+ _ = try machine.guardsPrepared(guards, now: 100)+ let permit = try XCTUnwrap(machine.permit)+ XCTAssertThrowsError(try machine.consumePermit(id: permit.id, owner: owner, now: permit.deadline))+ }++ func testRelockMustBeConfirmedBeforeUnshielding() throws {+ var machine = try active()+ XCTAssertEqual(try machine.end(owner: owner, reason: .turnEnded), [.stopActions, .revokePermit, .cancelUnlock, .requestRelock])+ XCTAssertEqual(try machine.observe(session: session(.unlocked), now: 101), [])+ XCTAssertEqual(try machine.observe(session: session(.unavailable), now: 102), [])+ XCTAssertEqual(machine.retryRelock(), [.requestRelock])+ XCTAssertEqual(try machine.observe(session: session(.locked), now: 102), [])+ try machine.confirmQuiescence(owner: owner)+ XCTAssertEqual(try machine.observe(session: session(.locked), now: 103), [.releaseGuards])+ XCTAssertEqual(machine.phase, .idle)+ }++ func testPhysicalTakeoverSuppressesQueuedUnlockUntilManualUnlock() throws {+ var machine = try active()+ XCTAssertEqual(machine.localInput(), [.stopActions, .revokePermit, .cancelUnlock, .requestRelock])+ XCTAssertEqual(machine.localInput(), [])+ XCTAssertThrowsError(try machine.authorizeAction(owner: owner, session: session(.unlocked), now: 101))+ try machine.confirmQuiescence(owner: owner)+ XCTAssertEqual(try machine.observe(session: session(.locked), now: 101), [.releaseGuards])+ XCTAssertEqual(machine.phase, .awaitingManualUnlock)+ XCTAssertThrowsError(try machine.begin(owner: owner, session: session(.locked), prerequisites: ready, now: 102))+ _ = try machine.observe(session: session(.unlocked, uid: 502), now: 103)+ XCTAssertEqual(machine.phase, .awaitingManualUnlock)+ _ = try machine.observe(session: session(.unlocked), now: 104)+ XCTAssertEqual(machine.phase, .idle)+ }++ func testTakeoverDuringPendingUnlockRevokesPermission() throws {+ var machine = LockedUseStateMachine()+ _ = try machine.begin(owner: owner, session: session(.locked), prerequisites: ready, now: 100)+ _ = try machine.guardsPrepared(guards, now: 100)+ let permit = try XCTUnwrap(machine.permit)+ XCTAssertEqual(machine.localInput(), [.stopActions, .revokePermit, .cancelUnlock, .requestRelock])+ XCTAssertThrowsError(try machine.consumePermit(id: permit.id, owner: owner, now: 100.1))+ XCTAssertEqual(try machine.observe(session: session(.unlocked), now: 100.2), [])+ XCTAssertEqual(machine.phase, .relocking)+ }++ func testOriginalLockedScreenCannotReleaseGuardsWhileUnlockIsPending() throws {+ var machine = LockedUseStateMachine()+ _ = try machine.begin(owner: owner, session: session(.locked), prerequisites: ready, now: 100)+ _ = try machine.guardsPrepared(guards, now: 100)+ _ = machine.localInput()+ XCTAssertEqual(try machine.observe(session: session(.locked), now: 101), [])+ XCTAssertEqual(machine.phase, .relocking)+ let stranger = LockedUseStateMachine.Owner(connectionID: UUID(), userID: 501, auditSessionID: 1)+ XCTAssertThrowsError(try machine.confirmQuiescence(owner: stranger))+ try machine.confirmQuiescence(owner: owner)+ XCTAssertEqual(try machine.observe(session: session(.unlocked), now: 102), [])+ XCTAssertEqual(try machine.observe(session: session(.locked), now: 103), [.releaseGuards])+ XCTAssertEqual(machine.phase, .awaitingManualUnlock)+ }++ func testCompetingClientCannotAcquireOrEndLease() throws {+ var machine = try active()+ let stranger = LockedUseStateMachine.Owner(connectionID: UUID(), userID: 501, auditSessionID: 1)+ XCTAssertThrowsError(try machine.begin(owner: stranger, session: session(.locked), prerequisites: ready, now: 101))+ XCTAssertThrowsError(try machine.end(owner: stranger, reason: .turnEnded))+ XCTAssertThrowsError(try machine.authorizeAction(owner: stranger, session: session(.unlocked), now: 101))+ XCTAssertEqual(machine.phase, .active)+ }++ func testChangedDisplayGenerationRelocksRatherThanAcceptingNewCoverage() throws {+ var machine = try active()+ let newDisplay = LockedUseStateMachine.Guards(allDisplaysCovered: true, inputTapHealthy: true, watchdogHealthy: true, displayGeneration: 2)+ XCTAssertEqual(try machine.heartbeat(newDisplay, now: 101), [.stopActions, .revokePermit, .cancelUnlock, .requestRelock])+ XCTAssertEqual(machine.stopReason, .guardLost)+ }++ func testLateHeartbeatCannotResurrectLease() throws {+ var machine = try active()+ XCTAssertEqual(try machine.heartbeat(guards, now: 104), [.stopActions, .revokePermit, .cancelUnlock, .requestRelock])+ XCTAssertEqual(machine.phase, .relocking)+ }++ func testIdleTimeoutWithHealthyHeartbeatAndNoFurtherActions() throws {+ var machine = try active()+ for second in 101...130 {+ XCTAssertEqual(try machine.heartbeat(guards, now: Double(second)), [])+ }+ XCTAssertEqual(try machine.tick(now: 130.3), [.stopActions, .revokePermit, .cancelUnlock, .requestRelock])+ XCTAssertEqual(machine.stopReason, .idleTimeout)+ }++ func testLeaseHasAbsoluteDeadlineDespiteActivityAndHeartbeats() throws {+ var machine = try active()+ for second in 101...399 {+ _ = try machine.heartbeat(guards, now: Double(second))+ XCTAssertEqual(try machine.authorizeAction(owner: owner, session: session(.unlocked), now: Double(second)), [])+ }+ XCTAssertEqual(try machine.tick(now: 400), [.stopActions, .revokePermit, .cancelUnlock, .requestRelock])+ XCTAssertEqual(machine.stopReason, .leaseExpired)+ }++ func testChangedConsoleAtActionBoundaryStopsActions() throws {+ var machine = try active()+ XCTAssertEqual(try machine.authorizeAction(owner: owner, session: session(.unlocked, console: 2), now: 101), [.stopActions, .revokePermit, .cancelUnlock, .requestRelock])+ XCTAssertEqual(try machine.observe(session: session(.locked, console: 2), now: 102), [])+ XCTAssertEqual(machine.phase, .relocking)+ }++ func testMonotonicClockRejectsRollbackAndNonFiniteValues() throws {+ var machine = try active()+ for time in [99, Double.nan, Double.infinity] {+ XCTAssertThrowsError(try machine.tick(now: time)) {+ XCTAssertEqual($0 as? LockedUseStateMachine.Failure, .invalidClock)+ }+ }+ }++ func testSessionParsingRejectsUnknownUnloggedAndOtherUserSessions() {+ let normal: [String: Any] = [+ kCGSessionOnConsoleKey as String: true,+ kCGSessionLoginDoneKey as String: true,+ kCGSessionUserIDKey as String: 501,+ "kCGSSessionAuditIDKey": 1+ ]+ XCTAssertEqual(LockedUseSession.from(dictionary: normal, effectiveUserID: 501, securitySessionID: 1), session(.unlocked))+ var locked = normal+ locked["CGSSessionScreenIsLocked"] = true+ XCTAssertEqual(LockedUseSession.from(dictionary: locked, effectiveUserID: 501, securitySessionID: 1), session(.locked))+ for malformed in [nil, [:], [kCGSessionOnConsoleKey as String: true]] as [[String: Any]?] {+ XCTAssertEqual(LockedUseSession.from(dictionary: malformed, effectiveUserID: 501, securitySessionID: 1).state, .unavailable)+ }+ XCTAssertEqual(LockedUseSession.from(dictionary: normal, effectiveUserID: 502, securitySessionID: 1).state, .unavailable)+ XCTAssertEqual(LockedUseSession.from(dictionary: normal, effectiveUserID: 501, securitySessionID: nil).state, .unavailable)+ XCTAssertEqual(LockedUseSession.from(dictionary: normal, effectiveUserID: 501, securitySessionID: 2).state, .unavailable)+ var withoutAuditKey = normal+ withoutAuditKey.removeValue(forKey: "kCGSSessionAuditIDKey")+ XCTAssertEqual(LockedUseSession.from(dictionary: withoutAuditKey, effectiveUserID: 501, securitySessionID: 1), session(.unlocked))+ for (key, value) in [(kCGSessionLoginDoneKey as String, false as Any), (kCGSessionOnConsoleKey as String, false as Any), ("CGSSessionScreenIsLocked", "false" as Any), (kCGSessionUserIDKey as String, true as Any), ("kCGSSessionAuditIDKey", -1 as Any), (kCGSessionLoginDoneKey as String, 1 as Any)] {+ var invalid = normal+ invalid[key] = value+ XCTAssertEqual(LockedUseSession.from(dictionary: invalid, effectiveUserID: 501, securitySessionID: 1).state, .unavailable)+ }+ }++ func testRealAppSessionGateRejectsLockedAndUnavailableSessions() throws {+ // This test isolates the session gate; an installed system Broker is+ // covered by IPC tests and must not require signing the XCTest host.+ try LockedUseActionScope.withValidator({}, body: {+ try requireUsableComputerUseSession(session(.unlocked))+ })+ XCTAssertThrowsError(try requireUsableComputerUseSession(session(.locked)))+ XCTAssertThrowsError(try requireUsableComputerUseSession(session(.unavailable)))+ }++ func testCLIRoutesAdministrationLocallyAndRejectsMalformedCommands() throws {+ XCTAssertEqual(try parseOpenComputerUseCLI(arguments: ["locked-use", "status"]), .lockedUseStatus(json: false))+ XCTAssertEqual(try parseOpenComputerUseCLI(arguments: ["locked-use", "status", "--json"]), .lockedUseStatus(json: true))+ XCTAssertEqual(try parseOpenComputerUseCLI(arguments: ["locked-use", "--help"]), .help(command: "locked-use"))+ XCTAssertTrue(shouldUseMacOSAppAgentProxy(command: .lockedUseStatus(json: true), proxyDisabled: false, appBundleAvailable: true, runningFromLaunchServicesAppInstance: false))+ for action in ["enable", "disable", "recover", "certify", "settings"] {+ let command = OpenComputerUseCLICommand.lockedUseManagement(action: action, validation: false)+ 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))+ 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/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseUnlockCancellationTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseUnlockCancellationTests.swiftnew file mode 100644index 0000000..bf0aeea--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseUnlockCancellationTests.swift@@ -0,0 +1,31 @@+import XCTest+@testable import OpenComputerUseKit++final class LockedUseUnlockCancellationTests: XCTestCase {+ func testCancelledReadonlyWorkCanNeverDispatchALateNativeWrite() {+ let cancellation = LockedUseUnlockCancellation()+ cancellation.cancel()+ XCTAssertTrue(cancellation.quiesced)+ let result = cancellation.performProbe { XCTFail("late UI write"); return 1 }+ XCTAssertNil(result)+ XCTAssertFalse(cancellation.allowsRequest())+ }++ func testAlreadyDispatchedWriteMustReturnBeforeQuiescence() {+ let entered = expectation(description: "write dispatched")+ let finished = expectation(description: "write returned")+ let release = DispatchSemaphore(value: 0)+ let cancellation = LockedUseUnlockCancellation()+ DispatchQueue.global().async {+ _ = cancellation.performProbe { entered.fulfill(); release.wait() }+ finished.fulfill()+ }+ wait(for: [entered], timeout: 1)+ cancellation.cancel()+ XCTAssertFalse(cancellation.quiesced)+ XCTAssertNil(cancellation.performProbe { XCTFail("second UI write"); return 1 })+ release.signal()+ wait(for: [finished], timeout: 1)+ XCTAssertTrue(cancellation.quiesced)+ }+}diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseUnshieldedDiagnosticTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseUnshieldedDiagnosticTests.swiftnew file mode 100644index 0000000..c861cc4--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseUnshieldedDiagnosticTests.swift@@ -0,0 +1,64 @@+import Foundation+@testable import OpenComputerUseKit+import XCTest++final class LockedUseUnshieldedDiagnosticTests: XCTestCase {+ private let owner = LockedUseBrokerCoordinator.Context(id: UUID(), role: .guardian, userID: 501, auditSessionID: 42)+ private let plugin = LockedUseBrokerCoordinator.Context(id: UUID(), role: .plugin, userID: 88, auditSessionID: 42)+ private let locked = LockedUseSession(state: .locked, userID: 501, auditSessionID: 42)++ func testUnshieldedEntryRequiresValidationAndNeverAuthorizesActionsOrEvidence() throws {+ var production = LockedUseBrokerCoordinator(enabled: true, backendValidated: true)+ XCTAssertThrowsError(try production.handle(.init(operation: .beginUnshieldedDiagnostic, session: locked), context: owner, now: 1))+ var diagnostic = LockedUseBrokerCoordinator(enabled: true, backendValidated: false, requiresWatchdog: true, validationMode: true)+ let begin = try diagnostic.handle(.init(operation: .beginUnshieldedDiagnostic, session: locked), context: owner, now: 1)+ XCTAssertEqual(begin.detail, "unshieldedDiagnostic")+ XCTAssertEqual(begin.phase, .authorizing)+ XCTAssertTrue(diagnostic.isFullyReleased)+ XCTAssertNil(diagnostic.recordedGuardian)+ XCTAssertNil(diagnostic.recordedWatchdog)+ for operation in [LockedUseIPCMessage.Operation.action, .validationPassed, .begin, .beginRecoveryProbe, .guardianReport] {+ XCTAssertThrowsError(try diagnostic.handle(.init(operation: operation, leaseID: begin.leaseID, session: locked), context: owner, now: 1.1))+ }+ XCTAssertNil(diagnostic.recoveryRecord(clientToken: Data(repeating: 0, count: 32)))+ }+ func testSameAuditSingleUsePermitAndNoResumeAfterExpiry() throws {+ var probe = try LockedUseUnshieldedDiagnostic(owner: owner, session: locked, now: 100)+ let foreign = LockedUseBrokerCoordinator.Context(id: UUID(), role: .plugin, userID: 88, auditSessionID: 43)+ XCTAssertThrowsError(try probe.handle(.init(operation: .pluginClaim), context: foreign, now: 118))+ let claim = try probe.handle(.init(operation: .pluginClaim), context: plugin, now: 118)+ XCTAssertEqual(claim.token?.count, 32)+ XCTAssertThrowsError(try probe.handle(.init(operation: .pluginClaim), context: plugin, now: 118.1))+ let consume = LockedUseIPCMessage(operation: .pluginConsume, leaseID: claim.leaseID, token: claim.token)+ XCTAssertEqual(try probe.handle(consume, context: plugin, now: 119).result, .authorized)+ XCTAssertThrowsError(try probe.handle(consume, context: plugin, now: 119.1))+ try probe.tick(now: 120)+ XCTAssertEqual(probe.phase, .awaitingManualUnlock)+ _ = try probe.handle(.init(operation: .status, session: locked), context: owner, now: 121)+ XCTAssertThrowsError(try probe.handle(.init(operation: .pluginClaim), context: plugin, now: 121))+ }+ func testFiveSecondPermitAndCancellationCannotRearm() throws {+ var probe = try LockedUseUnshieldedDiagnostic(owner: owner, session: locked, now: 0)+ let claim = try probe.handle(.init(operation: .pluginClaim), context: plugin, now: 1)+ XCTAssertThrowsError(try probe.handle(.init(operation: .pluginConsume, leaseID: claim.leaseID, token: claim.token), context: plugin, now: 6))+ XCTAssertEqual(probe.phase, .awaitingManualUnlock)+ probe.cancel()+ XCTAssertThrowsError(try probe.handle(.init(operation: .pluginClaim), context: plugin, now: 7))+ }+ func testEndRequiresSameOriginalLockedSessionAndCoordinatorReturnsIdle() throws {+ var coordinator = LockedUseBrokerCoordinator(enabled: true, backendValidated: false, validationMode: true)+ let begin = try coordinator.handle(.init(operation: .beginUnshieldedDiagnostic, session: locked), context: owner, now: 1)+ let wrong = LockedUseSession(state: .locked, userID: 502, auditSessionID: 42)+ XCTAssertThrowsError(try coordinator.handle(.init(operation: .endUnshieldedDiagnostic, leaseID: begin.leaseID, session: wrong), context: owner, now: 2))+ let end = try coordinator.handle(.init(operation: .endUnshieldedDiagnostic, leaseID: begin.leaseID, session: locked), context: owner, now: 2)+ XCTAssertEqual(end.phase, .idle)+ XCTAssertEqual(coordinator.phase, .idle)+ }+ func testWrongOwnerSessionAndClockRegressionAreDenied() throws {+ XCTAssertThrowsError(try LockedUseUnshieldedDiagnostic(owner: plugin, session: locked, now: 0))+ var probe = try LockedUseUnshieldedDiagnostic(owner: owner, session: locked, now: 100)+ XCTAssertThrowsError(try probe.tick(now: 99))+ let wrong = LockedUseSession(state: .locked, userID: 501, auditSessionID: 43)+ XCTAssertThrowsError(try probe.handle(.init(operation: .status, session: wrong), context: owner, now: 100))+ }+}diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseValidationTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseValidationTests.swiftnew file mode 100644index 0000000..252f99f--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseValidationTests.swift@@ -0,0 +1,26 @@+import Foundation+@testable import OpenComputerUseKit+import XCTest++final class LockedUseValidationTests: XCTestCase {+ private let evidence = LockedUseComponentValidation.Evidence(osBuild: "TEST1", brokerHash: "aa", guardianHash: "bb", pluginHash: "cc")++ func testCannotPromoteBeforeRelockReleaseAndManualKeychainVerification() {+ var report = LockedUseValidationReport(leaseID: UUID(), evidence: evidence, ownerToken: Data(repeating: 1, count: 32))+ XCTAssertFalse(report.canPromote(current: evidence))+ report.lockedAndReleased = true+ XCTAssertFalse(report.canPromote(current: evidence))+ report.afterManualUnlockPassed = true+ XCTAssertTrue(report.canPromote(current: evidence))+ let changed = LockedUseComponentValidation.Evidence(osBuild: "TEST2", brokerHash: "aa", guardianHash: "bb", pluginHash: "cc")+ XCTAssertFalse(report.canPromote(current: changed))+ let changedBinary = LockedUseComponentValidation.Evidence(osBuild: "TEST1", brokerHash: "new", guardianHash: "bb", pluginHash: "cc")+ XCTAssertFalse(report.canPromote(current: changedBinary))+ }++ func testUnattestedOwnerCannotProducePromotionEvidence() {+ var report = LockedUseValidationReport(leaseID: UUID(), evidence: evidence, ownerToken: Data())+ report.lockedAndReleased = true; report.afterManualUnlockPassed = true+ XCTAssertFalse(report.canPromote(current: evidence))+ }+}diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseValidationWaitingTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseValidationWaitingTests.swiftnew file mode 100644index 0000000..53212da--- /dev/null+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/LockedUseValidationWaitingTests.swift@@ -0,0 +1,41 @@+import XCTest+@testable import OpenComputerUseKit++final class LockedUseValidationWaitingTests: XCTestCase {+ private let owner = LockedUseStateMachine.Owner(connectionID: UUID(), userID: 501, auditSessionID: 1)+ private let ready = LockedUseStateMachine.Prerequisites(enabled: true, backendValidated: true, clientAuthorized: true)+ private let guards = LockedUseStateMachine.Guards(allDisplaysCovered: true, inputTapHealthy: true, watchdogHealthy: true, displayGeneration: 1)+ private var session: LockedUseSession { .init(state: .locked, userID: 501, auditSessionID: 1) }++ func testLateClaimGetsFreshPermitWithinOriginalValidationDeadline() throws {+ var machine = LockedUseStateMachine(validationWait: true)+ _ = try machine.begin(owner: owner, session: session, prerequisites: ready, now: 100)+ XCTAssertEqual(machine.startupDeadline, 120)+ XCTAssertEqual(try machine.guardsPrepared(guards, now: 101, deferPermitUntilClaim: true), [.requestUnlock])+ for time in 102...117 { XCTAssertEqual(try machine.heartbeat(guards, now: Double(time)), []) }+ XCTAssertNil(machine.permit)+ _ = try machine.authorizationRequested(now: 118)+ let permit = try XCTUnwrap(machine.permit)+ XCTAssertEqual(permit.deadline, 120)+ try machine.consumePermit(id: permit.id, owner: owner, now: 118.1)+ _ = try machine.observe(session: .init(state: .unlocked, userID: 501, auditSessionID: 1), now: 118.2)+ XCTAssertEqual(machine.phase, .active)+ XCTAssertNil(machine.startupDeadline)+ }+ func testValidationWaitExpiresAndCannotRestart() throws {+ var machine = LockedUseStateMachine(validationWait: true)+ _ = try machine.begin(owner: owner, session: session, prerequisites: ready, now: 100)+ _ = try machine.guardsPrepared(guards, now: 101, deferPermitUntilClaim: true)+ for time in 102...119 { _ = try machine.heartbeat(guards, now: Double(time)) }+ XCTAssertTrue(try machine.tick(now: 120).contains(.cancelUnlock))+ XCTAssertNil(machine.permit)+ XCTAssertThrowsError(try machine.authorizationRequested(now: 120.1))+ }+ func testLongWaitStillCancelsOnLocalInput() throws {+ var machine = LockedUseStateMachine(validationWait: true)+ _ = try machine.begin(owner: owner, session: session, prerequisites: ready, now: 100)+ _ = try machine.guardsPrepared(guards, now: 101, deferPermitUntilClaim: true)+ XCTAssertTrue(machine.localInput().contains(.cancelUnlock))+ XCTAssertThrowsError(try machine.authorizationRequested(now: 102))+ }+}diff --git a/scripts/build-locked-use-components.sh b/scripts/build-locked-use-components.shnew file mode 100755index 0000000..57c0839--- /dev/null+++ b/scripts/build-locked-use-components.sh@@ -0,0 +1,117 @@+#!/usr/bin/env bash+# Build only. Installing/starting the privileged service is a separate step.+set -euo pipefail+identity=""+configuration="debug"+while [[ $# -gt 0 ]]; do+ case "$1" in+ --identity) identity="${2:?Missing signing identity}"; shift 2 ;;+ --configuration) configuration="${2:?Missing configuration}"; shift 2 ;;+ *) echo 'Usage: scripts/build-locked-use-components.sh --identity ID [--configuration debug|release]' >&2; exit 64 ;;+ esac+done+[[ -n "$identity" && "$identity" != - ]] || exit 64+[[ "$configuration" == debug || "$configuration" == release ]] || exit 64+repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+cd "$repo_root"+swift build -c "$configuration" --product OCULockService+swift build -c "$configuration" --product OCULockInstaller+binary_dir="$(swift build -c "$configuration" --show-bin-path)"+output="$repo_root/.build/locked-use/components"+guardian_source=".build/locked-use/OCU Guardian (Dev).app"+if [[ "$configuration" == release ]]; then+ output="$repo_root/.build/locked-use/components-release"+ guardian_source=".build/locked-use/release/OCU Guardian.app"+fi+mkdir -p "$output"+cp "$binary_dir/OCULockService" "$output/OCULockService"+cp "$binary_dir/OCULockInstaller" "$output/OCULockInstaller"+codesign --force --options runtime --timestamp --identifier dev.opencomputeruse.locked-use.installer \+ --sign "$identity" "$output/OCULockInstaller"+codesign --force --options runtime --timestamp --identifier dev.opencomputeruse.locked-use.broker \+ --sign "$identity" "$output/OCULockService"+team="$(codesign -dv --verbose=4 "$output/OCULockService" 2>&1 | sed -n 's/^TeamIdentifier=//p')"+if [[ ! "$team" =~ ^[A-Z0-9]{10}$ ]]; then echo 'Developer ID team unavailable.' >&2; exit 1; fi+scripts/build-locked-use-guardian.sh --identity "$identity" --configuration "$configuration"+ditto "$guardian_source" "$output/$(basename "$guardian_source")"+bundle="$output/OCULockAuth.bundle"+mkdir -p "$bundle/Contents/MacOS"+native_arch="$(uname -m)"+xcrun swiftc -parse-as-library -emit-object -target "$native_arch-apple-macos14.0" \+ -module-name OCULockedUseTaskVerifier experiments/LockedUse/AuthorizationPlugin/TaskVerifier.swift \+ -o "$output/task-verifier.o"+xcrun clang -fobjc-arc -std=gnu11 -Wall -Wextra -Werror -fvisibility=hidden -mmacosx-version-min=14.0 \+ "-DOCU_SIGNING_TEAM=\"$team\"" -I packages/LockedUseNative/include -c \+ experiments/LockedUse/AuthorizationPlugin/RemotePlugin.m -o "$output/remote-plugin.o"+xcrun clang -std=gnu11 -Wall -Wextra -Werror -mmacosx-version-min=14.0 \+ -I packages/LockedUseNative/include -c packages/LockedUseNative/PeerIdentity.c -o "$output/plugin-peer.o"+xcrun swiftc -emit-library -Xlinker -bundle -target "$native_arch-apple-macos14.0" \+ -framework Security -framework Foundation -lbsm \+ "$output/remote-plugin.o" "$output/plugin-peer.o" "$output/task-verifier.o" \+ -o "$bundle/Contents/MacOS/OCULockAuth"+cat > "$bundle/Contents/Info.plist" <<'PLIST'+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0"><dict>+<key>CFBundleIdentifier</key><string>dev.opencomputeruse.locked-use.authorization</string>+<key>CFBundleExecutable</key><string>OCULockAuth</string>+<key>CFBundlePackageType</key><string>BNDL</string>+<key>CFBundleVersion</key><string>1</string>+<key>CFBundleShortVersionString</key><string>0.0.1</string>+</dict></plist>+PLIST+codesign --force --options runtime --timestamp --sign "$identity" "$bundle"+codesign --verify --strict "$bundle"+codesign --verify --strict "$output/OCULockService"+xcrun clang -std=c11 -Wall -Wextra -Werror -mmacosx-version-min=14.0 -framework Security \+ experiments/LockedUse/AuthorizationPlugin/RemotePluginTests.c -o "$output/remote-plugin-abi-tests"+"$output/remote-plugin-abi-tests" "$bundle/Contents/MacOS/OCULockAuth"+# Exercise the modern kernel verifier against independently signed live code.+# These executables are diagnostic artifacts, never installed or used as peers.+# Fresh inodes prevent kernel signature caches from seeing an in-place update.+test_output="$(mktemp -d "$output/task-verifier-checks.XXXXXX")"+xcrun clang -Wall -Wextra -Werror -mmacosx-version-min=14.0 "-DOCU_SIGNING_TEAM=\"$team\"" -c \+ experiments/LockedUse/AuthorizationPlugin/TaskVerifierTests.c -o "$test_output/task-verifier-tests.o"+xcrun swiftc -target "$native_arch-apple-macos14.0" "$test_output/task-verifier-tests.o" "$output/task-verifier.o" \+ -o "$test_output/task-verifier-tests"+codesign --force --options runtime --timestamp --identifier dev.opencomputeruse.locked-use.broker \+ --sign "$identity" "$test_output/task-verifier-tests"+"$test_output/task-verifier-tests" match+rm -f "$test_output/task-verifier-wrong-id"+cp "$test_output/task-verifier-tests" "$test_output/task-verifier-wrong-id"+codesign --force --options runtime --timestamp --identifier dev.opencomputeruse.locked-use.wrong \+ --sign "$identity" "$test_output/task-verifier-wrong-id"+"$test_output/task-verifier-wrong-id" reject+rm -f "$test_output/task-verifier-adhoc"+cp "$test_output/task-verifier-tests" "$test_output/task-verifier-adhoc"+codesign --force --options runtime --identifier dev.opencomputeruse.locked-use.broker --sign - "$test_output/task-verifier-adhoc"+"$test_output/task-verifier-adhoc" reject+cat > "$test_output/task-verifier-debug.plist" <<'PLIST'+<plist version="1.0"><dict><key>com.apple.security.get-task-allow</key><true/></dict></plist>+PLIST+rm -f "$test_output/task-verifier-debug"+cp "$test_output/task-verifier-tests" "$test_output/task-verifier-debug"+codesign --force --options runtime --timestamp --identifier dev.opencomputeruse.locked-use.broker \+ --entitlements "$test_output/task-verifier-debug.plist" --sign "$identity" "$test_output/task-verifier-debug"+"$test_output/task-verifier-debug" reject+echo 'Signed Broker, Guardian and remote plugin built. No system files or authorization rules changed.'++if [[ "$configuration" == debug ]]; then+fixture="$output/OCU Lock Demo (Dev).app"+mkdir -p "$fixture/Contents/MacOS"+cp "$binary_dir/OCUGuardian" "$fixture/Contents/MacOS/OCUGuardian"+cat > "$fixture/Contents/Info.plist" <<'PLIST'+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0"><dict>+<key>CFBundleIdentifier</key><string>dev.opencomputeruse.locked-use.fixture.dev</string>+<key>CFBundleExecutable</key><string>OCUGuardian</string>+<key>CFBundleName</key><string>OCU Lock Demo</string>+<key>CFBundleVersion</key><string>1</string>+<key>CFBundlePackageType</key><string>APPL</string>+<key>NSPrincipalClass</key><string>NSApplication</string>+</dict></plist>+PLIST+codesign --force --options runtime --timestamp --sign "$identity" "$fixture"++fidiff --git a/scripts/build-locked-use-guardian.sh b/scripts/build-locked-use-guardian.shnew file mode 100755index 0000000..9c5387a--- /dev/null+++ b/scripts/build-locked-use-guardian.sh@@ -0,0 +1,48 @@+#!/usr/bin/env bash+set -euo pipefail++repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+identity="-"+configuration="debug"+while [[ $# -gt 0 ]]; do+ case "$1" in+ --identity) identity="${2:?Missing signing identity}"; shift 2 ;;+ --configuration) configuration="${2:?Missing configuration}"; shift 2 ;;+ *) echo 'Usage: scripts/build-locked-use-guardian.sh [--identity ID] [--configuration debug|release]' >&2; exit 64 ;;+ esac+done+[[ "$configuration" == debug || "$configuration" == release ]] || exit 64+cd "$repo_root"+swift build -c "$configuration" --product OCUGuardian+binary_dir="$(swift build -c "$configuration" --show-bin-path)"+name="OCU Guardian (Dev)"+output="$repo_root/.build/locked-use"+if [[ "$configuration" == release ]]; then+ name="OCU Guardian"+ output="$output/release"+fi+app_path="$output/$name.app"+mkdir -p "$app_path/Contents/MacOS" "$app_path/Contents/Resources"+cp "$repo_root/assets/app-icons/open-computer-use-1024.png" "$app_path/Contents/Resources/OCUShieldLogo.png"+cp "$binary_dir/OCUGuardian" "$app_path/Contents/MacOS/OCUGuardian"+cat > "$app_path/Contents/Info.plist" <<PLIST+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0"><dict>+<key>CFBundleIdentifier</key><string>dev.opencomputeruse.locked-use.guardian.dev</string>+<key>CFBundleExecutable</key><string>OCUGuardian</string>+<key>CFBundleName</key><string>${name}</string>+<key>CFBundlePackageType</key><string>APPL</string>+<key>CFBundleVersion</key><string>1</string>+<key>CFBundleShortVersionString</key><string>0.0.1</string>+<key>LSUIElement</key><true/>+<key>NSInputMonitoringUsageDescription</key><string>Detect local takeover and relock during the Locked Use rehearsal.</string>+</dict></plist>+PLIST+if [[ "$identity" == "-" ]]; then+ codesign --force --sign - "$app_path"+else+ codesign --force --options runtime --timestamp --sign "$identity" "$app_path"+fi+codesign --verify --strict "$app_path"+printf '%s\n' "$app_path"diff --git a/scripts/build-locked-use-plugin.sh b/scripts/build-locked-use-plugin.shnew file mode 100755index 0000000..caa0fee--- /dev/null+++ b/scripts/build-locked-use-plugin.sh@@ -0,0 +1,45 @@+#!/usr/bin/env bash+set -euo pipefail+repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+if [[ "${1:-}" == "--help" ]]; then+ echo 'Usage: scripts/build-locked-use-plugin.sh [--identity <Developer ID Application identity>]'+ echo 'Build and test a deny-only ABI probe in .build/locked-use. Does not install or modify authorization rules.'+ exit 0+fi+identity="-"+if [[ $# -eq 2 && "$1" == "--identity" && -n "$2" ]]; then+ identity="$2"+elif [[ $# -ne 0 ]]; then+ echo 'Unexpected arguments; see --help.' >&2; exit 2+fi+if [[ "$(uname -s)" != Darwin ]]; then echo 'The Authorization plugin probe requires macOS.' >&2; exit 1; fi+output="${repo_root}/.build/locked-use"+bundle="${output}/OCULockProbe.bundle"+mkdir -p "${bundle}/Contents/MacOS"+xcrun clang -std=c11 -Wall -Wextra -Werror -fvisibility=hidden -mmacosx-version-min=14.0 \+ -bundle -framework Security -framework CoreFoundation \+ "${repo_root}/experiments/LockedUse/AuthorizationPlugin/Plugin.c" \+ -o "${bundle}/Contents/MacOS/OCULockProbe"+cat > "${bundle}/Contents/Info.plist" <<'PLIST'+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0"><dict>+<key>CFBundleIdentifier</key><string>dev.opencomputeruse.locked-use.authorization-probe</string>+<key>CFBundleExecutable</key><string>OCULockProbe</string>+<key>CFBundlePackageType</key><string>BNDL</string>+<key>CFBundleVersion</key><string>1</string>+<key>CFBundleShortVersionString</key><string>0.0.1</string>+<key>OCUProbeOnly</key><true/>+</dict></plist>+PLIST+sign_args=(--force --sign "${identity}")+if [[ "${identity}" != "-" ]]; then sign_args+=(--options runtime --timestamp); fi+codesign "${sign_args[@]}" "${bundle}"+codesign --verify --strict "${bundle}"+xcrun clang -std=c11 -Wall -Wextra -Werror -mmacosx-version-min=14.0 \+ -framework Security "${repo_root}/experiments/LockedUse/AuthorizationPlugin/PluginTests.c" \+ -o "${output}/plugin-abi-tests"+"${output}/plugin-abi-tests" "${bundle}/Contents/MacOS/OCULockProbe"+xcrun swiftc -framework Security "${repo_root}/experiments/LockedUse/Sources/AuthorizationProbe.swift" \+ -o "${output}/authorization-probe"+echo 'Built deny-only probe. Signing verification is not SecurityAgent Library Validation or notarization.'diff --git a/scripts/build-open-computer-use-app.sh b/scripts/build-open-computer-use-app.shindex d596b51..5df339f 100755--- a/scripts/build-open-computer-use-app.sh+++ b/scripts/build-open-computer-use-app.sh@@ -18,6 +18,7 @@ Examples:./scripts/build-open-computer-use-app.sh --configuration release --arch universalEnvironment:+ OPEN_COMPUTER_USE_APP_OUTPUT_DIR=/path/to/isolated/outputOPEN_COMPUTER_USE_CODESIGN_MODE=auto|identity|adhoc|noneOPEN_COMPUTER_USE_CODESIGN_IDENTITY="Developer ID Application: Example, Inc. (TEAMID)"OPEN_COMPUTER_USE_CODESIGN_KEYCHAIN=/path/to/signing.keychain-db@@ -211,7 +212,7 @@ codesign_app_bundle() {returnfi- local -a args=(--force --deep --sign "${identity}")+ local -a args=(--force --sign "${identity}")if [[ -n "${codesign_keychain}" && "${identity}" != "-" ]]; thenargs+=(--keychain "${codesign_keychain}")@@ -220,6 +221,16 @@ codesign_app_bundle() {if [[ "${identity}" != "-" ]]; thenargs+=(--options runtime)fi+ if [[ -n "${OPEN_COMPUTER_USE_PROVISIONING_PROFILE:-}" ]]; then+ if [[ "${identity}" == "-" ]]; then+ echo 'Keychain provisioning requires an Apple signing identity.' >&2+ exit 1+ fi+ profile_entitlements="${icon_work_dir}/keychain-entitlements.plist"+ python3 "${repo_root}/scripts/prepare-macos-keychain-profile.py" "${OPEN_COMPUTER_USE_PROVISIONING_PROFILE}" "${bundle_identifier}" "${profile_entitlements}"+ cp "${OPEN_COMPUTER_USE_PROVISIONING_PROFILE}" "${contents_dir}/embedded.provisionprofile"+ args+=(--entitlements "${profile_entitlements}")+ firun_with_codesign_keychain "${codesign_keychain}" \codesign "${args[@]}" "${app_path}" >/dev/null@@ -255,10 +266,11 @@ if [[ "${configuration}" != "release" ]]; thenapp_bundle_name="${development_app_bundle_name}"fi-app_root="${repo_root}/dist/${app_bundle_name}"-release_app_root="${repo_root}/dist/${release_app_bundle_name}"-development_app_root="${repo_root}/dist/${development_app_bundle_name}"-legacy_app_root="${repo_root}/dist/${legacy_app_bundle_name}"+app_output_dir="${OPEN_COMPUTER_USE_APP_OUTPUT_DIR:-${repo_root}/dist}"+app_root="${app_output_dir}/${app_bundle_name}"+release_app_root="${app_output_dir}/${release_app_bundle_name}"+development_app_root="${app_output_dir}/${development_app_bundle_name}"+legacy_app_root="${app_output_dir}/${legacy_app_bundle_name}"contents_dir="${app_root}/Contents"macos_dir="${contents_dir}/MacOS"resources_dir="${contents_dir}/Resources"@@ -319,6 +331,7 @@ iconutil -c icns "${iconset_dir}" -o "${resources_dir}/${bundle_icon_name}"cp "${cursor_reference_source}" "${resources_dir}/official-software-cursor-window-252.png"cp "${repo_root}/THIRD_PARTY_NOTICES.md" "${resources_dir}/THIRD_PARTY_NOTICES.md"+bundle_build_identifier="$(uuidgen)"cat > "${contents_dir}/Info.plist" <<PLIST<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">@@ -338,6 +351,8 @@ cat > "${contents_dir}/Info.plist" <<PLIST<string>${bundle_display_name}</string><key>CFBundleDisplayName</key><string>${bundle_display_name}</string>+ <key>OpenComputerUseBuildIdentifier</key>+ <string>${bundle_build_identifier}</string><key>OpenComputerUseAppVariant</key><string>${app_variant}</string><key>CFBundlePackageType</key>@@ -358,6 +373,28 @@ cat > "${contents_dir}/Info.plist" <<PLIST</plist>PLIST+if [[ "${OPEN_COMPUTER_USE_INCLUDE_LOCKED_USE:-0}" == 1 ]]; then+ if [[ "${arch_mode}" != native ]]; then+ echo 'Locked Use components currently require the native architecture build.' >&2+ exit 1+ fi+ locked_use_components="${repo_root}/.build/locked-use/components"+ guardian_component="OCU Guardian (Dev).app"+ if [[ "${app_variant}" == release ]]; then+ locked_use_components="${repo_root}/.build/locked-use/components-release"+ guardian_component="OCU Guardian.app"+ fi+ if [[ ! -x "${locked_use_components}/OCULockInstaller" ]]; then+ echo 'Build signed Locked Use components before embedding them.' >&2+ exit 1+ fi+ mkdir -p "${resources_dir}/LockedUse"+ for component in OCULockService OCULockInstaller OCULockAuth.bundle; do+ ditto "${locked_use_components}/${component}" "${resources_dir}/LockedUse/${component}"+ done+ ditto "${locked_use_components}/${guardian_component}" "${resources_dir}/LockedUse/OCU Guardian.app"+fi+plutil -lint "${contents_dir}/Info.plist" >/dev/nullcodesign_app_bundle "${app_root}"diff --git a/scripts/locked_use_report.py b/scripts/locked_use_report.pynew file mode 100644index 0000000..c3311ea--- /dev/null+++ b/scripts/locked_use_report.py@@ -0,0 +1,252 @@+"""Private diagnostic timeline. Never retain raw OS records, AX strings or images."""+import datetime+import json+import math+import os+import pathlib+import re+import subprocess+import threading+import time+import uuid++BOOL = r"(?:true|false)"+PHASE = r"(?:idle|preparing|authorizing|unlocking|active|relocking|awaitingManualUnlock)"+PATTERNS = {+ "GuardRelease": [r"release(?:Acknowledged|Retry) role=(?:main|watchdog) attempt=[1-3]"],+ "GuardianPreparation": [rf"preparing elapsedMilliseconds=[0-9]+ watchdogReady={BOOL} coverage=(?:none|topologyChanged|shieldNotVisible|shieldNotInWindowServer|shieldOwnerMismatch|shieldAlphaMismatch|shieldLayerMismatch|shieldBoundsUnavailable|activeDisplayUncovered|activeDisplayCountUnavailable|activeDisplayListUnavailable|windowListUnavailable|shieldBoundsMismatch expected=[0-9.,{{}} -]+ actual=[0-9.,{{}} -]+)"],+ "LockPresentation": [r"releaseBarrier state=(?:waitingForLock|waitingForCoverage|stabilizing|ready)"],+ "LockUIClickFilter": [r"clickAdmitted filter=(?:main|watchdog) type=(?:down|up)",+ r"clickFlags raw=[0-9]+ modifiers=[0-9]+",+ r"clickRejected filter=(?:main|watchdog) reason=(?:type|flags|window|inactive|timing|capability|source|target|sequence)"],+ "Watchdog": [r"stopping reason=(?:filterEvent|hardwareActivity|hardwareMonitorFailure|parentPipeFailed|parentHeartbeatExpired|protectionUnavailable|filterDisabled)"],+ "Broker": [rf"pluginDecision operation=(?:pluginClaim|pluginConsume|pluginFinished) result=(?:ok|waiting|denied|authorized|active|relock|release) phase={PHASE} sessionMatches={BOOL} auditUserMatches={BOOL}", rf"phase={PHASE}(?: stopReason=[A-Za-z]+)?", rf"denied operation=[A-Za-z]+ sessionMatches={BOOL} auditUserMatches={BOOL}",+ r"peerRejected endpoint=(?:agent|guardian|plugin|observer|admin)", "installationPolicyInvalidated", r"observerStage=(?:accepting|authenticated|readStarted|verified|handling|handled|persisting|persisted)", r"permitIssued maximumLifetimeSeconds=5",+ r"verificationSlow endpoint=(?:agent|guardian|plugin|observer|admin) elapsedMilliseconds=[0-9]+", r"originalClientVerificationSlow elapsedMilliseconds=[0-9]+"],+ "UnlockTrigger": [r"displayWakeReturned status=-?[0-9]+ authenticationRequested=false",+ rf"lockUISettled elapsed=[0-9.]+ notificationObserved={BOOL}",+ rf"AXProbe nodes=[0-9]+ primaryMatches=[0-9]+ fallbackMatches=[0-9]+ complete={BOOL}",+ rf"AXProbe writable={BOOL} status=-?[0-9]+", r"AXProbe fixedValueWrite status=-?[0-9]+",+ r"AXPublication attempt=[0-9]+", r"AXTrigger emptyValueWrite status=-?[0-9]+",+ r"AXPublication followup=true",+ r"AXTrigger clickTap=(?:hid|session)",+ rf"AXTrigger passwordConfirmSupported={BOOL} status=-?[0-9]+",+ r"AXTrigger passwordConfirm status=-?[0-9]+ authenticationEvidence=false",+ r"AXTrigger passwordConfirmTimeout milliseconds=[0-9]+ status=-?[0-9]+",+ r"AXTrigger passwordConfirmElapsed milliseconds=[0-9]+ status=-?[0-9]+",+ r"AXTrigger passwordConfirmDispatching=true",+ r"AXTrigger passwordConfirmSkipped=deadline",+ rf"AXTrigger annotatedClickQueued={BOOL}", r"AXTrigger annotatedClickTargetAvailable=false",+ r"AXTrigger annotatedClickWindowAvailable=false", r"AXTrigger annotatedClickWindowMatches=[0-9]+",+ rf"AXTrigger sessionClickQueued={BOOL}", r"AXTrigger sessionClickTargetAvailable=false",+ r"AXTrigger sessionClickWindowAvailable=false", r"AXTrigger sessionClickWindowMatches=[0-9]+",+ r"AXTrigger sessionClickWindowEncodingAvailable=false",+ r"AXTrigger focusedUserPress status=-?[0-9]+ authenticationEvidence=false",+ rf"AXTrigger targetedClickQueued={BOOL} authenticationEvidence=false",+ r"AXTrigger clickGeometryAvailable=false", rf"AXTrigger returnQueued={BOOL} authenticationEvidence=false",+ r"AXProbe process(?:Unavailable|SignatureRejected)=true"],+ "AuthorizationMechanism": [r"brokerTaskVerification status=-?[0-9]+", r"brokerConnect connected=[01]", r"pluginClaim replied=[01] authorizing=[01] denied=[01]", r"pluginConsume replied=[01] allowed=[01]", "mechanismInvoked", "brokerVerified", r"resultDelivered allowed=[01] status=-?[0-9]+",+ r"brokerVerification guest=-?[0-9]+ requirement=-?[0-9]+ validity=-?[0-9]+ static=-?[0-9]+ info=-?[0-9]+"],+ "AgentRecovery": ["actionDrainSubmitting", "recoveryProbeAcquireEnded",+ rf"actionDrainReply phase={PHASE} denied={BOOL}",+ rf"actionDrainDeferred brokerAvailable={BOOL} leaseAvailable={BOOL}",+ "brokerPollingFailed recoveryDeadlineArmed=true", "actionDrainRPCFailed recoveryDeadlinePending=true"],+ "NativeValidation": ["fixtureValidationStarted", r"fixtureBeforeCaptured counter=[0-9]+",+ "fixtureChanged counterIncremented=true imageChanged=true",+ rf"isolatedKeychainVerified dataProtectionIncluded={BOOL}"],+ "WatchdogBroker": ["registered"],+}+PATTERNS["Watchdog"].extend([r"stopping reason=shieldBoundsMismatch expected=[0-9.,{} -]+ actual=[0-9.,{} -]+", r"stopping reason=(?:topologyChanged|shieldNotVisible|shieldNotInWindowServer|shieldLayerMismatch|hardwareMonitorUnhealthy|inputTapDisabled|parentDisconnected)"])+PATTERNS["UnlockTrigger"].append(r"lockUIState=(?:candidateFound|candidateUnavailable|unknown) authenticationEvidence=false")+PATTERNS["Broker"].append(rf"guardLostEvidence guardianAgeMilliseconds=[0-9]+ watchdogAgeMilliseconds=[0-9]+ watchdogProtected={BOOL}")+PATTERNS["UnlockTrigger"].extend([r"AXProbe passwordUI enabledButtons=[0-9]+ disabledButtons=[0-9]+ unknownButtons=[0-9]+", rf"AXProbe passwordFocused={BOOL} status=-?[0-9]+"])++PATTERNS["UnlockTrigger"].extend(["AXTrigger returnDispatching=true keyCode=36 tap=hid", rf"AXTrigger returnPairQueued={BOOL} authenticationEvidence=false"])++PATTERNS["LockUIClickFilter"].extend([r"returnAdmitted filter=(?:main|watchdog) type=(?:down|up)", r"returnRejected filter=(?:main|watchdog) reason=(?:inactive|timing|capability|source|target|key|sequence)"])++# Normalize markers into enums; never retain the surrounding user/context text.+SYSTEM_MARKERS = {+ "loginwindow": [+ ("loginPressed", "localSubmitObserved"),+ ("return in secure textfield", "secureReturnObserved"),+ ("authBegan", "localAuthenticationBegan"),+ ("_authCopyRightsWithUsername", "loginwindowRightsRequested"),+ ("APEventTouchIDMatch", "touchIDMatchObserved"),+ ("evaluatePolicy", "localAuthenticationEvaluationObserved"),+ ("askForPasswordSecAgent", "securityAgentUIRequested"),+ ("Screensaver authorization succeeded", "screensaverAuthorizationSucceeded"),+ ("Unlock succeeded", "sessionUnlockReported"),+ ("did NOT unlock the user's keychain", "keychainUnlockSkipped"),+ ("SecKeychainLogin failed", "keychainLoginFailed"),+ ("attempting to unlock with empty might rekey", "emptyInputKeychainPathObserved"),+ ],+}+LOG_PREDICATE = ('subsystem == "dev.opencomputeruse.locked-use" OR process == "loginwindow" '+ 'OR process == "authd" OR process == "SecurityAgentHelper-arm64" '+ 'OR process == "SecurityAgentHelper-x86_64"')+++def curate(records, started):+ events = []+ if not isinstance(records, list): return events+ for entry in records[:2000]:+ if not isinstance(entry, dict): continue+ if not all(isinstance(entry.get(key, ""), str) for key in ["processImagePath", "category", "eventMessage", "timestamp"]): continue+ process = pathlib.Path(entry.get("processImagePath", "")).name+ try: timestamp = datetime.datetime.fromisoformat(entry["timestamp"]).timestamp()+ except (KeyError, ValueError, OverflowError): continue+ if not math.isfinite(timestamp) or timestamp < started: continue+ def emit(category, message):+ events.append({"elapsedSeconds": round(timestamp-started, 3), "category": category, "message": message})+ message = entry["eventMessage"]+ if process == "authd":+ if "system.login.screensaver" in message:+ action = "systemRightSucceeded" if "Succeeded authorizing right" in message else "systemRightFailed" if "Failed authorizing right" in message else "systemRightEvaluationObserved" if "evaluates" in message and "rights" in message else None+ if action: emit("SystemAuthorization", action)+ if any(name in message for name in ("running mechanism OCULockAuth:remote",+ "running mechanism OpenComputerUseLockedUseAuthorizationPlugin:remote")):+ emit("SystemAuthorization", "remoteMechanismRunning")+ continue+ if process in SYSTEM_MARKERS:+ for marker, action in SYSTEM_MARKERS[process]:+ if marker in message: emit("LoginWindow", action)+ continue+ if process in {"SecurityAgentHelper-arm64", "SecurityAgentHelper-x86_64"}:+ emit("SecurityAgentHost", "helperActivityObserved")+ if process not in {"OpenComputerUse", "OCUGuardian", "OCULockService",+ "OpenComputerUseGuardian", "OpenComputerUseLockedUseBroker",+ "SecurityAgentHelper-arm64", "SecurityAgentHelper-x86_64"}: continue+ category = entry.get("category", "")+ message = entry.get("eventMessage", "")+ if not any(re.fullmatch(pattern, message) for pattern in PATTERNS.get(category, [])): continue+ emit(category, message)+ return events+++def authentication_windows(events):+ """Keep manual recovery outside the permit window. Silence is not absence."""+ windows = []+ current = None+ for event in sorted(events, key=lambda item: item["elapsedSeconds"]):+ message = event["message"]+ if event["category"] == "Broker" and message == "phase=authorizing stopReason=none":+ # Streaming and historical logs may report the same transition with+ # slightly different timestamps. A repeated phase is not a new lease.+ if current: continue+ current = {"startedAt": event["elapsedSeconds"], "endedAt": None,+ "permitIssuedObservedAt": None, "rightEvaluationObserved": False, "mechanismObserved": False,+ "allowObserved": False, "localAuthenticationObserved": False}+ windows.append(current)+ elif event["category"] == "Broker" and message.split(" ")[0] in {+ "phase=relocking", "phase=awaitingManualUnlock", "phase=idle"} and current:+ current["endedAt"] = event["elapsedSeconds"]+ current = None+ if current:+ if event["category"] == "Broker" and message == "permitIssued maximumLifetimeSeconds=5":+ if current["permitIssuedObservedAt"] is None: current["permitIssuedObservedAt"] = event["elapsedSeconds"]+ if event["category"] == "SystemAuthorization" and message in {+ "systemRightEvaluationObserved", "systemRightSucceeded", "systemRightFailed"}:+ current["rightEvaluationObserved"] = True+ if message in {"mechanismInvoked", "remoteMechanismRunning"}:+ current["mechanismObserved"] = True+ if message == "resultDelivered allowed=1 status=0": current["allowObserved"] = True+ if event["category"] == "LoginWindow" and message in {+ "localSubmitObserved", "touchIDMatchObserved", "localAuthenticationEvaluationObserved"}:+ current["localAuthenticationObserved"] = True+ return windows+++class LiveAuthenticationTrace:+ """Read debug logs before a lock; retain bounded enums in memory only.++ This collector never invokes authentication or holds protection. A broken+ stream is diagnostic only, never permission to unlock or remove a shield.+ """+ def __init__(self, started, max_seconds=150):+ self.started = started+ self.max_seconds = max_seconds+ self.events = []+ self.process = None+ self.thread = None+ self.stop = threading.Event()+ self.status = "unavailable"++ def start(self):+ try:+ self.process = subprocess.Popen(["/usr/bin/log", "stream", "--level", "debug",+ "--style", "ndjson", "--predicate", LOG_PREDICATE],+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)+ except OSError: return+ self.status = "started"+ self.thread = threading.Thread(target=self._read, daemon=True)+ self.thread.start()++ def _read(self):+ import select+ deadline = time.monotonic() + self.max_seconds+ buffer = b""+ discarding = False+ try:+ while not self.stop.is_set() and time.monotonic() < deadline:+ ready, _, _ = select.select([self.process.stdout], [], [], 0.2)+ if not ready: continue+ chunk = os.read(self.process.stdout.fileno(), 16384)+ if not chunk:+ self.status = "stopped" if self.stop.is_set() else "ended"+ return+ self.status = "receiving"+ for part in chunk.splitlines(keepends=True):+ ended = part.endswith(b"\n")+ if not discarding: buffer += part+ if len(buffer) > 65536:+ buffer = b""+ discarding = True+ if ended:+ if not discarding:+ try: record = json.loads(buffer)+ except (ValueError, UnicodeError): record = None+ if len(self.events) < 2000:+ self.events.extend(curate([record], self.started)[:2000-len(self.events)])+ buffer = b""+ discarding = False+ if not self.stop.is_set(): self.status = "deadlineReached"+ except (OSError, ValueError): self.status = "readFailed"+ finally:+ if self.process.poll() is None: self.process.terminate()++ def finish(self):+ self.stop.set()+ if self.process and self.process.poll() is None: self.process.terminate()+ if self.thread: self.thread.join(timeout=1)+ if self.process:+ try: self.process.wait(timeout=1)+ except subprocess.TimeoutExpired:+ self.process.kill() # Only this read-only collector.+ self.process.wait(timeout=1)+ if self.process.stdout: self.process.stdout.close()+ return list(self.events), self.status+++def write_report(root, started, events, error=None, live_events=None, trace_status="notStarted"):+ records = []+ try:+ result = subprocess.run(["/usr/bin/log", "show", "--last", f"{math.ceil(time.time()-started)+2}s",+ "--style", "json", "--predicate", LOG_PREDICATE],+ capture_output=True, timeout=5, check=True)+ if len(result.stdout) <= 4*1024*1024: records = json.loads(result.stdout)+ except (OSError, subprocess.SubprocessError, ValueError): pass+ timeline = curate(records, started) + (live_events or [])+ timeline = sorted({(event["elapsedSeconds"], event["category"], event["message"]): event+ for event in timeline}.values(), key=lambda item: item["elapsedSeconds"])+ payload = {"schemaVersion": 2, "diagnosticOnly": True, "productionEvidenceEligible": False,+ "elapsedSeconds": round(time.time()-started, 3), "controllerEvents": events,+ "systemEvents": timeline, "failureType": error,+ "liveTraceStatus": trace_status, "missingEventsProveAbsence": False,+ "authorizationWindows": authentication_windows(timeline)}+ directory = pathlib.Path(root)/".build/locked-use/reports"+ directory.mkdir(parents=True, exist_ok=True, mode=0o700)+ path = directory/(uuid.uuid4().hex+".json")+ descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)+ with os.fdopen(descriptor, "w") as output: json.dump(payload, output, ensure_ascii=False, indent=2)+ return pathdiff --git a/scripts/manage-locked-use-probe.sh b/scripts/manage-locked-use-probe.shnew file mode 100755index 0000000..c63c87d--- /dev/null+++ b/scripts/manage-locked-use-probe.sh@@ -0,0 +1,96 @@+#!/usr/bin/env bash+# Isolated deny-only right; NEVER writes system.login.screensaver.+set -euo pipefail+repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+right='dev.opencomputeruse.locked-use.preflight'+plugin_name='OCULockProbe'+plugin_id='dev.opencomputeruse.locked-use.authorization-probe'+plugins='/Library/Security/SecurityAgentPlugins'+destination="${plugins}/${plugin_name}.bundle"+usage() {+ echo 'Usage: scripts/manage-locked-use-probe.sh install|uninstall'+ echo 'Requires administrator execution. Registers ONLY an independent deny-only diagnostic right.'+ echo 'Build with --identity before install; reads no credentials and never modifies system.login.screensaver.'+}+if [[ "${1:-}" == '--help' ]]; then usage; exit 0; fi+if [[ $# -ne 1 || ( "$1" != 'install' && "$1" != 'uninstall' ) ]]; then usage >&2; exit 2; fi+if [[ "$(uname -s)" != Darwin ]]; then echo 'macOS required.' >&2; exit 1; fi+if [[ "$(id -u)" != 0 ]]; then echo 'Run this reviewed script with sudo; administrator privileges are required.' >&2; exit 1; fi+# A root-owned scratch directory, not a predictable /tmp file.+scratch="$(mktemp -d /private/var/tmp/ocu-auth-probe.XXXXXX)"+staging=''+cleanup() {+ if [[ -n "${staging}" ]]; then rm -rf "${staging}"; fi+ rm -rf "${scratch}"+}+trap cleanup EXIT++if [[ "$1" == 'uninstall' ]]; then+ staged_copy="${plugins}/StagedPlugins/${plugin_name}.bundle"+ for candidate in "${destination}" "${staged_copy}"; do+ if [[ -e "${candidate}" ]]; then+ installed_id="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "${candidate}/Contents/Info.plist")"+ if [[ "${installed_id}" != "${plugin_id}" ]]; then echo 'Bundle identity changed; refusing removal.' >&2; exit 1; fi+ fi+ done+ if /usr/bin/security authorizationdb read "${right}" > "${scratch}/current.plist" 2> "${scratch}/read-error"; then+ /usr/bin/python3 - "${scratch}/current.plist" <<'PY'+import plistlib, sys+with open(sys.argv[1], 'rb') as stream:+ rule = plistlib.load(stream)+if rule.get('class') != 'evaluate-mechanisms' or rule.get('mechanisms') != ['OCULockProbe:preflight']:+ sys.exit('The probe right has changed; refusing to remove another configuration.')+PY+ /usr/bin/security authorizationdb remove "${right}"+ elif [[ "$(cat "${scratch}/read-error")" != *'-60005'* ]]; then+ cat "${scratch}/read-error" >&2; exit 1+ fi+ for candidate in "${destination}" "${staged_copy}"; do+ if [[ -e "${candidate}" ]]; then rm -rf "${candidate}"; fi+ done+ echo 'Removed diagnostic right and probe bundle. Screensaver rules were not modified.'+ exit 0+fi++source_bundle="${repo_root}/.build/locked-use/${plugin_name}.bundle"+if [[ ! -d "${source_bundle}" ]]; then echo 'Build the signed probe first; see docs/locked-use.md.' >&2; exit 1; fi+if [[ -e "${destination}" ]]; then echo 'Probe destination already exists; uninstall the reviewed previous probe first.' >&2; exit 1; fi+if /usr/bin/security authorizationdb read "${right}" > "${scratch}/existing.plist" 2> "${scratch}/read-error"; then+ echo 'Probe right already exists; refusing to overwrite it.' >&2; exit 1+elif [[ "$(cat "${scratch}/read-error")" != *'-60005'* ]]; then+ cat "${scratch}/read-error" >&2; exit 1+fi+mkdir -p "${plugins}"+staging="$(mktemp -d "${plugins}/.ocu-auth-probe.XXXXXX")"+/usr/bin/ditto "${source_bundle}" "${staging}/${plugin_name}.bundle"+staged_bundle="${staging}/${plugin_name}.bundle"+/usr/bin/codesign --verify --strict -R "=identifier \"${plugin_id}\" and anchor apple generic" "${staged_bundle}"+signature="$(/usr/bin/codesign -dv --verbose=4 "${staged_bundle}" 2>&1)"+if [[ "${signature}" != *'Authority=Developer ID Application:'* ]]; then+ echo 'A Developer ID Application signature is required; ad-hoc and development probes cannot be installed by this script.' >&2; exit 1+fi+if [[ "$(/usr/libexec/PlistBuddy -c 'Print :OCUProbeOnly' "${staged_bundle}/Contents/Info.plist")" != true ]]; then+ echo 'Not a diagnostic probe bundle.' >&2; exit 1+fi+chown -R root:wheel "${staged_bundle}"+chmod -R go-w "${staged_bundle}"+mv "${staged_bundle}" "${destination}"+cat > "${scratch}/right.plist" <<'PLIST'+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0"><dict>+<key>class</key><string>evaluate-mechanisms</string>+<key>mechanisms</key><array><string>OCULockProbe:preflight</string></array>+<key>shared</key><false/>+<key>timeout</key><integer>0</integer>+<key>tries</key><integer>1</integer>+<key>comment</key><string>OCU isolated deny-only ABI probe; never grants session unlock.</string>+</dict></plist>+PLIST+if ! /usr/bin/security authorizationdb write "${right}" < "${scratch}/right.plist"; then+ rm -rf "${destination}"+ echo 'Right registration failed; removed staged probe bundle.' >&2+ exit 1+fi+echo 'Installed ONLY the diagnostic right. Run .build/locked-use/authorization-probe as your ordinary GUI user.'+echo 'A denied return is expected; confirm the plugin marker in unified logs before claiming loading succeeded.'diff --git a/scripts/node-repl/open-computer-use-cli.mjs b/scripts/node-repl/open-computer-use-cli.mjsindex 0b88af6..d085910 100644--- a/scripts/node-repl/open-computer-use-cli.mjs+++ b/scripts/node-repl/open-computer-use-cli.mjs@@ -126,6 +126,7 @@ Commands:config View or persist macOS screenshot settings.capabilities Report Node, adapter, native, js, and repl availability.doctor Print permission status and launch onboarding if needed on macOS.+ locked-use macOS status, settings, enable, disable, or recovery.list-apps Print running or recently used apps.snapshot <app> Print the current accessibility snapshot for an app.call <tool> Call one tool, or run a JSON array of tool calls.diff --git a/scripts/node-repl/open-computer-use-repl.mjs b/scripts/node-repl/open-computer-use-repl.mjsindex 7d101d8..6fb1dfa 100755--- a/scripts/node-repl/open-computer-use-repl.mjs+++ b/scripts/node-repl/open-computer-use-repl.mjs@@ -96,18 +96,39 @@ function normalizeImage(value) {export class JsonLinePeer extends EventEmitter {constructor({ command, args = [], cwd, env = process.env, child } = {}) {super();- this.child = child ?? spawn(command, args, { cwd, env, stdio: ["pipe", "pipe", "pipe"] });+ this.options = { command, args, cwd, env };+ this.injected = Boolean(child);+ this.disposed = false;+ this.reopening = null;+ this.#start(child ?? spawn(command, args, { cwd, env, stdio: ["pipe", "pipe", "pipe"] }));+ }++ #start(child) {+ this.child = child;this.nextId = 1;this.pending = new Map();this.buffer = "";this.stderr = "";this.closed = false;- this.child.stdout.setEncoding("utf8");- this.child.stderr.setEncoding("utf8");- this.child.stdout.on("data", chunk => this.#onData(chunk));- this.child.stderr.on("data", chunk => { this.stderr = (this.stderr + chunk).slice(-8192); });- this.child.on("error", error => this.#close(error));- this.child.on("exit", (code, signal) => this.#close(new Error(`native MCP exited (code=${code ?? "null"}, signal=${signal ?? "null"})${this.stderr ? `: ${this.stderr.trim()}` : ""}`)));+ child.stdout.setEncoding("utf8");+ child.stderr.setEncoding("utf8");+ child.stdout.on("data", chunk => { if (this.child === child) this.#onData(chunk); });+ child.stderr.on("data", chunk => { if (this.child === child) this.stderr = (this.stderr + chunk).slice(-8192); });+ child.on("error", error => { if (this.child === child) this.#close(error); });+ child.on("exit", (code, signal) => {+ if (this.child === child) this.#close(new Error(`native MCP exited (code=${code ?? "null"}, signal=${signal ?? "null"})${this.stderr ? `: ${this.stderr.trim()}` : ""}`));+ });+ }++ #reopen() {+ if (!this.reopening) {+ this.reopening = (async () => {+ const { command, args, cwd, env } = this.options;+ this.#start(spawn(command, args, { cwd, env, stdio: ["pipe", "pipe", "pipe"] }));+ await this.initialize();+ })().catch(error => { this.endSession(); throw error; }).finally(() => { this.reopening = null; });+ }+ return this.reopening;}#onData(chunk) {@@ -142,11 +163,17 @@ export class JsonLinePeer extends EventEmitter {}request(method, params = {}, timeoutMs = DEFAULT_TIMEOUT_MS) {+ if (this.reopening && method !== "initialize") return this.reopening.then(() => this.request(method, params, timeoutMs));+ if (this.closed && !this.injected && !this.disposed) return this.#reopen().then(() => this.request(method, params, timeoutMs));if (this.closed) return Promise.reject(new Error("native MCP is closed"));const id = this.nextId++;return new Promise((resolve, reject) => {const timer = timeoutMs > 0- ? setTimeout(() => { this.pending.delete(String(id)); reject(new Error(`native MCP ${method} timed out after ${timeoutMs} ms`)); }, timeoutMs)+ ? setTimeout(() => {+ this.pending.delete(String(id));+ reject(new Error(`native MCP ${method} timed out after ${timeoutMs} ms`));+ this.endSession();+ }, timeoutMs): undefined;this.pending.set(String(id), { resolve, reject, timer });this.child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`, error => {@@ -172,13 +199,21 @@ export class JsonLinePeer extends EventEmitter {return result;}- close() {+ endSession() {if (this.closed) return;- this.child.stdin.end();- const timer = setTimeout(() => this.child.kill("SIGKILL"), 1_000);+ const child = this.child;+ this.#close(new Error("native Computer Use session ended"));+ child.stdin.end();+ const timer = setTimeout(() => child.kill("SIGKILL"), 1_000);timer.unref();- this.child.kill("SIGTERM");+ child.kill("SIGTERM");}++ close() {+ this.disposed = true;+ this.endSession();+ }+}function toolResultText(result) {@@ -469,6 +504,7 @@ export class WorkerJavaScriptSession {this.nextId = 1;this.pending = new Map();this.runQueue = Promise.resolve();+ this.invalidatedWorkers = new WeakSet();this.#start();}@@ -476,11 +512,18 @@ export class WorkerJavaScriptSession {const worker = new Worker(new URL("./open-computer-use-kernel.mjs", import.meta.url));this.worker = worker;worker.on("message", message => void this.#onMessage(worker, message));- worker.on("error", error => this.#failWorker(worker, error));+ worker.on("error", error => {+ if (this.worker === worker && !this.invalidatedWorkers.has(worker)) {+ this.invalidatedWorkers.add(worker);+ this.native.endSession?.();+ }+ this.#failWorker(worker, error);+ });worker.on("exit", code => { if (code !== 0) this.#failWorker(worker, new Error(`JavaScript kernel exited with code ${code}`)); });}async #onMessage(worker, message) {+ if (this.worker !== worker || this.invalidatedWorkers.has(worker)) return;if (message.type === "result") {const pending = this.pending.get(message.id);if (!pending || pending.worker !== worker) return;@@ -510,6 +553,8 @@ export class WorkerJavaScriptSession {async reset() {const old = this.worker;+ this.invalidatedWorkers.add(old);+ this.native.endSession?.();this.#failWorker(old, new Error("JavaScript session reset"));await old.terminate();if (this.worker === old) this.#start();@@ -517,6 +562,8 @@ export class WorkerJavaScriptSession {async close() {const old = this.worker;+ this.invalidatedWorkers.add(old);+ this.native.endSession?.();this.#failWorker(old, new Error("JavaScript session closed"));await old.terminate();}@@ -535,6 +582,8 @@ export class WorkerJavaScriptSession {const pending = this.pending.get(id);if (!pending || pending.worker !== worker) return;this.pending.delete(id);+ this.invalidatedWorkers.add(worker);+ this.native.endSession?.();await worker.terminate();if (this.worker === worker) this.#start();resolve({ content: [{ type: "text", text: `Error: js execution timed out after ${timeoutMs} ms; session reset` }], isError: true });@@ -588,7 +637,7 @@ export async function runServer({ command, args }) {try { request = JSON.parse(line); } catch { return send({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Invalid JSON-RPC payload" } }); }const { id, method, params = {} } = request;if (id === undefined) {- if (method === "notifications/turn-ended") native.notify(method, params);+ if (method === "notifications/turn-ended") { native.notify(method, params); native.endSession(); }return;}try {diff --git a/scripts/node-repl/open-computer-use-repl.test.mjs b/scripts/node-repl/open-computer-use-repl.test.mjsindex 62ad87d..fcea8a6 100644--- a/scripts/node-repl/open-computer-use-repl.test.mjs+++ b/scripts/node-repl/open-computer-use-repl.test.mjs@@ -246,6 +246,68 @@ test("worker session serializes concurrent callers", async () => {await session.close();});+test("native session end rejects pending work and initializes a fresh child without replay", async () => {+ const source = `+ let buffer = '';+ process.stdin.setEncoding('utf8');+ process.stdin.on('data', chunk => {+ buffer += chunk;+ for (;;) {+ const end = buffer.indexOf('\\n'); if (end < 0) break;+ const request = JSON.parse(buffer.slice(0, end)); buffer = buffer.slice(end + 1);+ if (request.id === undefined || request.method === 'stall') continue;+ process.stdout.write(JSON.stringify({jsonrpc:'2.0', id:request.id, result:{pid:process.pid}}) + '\\n');+ }+ });+ `;+ const peer = new JsonLinePeer({ command: process.execPath, args: ["--input-type=module", "-e", source] });+ try {+ const first = await peer.initialize();+ const old = peer.child;+ const pending = peer.request("stall", {}, 5_000);+ const rejected = assert.rejects(pending, /session ended/);+ peer.endSession();+ await rejected;+ const next = await peer.request("ping", {}, 5_000);+ assert.notEqual(next.pid, first.pid);+ old.emit("exit", 1, null);+ assert.equal(peer.closed, false);+ await assert.rejects(peer.request("stall", {}, 20), /timed out/);+ assert.equal(peer.closed, true);+ const recovered = await peer.request("ping", {}, 5_000);+ assert.notEqual(recovered.pid, next.pid);+ } finally { peer.close(); }+});++test("worker reset and timeout end the native GUI lease", async () => {+ const native = mockNative();+ let ended = 0;+ native.endSession = () => { ended += 1; };+ const session = new WorkerJavaScriptSession({ native });+ try {+ await session.reset();+ assert.equal(ended, 1);+ const result = await session.run("while (true) {}", 100);+ assert.equal(result.isError, true);+ assert.equal(ended, 2);+ } finally { await session.close(); }+});+++test("reset drops old worker native requests before a replacement kernel starts", async () => {+ const native = mockNative();+ const session = new WorkerJavaScriptSession({ native });+ try {+ const old = session.worker;+ const resetting = session.reset();+ old.emit("message", { type: "native_request", id: 1, method: "tools/call", params: { name: "click", arguments: {} } });+ await resetting;+ assert.equal(native.calls.length, 0);+ old.emit("message", { type: "native_request", id: 2, method: "tools/call", params: { name: "click", arguments: {} } });+ assert.equal(native.calls.length, 0);+ } finally { await session.close(); }+});+test("lightweight app binding queries and acts across persistent JS calls without a snapshot", async () => {const native = mockNative();const request = native.request;diff --git a/scripts/prepare-macos-keychain-profile.py b/scripts/prepare-macos-keychain-profile.pynew file mode 100644index 0000000..aedf47b--- /dev/null+++ b/scripts/prepare-macos-keychain-profile.py@@ -0,0 +1,53 @@+#!/usr/bin/env python3+"""Prepare narrowly scoped Keychain entitlements from a macOS profile.++OS code-signature/profile validation remains authoritative at launch. This+build-time check refuses mismatched, expired and debugging-enabled profiles.+It never copies private certificate keys or unrelated profile entitlements.+"""+import argparse+import datetime+import pathlib+import plistlib+import subprocess+++def entitlements(profile, bundle_id, now=None):+ now = now or datetime.datetime.now(datetime.timezone.utc)+ expiry = profile.get("ExpirationDate")+ claims = profile.get("Entitlements", {})+ team = claims.get("com.apple.developer.team-identifier", "")+ app_id = claims.get("com.apple.application-identifier", "")+ if not isinstance(expiry, datetime.datetime):+ raise ValueError("Profile expiry is missing")+ expiry = expiry.replace(tzinfo=datetime.timezone.utc) if expiry.tzinfo is None else expiry+ if ("OSX" not in profile.get("Platform", []) or expiry <= now+ or claims.get("get-task-allow", False)+ or claims.get("com.apple.security.get-task-allow", False)+ or len(team) != 10 or not team.isascii() or not team.isalnum()+ or team not in profile.get("TeamIdentifier", [])+ or app_id not in (team + "." + bundle_id, team + ".*")):+ raise ValueError("Use a valid non-debug macOS profile matching this bundle")+ exact = team + "." + bundle_id+ groups = claims.get("keychain-access-groups", [])+ if exact not in groups and team + ".*" not in groups:+ raise ValueError("Profile does not authorize the app's own Keychain group")+ return {"com.apple.application-identifier": exact,+ "com.apple.developer.team-identifier": team,+ "keychain-access-groups": [exact]}+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("profile")+ parser.add_argument("bundle_id")+ parser.add_argument("output")+ args = parser.parse_args()+ decoded = subprocess.run(["/usr/bin/security", "cms", "-D", "-i", args.profile],+ capture_output=True, check=True).stdout+ result = entitlements(plistlib.loads(decoded), args.bundle_id)+ pathlib.Path(args.output).write_bytes(plistlib.dumps(result))+++if __name__ == "__main__":+ main()diff --git a/scripts/run-locked-use-native-validation.py b/scripts/run-locked-use-native-validation.pynew file mode 100644index 0000000..c0d3ed1--- /dev/null+++ b/scripts/run-locked-use-native-validation.py@@ -0,0 +1,270 @@+#!/usr/bin/env python3+"""Supervised real unlock test. Never print screenshots or Keychain contents.++Run --prepare-only first. --confirm-lock-test locks the current session, invokes+the fixed signed native AX/SCK probe, holds the lease, ends it and waits for+manual unlock. Do not terminate Guardian/watchdog on a failed transaction.+"""+import argparse+import json+import os+import pathlib+import select+import subprocess+import sys+import time+import uuid+from locked_use_report import LiveAuthenticationTrace, write_report+++class RPC:+ def __init__(self, binary):+ environment = dict(os.environ)+ # A previous test agent may survive a rebuild at the same bundle path.+ # A fresh namespace ensures this run executes the freshly signed code.+ environment["OPEN_COMPUTER_USE_AGENT_SOCKET_NAMESPACE"] = "locked-use-native-validation-" + uuid.uuid4().hex+ environment["OPEN_COMPUTER_USE_VISUAL_CURSOR"] = "0"+ self.process = subprocess.Popen([str(binary), "mcp"], env=environment,+ stdin=subprocess.PIPE, stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL)+ self.buffer = b""+ self.sequence = 0+ self.call("initialize", {"protocolVersion": "2024-11-05", "capabilities": {},+ "clientInfo": {"name": "locked-use-native-validation", "version": "1"}})++ def notify(self, method):+ self.send({"jsonrpc": "2.0", "method": method})++ def send(self, message):+ self.process.stdin.write(json.dumps(message).encode() + b"\n")+ self.process.stdin.flush()++ def call(self, method, params=None, timeout=10):+ self.sequence += 1+ identifier = self.sequence+ self.send({"jsonrpc": "2.0", "id": identifier, "method": method, "params": params or {}})+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ while b"\n" in self.buffer:+ line, self.buffer = self.buffer.split(b"\n", 1)+ response = json.loads(line)+ if response.get("id") == identifier:+ if "error" in response:+ raise RuntimeError(response["error"].get("message", "Native RPC failed"))+ return response.get("result")+ ready, _, _ = select.select([self.process.stdout], [], [], min(1, max(0, deadline-time.monotonic())))+ if ready:+ chunk = os.read(self.process.stdout.fileno(), 65536)+ if not chunk: raise RuntimeError("Native validation connection closed")+ self.buffer += chunk+ if len(self.buffer) > 8*1024*1024: raise RuntimeError("Native response exceeded bound")+ raise TimeoutError("Native validation response timed out")++ def close(self):+ if self.process.stdin and not self.process.stdin.closed:+ try: self.process.stdin.close()+ except BrokenPipeError: pass+ try: self.process.wait(timeout=5)+ except subprocess.TimeoutExpired: self.process.terminate()+++def session(guardian, timeout=3):+ result = subprocess.run([str(guardian), "--session-only"], capture_output=True, timeout=timeout, check=True)+ for line in result.stdout.splitlines():+ value = json.loads(line)+ if value.get("event") == "sessionState": return value["session"]+ raise RuntimeError("Native session observation unavailable")+++def wait_for(guardian, state, timeout=15):+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if session(guardian) == state: return+ time.sleep(0.2)+ raise TimeoutError("Did not observe original session " + state)+++def wait_for_release(rpc, timeout=8):+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if rpc.call("ocu/locked-use/protection-released", timeout=min(2, deadline-time.monotonic()))["passed"]: return+ time.sleep(0.1)+ raise TimeoutError("Both protection release acknowledgments were not observed")+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ mode = parser.add_mutually_exclusive_group(required=True)+ mode.add_argument("--prepare-only", action="store_true")+ mode.add_argument("--confirm-lock-test", action="store_true")+ mode.add_argument("--unlocked-fixture-test", action="store_true")+ mode.add_argument("--observe-auth-only", action="store_true", help="Read normalized authentication logs only; never lock, submit credentials or acquire a permit")+ mode.add_argument("--confirm-recovery-test", action="store_true", help="Lock once and verify both guards drain, without issuing an unlock permit")+ mode.add_argument("--confirm-wake-test", action="store_true", help="Validate protected unlock then immediately relock; no GUI/Keychain operations")+ parser.add_argument("--wait-for-manual-unlock", action="store_true", help="Observe normal user unlock without an interactive continue prompt")+ parser.add_argument("--keep-fixture", action="store_true", help="After successful validation and cleanup, leave the Increment Counter window open for recording; quit it manually afterward")+ parser.add_argument("--legacy-only", action="store_true", help="Does not produce production validation evidence")+ parser.add_argument("--hold-seconds", type=int, default=15, choices=range(0, 21))+ parser.add_argument("--fast", action="store_true", help="Relock immediately after the fixed AX/SCK validation")+ parser.add_argument("--observe-seconds", type=int, default=30, choices=range(5, 61))+ args = parser.parse_args()+ if args.fast: args.hold_seconds = 0+ run_started = time.time()+ events = []+ failure = None+ def record(event, **details):+ value = {"event": event, "elapsedSeconds": round(time.time()-run_started, 3), **details}+ events.append(value)+ print(json.dumps(value), flush=True)+ root = pathlib.Path(__file__).resolve().parent.parent+ if args.observe_auth_only:+ trace = LiveAuthenticationTrace(run_started, max_seconds=args.observe_seconds)+ trace.start()+ record("authenticationObserverStarted", authenticationRequested=False, lockRequested=False)+ try:+ time.sleep(args.observe_seconds)+ finally:+ live_events, trace_status = trace.finish()+ report = write_report(root, run_started, events, live_events=live_events, trace_status=trace_status)+ record("diagnosticReportSaved", path=str(report), traceStatus=trace_status)+ return+ binary = root / "dist/Open Computer Use (Dev).app/Contents/MacOS/OpenComputerUse"+ components = root / ".build/locked-use/components"+ guardian = components / "OCU Guardian (Dev).app/Contents/MacOS/OCUGuardian"+ fixture_binary = components / "OCU Lock Demo (Dev).app/Contents/MacOS/OCUGuardian"+ if session(guardian, timeout=15) != "unlocked": raise RuntimeError("Unlock normally before starting validation")+ rpc = RPC(binary)+ fixture = None+ locked = False+ completed = False+ trace = LiveAuthenticationTrace(run_started)+ trace.start()+ try:+ if args.confirm_lock_test or args.confirm_recovery_test or args.confirm_wake_test:+ if not rpc.call("ocu/locked-use/ready", timeout=5)["passed"]:+ raise RuntimeError("Broker has not observed a normal unlock and released protection; no lock test started")+ record("brokerReady", passed=True)+ if args.confirm_recovery_test or args.confirm_wake_test:+ print("Locking in 5 seconds; recovery-only." if args.confirm_recovery_test else+ "Locking in 5 seconds; protected waiting up to 20 seconds, then relock. Stay still until countdown ends.", flush=True)+ time.sleep(5)+ subprocess.run([str(guardian), "--request-lock"], check=True, stdout=subprocess.DEVNULL, timeout=3)+ locked = True+ wait_for(guardian, "locked", timeout=5)+ record("lockedObserved")+ started = time.monotonic()+ method = "ocu/locked-use/validate-recovery" if args.confirm_recovery_test else "ocu/locked-use/validate-unlock"+ assert rpc.call(method, timeout=24)["passed"]+ if args.confirm_wake_test:+ record("protectedUnlockObserved", acquisitionSeconds=round(time.monotonic()-started, 3), guiActionsPerformed=False)+ rpc.notify("notifications/turn-ended")+ wait_for(guardian, "locked", timeout=5)+ wait_for_release(rpc)+ record("bothGuardsReleased", passed=True)+ completed = True+ record("bothGuardsRecoveryPassed" if args.confirm_recovery_test else "relockObserved",+ transactionSeconds=round(time.monotonic()-started, 3), unlockPermitIssued=args.confirm_wake_test, guiActionsPerformed=False)+ if args.wait_for_manual_unlock:+ # Both guards have released; retain only diagnostic observation.+ wait_for(guardian, "unlocked", timeout=60)+ record("manualUnlockObserved", passed=True, guiActionsPerformed=False)+ return+ prepare = "prepare-legacy" if args.legacy_only else "prepare"+ result = rpc.call("ocu/locked-use/keychain/" + prepare)+ assert result["passed"] and result["existingItemsRead"] is False+ record("isolatedKeychainPrepared", dataProtectionIncluded=not args.legacy_only)+ if args.prepare_only:+ assert rpc.call("ocu/locked-use/keychain/cleanup")["passed"]+ completed = True+ return+ # A retained demo must survive the runner's process-group cleanup,+ # without inheriting its input stream. It remains the same AX target.+ fixture = subprocess.Popen([str(fixture_binary), "--external-fixture"],+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL, start_new_session=args.keep_fixture)+ rpc.call("tools/call", {"name": "get_app_state", "arguments": {"app": "dev.opencomputeruse.locked-use.fixture.dev"}})+ if args.unlocked_fixture_test:+ assert rpc.call("ocu/locked-use/validate-unlocked")["passed"]+ assert rpc.call("ocu/locked-use/keychain/cleanup")["passed"]+ completed = True+ print(json.dumps({"event": "unlockedRealAXSCKPassed", "unlockRequested": False}), flush=True)+ return+ print("Locking in 5 seconds. Leave mouse and keyboard still.", flush=True)+ time.sleep(5)+ subprocess.run([str(guardian), "--request-lock"], check=True, stdout=subprocess.DEVNULL, timeout=3)+ locked = True+ wait_for(guardian, "locked", timeout=5)+ record("lockedObserved")+ result = rpc.call("ocu/locked-use/validate", timeout=28)+ assert result["passed"]+ record("protectedNativeAXSCKKeychainPassed", dataProtectionIncluded=not args.legacy_only)+ record("protectedHoldStarted", requestedSeconds=args.hold_seconds)+ hold_started = time.monotonic()+ time.sleep(args.hold_seconds)+ record("protectedHoldEnded", actualSeconds=round(time.monotonic()-hold_started, 3))+ rpc.notify("notifications/turn-ended")+ wait_for(guardian, "locked", timeout=5)+ record("relockObserved")+ wait_for_release(rpc)+ record("bothGuardsReleased", passed=True)+ if args.wait_for_manual_unlock:+ print("Relock observed. Waiting for normal manual unlock.", flush=True)+ wait_for(guardian, "unlocked", timeout=120)+ else:+ print("Relock observed. Unlock normally, then enter continue here.", flush=True)+ if sys.stdin.readline().strip() != "continue": raise RuntimeError("Manual verification interrupted")+ wait_for(guardian, "unlocked", timeout=5)+ assert rpc.call("ocu/locked-use/keychain/verify-manual")["passed"]+ assert rpc.call("ocu/locked-use/keychain/cleanup")["passed"]+ completed = True+ record("manualUnlockKeychainCleanupPassed", productionEvidenceEligible=not args.legacy_only)+ except Exception as error:+ failure = type(error).__name__+ record("failed", failureType=failure)+ raise+ finally:+ if not completed and locked:+ # End the lease before waiting for release. Keeping this RPC open+ # without ending its turn would leave protection active until the+ # wait timed out and close() finally disconnected the controller.+ try: rpc.notify("notifications/turn-ended")+ except Exception: pass+ # Root and the independent guards own relock. An extra controller+ # SPI request can interrupt a user's normal recovery login.+ print("Validation failed; independent guards own recovery. Unlock normally before retrying cleanup.", file=sys.stderr)+ try:+ wait_for_release(rpc)+ record("bothGuardsReleasedAfterFailure", passed=True)+ except Exception:+ record("bothGuardsReleasedAfterFailure", passed=False)+ else:+ if args.wait_for_manual_unlock:+ try:+ # Protection is gone; this wait does not keep the desktop+ # covered. Capture the normal-login mechanism diagnostics.+ wait_for(guardian, "unlocked", timeout=60)+ record("manualUnlockAfterFailure", passed=True)+ if fixture is not None:+ assert rpc.call("ocu/locked-use/keychain/verify-manual")["passed"]+ assert rpc.call("ocu/locked-use/keychain/cleanup")["passed"]+ record("isolatedKeychainCleanupAfterFailure", passed=True)+ except Exception:+ record("manualRecoveryVerification", passed=False)+ if not locked or completed:+ try: rpc.call("ocu/locked-use/keychain/cleanup", timeout=5)+ except Exception: pass+ rpc.close()+ if fixture is not None:+ if completed and args.keep_fixture and fixture.poll() is None:+ # Retain only the harmless native target after the full cleanup.+ # This does not retain a lease, permit, shield or agent connection.+ record("fixtureRetainedForRecording", passed=True)+ else:+ fixture.terminate()+ live_events, trace_status = trace.finish()+ report = write_report(root, run_started, events, failure, live_events, trace_status)+ print(json.dumps({"event": "diagnosticReportSaved", "path": str(report)}), flush=True)+++if __name__ == "__main__":+ main()diff --git a/scripts/run-locked-use-rehearsal.py b/scripts/run-locked-use-rehearsal.pynew file mode 100644index 0000000..385c604--- /dev/null+++ b/scripts/run-locked-use-rehearsal.py@@ -0,0 +1,111 @@+#!/usr/bin/env python3+"""Interactive development test only. Never called from CI or normal OCU tools.++The controller retains a recovery path while the GUI test filters local input.+An emergency timeout tears down only this test's process group. That recovery+is not a production privacy guarantee and must not be reused as shield release.+"""+import argparse+import json+import os+from pathlib import Path+import signal+import subprocess+import sys+import time+++def recover_lock(binary):+ """Retain the independent watchdog while requesting and observing relock."""+ try:+ subprocess.run([str(binary), "--request-lock"], timeout=3, check=False)+ deadline = time.monotonic() + 5+ while time.monotonic() < deadline:+ result = subprocess.run([str(binary), "--diagnose"], capture_output=True, text=True, timeout=2)+ state = json.loads(result.stdout).get("session")+ if state == "locked":+ print(json.dumps({"event": "recoveryLockConfirmed"}), flush=True)+ return True+ time.sleep(0.1)+ except (subprocess.TimeoutExpired, ValueError, OSError):+ pass+ print(json.dumps({"event": "recoveryLockUnconfirmed", "productionReady": False}), flush=True)+ return False+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ modes = parser.add_mutually_exclusive_group(required=True)+ modes.add_argument("--confirm-lock-test", action="store_true",+ help="confirm that the user is ready for shields and a screen lock")+ modes.add_argument("--shield-preview", action="store_true",+ help="show countdown shields only; no lock, unlock, AX action or capture")+ modes.add_argument("--confirm-watchdog-test", action="store_true",+ help="confirm a 5-second Guardian stall and independent watchdog lock test")+ parser.add_argument("--delay", type=float, default=5,+ help="seconds before preflight, to let the user release input (default: 5)")+ args = parser.parse_args()+ if not 0 <= args.delay <= 30:+ parser.error("--delay must be between 0 and 30 seconds")+ root = Path(__file__).resolve().parent.parent+ binary = root / ".build/locked-use/OCU Guardian (Dev).app/Contents/MacOS/OCUGuardian"+ if not binary.is_file():+ print("Build the Guardian bundle first.", file=sys.stderr)+ return 1+ print(json.dumps({"event": "countdown", "seconds": args.delay}), flush=True)+ time.sleep(args.delay)+ probe = subprocess.run([str(binary), "--diagnose"], capture_output=True, text=True, timeout=10)+ diagnostics = json.loads(probe.stdout)+ required = ["inputMonitoring"] if args.shield_preview else ["accessibility", "inputMonitoring", "lockSPIAvailable"]+ if probe.returncode or not all(diagnostics.get(key) is True for key in required):+ print(json.dumps({"event": "preflightFailed", "diagnostics": diagnostics}), flush=True)+ return 1+ if (not args.shield_preview and diagnostics.get("secureInput")) or diagnostics.get("session") != "unlocked":+ print("Rehearsal requires a manually unlocked GUI session with Secure Input off.", file=sys.stderr)+ return 1+ print(json.dumps({"event": "controllerStarting", "timeoutSeconds": 35,+ "mode": "shieldPreview" if args.shield_preview else "watchdogTest" if args.confirm_watchdog_test else "rehearsal",+ "unlockRequested": False}), flush=True)+ if args.shield_preview:+ command = ["--shield-preview"]+ elif args.confirm_watchdog_test:+ command = ["--watchdog-test", "--confirm-lock-test"]+ else:+ command = ["--rehearse", "--confirm-lock-test"]+ process = subprocess.Popen([str(binary), *command], start_new_session=True)+ recovered = False+ try:+ status = process.wait(timeout=35)+ if status != 0:+ recovered = True+ print(json.dumps({"event": "guardianUnexpectedExit", "status": status}), flush=True)+ # Do not kill the independent watchdog before it has relocked.+ if not args.shield_preview:+ recover_lock(binary)+ return status+ except (subprocess.TimeoutExpired, KeyboardInterrupt):+ recovered = True+ print(json.dumps({"event": "rehearsalRecovery", "productionReady": False}), flush=True)+ if not args.shield_preview:+ recover_lock(binary)+ return 2+ finally:+ # The watchdog is intentionally a separate process. Remove only this+ # controller's new process group, including any surviving test child.+ if recovered or process.poll() is not None:+ try:+ os.killpg(process.pid, signal.SIGTERM)+ except ProcessLookupError:+ pass+ try:+ process.wait(timeout=2)+ except subprocess.TimeoutExpired:+ try:+ os.killpg(process.pid, signal.SIGKILL)+ except ProcessLookupError:+ pass+ process.wait()+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/run-locked-use-unshielded-diagnostic.py b/scripts/run-locked-use-unshielded-diagnostic.pynew file mode 100644index 0000000..4d7c8d5--- /dev/null+++ b/scripts/run-locked-use-unshielded-diagnostic.py@@ -0,0 +1,105 @@+#!/usr/bin/env python3+"""Explicit visible-desktop unlock diagnostic. No shields or application tools."""+import argparse+import json+import math+import os+import select+from pathlib import Path+import subprocess+import time+from locked_use_report import LiveAuthenticationTrace, write_report, authentication_windows+++def touch_id_intervened(timeline):+ windows = authentication_windows(timeline)+ return any(event['category'] == 'LoginWindow' and event['message'] == 'touchIDMatchObserved'+ and any(window['startedAt'] <= event['elapsedSeconds'] <= window['endedAt']+ for window in windows if window['endedAt'] is not None)+ for event in timeline)+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--confirm-visible-desktop-test', action='store_true', required=True)+ args = parser.parse_args()+ root = Path(__file__).resolve().parents[1]+ binary = root / '.build/locked-use/components/OCU Guardian (Dev).app/Contents/MacOS/OCUGuardian'+ started = time.time()+ events = []+ def record(event, elapsed=None, **fields):+ entry = dict(event=event, elapsedSeconds=round(time.time()-started if elapsed is None else elapsed, 3), **fields)+ events.append(entry); print(json.dumps(entry), flush=True)+ native_anchor = None+ anchor_elapsed = None+ def state():+ nonlocal native_anchor, anchor_elapsed+ result = subprocess.run([str(binary), '--session-only'], capture_output=True, check=True, timeout=3)+ entry = next(json.loads(line) for line in result.stdout.splitlines() if json.loads(line).get('event') == 'sessionState')+ if native_anchor is None:+ native_anchor = entry['uptime']; anchor_elapsed = time.time() - started+ return entry['session']+ if state() != 'unlocked': raise RuntimeError('Unlock normally before starting the diagnostic')+ trace = LiveAuthenticationTrace(started); trace.start()+ failure = None+ try:+ print('Locking in 5 seconds; no shields, no input filters. Wait up to 20 seconds or immediate relock before manual unlock.', flush=True)+ time.sleep(5)+ subprocess.run([str(binary), '--request-lock'], check=True, stdout=subprocess.DEVNULL, timeout=3)+ for _ in range(25):+ if state() == 'locked': break+ time.sleep(0.2)+ if state() != 'locked': raise RuntimeError('Initial lock not observed')+ record('lockedObserved')+ allowed = {'unshieldedDiagnosticStarted', 'unshieldedUnlockObserved', 'unshieldedDiagnosticEnded'}+ process = subprocess.Popen([str(binary), '--unshielded-unlock-diagnostic', '--confirm-visible-desktop-test'],+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)+ buffer = b''+ deadline = time.monotonic() + 32+ try:+ while time.monotonic() < deadline:+ ready, _, _ = select.select([process.stdout], [], [], 0.2)+ if not ready: continue+ chunk = os.read(process.stdout.fileno(), 4096)+ if not chunk: break+ buffer += chunk+ if len(buffer) > 65536: raise RuntimeError('Native diagnostic record exceeded bound')+ while b'\n' in buffer:+ line, buffer = buffer.split(b'\n', 1)+ try: entry = json.loads(line)+ except (ValueError, TypeError): continue+ if not isinstance(entry, dict) or entry.get('event') not in allowed: continue+ uptime = entry.get('uptime')+ if not isinstance(uptime, (int, float)) or not math.isfinite(uptime): continue+ elapsed = uptime - native_anchor + anchor_elapsed+ if not 0 <= elapsed <= 40: raise RuntimeError('Native diagnostic clock outside run')+ fields = {k:v for k,v in entry.items() if k in {'shieldProcesses', 'inputFilters', 'maximumSeconds',+ 'productionEvidenceEligible', 'unlockObserved', 'permitConsumed', 'relockObserved', 'guiActionsPerformed'}}+ record(entry['event'], elapsed=elapsed, **fields)+ else: raise TimeoutError('Native diagnostic exceeded deadline')+ if process.wait(timeout=2): raise RuntimeError('Unshielded native diagnostic failed; see curated timeline')+ finally:+ if process.poll() is None:+ process.terminate() # Only this unshielded UI probe, no guards.+ try: process.wait(timeout=2)+ except subprocess.TimeoutExpired: process.kill(); process.wait(timeout=2)+ process.stdout.close()+ except Exception as exc:+ failure = type(exc).__name__; record('failed', failureType=failure)+ raise+ finally:+ timeline, trace_status = trace.finish()+ path = write_report(root, started, events, failure,+ live_events=timeline, trace_status=trace_status)+ payload = json.loads(path.read_text())+ intervened = touch_id_intervened(payload['systemEvents'])+ summary = {'event': 'diagnosticAttribution', 'touchIDIntervened': intervened,+ 'automaticUnlockSupported': False if intervened else None,+ 'productionEvidenceEligible': False}+ payload['controllerEvents'].append(dict(summary, elapsedSeconds=round(time.time()-started, 3)))+ path.write_text(json.dumps(payload, ensure_ascii=False, indent=2))+ print(json.dumps(summary), flush=True)+ print(json.dumps({'event': 'diagnosticReportSaved', 'path': str(path)}), flush=True)+++if __name__ == '__main__': main()diff --git a/scripts/test-macos-keychain-profile.py b/scripts/test-macos-keychain-profile.pynew file mode 100644index 0000000..60ed1a7--- /dev/null+++ b/scripts/test-macos-keychain-profile.py@@ -0,0 +1,38 @@+import datetime+import importlib.util+import pathlib+import unittest++spec = importlib.util.spec_from_file_location("profile_check", pathlib.Path(__file__).with_name("prepare-macos-keychain-profile.py"))+module = importlib.util.module_from_spec(spec)+spec.loader.exec_module(module)+++class ProfileTests(unittest.TestCase):+ def profile(self):+ return {"Platform": ["OSX"], "TeamIdentifier": ["TESTTEAM12"],+ "ExpirationDate": datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=1),+ "Entitlements": {"com.apple.application-identifier": "TESTTEAM12.dev.example.ocu",+ "com.apple.developer.team-identifier": "TESTTEAM12",+ "keychain-access-groups": ["TESTTEAM12.*", "unrelated.group"]}}++ def test_scopes_claims_to_own_group(self):+ result = module.entitlements(self.profile(), "dev.example.ocu")+ self.assertEqual(result["keychain-access-groups"], ["TESTTEAM12.dev.example.ocu"])+ self.assertEqual(len(result), 3)++ def test_rejects_wrong_app_and_debug_and_expiry(self):+ for change in ("app", "debug", "expiry", "platform", "team", "group"):+ profile = self.profile()+ if change == "app": profile["Entitlements"]["com.apple.application-identifier"] = "TESTTEAM12.other"+ if change == "debug": profile["Entitlements"]["get-task-allow"] = True+ if change == "expiry": profile["ExpirationDate"] = datetime.datetime(2000, 1, 1)+ if change == "platform": profile["Platform"] = ["iOS"]+ if change == "team": profile["TeamIdentifier"] = ["OTHERTEAM1"]+ if change == "group": profile["Entitlements"]["keychain-access-groups"] = ["unrelated.group"]+ with self.subTest(change=change), self.assertRaises(ValueError):+ module.entitlements(profile, "dev.example.ocu")+++if __name__ == "__main__":+ unittest.main()diff --git a/scripts/tests/locked-use-native-validation.test.py b/scripts/tests/locked-use-native-validation.test.pynew file mode 100644index 0000000..6efc625--- /dev/null+++ b/scripts/tests/locked-use-native-validation.test.py@@ -0,0 +1,25 @@+"""Native controller transport shutdown, without GUI or system authentication."""+import importlib.util+from pathlib import Path+import sys+import unittest+from unittest.mock import Mock++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+spec = importlib.util.spec_from_file_location('native_validation', Path(__file__).resolve().parents[1] / 'run-locked-use-native-validation.py')+native = importlib.util.module_from_spec(spec)+spec.loader.exec_module(native)+++class TransportTests(unittest.TestCase):+ def testAgentExitDoesNotMaskOriginalFailureDuringCleanup(self):+ rpc = native.RPC.__new__(native.RPC)+ rpc.process = Mock()+ rpc.process.stdin.closed = False+ rpc.process.stdin.close.side_effect = BrokenPipeError('agent exited')+ rpc.close()+ rpc.process.wait.assert_called_once_with(timeout=5)+ rpc.process.terminate.assert_not_called()+++if __name__ == '__main__': unittest.main()diff --git a/scripts/tests/locked-use-rehearsal.test.py b/scripts/tests/locked-use-rehearsal.test.pynew file mode 100644index 0000000..d711737--- /dev/null+++ b/scripts/tests/locked-use-rehearsal.test.py@@ -0,0 +1,73 @@+"""Controller recovery tests. No GUI launch, system lock or real processes."""+import importlib.util+import json+from pathlib import Path+import subprocess+import unittest+from unittest.mock import Mock, patch++spec = importlib.util.spec_from_file_location(+ "rehearsal", Path(__file__).resolve().parents[1] / "run-locked-use-rehearsal.py")+rehearsal = importlib.util.module_from_spec(spec)+spec.loader.exec_module(rehearsal)+++class RecoveryTests(unittest.TestCase):+ def run_controller(self, mode, wait_result, session="unlocked"):+ diagnostics = {"session": session, "secureInput": False,+ "accessibility": True, "inputMonitoring": True,+ "lockSPIAvailable": True}+ probe = Mock(returncode=0, stdout=json.dumps(diagnostics))+ process = Mock(pid=4242)+ process.poll.return_value = -5+ if isinstance(wait_result, BaseException):+ process.wait.side_effect = [wait_result, 0]+ else:+ process.wait.return_value = wait_result+ calls = []+ with patch.object(rehearsal.sys, "argv", ["test", mode, "--delay", "0"]), \+ patch.object(rehearsal.Path, "is_file", return_value=True), \+ patch.object(rehearsal.time, "sleep"), \+ patch.object(rehearsal.subprocess, "run", return_value=probe), \+ patch.object(rehearsal.subprocess, "Popen", return_value=process) as launch, \+ patch.object(rehearsal, "recover_lock", side_effect=lambda _: calls.append("relock")), \+ patch.object(rehearsal.os, "killpg", side_effect=lambda *_: calls.append("cleanup")), \+ patch("builtins.print"):+ result = rehearsal.main()+ return result, calls, launch++ def test_crash_retains_watchdog_until_relock_attempt(self):+ result, calls, _ = self.run_controller("--confirm-lock-test", -5)+ self.assertEqual(result, -5)+ self.assertEqual(calls, ["relock", "cleanup"])++ def test_timeout_retains_watchdog_until_relock_attempt(self):+ result, calls, _ = self.run_controller(+ "--confirm-lock-test", subprocess.TimeoutExpired("test", 35))+ self.assertEqual(result, 2)+ self.assertEqual(calls, ["relock", "cleanup"])++ def test_preview_crash_and_timeout_never_request_lock(self):+ for failure in [-5, subprocess.TimeoutExpired("test", 35)]:+ with self.subTest(failure=failure):+ _, calls, launch = self.run_controller("--shield-preview", failure)+ self.assertEqual(calls, ["cleanup"])+ self.assertEqual(launch.call_args.args[0][1:], ["--shield-preview"])++ def test_locked_session_never_launches_preview_or_rehearsal(self):+ for mode in ["--shield-preview", "--confirm-lock-test"]:+ with self.subTest(mode=mode):+ result, calls, launch = self.run_controller(mode, 0, session="locked")+ self.assertEqual(result, 1)+ self.assertEqual(calls, [])+ launch.assert_not_called()++ def test_watchdog_test_crash_keeps_recovery_order(self):+ result, calls, launch = self.run_controller("--confirm-watchdog-test", -5)+ self.assertEqual(result, -5)+ self.assertEqual(calls, ["relock", "cleanup"])+ self.assertEqual(launch.call_args.args[0][1:], ["--watchdog-test", "--confirm-lock-test"])+++if __name__ == "__main__":+ unittest.main()diff --git a/scripts/tests/locked-use-report.test.py b/scripts/tests/locked-use-report.test.pynew file mode 100644index 0000000..e47b76d--- /dev/null+++ b/scripts/tests/locked-use-report.test.py@@ -0,0 +1,178 @@+"""Report privacy filters; no desktop, daemon, lock or authentication calls."""+import importlib.util+from pathlib import Path+import unittest+from unittest.mock import patch+import json+import subprocess+import sys++spec = importlib.util.spec_from_file_location("report", Path(__file__).resolve().parents[1]/"locked_use_report.py")+report = importlib.util.module_from_spec(spec)+spec.loader.exec_module(report)+++class ReportTests(unittest.TestCase):+ def entry(self, message, category="UnlockTrigger", process="OCUGuardian"):+ return {"eventMessage": message, "category": category, "processImagePath": "/private/"+process,+ "timestamp": "2026-10-05T10:00:00+00:00", "privateData": "must never be retained"}++ def testRenamedAndLegacyComponentsKeepNormalizedDiagnostics(self):+ for process in ['OCUGuardian', 'OpenComputerUseGuardian']:+ result = report.curate([self.entry('AXTrigger returnPairQueued=true authenticationEvidence=false', process=process)], 0)+ self.assertEqual(len(result), 1)+ for plugin in ['OCULockAuth', 'OpenComputerUseLockedUseAuthorizationPlugin']:+ result = report.curate([self.entry('running mechanism '+plugin+':remote', process='authd')], 0)+ self.assertEqual(result[0]['message'], 'remoteMechanismRunning')++ def testReturnSubmissionMarkersAreCuratedWithoutContext(self):+ entries = [self.entry('AXTrigger returnDispatching=true keyCode=36 tap=hid'),+ self.entry('AXTrigger returnPairQueued=true authenticationEvidence=false'),+ self.entry('keyPressed: return in secure textfield private-context', process='loginwindow'),+ self.entry('authBegan private-context', process='loginwindow'),+ self.entry('_authCopyRightsWithUsername private-context', process='loginwindow')]+ result = report.curate(entries, 0)+ self.assertEqual(len(result), 5)+ self.assertEqual([e['message'] for e in result[2:]],+ ['secureReturnObserved', 'localAuthenticationBegan', 'loginwindowRightsRequested'])+ self.assertNotIn('private-context', str(result))++ def testKeepsCodesAndBooleansWithoutRawMetadata(self):+ result = report.curate([self.entry("AXProbe nodes=14 primaryMatches=0 fallbackMatches=1 complete=true")], 0)+ self.assertEqual(len(result), 1)+ self.assertEqual(set(result[0]), {"elapsedSeconds", "category", "message"})+ self.assertNotIn("privateData", str(result))++ def testUnknownAXContentAndTrailingFieldsAreDiscarded(self):+ for message in ["AXValue=user-secret", "AXProbe nodes=14 primaryMatches=0 fallbackMatches=1 complete=true password=user-secret",+ "AXProbe writable=true status=0 AXTitle=User Name"]:+ self.assertEqual(report.curate([self.entry(message)], 0), [])++ def testSystemRuleEventsDoNotRetainCallerOrAccount(self):+ entry = self.entry("Succeeded authorizing right 'system.login.screensaver' by client /private/example user=secret-account", process="authd")+ result = report.curate([entry], 0)+ self.assertEqual(result[0]["message"], "systemRightSucceeded")+ self.assertNotIn("secret-account", str(result))++ def testPluginPositiveAndNegativeResultsArePreserved(self):+ for message in ["brokerTaskVerification status=1", "pluginConsume replied=1 allowed=1", "resultDelivered allowed=1 status=0"]:+ self.assertEqual(len(report.curate([self.entry(message, "AuthorizationMechanism")], 0)), 1)++ def testConfirmationAndAllWatchdogStopReasonsRemainVisible(self):+ for message in ['AXTrigger passwordConfirmSupported=true status=0',+ 'AXTrigger passwordConfirm status=0 authenticationEvidence=false',+ 'AXTrigger passwordConfirmTimeout milliseconds=2000 status=0',+ 'AXTrigger passwordConfirmElapsed milliseconds=80 status=-25204',+ 'AXTrigger passwordConfirmDispatching=true',+ 'AXTrigger passwordConfirmSkipped=deadline',+ 'AXProbe passwordUI enabledButtons=1 disabledButtons=1 unknownButtons=0',+ 'AXProbe passwordFocused=true status=0']:+ self.assertEqual(len(report.curate([self.entry(message)], 0)), 1)+ self.assertEqual(report.curate([self.entry(message + ' secret=private')], 0), [])+ for reason in ['filterEvent', 'hardwareActivity', 'parentHeartbeatExpired',+ 'shieldNotVisible', 'parentDisconnected']:+ self.assertEqual(len(report.curate([self.entry('stopping reason=' + reason, 'Watchdog')], 0)), 1)++ def testProtectionAgeEvidenceRejectsExtraFields(self):+ message = 'guardLostEvidence guardianAgeMilliseconds=20 watchdogAgeMilliseconds=1501 watchdogProtected=true'+ self.assertEqual(len(report.curate([self.entry(message, 'Broker')], 0)), 1)+ self.assertEqual(report.curate([self.entry(message + ' user=private', 'Broker')], 0), [])++ def testMalformedLogsAreDiscarded(self):+ self.assertEqual(report.curate({"unexpected": "object"}, 0), [])+ self.assertEqual(report.curate([None, {"processImagePath": 3}, {"timestamp": []}], 0), [])++ def testOfflineABIAndPreviousRunsCannotCountAsLiveResults(self):+ self.assertEqual(report.curate([self.entry("resultDelivered allowed=1 status=0", "AuthorizationMechanism", "remote-plugin-abi-tests")], 0), [])+ self.assertEqual(report.curate([self.entry("AXProbe writable=true status=0")], 9999999999), [])++ def testSystemStartAndInputMarkersRetainNoCredentials(self):+ for message, process, expected in [+ ('engine 77 evaluates 1 rights "system.login.screensaver" username=secret', 'authd', 'systemRightEvaluationObserved'),+ ('loginPressed password=secret', 'loginwindow', 'localSubmitObserved'),+ ('APEventTouchIDMatch user=secret', 'loginwindow', 'touchIDMatchObserved'),+ ('attempting to unlock with empty might rekey secret', 'loginwindow', 'emptyInputKeychainPathObserved')]:+ result = report.curate([self.entry(message, process=process)], 0)+ self.assertEqual(result[0]['message'], expected)+ self.assertNotIn('secret', str(result))+ self.assertEqual(report.curate([self.entry('loginPressed', process='fake-loginwindow')], 0), [])++ def testManualRecoveryCannotCountAsAutomaticAuthorization(self):+ def event(at, category, message):+ return {'elapsedSeconds': at, 'category': category, 'message': message}+ events = [event(1, 'Broker', 'phase=authorizing stopReason=none'),+ event(6, 'Broker', 'phase=relocking stopReason=unlockTimeout'),+ event(10, 'LoginWindow', 'localSubmitObserved'),+ event(11, 'AuthorizationMechanism', 'mechanismInvoked'),+ event(12, 'SystemAuthorization', 'systemRightSucceeded')]+ window = report.authentication_windows(events)[0]+ self.assertEqual(window['endedAt'], 6)+ self.assertFalse(window['rightEvaluationObserved'])+ self.assertFalse(window['mechanismObserved'])+ self.assertFalse(window['localAuthenticationObserved'])+ # Root transitions before SetResult; do not drop the actual Allow.+ events = [event(1, 'Broker', 'phase=authorizing stopReason=none'),+ event(2, 'Broker', 'phase=unlocking stopReason=none'),+ event(3, 'AuthorizationMechanism', 'resultDelivered allowed=1 status=0')]+ self.assertTrue(report.authentication_windows(events)[0]['allowObserved'])++ def testRepeatedAuthorizingTransitionDoesNotLeaveAnOpenWindow(self):+ def event(at, message):+ return {'elapsedSeconds': at, 'category': 'Broker', 'message': message}+ windows = report.authentication_windows([+ event(1, 'phase=authorizing stopReason=none'),+ event(1.012, 'phase=authorizing stopReason=none'),+ event(6, 'phase=relocking stopReason=unlockTimeout'),+ event(6.012, 'phase=relocking stopReason=unlockTimeout')])+ self.assertEqual(len(windows), 1)+ self.assertEqual(windows[0]['startedAt'], 1)+ self.assertEqual(windows[0]['endedAt'], 6)++ def testTriggerLogsNeverRetainFieldContentsOrClickCoordinates(self):+ for message in ['AXTrigger emptyValueWrite status=0',+ 'AXTrigger focusedUserPress status=-25206 authenticationEvidence=false',+ 'AXTrigger targetedClickQueued=true authenticationEvidence=false',+ 'AXTrigger annotatedClickQueued=true']:+ self.assertEqual(len(report.curate([self.entry(message)], 0)), 1)+ self.assertEqual(report.curate([self.entry(message+' value=private')], 0), [])+ self.assertEqual(report.curate([self.entry(message+' x=123 y=456')], 0), [])++ def testClickCapabilityAndIdentityAreNeverIncluded(self):+ for category, message in [('LockUIClickFilter', 'clickAdmitted filter=watchdog type=down'),+ ('Broker', 'verificationSlow endpoint=guardian elapsedMilliseconds=300'),+ ('UnlockTrigger', 'AXTrigger sessionClickQueued=true')]:+ self.assertEqual(len(report.curate([self.entry(message, category)], 0)), 1)+ self.assertEqual(report.curate([self.entry(message+' clickTag=123', category)], 0), [])++ def testProtectedWaitingDoesNotImplyPermitIssued(self):+ events = [{'elapsedSeconds': 1, 'category': 'Broker', 'message': 'phase=authorizing stopReason=none'},+ {'elapsedSeconds': 4, 'category': 'Broker', 'message': 'permitIssued maximumLifetimeSeconds=5'},+ {'elapsedSeconds': 5, 'category': 'Broker', 'message': 'phase=relocking stopReason=unlockTimeout'}]+ window = report.authentication_windows(events)[0]+ self.assertEqual(window['startedAt'], 1)+ self.assertEqual(window['permitIssuedObservedAt'], 4)+ self.assertIsNone(report.authentication_windows([events[0], events[2]])[0]['permitIssuedObservedAt'])++ def testUnavailableStreamRemainsDiagnosticOnly(self):+ trace = report.LiveAuthenticationTrace(0)+ with patch.object(report.subprocess, 'Popen', side_effect=OSError): trace.start()+ events, status = trace.finish()+ self.assertEqual(events, [])+ self.assertEqual(status, 'unavailable')++ def testStreamDiscardsOversizedRawRecordsAndResumes(self):+ # A synthetic pipe exercises framing/lifecycle without invoking OS logs.+ record = self.entry('loginPressed credential=must_not_persist', process='loginwindow')+ code = 'import sys; sys.stdout.write("x"*70000+"\\n"+' + repr(json.dumps(record)+'\n') + '); sys.stdout.flush()'+ child = subprocess.Popen([sys.executable, '-c', code], stdout=subprocess.PIPE)+ trace = report.LiveAuthenticationTrace(0, max_seconds=1)+ with patch.object(report.subprocess, 'Popen', return_value=child): trace.start()+ trace.thread.join(timeout=2)+ events, status = trace.finish()+ self.assertEqual(len(events), 1)+ self.assertEqual(events[0]['message'], 'localSubmitObserved')+ self.assertNotIn('must_not_persist', str(events))+ self.assertEqual(status, 'ended')+++if __name__ == "__main__": unittest.main()diff --git a/scripts/tests/locked-use-unshielded-diagnostic.test.py b/scripts/tests/locked-use-unshielded-diagnostic.test.pynew file mode 100644index 0000000..4e51646--- /dev/null+++ b/scripts/tests/locked-use-unshielded-diagnostic.test.py@@ -0,0 +1,29 @@+"""Diagnostic attribution must distinguish user biometrics from unlock proof."""+import importlib.util+from pathlib import Path+import sys+import unittest+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+spec = importlib.util.spec_from_file_location('unshielded', Path(__file__).resolve().parents[1] / 'run-locked-use-unshielded-diagnostic.py')+module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module)++class AttributionTests(unittest.TestCase):+ def event(self, at, category, message):+ return dict(elapsedSeconds=at, category=category, message=message)+ def window(self):+ return [self.event(1, 'Broker', 'phase=authorizing stopReason=none'),+ self.event(20, 'Broker', 'phase=idle stopReason=none')]+ def testTouchIDBeforePermitIsNotAutomaticUnlock(self):+ events = self.window() + [self.event(15, 'LoginWindow', 'touchIDMatchObserved'),+ self.event(16, 'AuthorizationMechanism', 'resultDelivered allowed=1 status=0')]+ self.assertTrue(module.touch_id_intervened(events))+ def testManualRecoveryAndEarlierTouchIDAreExcluded(self):+ events = self.window() + [self.event(0, 'LoginWindow', 'touchIDMatchObserved'),+ self.event(21, 'LoginWindow', 'touchIDMatchObserved')]+ self.assertFalse(module.touch_id_intervened(events))+ def testUIEvaluationOrSubmitDoesNotProveHumanInput(self):+ events = self.window() + [self.event(2, 'LoginWindow', 'localAuthenticationEvaluationObserved'),+ self.event(3, 'LoginWindow', 'localSubmitObserved')]+ self.assertFalse(module.touch_id_intervened(events))++if __name__ == '__main__': unittest.main()