diff --git a/config/scripts/check-styled-scrollbars.test.mjs b/config/scripts/check-styled-scrollbars.test.mjs index 5ab2f46b1..c6ff4a72a 100644 --- a/config/scripts/check-styled-scrollbars.test.mjs +++ b/config/scripts/check-styled-scrollbars.test.mjs @@ -175,7 +175,7 @@ describe('check-styled-scrollbars', () => { it('uses later spread className props over earlier explicit className props', () => { const reports = reportUnstyledScrollbars( 'Example.tsx', - "export function Example() { return
}" + 'export function Example() { return
}' ) expect(reports).toHaveLength(1) diff --git a/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift b/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift index eaadb8553..1094fc9e5 100644 --- a/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift +++ b/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift @@ -3044,11 +3044,11 @@ private final class SocketListener: @unchecked Sendable { close(socketFd) socketFd = -1 } - unlink(socketPath) + // Why: the parent owns the private temp directory cleanup; the helper + // must not unlink arbitrary caller-supplied paths on shutdown. } private func bindSocket() throws { - unlink(socketPath) socketFd = socket(AF_UNIX, SOCK_STREAM, 0) guard socketFd >= 0 else { throw ProviderError.coded("accessibility_error", "failed to create computer-use socket") @@ -3072,9 +3072,16 @@ private final class SocketListener: @unchecked Sendable { } } guard result == 0 else { - let message = String(cString: strerror(errno)) + let bindErrno = errno + let message = String(cString: strerror(bindErrno)) close(socketFd) socketFd = -1 + if UnixSocketPathSafety.shouldRejectExistingPathAfterBindFailure( + bindErrno: bindErrno, + existingMode: existingPathMode(socketPath) + ) { + throw ProviderError.coded("invalid_argument", "refusing to replace non-socket file at computer-use socket path") + } throw ProviderError.coded("accessibility_error", "failed to bind computer-use socket: \(message)") } chmod(socketPath, 0o600) @@ -3124,6 +3131,14 @@ private final class SocketListener: @unchecked Sendable { } } +private func existingPathMode(_ path: String) -> mode_t? { + var statInfo = stat() + guard lstat(path, &statInfo) == 0 else { + return nil + } + return statInfo.st_mode +} + private func peerProcessId(_ fd: Int32) -> pid_t? { var pid = pid_t(0) var length = socklen_t(MemoryLayout.size) @@ -3334,7 +3349,6 @@ if arguments.first == "--agent" { let valueIndex = index + 1 guard valueIndex < arguments.count else { return nil } let tokenPath = arguments[valueIndex] - defer { unlink(tokenPath) } return try? String(contentsOfFile: tokenPath, encoding: .utf8) .trimmingCharacters(in: .whitespacesAndNewlines) } diff --git a/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/UnixSocketPathSafety.swift b/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/UnixSocketPathSafety.swift new file mode 100644 index 000000000..49644edca --- /dev/null +++ b/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/UnixSocketPathSafety.swift @@ -0,0 +1,14 @@ +import Darwin + +public enum UnixSocketPathSafety { + public static func isSocketMode(_ mode: mode_t) -> Bool { + (mode & mode_t(S_IFMT)) == mode_t(S_IFSOCK) + } + + public static func shouldRejectExistingPathAfterBindFailure( + bindErrno: Int32, + existingMode: mode_t? + ) -> Bool { + bindErrno == EADDRINUSE && existingMode.map { !isSocketMode($0) } == true + } +} diff --git a/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/AgentEntrypointSourceSafetyTests.swift b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/AgentEntrypointSourceSafetyTests.swift new file mode 100644 index 000000000..98dc81b8d --- /dev/null +++ b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/AgentEntrypointSourceSafetyTests.swift @@ -0,0 +1,21 @@ +import XCTest + +final class AgentEntrypointSourceSafetyTests: XCTestCase { + func testAgentEntrypointDoesNotUnlinkCallerSuppliedPaths() throws { + let testFile = URL(fileURLWithPath: #filePath) + let packageRoot = testFile + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + let mainPath = packageRoot + .appendingPathComponent("Sources") + .appendingPathComponent("OrcaComputerUseMacOS") + .appendingPathComponent("main.swift") + let source = try String(contentsOf: mainPath, encoding: .utf8) + + // Why: --agent accepts caller-supplied paths; deleting them in the + // helper can remove user files if argument validation is bypassed. + XCTAssertFalse(source.contains("unlink(tokenPath)")) + XCTAssertFalse(source.contains("unlink(socketPath)")) + } +} diff --git a/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/UnixSocketPathSafetyTests.swift b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/UnixSocketPathSafetyTests.swift new file mode 100644 index 000000000..cbbf4a44f --- /dev/null +++ b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/UnixSocketPathSafetyTests.swift @@ -0,0 +1,39 @@ +import Darwin +import XCTest +@testable import OrcaComputerUseMacOSCore + +final class UnixSocketPathSafetyTests: XCTestCase { + func testOnlyUnixSocketModesAreAccepted() { + XCTAssertTrue(UnixSocketPathSafety.isSocketMode(mode_t(S_IFSOCK | 0o600))) + XCTAssertFalse(UnixSocketPathSafety.isSocketMode(mode_t(S_IFREG | 0o600))) + XCTAssertFalse(UnixSocketPathSafety.isSocketMode(mode_t(S_IFDIR | 0o700))) + XCTAssertFalse(UnixSocketPathSafety.isSocketMode(mode_t(S_IFLNK | 0o777))) + } + + func testRejectsOnlyNonSocketPathsAfterAddressInUseBindFailure() { + XCTAssertTrue( + UnixSocketPathSafety.shouldRejectExistingPathAfterBindFailure( + bindErrno: EADDRINUSE, + existingMode: mode_t(S_IFREG | 0o600) + ) + ) + XCTAssertFalse( + UnixSocketPathSafety.shouldRejectExistingPathAfterBindFailure( + bindErrno: EADDRINUSE, + existingMode: mode_t(S_IFSOCK | 0o600) + ) + ) + XCTAssertFalse( + UnixSocketPathSafety.shouldRejectExistingPathAfterBindFailure( + bindErrno: EACCES, + existingMode: mode_t(S_IFREG | 0o600) + ) + ) + XCTAssertFalse( + UnixSocketPathSafety.shouldRejectExistingPathAfterBindFailure( + bindErrno: EADDRINUSE, + existingMode: nil + ) + ) + } +} diff --git a/src/main/computer/macos-native-provider-client.test.ts b/src/main/computer/macos-native-provider-client.test.ts index c097c289a..18af7264a 100644 --- a/src/main/computer/macos-native-provider-client.test.ts +++ b/src/main/computer/macos-native-provider-client.test.ts @@ -1,4 +1,5 @@ import { EventEmitter } from 'events' +import { join } from 'path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const { @@ -75,7 +76,7 @@ describe('MacOSNativeProviderClient', () => { resolveMacOSComputerUseExecutablePathMock.mockReturnValue( '/Applications/Orca Computer Use.app/Contents/MacOS/orca-computer-use-macos' ) - spawnMock.mockReturnValue({ unref: vi.fn() }) + spawnMock.mockReturnValue({ unref: vi.fn(), kill: vi.fn() }) connectMacOSProviderSocketMock.mockImplementation(async () => { const socket = new FakeSocket() sockets.push(socket) @@ -176,6 +177,78 @@ describe('MacOSNativeProviderClient', () => { await expect(secondCall).resolves.toEqual(capabilities) }) + it('removes the parent-owned token file after the helper socket connects', async () => { + const { MacOSNativeProviderClient } = await loadClientModule() + const client = new MacOSNativeProviderClient() + + const call = client.capabilities() + await vi.waitFor(() => expect(sockets).toHaveLength(1)) + const socket = sockets[0]! + await vi.waitFor(() => expect(socket.writes).toHaveLength(1)) + const request = JSON.parse(socket.writes[0]!) as { id: number } + const socketDirectory = mkdtempSyncMock.mock.results[0]?.value as string + + expect(rmSyncMock).toHaveBeenCalledWith(join(socketDirectory, 'provider.token'), { + force: true + }) + + socket.emit( + 'data', + `${JSON.stringify({ + id: request.id, + ok: true, + result: { protocolVersion: 1, supports: {} } + })}\n` + ) + await expect(call).resolves.toMatchObject({ protocolVersion: 1 }) + }) + + it('does not let a superseded startup clean up the replacement helper token', async () => { + const pendingConnects: { + resolve: (socket: FakeSocket) => void + }[] = [] + connectMacOSProviderSocketMock.mockImplementation( + async () => + await new Promise((resolve) => { + pendingConnects.push({ resolve }) + }) + ) + const { MacOSNativeProviderClient } = await loadClientModule() + const client = new MacOSNativeProviderClient() + + const firstCall = client.capabilities() + await vi.waitFor(() => expect(pendingConnects).toHaveLength(1)) + const firstSocketDirectory = mkdtempSyncMock.mock.results[0]?.value as string + + client.shutdown() + + const secondCall = client.capabilities() + await vi.waitFor(() => expect(pendingConnects).toHaveLength(2)) + const secondSocket = new FakeSocket() + pendingConnects[1]!.resolve(secondSocket) + await vi.waitFor(() => expect(secondSocket.writes).toHaveLength(1)) + const secondRequest = JSON.parse(secondSocket.writes[0]!) as { id: number } + + const firstSocket = new FakeSocket() + pendingConnects[0]!.resolve(firstSocket) + + await expect(firstCall).rejects.toThrow('native macOS provider startup was superseded') + expect(firstSocket.destroyed).toBe(true) + expect(rmSyncMock).toHaveBeenCalledWith(join(firstSocketDirectory, 'provider.token'), { + force: true + }) + + secondSocket.emit( + 'data', + `${JSON.stringify({ + id: secondRequest.id, + ok: true, + result: { protocolVersion: 1, supports: {} } + })}\n` + ) + await expect(secondCall).resolves.toMatchObject({ protocolVersion: 1 }) + }) + it('terminates the helper process when socket startup fails', async () => { const providerKill = vi.fn() spawnMock.mockReturnValueOnce({ unref: vi.fn(), kill: providerKill }) diff --git a/src/main/computer/macos-native-provider-client.ts b/src/main/computer/macos-native-provider-client.ts index 929ab78bc..169cf1abd 100644 --- a/src/main/computer/macos-native-provider-client.ts +++ b/src/main/computer/macos-native-provider-client.ts @@ -45,13 +45,13 @@ export class MacOSNativeProviderClient { private socketStartPromise: Promise | null = null private socketPath: string | null = null private socketDirectory: string | null = null - private socketTokenPath: string | null = null private socketToken: string | null = null private nextId = 1 private pending = new Map() private socketBuffer = '' private providerCapabilities: ComputerProviderCapabilities | null = null private socketListenerCleanup: (() => void) | null = null + private socketStartGeneration = 0 async listApps(): Promise { return (await this.call('listApps', {})) as ComputerListAppsResult } @@ -74,6 +74,7 @@ export class MacOSNativeProviderClient { const token = this.socketToken this.socket = null this.socketStartPromise = null + this.socketStartGeneration++ this.providerCapabilities = null this.socketBuffer = '' this.cleanupActiveSocketListeners() @@ -176,30 +177,47 @@ export class MacOSNativeProviderClient { if (this.socketStartPromise) { return await this.socketStartPromise } - this.socketStartPromise = this.startSocket(helperExecutablePath) + const socketStartPromise = this.startSocket(helperExecutablePath) + this.socketStartPromise = socketStartPromise try { - return await this.socketStartPromise + return await socketStartPromise } finally { - this.socketStartPromise = null + if (this.socketStartPromise === socketStartPromise) { + this.socketStartPromise = null + } } } private async startSocket(helperExecutablePath: string): Promise { - this.socketDirectory = mkdtempSync(join(tmpdir(), 'orca-computer-use-')) - chmodSync(this.socketDirectory, 0o700) - this.socketPath = join(this.socketDirectory, 'provider.sock') - this.socketToken = randomUUID() - this.socketTokenPath = join(this.socketDirectory, 'provider.token') - writeFileSync(this.socketTokenPath, this.socketToken, { encoding: 'utf8', mode: 0o600 }) + const startGeneration = ++this.socketStartGeneration + const socketDirectory = mkdtempSync(join(tmpdir(), 'orca-computer-use-')) + chmodSync(socketDirectory, 0o700) + const socketPath = join(socketDirectory, 'provider.sock') + const socketToken = randomUUID() + const socketTokenPath = join(socketDirectory, 'provider.token') + this.socketDirectory = socketDirectory + this.socketPath = socketPath + this.socketToken = socketToken + writeFileSync(socketTokenPath, socketToken, { encoding: 'utf8', mode: 0o600 }) // Why: launching the nested helper via LaunchServices can make TCC evaluate // Orca.app as responsible; the signed helper executable owns this grant. const provider = spawn( helperExecutablePath, - ['--agent', this.socketPath, '--token-file', this.socketTokenPath], + ['--agent', socketPath, '--token-file', socketTokenPath], { detached: true, stdio: 'ignore' } ) provider.unref() try { - const socket = await connectMacOSProviderSocket(this.socketPath, HELPER_CONNECT_TIMEOUT_MS) + const socket = await connectMacOSProviderSocket(socketPath, HELPER_CONNECT_TIMEOUT_MS) + rmSync(socketTokenPath, { force: true }) + // Why: shutdown/retry can supersede an in-flight connect; old starts + // must not adopt replacement state or clean up the replacement helper. + if (this.socketStartGeneration !== startGeneration || this.socketPath !== socketPath) { + socket.destroy() + throw new RuntimeClientError( + 'accessibility_error', + 'native macOS provider startup was superseded' + ) + } socket.setEncoding('utf8') this.socketBuffer = '' const onData = (chunk: string) => this.handleSocketData(socket, chunk) @@ -221,10 +239,13 @@ export class MacOSNativeProviderClient { // Why: connect failures happen after spawn; terminate the detached // helper so repeated startup attempts do not leave orphan providers. provider.kill('SIGTERM') - this.cleanupSocketDirectory() - this.socketPath = null - this.socketTokenPath = null - this.socketToken = null + if ( + this.socketStartGeneration === startGeneration && + this.socketDirectory === socketDirectory + ) { + this.cleanupSocketDirectory() + this.socketToken = null + } throw error } } @@ -307,7 +328,6 @@ export class MacOSNativeProviderClient { rmSync(this.socketDirectory, { recursive: true, force: true }) this.socketDirectory = null this.socketPath = null - this.socketTokenPath = null } private rejectPending(error: Error): void { for (const [id, pending] of this.pending) { diff --git a/src/main/git/status-upstream-probe-churn.test.ts b/src/main/git/status-upstream-probe-churn.test.ts index c61fda98d..4d9344a6c 100644 --- a/src/main/git/status-upstream-probe-churn.test.ts +++ b/src/main/git/status-upstream-probe-churn.test.ts @@ -59,13 +59,14 @@ describe('getStatus missing-upstream polling churn', () => { await getStatus('/repo') await getStatus('/repo') - const upstreamProbeCalls = gitExecFileAsyncMock.mock.calls.filter( - ([args]: [string[]]) => args[0] === 'rev-parse' && args.includes('HEAD@{u}') - ) - const sameNameOriginProbeCalls = gitExecFileAsyncMock.mock.calls.filter( - ([args]: [string[]]) => - args[0] === 'rev-parse' && args.includes('refs/remotes/origin/Initi-Project') - ) + const upstreamProbeCalls = gitExecFileAsyncMock.mock.calls.filter(([args]) => { + const gitArgs = args as string[] + return gitArgs[0] === 'rev-parse' && gitArgs.includes('HEAD@{u}') + }) + const sameNameOriginProbeCalls = gitExecFileAsyncMock.mock.calls.filter(([args]) => { + const gitArgs = args as string[] + return gitArgs[0] === 'rev-parse' && gitArgs.includes('refs/remotes/origin/Initi-Project') + }) expect(upstreamProbeCalls).toHaveLength(1) expect(sameNameOriginProbeCalls).toHaveLength(1) diff --git a/src/renderer/src/components/feature-wall/FeatureWallSetupStepVisuals.tsx b/src/renderer/src/components/feature-wall/FeatureWallSetupStepVisuals.tsx index 1df8f9e9e..6fa9f5b49 100644 --- a/src/renderer/src/components/feature-wall/FeatureWallSetupStepVisuals.tsx +++ b/src/renderer/src/components/feature-wall/FeatureWallSetupStepVisuals.tsx @@ -458,7 +458,9 @@ function ModalField(props: {
{props.label}
- {props.icon ? {props.icon} : null} + {props.icon ? ( + {props.icon} + ) : null} {props.value} {props.typing ? ( diff --git a/src/renderer/src/components/settings/SettingsSidebar.tsx b/src/renderer/src/components/settings/SettingsSidebar.tsx index b70868672..abfdf5211 100644 --- a/src/renderer/src/components/settings/SettingsSidebar.tsx +++ b/src/renderer/src/components/settings/SettingsSidebar.tsx @@ -211,35 +211,35 @@ export function SettingsSidebar({ const Icon = section.icon const isActive = activeSectionId === section.id - return ( - - ) - })} + return ( + + ) + })}
))} diff --git a/src/renderer/src/components/setup-guide/use-setup-guide-telemetry.test.ts b/src/renderer/src/components/setup-guide/use-setup-guide-telemetry.test.ts index 8fcd2ebc6..c732a39a2 100644 --- a/src/renderer/src/components/setup-guide/use-setup-guide-telemetry.test.ts +++ b/src/renderer/src/components/setup-guide/use-setup-guide-telemetry.test.ts @@ -66,16 +66,13 @@ describe('setup guide step completion telemetry', () => { setupGuideVisible: true }) - expect(trackMock).toHaveBeenCalledWith( - 'setup_guide_step_completed', - { - step_id: 'notifications', - section_id: 'setup', - completed_count: 1, - total_steps: 8, - setup_guide_visible: true - } - ) + expect(trackMock).toHaveBeenCalledWith('setup_guide_step_completed', { + step_id: 'notifications', + section_id: 'setup', + completed_count: 1, + total_steps: 8, + setup_guide_visible: true + }) }) }) diff --git a/src/renderer/src/components/terminal-pane/keyboard-handlers.ts b/src/renderer/src/components/terminal-pane/keyboard-handlers.ts index af6d2fac3..9a2c53145 100644 --- a/src/renderer/src/components/terminal-pane/keyboard-handlers.ts +++ b/src/renderer/src/components/terminal-pane/keyboard-handlers.ts @@ -388,12 +388,12 @@ export function useTerminalKeyboardShortcuts({ // back to an async resolve that queries pty.getCwd. const cached = paneCwdRef.current.get(pane.id) if (cached?.confirmed && cached.cwd) { - const createdPane = manager.splitPane(pane.id, action.direction, { cwd: cached.cwd }) - if (createdPane) { - trackTerminalPaneSplit({ - source: telemetrySource, - direction: action.direction - }) + const createdPane = manager.splitPane(pane.id, action.direction, { cwd: cached.cwd }) + if (createdPane) { + trackTerminalPaneSplit({ + source: telemetrySource, + direction: action.direction + }) } return } diff --git a/src/renderer/src/components/ui/toggle-group.tsx b/src/renderer/src/components/ui/toggle-group.tsx index 61a76ae0d..23e454bb4 100644 --- a/src/renderer/src/components/ui/toggle-group.tsx +++ b/src/renderer/src/components/ui/toggle-group.tsx @@ -43,9 +43,7 @@ function ToggleGroup({ )} {...props} > - - {children} - + {children} ) } diff --git a/src/renderer/src/lib/feature-education-telemetry.test.ts b/src/renderer/src/lib/feature-education-telemetry.test.ts index 7ec2bc6e2..24165d725 100644 --- a/src/renderer/src/lib/feature-education-telemetry.test.ts +++ b/src/renderer/src/lib/feature-education-telemetry.test.ts @@ -132,30 +132,18 @@ describe('feature education telemetry helpers', () => { trackTerminalPaneSplit({ source: 'context_menu', direction: 'horizontal' }) expect(trackMock).toHaveBeenCalledTimes(3) - expect(trackMock).toHaveBeenNthCalledWith( - 1, - 'terminal_pane_split', - { - source: 'keyboard', - direction: 'horizontal' - } - ) - expect(trackMock).toHaveBeenNthCalledWith( - 2, - 'terminal_pane_split', - { - source: 'keyboard', - direction: 'vertical' - } - ) - expect(trackMock).toHaveBeenNthCalledWith( - 3, - 'terminal_pane_split', - { - source: 'context_menu', - direction: 'horizontal' - } - ) + expect(trackMock).toHaveBeenNthCalledWith(1, 'terminal_pane_split', { + source: 'keyboard', + direction: 'horizontal' + }) + expect(trackMock).toHaveBeenNthCalledWith(2, 'terminal_pane_split', { + source: 'keyboard', + direction: 'vertical' + }) + expect(trackMock).toHaveBeenNthCalledWith(3, 'terminal_pane_split', { + source: 'context_menu', + direction: 'horizontal' + }) vi.setSystemTime(new Date('2026-06-03T00:00:00.000Z')) trackTerminalPaneSplit({ source: 'keyboard', direction: 'horizontal' }) @@ -164,7 +152,10 @@ describe('feature education telemetry helpers', () => { }) }) -function expectTrackedFeatureEducationTelemetry(name: string, props: Record): void { +function expectTrackedFeatureEducationTelemetry( + name: string, + props: Record +): void { expect(trackMock).toHaveBeenCalledWith(name, props) } diff --git a/src/renderer/src/runtime/web-runtime-session.test.ts b/src/renderer/src/runtime/web-runtime-session.test.ts index 92af88d1a..443b1cf03 100644 --- a/src/renderer/src/runtime/web-runtime-session.test.ts +++ b/src/renderer/src/runtime/web-runtime-session.test.ts @@ -805,9 +805,9 @@ describe('splitWebRuntimeTerminal', () => { expect(splitWebRuntimeTerminal('remote:web-env-1@@terminal-1', 'horizontal', 'keyboard')).toBe( true ) - expect(consumePendingWebRuntimeSplitMirrorTelemetry('remote:web-env-1@@terminal-other', 'horizontal')).toBe( - false - ) + expect( + consumePendingWebRuntimeSplitMirrorTelemetry('remote:web-env-1@@terminal-other', 'horizontal') + ).toBe(false) expect( consumePendingWebRuntimeSplitMirrorTelemetry('remote:web-env-1@@terminal-1', 'horizontal') ).toBe(true)