fix(terminal): bypass rejected macOS login sessions (#9301)
* fix(terminal): bypass rejected macOS login sessions * fix(terminal): bound macOS login preflight * test(terminal): isolate macOS login preflight * fix(terminal): avoid blocking macOS login preflight * fix(terminal): cancel pending PTY preparation * fix(terminal): cancel preparation on daemon shutdown
This commit is contained in:
@@ -12,6 +12,7 @@ import { warmWindowsConptyOnce } from './windows-conpty-warmup'
|
||||
import { warmPwshAvailabilityCache } from '../pwsh'
|
||||
import { createDaemonFileLog, createNoopDaemonFileLog } from './daemon-file-log'
|
||||
import { PROTOCOL_VERSION } from './types'
|
||||
import { prepareMacosTccLoginShell } from '../providers/macos-tcc-login-shell'
|
||||
|
||||
export type ParsedDaemonArgs = {
|
||||
socketPath: string
|
||||
@@ -126,6 +127,7 @@ async function main(): Promise<void> {
|
||||
socketPath,
|
||||
tokenPath,
|
||||
log: daemonLog,
|
||||
preparePtySpawn: prepareMacosTccLoginShell,
|
||||
spawnSubprocess: (opts) => createPtySubprocess(opts)
|
||||
})
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ export type DaemonStartOptions = {
|
||||
socketPath: string
|
||||
tokenPath: string
|
||||
spawnSubprocess: DaemonServerOptions['spawnSubprocess']
|
||||
preparePtySpawn?: DaemonServerOptions['preparePtySpawn']
|
||||
log?: DaemonFileLog
|
||||
}
|
||||
|
||||
@@ -17,6 +18,7 @@ export async function startDaemon(opts: DaemonStartOptions): Promise<DaemonHandl
|
||||
socketPath: opts.socketPath,
|
||||
tokenPath: opts.tokenPath,
|
||||
spawnSubprocess: opts.spawnSubprocess,
|
||||
...(opts.preparePtySpawn ? { preparePtySpawn: opts.preparePtySpawn } : {}),
|
||||
...(opts.log ? { log: opts.log } : {})
|
||||
})
|
||||
|
||||
|
||||
@@ -181,6 +181,134 @@ describe('DaemonServer', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps RPC responsive and creates one subprocess while spawn preparation is pending', async () => {
|
||||
let finishPreparation!: () => void
|
||||
const preparation = new Promise<void>((resolve) => {
|
||||
finishPreparation = resolve
|
||||
})
|
||||
const preparePtySpawn = vi.fn(() => preparation)
|
||||
const spawnSubprocess = vi.fn(() => createMockSubprocess())
|
||||
server = new DaemonServer({
|
||||
socketPath,
|
||||
tokenPath,
|
||||
preparePtySpawn,
|
||||
spawnSubprocess
|
||||
})
|
||||
await server.start()
|
||||
const c = await connectClient()
|
||||
|
||||
const firstCreate = c.request<{ isNew: boolean }>('createOrAttach', {
|
||||
sessionId: 'prepared-session',
|
||||
cols: 80,
|
||||
rows: 24
|
||||
})
|
||||
const concurrentCreate = c.request<{ isNew: boolean }>('createOrAttach', {
|
||||
sessionId: 'prepared-session',
|
||||
cols: 80,
|
||||
rows: 24
|
||||
})
|
||||
await vi.waitFor(() => expect(preparePtySpawn).toHaveBeenCalledTimes(2))
|
||||
|
||||
// The old spawnSync probe blocked this ping and all live PTY traffic.
|
||||
await expect(c.request('ping', undefined)).resolves.toEqual({ pong: true })
|
||||
expect(spawnSubprocess).not.toHaveBeenCalled()
|
||||
|
||||
finishPreparation()
|
||||
const results = await Promise.all([firstCreate, concurrentCreate])
|
||||
expect(results.map((result) => result.isNew).sort()).toEqual([false, true])
|
||||
expect(spawnSubprocess).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it.each(['cancelCreateOrAttach', 'kill'] as const)(
|
||||
'prevents a pending subprocess after %s and permits later session reuse',
|
||||
async (requestType) => {
|
||||
let finishPreparation!: () => void
|
||||
const preparation = new Promise<void>((resolve) => {
|
||||
finishPreparation = resolve
|
||||
})
|
||||
const preparePtySpawn = vi.fn(() => preparation)
|
||||
const spawnSubprocess = vi.fn(() => createMockSubprocess())
|
||||
server = new DaemonServer({
|
||||
socketPath,
|
||||
tokenPath,
|
||||
preparePtySpawn,
|
||||
spawnSubprocess
|
||||
})
|
||||
await server.start()
|
||||
const c = await connectClient()
|
||||
|
||||
const creates = [
|
||||
c.request('createOrAttach', {
|
||||
sessionId: 'canceled-preparation',
|
||||
cols: 80,
|
||||
rows: 24
|
||||
}),
|
||||
c.request('createOrAttach', {
|
||||
sessionId: 'canceled-preparation',
|
||||
cols: 80,
|
||||
rows: 24
|
||||
})
|
||||
]
|
||||
const canceledCreates = Promise.all(
|
||||
creates.map((create) =>
|
||||
expect(create).rejects.toThrow('Attach canceled for session canceled-preparation')
|
||||
)
|
||||
)
|
||||
await vi.waitFor(() => expect(preparePtySpawn).toHaveBeenCalledTimes(2))
|
||||
|
||||
const cancelRequest =
|
||||
requestType === 'kill'
|
||||
? c.request('kill', { sessionId: 'canceled-preparation', immediate: true })
|
||||
: c.request('cancelCreateOrAttach', { sessionId: 'canceled-preparation' })
|
||||
await expect(cancelRequest).resolves.toEqual({})
|
||||
finishPreparation()
|
||||
await canceledCreates
|
||||
expect(spawnSubprocess).not.toHaveBeenCalled()
|
||||
|
||||
await expect(
|
||||
c.request('createOrAttach', {
|
||||
sessionId: 'canceled-preparation',
|
||||
cols: 80,
|
||||
rows: 24
|
||||
})
|
||||
).resolves.toMatchObject({ isNew: true })
|
||||
expect(spawnSubprocess).toHaveBeenCalledOnce()
|
||||
}
|
||||
)
|
||||
|
||||
it('cancels pending subprocess preparation during daemon shutdown', async () => {
|
||||
let finishPreparation!: () => void
|
||||
const preparation = new Promise<void>((resolve) => {
|
||||
finishPreparation = resolve
|
||||
})
|
||||
const preparePtySpawn = vi.fn(() => preparation)
|
||||
const spawnSubprocess = vi.fn(() => createMockSubprocess())
|
||||
server = new DaemonServer({
|
||||
socketPath,
|
||||
tokenPath,
|
||||
preparePtySpawn,
|
||||
spawnSubprocess
|
||||
})
|
||||
await server.start()
|
||||
const daemon = server as unknown as DaemonServerPrivate
|
||||
|
||||
const create = daemon.routeRequest('shutdown-client', {
|
||||
id: 'shutdown-create',
|
||||
type: 'createOrAttach',
|
||||
payload: { sessionId: 'shutdown-pending', cols: 80, rows: 24 }
|
||||
})
|
||||
const canceledCreate = expect(create).rejects.toThrow(
|
||||
'Attach canceled for session shutdown-pending'
|
||||
)
|
||||
await vi.waitFor(() => expect(preparePtySpawn).toHaveBeenCalledOnce())
|
||||
|
||||
const shutdown = server.shutdown()
|
||||
finishPreparation()
|
||||
await canceledCreate
|
||||
await shutdown
|
||||
expect(spawnSubprocess).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('persists only an allowlisted launch identity across reattach', async () => {
|
||||
await startServer()
|
||||
const c = await connectClient()
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
PROTOCOL_VERSION,
|
||||
NOTIFY_PREFIX,
|
||||
SessionNotFoundError,
|
||||
TerminalAttachCanceledError,
|
||||
type HelloMessage,
|
||||
type DaemonRequest
|
||||
} from './types'
|
||||
@@ -35,6 +36,7 @@ export type DaemonServerOptions = {
|
||||
socketPath: string
|
||||
tokenPath: string
|
||||
ptySpawnHealthCheck?: () => Promise<void>
|
||||
preparePtySpawn?: () => Promise<void>
|
||||
log?: DaemonFileLog
|
||||
spawnSubprocess: (opts: {
|
||||
sessionId: string
|
||||
@@ -53,6 +55,10 @@ type ConnectedClient = {
|
||||
streamSocket: Socket | null
|
||||
}
|
||||
|
||||
type PendingPtySpawnPreparation = {
|
||||
canceled: boolean
|
||||
}
|
||||
|
||||
export class DaemonServer {
|
||||
private server: Server | null = null
|
||||
private token: string
|
||||
@@ -60,6 +66,7 @@ export class DaemonServer {
|
||||
private socketPath: string
|
||||
private tokenPath: string
|
||||
private ptySpawnHealthCheck: () => Promise<void>
|
||||
private preparePtySpawn: () => Promise<void>
|
||||
private log: DaemonFileLog
|
||||
|
||||
private clients = new Map<string, ConnectedClient>()
|
||||
@@ -96,6 +103,7 @@ export class DaemonServer {
|
||||
})
|
||||
private streamClientIdBySessionId = new Map<string, string>()
|
||||
private lastInputAtBySessionId = new Map<string, number>()
|
||||
private pendingPtySpawnPreparations = new Map<string, Set<PendingPtySpawnPreparation>>()
|
||||
private stopStreamBacklogProbe: () => void = () => {}
|
||||
|
||||
// Why: main-process PTY IPC has the same recent-input bypass, but daemon
|
||||
@@ -111,6 +119,7 @@ export class DaemonServer {
|
||||
this.token = randomUUID()
|
||||
this.host = new TerminalHost({ spawnSubprocess: opts.spawnSubprocess })
|
||||
this.ptySpawnHealthCheck = opts.ptySpawnHealthCheck ?? checkPtySpawnHealth
|
||||
this.preparePtySpawn = opts.preparePtySpawn ?? (() => Promise.resolve())
|
||||
this.stopStreamBacklogProbe = startDaemonStreamBacklogProbe(() => ({
|
||||
clients: Array.from(this.clients.values(), (client) => ({
|
||||
clientId: client.clientId,
|
||||
@@ -149,6 +158,7 @@ export class DaemonServer {
|
||||
async shutdown(): Promise<void> {
|
||||
this.stopStreamBacklogProbe()
|
||||
this.transientFactRelay.dispose()
|
||||
this.cancelAllPendingPtySpawnPreparations()
|
||||
try {
|
||||
await this.host.dispose()
|
||||
} catch (err) {
|
||||
@@ -335,12 +345,50 @@ export class DaemonServer {
|
||||
}
|
||||
}
|
||||
|
||||
private async preparePtySpawnUnlessCanceled(sessionId: string): Promise<void> {
|
||||
const preparation: PendingPtySpawnPreparation = { canceled: false }
|
||||
const pending = this.pendingPtySpawnPreparations.get(sessionId) ?? new Set()
|
||||
pending.add(preparation)
|
||||
this.pendingPtySpawnPreparations.set(sessionId, pending)
|
||||
try {
|
||||
// Why: registration precedes the async capability probe so a concurrent
|
||||
// close can cancel this exact creation before a subprocess exists.
|
||||
await this.preparePtySpawn()
|
||||
if (preparation.canceled) {
|
||||
throw new TerminalAttachCanceledError(sessionId)
|
||||
}
|
||||
} finally {
|
||||
pending.delete(preparation)
|
||||
if (pending.size === 0) {
|
||||
this.pendingPtySpawnPreparations.delete(sessionId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private cancelPendingPtySpawnPreparations(sessionId: string): boolean {
|
||||
const pending = this.pendingPtySpawnPreparations.get(sessionId)
|
||||
if (!pending) {
|
||||
return false
|
||||
}
|
||||
for (const preparation of pending) {
|
||||
preparation.canceled = true
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private cancelAllPendingPtySpawnPreparations(): void {
|
||||
for (const sessionId of this.pendingPtySpawnPreparations.keys()) {
|
||||
this.cancelPendingPtySpawnPreparations(sessionId)
|
||||
}
|
||||
}
|
||||
|
||||
private async routeRequest(clientId: string, request: DaemonRequest): Promise<unknown> {
|
||||
const client = this.clients.get(clientId)
|
||||
|
||||
switch (request.type) {
|
||||
case 'createOrAttach': {
|
||||
const p = request.payload
|
||||
await this.preparePtySpawnUnlessCanceled(p.sessionId)
|
||||
const result = await this.host.createOrAttach({
|
||||
sessionId: p.sessionId,
|
||||
cols: p.cols,
|
||||
@@ -424,6 +472,7 @@ export class DaemonServer {
|
||||
}
|
||||
|
||||
case 'cancelCreateOrAttach':
|
||||
this.cancelPendingPtySpawnPreparations(request.payload.sessionId)
|
||||
return {}
|
||||
|
||||
case 'write':
|
||||
@@ -500,14 +549,26 @@ export class DaemonServer {
|
||||
return {}
|
||||
}
|
||||
|
||||
case 'kill':
|
||||
case 'kill': {
|
||||
const canceledPendingSpawn = this.cancelPendingPtySpawnPreparations(
|
||||
request.payload.sessionId
|
||||
)
|
||||
this.lastInputAtBySessionId.delete(request.payload.sessionId)
|
||||
this.log.log('session-killed', {
|
||||
sessionId: request.payload.sessionId,
|
||||
immediate: request.payload.immediate === true
|
||||
})
|
||||
await this.host.kill(request.payload.sessionId, { immediate: request.payload.immediate })
|
||||
try {
|
||||
await this.host.kill(request.payload.sessionId, { immediate: request.payload.immediate })
|
||||
} catch (error) {
|
||||
// Why: a kill that wins before session registration has already
|
||||
// canceled the pending spawn and therefore completed its intent.
|
||||
if (!(canceledPendingSpawn && error instanceof SessionNotFoundError)) {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
return {}
|
||||
}
|
||||
|
||||
case 'signal':
|
||||
this.host.signal(request.payload.sessionId, request.payload.signal)
|
||||
|
||||
@@ -324,9 +324,9 @@ describe('createPtySubprocess', () => {
|
||||
expect(Object.values(spawnEnv)).toContain('credential.guiPrompt')
|
||||
})
|
||||
|
||||
it('uses a new daemon protocol for post-merge Git guard behavior', () => {
|
||||
expect(PROTOCOL_VERSION).toBeGreaterThan(21)
|
||||
expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(21)
|
||||
it('uses a new daemon protocol for the macOS login preflight host behavior', () => {
|
||||
expect(PROTOCOL_VERSION).toBeGreaterThan(22)
|
||||
expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(22)
|
||||
})
|
||||
|
||||
it('resolves a missing Unix default before spawning node-pty', () => {
|
||||
@@ -518,17 +518,11 @@ describe('createPtySubprocess', () => {
|
||||
}
|
||||
}
|
||||
|
||||
// On macOS the shell is spawned through /usr/bin/login so terminal children
|
||||
// carry their own TCC identity (#6996); the real shell rides behind it, and
|
||||
// env(1) re-asserts the SHELL that login(1) would overwrite.
|
||||
// The sync subprocess layer consumes the capability prepared by its async
|
||||
// daemon boundary; this cwd-repair test deliberately exercises it unprepared.
|
||||
expect(spawnMock).toHaveBeenCalledWith(
|
||||
'/usr/bin/login',
|
||||
expect.arrayContaining([
|
||||
'-flpq',
|
||||
'/usr/bin/env',
|
||||
expect.stringMatching(/^SHELL=/),
|
||||
'/bin/bash'
|
||||
]),
|
||||
'/bin/bash',
|
||||
expect.any(Array),
|
||||
expect.objectContaining({ cwd: originalCwd })
|
||||
)
|
||||
})
|
||||
|
||||
@@ -16,10 +16,10 @@ import type { TuiAgent } from '../../shared/types'
|
||||
// when daemon-baked behavior cannot be delivered by on-disk wrapper refresh.
|
||||
// Why: bump when adding daemon wire behavior so same-version old daemons do
|
||||
// not silently accept the handshake and then reject new RPCs.
|
||||
export const PROTOCOL_VERSION = 22
|
||||
export const PROTOCOL_VERSION = 23
|
||||
export const GIT_CREDENTIAL_GUARD_HOST_PROTOCOL_VERSION = 22
|
||||
export const PREVIOUS_DAEMON_PROTOCOL_VERSIONS = [
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22
|
||||
] as const
|
||||
|
||||
// ─── Session State Machine ──────────────────────────────────────────
|
||||
|
||||
@@ -41,6 +41,7 @@ const {
|
||||
writeFileSyncMock,
|
||||
chmodSyncMock,
|
||||
getPathMock,
|
||||
loginPreflightExecFileMock,
|
||||
spawnMock,
|
||||
openCodeBuildPtyEnvMock,
|
||||
openCodeClearPtyMock,
|
||||
@@ -72,6 +73,7 @@ const {
|
||||
writeFileSyncMock: vi.fn(),
|
||||
chmodSyncMock: vi.fn(),
|
||||
getPathMock: vi.fn(),
|
||||
loginPreflightExecFileMock: vi.fn(),
|
||||
spawnMock: vi.fn(),
|
||||
openCodeBuildPtyEnvMock: vi.fn(),
|
||||
mimoCodeBuildPtyEnvMock: vi.fn(),
|
||||
@@ -129,6 +131,13 @@ vi.mock('node-pty', () => ({
|
||||
spawn: spawnMock
|
||||
}))
|
||||
|
||||
// Why: this suite forces darwin on non-macOS hosts; isolate the PAM probe
|
||||
// while preserving every other child_process API used by the IPC graph.
|
||||
vi.mock('node:child_process', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
execFile: loginPreflightExecFileMock
|
||||
}))
|
||||
|
||||
vi.mock('../opencode/hook-service', () => ({
|
||||
openCodeHookService: {
|
||||
buildPtyEnv: openCodeBuildPtyEnvMock,
|
||||
@@ -206,6 +215,7 @@ import {
|
||||
getLocalPtyProvider
|
||||
} from './pty'
|
||||
import { _resetLocalPtyProviderStateForTest } from '../providers/local-pty-provider'
|
||||
import { resetMacosLoginShellPreflightForTests } from '../providers/macos-tcc-login-shell'
|
||||
import {
|
||||
_resetHiddenRendererPtyDeliveryGateForTest,
|
||||
isHiddenRendererPty
|
||||
@@ -326,6 +336,7 @@ describe('registerPtyHandlers', () => {
|
||||
writeFileSyncMock.mockReset()
|
||||
chmodSyncMock.mockReset()
|
||||
getPathMock.mockReset()
|
||||
loginPreflightExecFileMock.mockReset()
|
||||
spawnMock.mockReset()
|
||||
openCodeBuildPtyEnvMock.mockReset()
|
||||
mimoCodeBuildPtyEnvMock.mockReset()
|
||||
@@ -7203,6 +7214,18 @@ describe('registerPtyHandlers', () => {
|
||||
// Re-enable the TCC login wrapper the suite-level beforeEach disables.
|
||||
delete process.env.ORCA_DISABLE_MACOS_LOGIN_SHELL
|
||||
process.env.SHELL = '/bin/zsh'
|
||||
loginPreflightExecFileMock.mockImplementation(
|
||||
(
|
||||
_file: string,
|
||||
_args: string[],
|
||||
_options: unknown,
|
||||
callback: (error: Error | null, stdout: string, stderr: string) => void
|
||||
) => {
|
||||
callback(null, 'ORCA_LOGIN_PREFLIGHT_OK', '')
|
||||
return { stdin: { end: vi.fn() } }
|
||||
}
|
||||
)
|
||||
resetMacosLoginShellPreflightForTests()
|
||||
|
||||
try {
|
||||
const [file, args, options] = await spawnAndGetCall({ cwd: '/tmp' })
|
||||
@@ -7218,6 +7241,7 @@ describe('registerPtyHandlers', () => {
|
||||
// The spawn env keeps the real shell so identity/name logic is intact.
|
||||
expect(options.env.SHELL).toBe('/bin/zsh')
|
||||
} finally {
|
||||
resetMacosLoginShellPreflightForTests()
|
||||
process.env.ORCA_DISABLE_MACOS_LOGIN_SHELL = '1'
|
||||
if (originalShell === undefined) {
|
||||
delete process.env.SHELL
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* oxlint-disable max-lines */
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { delimiter } from 'node:path'
|
||||
import type * as MacosTccLoginShell from './macos-tcc-login-shell'
|
||||
|
||||
const {
|
||||
existsSyncMock,
|
||||
@@ -9,6 +10,7 @@ const {
|
||||
mkdirSyncMock,
|
||||
writeFileSyncMock,
|
||||
spawnMock,
|
||||
prepareMacosTccLoginShellMock,
|
||||
resolveAgentForegroundProcessMock,
|
||||
captureDescendantSnapshotMock,
|
||||
terminateDescendantSnapshotMock
|
||||
@@ -19,6 +21,7 @@ const {
|
||||
mkdirSyncMock: vi.fn(),
|
||||
writeFileSyncMock: vi.fn(),
|
||||
spawnMock: vi.fn(),
|
||||
prepareMacosTccLoginShellMock: vi.fn(),
|
||||
resolveAgentForegroundProcessMock: vi.fn(),
|
||||
captureDescendantSnapshotMock: vi.fn(),
|
||||
terminateDescendantSnapshotMock: vi.fn()
|
||||
@@ -44,6 +47,11 @@ vi.mock('node-pty', () => ({
|
||||
spawn: spawnMock
|
||||
}))
|
||||
|
||||
vi.mock('./macos-tcc-login-shell', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof MacosTccLoginShell>()),
|
||||
prepareMacosTccLoginShell: prepareMacosTccLoginShellMock
|
||||
}))
|
||||
|
||||
vi.mock('../pty-descendant-termination', () => ({
|
||||
captureDescendantSnapshot: captureDescendantSnapshotMock,
|
||||
terminateDescendantSnapshot: terminateDescendantSnapshotMock
|
||||
@@ -139,6 +147,8 @@ describe('LocalPtyProvider', () => {
|
||||
captureDescendantSnapshotMock.mockReset()
|
||||
captureDescendantSnapshotMock.mockResolvedValue(null)
|
||||
terminateDescendantSnapshotMock.mockReset()
|
||||
prepareMacosTccLoginShellMock.mockReset()
|
||||
prepareMacosTccLoginShellMock.mockResolvedValue(undefined)
|
||||
resolveAgentForegroundProcessMock.mockReset()
|
||||
resolveAgentForegroundProcessMock.mockImplementation(
|
||||
async (_pid: number, fallbackProcess: string | null) => ({
|
||||
@@ -226,6 +236,37 @@ describe('LocalPtyProvider', () => {
|
||||
expect(spawnMock).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('does not spawn after shutdown cancels a pending stable session id', async () => {
|
||||
let finishPreparation!: () => void
|
||||
spawnMock.mockClear()
|
||||
prepareMacosTccLoginShellMock.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
finishPreparation = resolve
|
||||
})
|
||||
)
|
||||
|
||||
const spawn = provider.spawn({
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
sessionId: 'pending-local-session'
|
||||
})
|
||||
const canceledSpawn = expect(spawn).rejects.toThrow(
|
||||
'PTY spawn canceled: pending-local-session'
|
||||
)
|
||||
await vi.waitFor(() => expect(prepareMacosTccLoginShellMock).toHaveBeenCalledOnce())
|
||||
|
||||
await provider.shutdown('pending-local-session', { immediate: true })
|
||||
finishPreparation()
|
||||
await canceledSpawn
|
||||
expect(spawnMock).not.toHaveBeenCalled()
|
||||
|
||||
await expect(
|
||||
provider.spawn({ cols: 80, rows: 24, sessionId: 'pending-local-session' })
|
||||
).resolves.toMatchObject({ id: 'pending-local-session' })
|
||||
expect(spawnMock).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('calls node-pty spawn with correct args', async () => {
|
||||
await provider.spawn({ cols: 120, rows: 40, cwd: '/tmp' })
|
||||
expect(spawnMock).toHaveBeenCalledWith(
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
validateWorkingDirectory,
|
||||
spawnShellWithFallback
|
||||
} from './local-pty-utils'
|
||||
import { prepareMacosTccLoginShell } from './macos-tcc-login-shell'
|
||||
import {
|
||||
getAttributionShellLaunchConfig,
|
||||
getShellReadyLaunchConfig,
|
||||
@@ -90,6 +91,10 @@ type PtyShutdownOperation = {
|
||||
proc: pty.IPty
|
||||
}
|
||||
const ptyShutdownOperations = new Map<string, PtyShutdownOperation>()
|
||||
type PendingLocalPtySpawn = {
|
||||
canceled: boolean
|
||||
}
|
||||
const pendingLocalPtySpawns = new Map<string, Set<PendingLocalPtySpawn>>()
|
||||
const ptyShellName = new Map<string, string>()
|
||||
const ptyAgentForegroundContextPaths = new Map<string, string[]>()
|
||||
// Why: remembers the last positively-recognized agent foreground per PTY so a
|
||||
@@ -313,6 +318,42 @@ function allocatePtyId(sessionId: string | undefined): string {
|
||||
return id
|
||||
}
|
||||
|
||||
async function prepareLocalPtySpawn(id: string): Promise<void> {
|
||||
const pendingSpawn: PendingLocalPtySpawn = { canceled: false }
|
||||
const pending = pendingLocalPtySpawns.get(id) ?? new Set()
|
||||
pending.add(pendingSpawn)
|
||||
pendingLocalPtySpawns.set(id, pending)
|
||||
try {
|
||||
// Why: shutdown must be able to cancel a stable session id while the
|
||||
// asynchronous macOS capability probe runs and before node-pty exists.
|
||||
await prepareMacosTccLoginShell()
|
||||
if (pendingSpawn.canceled) {
|
||||
throw new Error(`PTY spawn canceled: ${id}`)
|
||||
}
|
||||
} finally {
|
||||
pending.delete(pendingSpawn)
|
||||
if (pending.size === 0) {
|
||||
pendingLocalPtySpawns.delete(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function cancelPendingLocalPtySpawns(id: string): void {
|
||||
const pending = pendingLocalPtySpawns.get(id)
|
||||
if (!pending) {
|
||||
return
|
||||
}
|
||||
for (const pendingSpawn of pending) {
|
||||
pendingSpawn.canceled = true
|
||||
}
|
||||
}
|
||||
|
||||
function cancelAllPendingLocalPtySpawns(): void {
|
||||
for (const id of pendingLocalPtySpawns.keys()) {
|
||||
cancelPendingLocalPtySpawns(id)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes renderer session ids that should be reused for local PTY reattach.
|
||||
*/
|
||||
@@ -795,6 +836,7 @@ export class LocalPtyProvider implements IPtyProvider {
|
||||
logHistoryInjection(worktreeId, historyResult)
|
||||
}
|
||||
|
||||
await prepareLocalPtySpawn(id)
|
||||
const spawnResult = spawnShellWithFallback({
|
||||
shellPath,
|
||||
shellArgs,
|
||||
@@ -1037,6 +1079,7 @@ export class LocalPtyProvider implements IPtyProvider {
|
||||
}
|
||||
|
||||
async shutdown(id: string, opts: { immediate?: boolean; keepHistory?: boolean }): Promise<void> {
|
||||
cancelPendingLocalPtySpawns(id)
|
||||
const pending = ptyShutdownOperations.get(id)
|
||||
if (pending) {
|
||||
if (opts.immediate === true) {
|
||||
@@ -1342,6 +1385,7 @@ export class LocalPtyProvider implements IPtyProvider {
|
||||
|
||||
/** Kill all in-process local PTYs. Call on app quit. */
|
||||
killAll(): void {
|
||||
cancelAllPendingLocalPtySpawns()
|
||||
for (const [id, proc] of ptyProcesses) {
|
||||
runPtyCleanup(id)
|
||||
disposePtyListeners(id)
|
||||
@@ -1365,6 +1409,8 @@ export class LocalPtyProvider implements IPtyProvider {
|
||||
}
|
||||
|
||||
export function _resetLocalPtyProviderStateForTest(): void {
|
||||
cancelAllPendingLocalPtySpawns()
|
||||
pendingLocalPtySpawns.clear()
|
||||
for (const id of ptyProcesses.keys()) {
|
||||
clearPtyState(id)
|
||||
}
|
||||
|
||||
@@ -1,14 +1,23 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { existsSyncMock, userInfoMock } = vi.hoisted(() => ({
|
||||
const { existsSyncMock, userInfoMock, execFileMock, stdinEndMock } = vi.hoisted(() => ({
|
||||
existsSyncMock: vi.fn(),
|
||||
userInfoMock: vi.fn()
|
||||
userInfoMock: vi.fn(),
|
||||
execFileMock: vi.fn(),
|
||||
stdinEndMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('node:fs', () => ({ existsSync: existsSyncMock }))
|
||||
vi.mock('node:os', () => ({ userInfo: userInfoMock }))
|
||||
vi.mock('node:child_process', () => ({ execFile: execFileMock }))
|
||||
|
||||
import { wrapShellSpawnForMacosTccAttribution } from './macos-tcc-login-shell'
|
||||
import {
|
||||
prepareMacosTccLoginShell,
|
||||
resetMacosLoginShellPreflightForTests,
|
||||
wrapShellSpawnForMacosTccAttribution
|
||||
} from './macos-tcc-login-shell'
|
||||
|
||||
type ExecFileCallback = (error: Error | null, stdout: string, stderr: string) => void
|
||||
|
||||
describe('wrapShellSpawnForMacosTccAttribution', () => {
|
||||
let origPlatform: PropertyDescriptor | undefined
|
||||
@@ -23,7 +32,14 @@ describe('wrapShellSpawnForMacosTccAttribution', () => {
|
||||
origDisable = process.env.ORCA_DISABLE_MACOS_LOGIN_SHELL
|
||||
delete process.env.ORCA_DISABLE_MACOS_LOGIN_SHELL
|
||||
existsSyncMock.mockReturnValue(true)
|
||||
userInfoMock.mockReturnValue({ username: 'ada' })
|
||||
userInfoMock.mockReturnValue({ username: 'ada', homedir: '/Users/ada' })
|
||||
execFileMock.mockImplementation(
|
||||
(_file: string, _args: string[], _options: unknown, callback: ExecFileCallback) => {
|
||||
callback(null, 'ORCA_LOGIN_PREFLIGHT_OK', '')
|
||||
return { stdin: { end: stdinEndMock } }
|
||||
}
|
||||
)
|
||||
resetMacosLoginShellPreflightForTests()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -38,16 +54,99 @@ describe('wrapShellSpawnForMacosTccAttribution', () => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('wraps the shell in /usr/bin/login on macOS, preserving the shell args behind it', () => {
|
||||
it('wraps the shell in /usr/bin/login on macOS, preserving the shell args behind it', async () => {
|
||||
setPlatform('darwin')
|
||||
await prepareMacosTccLoginShell()
|
||||
expect(wrapShellSpawnForMacosTccAttribution('/bin/zsh', ['-l'])).toEqual({
|
||||
file: '/usr/bin/login',
|
||||
args: ['-flpq', 'ada', '/usr/bin/env', 'SHELL=/bin/zsh', '/bin/zsh', '-l']
|
||||
})
|
||||
expect(execFileMock).toHaveBeenCalledWith(
|
||||
'/usr/bin/login',
|
||||
['-flpq', 'ada', '/usr/bin/printf', 'ORCA_LOGIN_PREFLIGHT_OK'],
|
||||
{
|
||||
cwd: '/Users/ada',
|
||||
encoding: 'utf8',
|
||||
killSignal: 'SIGKILL',
|
||||
maxBuffer: 1024,
|
||||
timeout: 500
|
||||
},
|
||||
expect.any(Function)
|
||||
)
|
||||
expect(stdinEndMock).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('keeps bash rcfile args intact after the shell path', () => {
|
||||
it('spawns the shell directly when login PAM policy rejects the current user', async () => {
|
||||
setPlatform('darwin')
|
||||
execFileMock.mockImplementation(
|
||||
(_file: string, _args: string[], _options: unknown, callback: ExecFileCallback) => {
|
||||
callback(null, 'Login incorrect\nlogin: ', '')
|
||||
return { stdin: { end: stdinEndMock } }
|
||||
}
|
||||
)
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
|
||||
await prepareMacosTccLoginShell()
|
||||
expect(wrapShellSpawnForMacosTccAttribution('/bin/zsh', ['-l'])).toEqual({
|
||||
file: '/bin/zsh',
|
||||
args: ['-l']
|
||||
})
|
||||
expect(console.warn).toHaveBeenCalledWith(
|
||||
'[pty] macOS login(1) preflight failed; spawning shells directly'
|
||||
)
|
||||
})
|
||||
|
||||
it('caches a failed login preflight for later terminal spawns', async () => {
|
||||
setPlatform('darwin')
|
||||
execFileMock.mockImplementation(
|
||||
(_file: string, _args: string[], _options: unknown, callback: ExecFileCallback) => {
|
||||
callback(new Error('timed out'), '', '')
|
||||
return { stdin: { end: stdinEndMock } }
|
||||
}
|
||||
)
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
|
||||
await prepareMacosTccLoginShell()
|
||||
await prepareMacosTccLoginShell()
|
||||
expect(wrapShellSpawnForMacosTccAttribution('/bin/zsh', ['-l']).file).toBe('/bin/zsh')
|
||||
expect(wrapShellSpawnForMacosTccAttribution('/bin/bash', ['-l']).file).toBe('/bin/bash')
|
||||
expect(execFileMock).toHaveBeenCalledTimes(1)
|
||||
expect(console.warn).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('rejects a marker emitted by a preflight that does not exit cleanly', async () => {
|
||||
setPlatform('darwin')
|
||||
execFileMock.mockImplementation(
|
||||
(_file: string, _args: string[], _options: unknown, callback: ExecFileCallback) => {
|
||||
callback(
|
||||
Object.assign(new Error('timed out'), { code: 'ETIMEDOUT' }),
|
||||
'ORCA_LOGIN_PREFLIGHT_OK',
|
||||
''
|
||||
)
|
||||
return { stdin: { end: stdinEndMock } }
|
||||
}
|
||||
)
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
|
||||
await prepareMacosTccLoginShell()
|
||||
expect(wrapShellSpawnForMacosTccAttribution('/bin/zsh', ['-l'])).toEqual({
|
||||
file: '/bin/zsh',
|
||||
args: ['-l']
|
||||
})
|
||||
})
|
||||
|
||||
it('dedupes concurrent successful preflights and caches later terminal spawns', async () => {
|
||||
setPlatform('darwin')
|
||||
|
||||
await Promise.all([prepareMacosTccLoginShell(), prepareMacosTccLoginShell()])
|
||||
expect(wrapShellSpawnForMacosTccAttribution('/bin/zsh', ['-l']).file).toBe('/usr/bin/login')
|
||||
expect(wrapShellSpawnForMacosTccAttribution('/bin/bash', ['-l']).file).toBe('/usr/bin/login')
|
||||
expect(execFileMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('keeps bash rcfile args intact after the shell path', async () => {
|
||||
setPlatform('darwin')
|
||||
await prepareMacosTccLoginShell()
|
||||
expect(
|
||||
wrapShellSpawnForMacosTccAttribution('/bin/bash', ['--rcfile', '/orca/bash/rcfile'])
|
||||
).toEqual({
|
||||
@@ -64,8 +163,9 @@ describe('wrapShellSpawnForMacosTccAttribution', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('re-asserts the spawn env SHELL that login(1) would overwrite', () => {
|
||||
it('re-asserts the spawn env SHELL that login(1) would overwrite', async () => {
|
||||
setPlatform('darwin')
|
||||
await prepareMacosTccLoginShell()
|
||||
expect(
|
||||
wrapShellSpawnForMacosTccAttribution('/bin/zsh', ['-l'], { SHELL: '/opt/homebrew/bin/fish' })
|
||||
).toEqual({
|
||||
@@ -74,25 +174,30 @@ describe('wrapShellSpawnForMacosTccAttribution', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('falls back to the spawned shell for SHELL when the env value is empty', () => {
|
||||
it('falls back to the spawned shell for SHELL when the env value is empty', async () => {
|
||||
setPlatform('darwin')
|
||||
await prepareMacosTccLoginShell()
|
||||
expect(wrapShellSpawnForMacosTccAttribution('/bin/zsh', ['-l'], { SHELL: '' })).toEqual({
|
||||
file: '/usr/bin/login',
|
||||
args: ['-flpq', 'ada', '/usr/bin/env', 'SHELL=/bin/zsh', '/bin/zsh', '-l']
|
||||
})
|
||||
})
|
||||
|
||||
it('skips the env(1) interposition when the shell path would parse as an assignment', () => {
|
||||
it('skips the env(1) interposition when the shell path would parse as an assignment', async () => {
|
||||
setPlatform('darwin')
|
||||
await prepareMacosTccLoginShell()
|
||||
expect(wrapShellSpawnForMacosTccAttribution('/odd=dir/zsh', ['-l'])).toEqual({
|
||||
file: '/usr/bin/login',
|
||||
args: ['-flpq', 'ada', '/odd=dir/zsh', '-l']
|
||||
})
|
||||
})
|
||||
|
||||
it('still wraps with login when /usr/bin/env is missing, without interposition', () => {
|
||||
it('still wraps with login when /usr/bin/env is missing, without interposition', async () => {
|
||||
setPlatform('darwin')
|
||||
existsSyncMock.mockImplementation((path: string) => path === '/usr/bin/login')
|
||||
existsSyncMock.mockImplementation(
|
||||
(path: string) => path === '/usr/bin/login' || path === '/usr/bin/printf'
|
||||
)
|
||||
await prepareMacosTccLoginShell()
|
||||
expect(wrapShellSpawnForMacosTccAttribution('/bin/zsh', ['-l'])).toEqual({
|
||||
file: '/usr/bin/login',
|
||||
args: ['-flpq', 'ada', '/bin/zsh', '-l']
|
||||
@@ -138,7 +243,7 @@ describe('wrapShellSpawnForMacosTccAttribution', () => {
|
||||
|
||||
it('falls back to the plain spawn when the username is empty', () => {
|
||||
setPlatform('darwin')
|
||||
userInfoMock.mockReturnValue({ username: '' })
|
||||
userInfoMock.mockReturnValue({ username: '', homedir: '/Users/ada' })
|
||||
expect(wrapShellSpawnForMacosTccAttribution('/bin/zsh', ['-l'])).toEqual({
|
||||
file: '/bin/zsh',
|
||||
args: ['-l']
|
||||
@@ -152,5 +257,6 @@ describe('wrapShellSpawnForMacosTccAttribution', () => {
|
||||
file: '/bin/zsh',
|
||||
args: ['-l']
|
||||
})
|
||||
expect(execFileMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import { execFile } from 'node:child_process'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { userInfo } from 'node:os'
|
||||
|
||||
const MACOS_LOGIN_PATH = '/usr/bin/login'
|
||||
const MACOS_ENV_PATH = '/usr/bin/env'
|
||||
const MACOS_PRINTF_PATH = '/usr/bin/printf'
|
||||
const LOGIN_PREFLIGHT_TIMEOUT_MS = 500
|
||||
const LOGIN_PREFLIGHT_MARKER = 'ORCA_LOGIN_PREFLIGHT_OK'
|
||||
const LOGIN_PREFLIGHT_MAX_BUFFER_BYTES = 1024
|
||||
|
||||
/**
|
||||
* Env escape hatch to force the plain (unwrapped) spawn. Set to `1`/`true` if a
|
||||
@@ -11,11 +16,100 @@ const MACOS_ENV_PATH = '/usr/bin/env'
|
||||
*/
|
||||
const DISABLE_ENV_VAR = 'ORCA_DISABLE_MACOS_LOGIN_SHELL'
|
||||
|
||||
let cachedLoginPreflightResult: boolean | null = null
|
||||
let loginPreflightInFlight: Promise<boolean> | null = null
|
||||
|
||||
function isDisabledByEnv(): boolean {
|
||||
const value = process.env[DISABLE_ENV_VAR]
|
||||
return value === '1' || value === 'true'
|
||||
}
|
||||
|
||||
function runLoginPreflight(username: string, accountHome: string): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
try {
|
||||
const child = execFile(
|
||||
MACOS_LOGIN_PATH,
|
||||
['-flpq', username, MACOS_PRINTF_PATH, LOGIN_PREFLIGHT_MARKER],
|
||||
{
|
||||
// Why: detached daemons can outlive their launch worktree. The PAM
|
||||
// probe must not inherit a deleted cwd before PTY spawn repairs it.
|
||||
cwd: accountHome,
|
||||
encoding: 'utf8',
|
||||
// Why: PAM policy can wait indefinitely. Bound both child lifetime and
|
||||
// captured diagnostics without blocking the PTY host's event loop.
|
||||
killSignal: 'SIGKILL',
|
||||
maxBuffer: LOGIN_PREFLIGHT_MAX_BUFFER_BYTES,
|
||||
timeout: LOGIN_PREFLIGHT_TIMEOUT_MS
|
||||
},
|
||||
(error, stdout) => {
|
||||
// login(1) can return zero after an EOF-driven failed prompt, so only the
|
||||
// requested child program's output plus a clean exit proves PAM accepted it.
|
||||
resolve(error === null && stdout === LOGIN_PREFLIGHT_MARKER)
|
||||
}
|
||||
)
|
||||
// Why: login(1) must see immediate EOF, not an interactive pipe, so a PAM
|
||||
// rejection exits instead of waiting at `login:` until the timeout.
|
||||
child.stdin?.end()
|
||||
} catch {
|
||||
resolve(false)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function loginPreflightSucceeds(username: string, accountHome: string): Promise<boolean> {
|
||||
if (cachedLoginPreflightResult !== null) {
|
||||
return Promise.resolve(cachedLoginPreflightResult)
|
||||
}
|
||||
if (!loginPreflightInFlight) {
|
||||
// Why: simultaneous pane restores share one PAM child instead of multiplying
|
||||
// subprocesses at exactly the point terminal startup is already busiest.
|
||||
loginPreflightInFlight = runLoginPreflight(username, accountHome).then((result) => {
|
||||
cachedLoginPreflightResult = result
|
||||
if (!result) {
|
||||
console.warn('[pty] macOS login(1) preflight failed; spawning shells directly')
|
||||
}
|
||||
return result
|
||||
})
|
||||
}
|
||||
return loginPreflightInFlight
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the one-time PAM capability check before a fresh PTY is spawned.
|
||||
* Callers await this at their async request boundary so existing terminals and
|
||||
* the Electron main thread remain responsive while login(1) runs.
|
||||
*/
|
||||
export async function prepareMacosTccLoginShell(): Promise<void> {
|
||||
if (process.platform !== 'darwin' || isDisabledByEnv()) {
|
||||
return
|
||||
}
|
||||
if (cachedLoginPreflightResult !== null) {
|
||||
return
|
||||
}
|
||||
if (!existsSync(MACOS_LOGIN_PATH)) {
|
||||
return
|
||||
}
|
||||
|
||||
let username: string
|
||||
let accountHome: string
|
||||
try {
|
||||
const account = userInfo()
|
||||
username = account.username
|
||||
accountHome = account.homedir
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
if (!username || !accountHome) {
|
||||
return
|
||||
}
|
||||
await loginPreflightSucceeds(username, accountHome)
|
||||
}
|
||||
|
||||
export function resetMacosLoginShellPreflightForTests(): void {
|
||||
cachedLoginPreflightResult = null
|
||||
loginPreflightInFlight = null
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap a macOS shell spawn in `/usr/bin/login -flpq <user> …` so terminal children
|
||||
* get their own TCC identity instead of collapsing into Orca's bundle id — signed
|
||||
@@ -26,7 +120,8 @@ function isDisabledByEnv(): boolean {
|
||||
* under -p, so `/usr/bin/env SHELL=<shell>` re-asserts the shell Orca actually runs
|
||||
* without disturbing login's attribution (skipped when the shell path contains `=`).
|
||||
*
|
||||
* No-op off macOS, when already wrapped, or when disabled via {@link DISABLE_ENV_VAR}.
|
||||
* No-op off macOS, when already wrapped, when disabled via {@link DISABLE_ENV_VAR},
|
||||
* or when the login(1) PAM preflight rejects this process's user.
|
||||
*/
|
||||
export function wrapShellSpawnForMacosTccAttribution(
|
||||
file: string,
|
||||
@@ -52,6 +147,11 @@ export function wrapShellSpawnForMacosTccAttribution(
|
||||
if (!username) {
|
||||
return { file, args }
|
||||
}
|
||||
// Why: an unprepared or failed host must fail open to a usable direct shell;
|
||||
// production fresh-spawn boundaries await prepareMacosTccLoginShell first.
|
||||
if (cachedLoginPreflightResult !== true) {
|
||||
return { file, args }
|
||||
}
|
||||
|
||||
const shellEnvValue = env?.SHELL || file
|
||||
const interposedShellEnv =
|
||||
|
||||
Reference in New Issue
Block a user