Skip to content
32 changes: 32 additions & 0 deletions src/main/ipc/local-path-target-guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { stat } from 'node:fs/promises'
import { isAbsolute, normalize } from 'node:path'
import type { Store } from '../persistence'

/** True when the path exists on this machine's filesystem. */
export async function pathExists(pathValue: string): Promise<boolean> {
try {
await stat(pathValue)
return true
} catch {
return false
}
}

/** Normalizes a caller-supplied path, refusing anything not absolute or not present on disk. */
export async function validateLocalPathTarget(
pathValue: string
): Promise<{ ok: true; path: string } | { ok: false; reason: 'not-absolute' | 'not-found' }> {
const normalizedPath = normalize(pathValue)
if (!isAbsolute(normalizedPath)) {
return { ok: false, reason: 'not-absolute' }
}
if (!(await pathExists(normalizedPath))) {
return { ok: false, reason: 'not-found' }
}
return { ok: true, path: normalizedPath }
}

/** True when a remote runtime owns the session, so local-machine shell actions must refuse. */
export function hasActiveRuntime(store: Store): boolean {
return Boolean(store.getSettings().activeRuntimeEnvironmentId?.trim())
}
60 changes: 60 additions & 0 deletions src/main/ipc/shell-open-with-handlers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { ipcMain } from 'electron'
import { extname } from 'node:path'
import {
OPEN_WITH_CHOOSER_APPLICATION_ID,
type ShellListOpenWithApplicationsResult,
type ShellOpenLocalPathResult,
type ShellOpenPathWithApplicationRequest
} from '../../shared/shell-open-types'
import type { Store } from '../persistence'
import {
launchOpenWithApplication,
listOpenWithApplications
} from '../open-with/open-with-applications'
import { hasActiveRuntime, validateLocalPathTarget } from './local-path-target-guard'

/** Registers the Open With listing and launch IPC handlers. */
export function registerShellOpenWithHandlers(store: Store): void {
ipcMain.handle(
'shell:listOpenWithApplications',
async (_event, filePath: string): Promise<ShellListOpenWithApplicationsResult> => {
if (hasActiveRuntime(store)) {
return { ok: false, reason: 'remote-runtime-unsupported' }
}
const target = await validateLocalPathTarget(filePath)
if (!target.ok) {
return target
}
const listing = await listOpenWithApplications(target.path, {
recentApplicationIds: store.getOpenWithRecentApplicationIds(extname(target.path))
})
return { ok: true, ...listing }
}
)

ipcMain.handle(
'shell:openPathWithApplication',
async (
_event,
request: ShellOpenPathWithApplicationRequest
): Promise<ShellOpenLocalPathResult> => {
if (hasActiveRuntime(store)) {
return { ok: false, reason: 'remote-runtime-unsupported' }
}
const target = await validateLocalPathTarget(request.path)
if (!target.ok) {
return target
}
const launched = await launchOpenWithApplication(request.applicationId, target.path)
if (!launched) {
return { ok: false, reason: 'launch-failed' }
}
// Why: the Windows chooser dialog is not an application choice; Windows
// keeps its own MRU for it.
if (request.applicationId !== OPEN_WITH_CHOOSER_APPLICATION_ID) {
store.recordOpenWithApplicationLaunch(extname(target.path), request.applicationId)
}
return { ok: true }
}
)
}
114 changes: 113 additions & 1 deletion src/main/ipc/shell.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { pathToFileURL } from 'node:url'
const {
getSpawnArgsForWindowsMock,
handleMock,
launchOpenWithApplicationMock,
listOpenWithApplicationsMock,
openPathMock,
resolveCliCommandMock,
showItemInFolderMock,
Expand All @@ -14,6 +16,8 @@ const {
} = vi.hoisted(() => ({
getSpawnArgsForWindowsMock: vi.fn(),
handleMock: vi.fn(),
launchOpenWithApplicationMock: vi.fn(),
listOpenWithApplicationsMock: vi.fn(),
openPathMock: vi.fn(),
resolveCliCommandMock: vi.fn(),
showItemInFolderMock: vi.fn(),
Expand Down Expand Up @@ -55,6 +59,11 @@ vi.mock('../win32-utils', () => ({
getSpawnArgsForWindows: getSpawnArgsForWindowsMock
}))

vi.mock('../open-with/open-with-applications', () => ({
launchOpenWithApplication: launchOpenWithApplicationMock,
listOpenWithApplications: listOpenWithApplicationsMock
}))

import { EXTERNAL_EDITOR_CLI_COMMAND, registerShellHandlers } from './shell'
import { resolveExternalEditorLaunchSpec } from '../external-editor-launch'
import type { SshTarget } from '../../shared/ssh-types'
Expand Down Expand Up @@ -95,9 +104,13 @@ function createSshTarget(overrides: Partial<SshTarget> = {}): SshTarget {
describe('registerShellHandlers', () => {
const settings = { activeRuntimeEnvironmentId: null as string | null }
const sshTargets = new Map<string, SshTarget>()
const getOpenWithRecentApplicationIdsMock = vi.fn()
const recordOpenWithApplicationLaunchMock = vi.fn()
const store = {
getSettings: () => settings,
getSshTarget: (id: string) => sshTargets.get(id)
getSshTarget: (id: string) => sshTargets.get(id),
getOpenWithRecentApplicationIds: getOpenWithRecentApplicationIdsMock,
recordOpenWithApplicationLaunch: recordOpenWithApplicationLaunchMock
}

beforeEach(() => {
Expand All @@ -119,6 +132,11 @@ describe('registerShellHandlers', () => {
}))
spawnMock.mockReturnValue(createSpawnedProcess())
statMock.mockResolvedValue({ isDirectory: () => true })
launchOpenWithApplicationMock.mockReset()
listOpenWithApplicationsMock.mockReset()
getOpenWithRecentApplicationIdsMock.mockReset()
getOpenWithRecentApplicationIdsMock.mockReturnValue([])
recordOpenWithApplicationLaunchMock.mockReset()
})

function getHandler(channel: string): (event: unknown, ...args: unknown[]) => Promise<unknown> {
Expand Down Expand Up @@ -257,6 +275,100 @@ describe('registerShellHandlers', () => {
})
})

describe('shell:listOpenWithApplications', () => {
it('blocks discovery while a remote runtime is active', async () => {
settings.activeRuntimeEnvironmentId = 'runtime-1'
const handler = getHandler('shell:listOpenWithApplications')

await expect(handler({}, resolve('notes.md'))).resolves.toEqual({
ok: false,
reason: 'remote-runtime-unsupported'
})
expect(listOpenWithApplicationsMock).not.toHaveBeenCalled()
})

it('rejects relative paths', async () => {
const handler = getHandler('shell:listOpenWithApplications')

await expect(handler({}, 'relative/notes.md')).resolves.toEqual({
ok: false,
reason: 'not-absolute'
})
expect(listOpenWithApplicationsMock).not.toHaveBeenCalled()
})

it('returns the discovered applications for existing files', async () => {
const filePath = resolve('notes.md')
getOpenWithRecentApplicationIdsMock.mockReturnValue(['windows:c:\\recent.exe'])
listOpenWithApplicationsMock.mockResolvedValue({
applications: [{ id: 'windows:c:\\app.exe', name: 'App', isDefault: true }],
supportsChooserDialog: true
})
const handler = getHandler('shell:listOpenWithApplications')

await expect(handler({}, filePath)).resolves.toEqual({
ok: true,
applications: [{ id: 'windows:c:\\app.exe', name: 'App', isDefault: true }],
supportsChooserDialog: true
})
expect(getOpenWithRecentApplicationIdsMock).toHaveBeenCalledWith('.md')
expect(listOpenWithApplicationsMock).toHaveBeenCalledWith(normalize(filePath), {
recentApplicationIds: ['windows:c:\\recent.exe']
})
})
})

describe('shell:openPathWithApplication', () => {
it('blocks launches while a remote runtime is active', async () => {
settings.activeRuntimeEnvironmentId = 'runtime-1'
const handler = getHandler('shell:openPathWithApplication')

await expect(
handler({}, { path: resolve('notes.md'), applicationId: 'windows:c:\\app.exe' })
).resolves.toEqual({ ok: false, reason: 'remote-runtime-unsupported' })
expect(launchOpenWithApplicationMock).not.toHaveBeenCalled()
})

it('maps unknown applications and spawn errors to launch-failed', async () => {
launchOpenWithApplicationMock.mockResolvedValue(false)
const handler = getHandler('shell:openPathWithApplication')

await expect(
handler({}, { path: resolve('notes.md'), applicationId: 'windows:c:\\missing.exe' })
).resolves.toEqual({ ok: false, reason: 'launch-failed' })
})

it('launches the selected application and records the recency choice', async () => {
const filePath = resolve('notes.md')
launchOpenWithApplicationMock.mockResolvedValue(true)
const handler = getHandler('shell:openPathWithApplication')

await expect(
handler({}, { path: filePath, applicationId: 'windows:c:\\app.exe' })
).resolves.toEqual({ ok: true })
expect(launchOpenWithApplicationMock).toHaveBeenCalledWith(
'windows:c:\\app.exe',
normalize(filePath)
)
expect(recordOpenWithApplicationLaunchMock).toHaveBeenCalledWith('.md', 'windows:c:\\app.exe')
})

it('does not record recency for failed launches or the chooser dialog', async () => {
const filePath = resolve('notes.md')
const handler = getHandler('shell:openPathWithApplication')

launchOpenWithApplicationMock.mockResolvedValue(false)
await handler({}, { path: filePath, applicationId: 'windows:c:\\app.exe' })
expect(recordOpenWithApplicationLaunchMock).not.toHaveBeenCalled()

launchOpenWithApplicationMock.mockResolvedValue(true)
await expect(
handler({}, { path: filePath, applicationId: 'system:open-with-chooser' })
).resolves.toEqual({ ok: true })
expect(recordOpenWithApplicationLaunchMock).not.toHaveBeenCalled()
})
})

describe('shell:openInExternalEditor', () => {
it('rejects relative paths', async () => {
const handler = getHandler('shell:openInExternalEditor')
Expand Down
30 changes: 4 additions & 26 deletions src/main/ipc/shell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import type {
ShellOpenExternalEditorResult,
ShellOpenLocalPathResult
} from '../../shared/shell-open-types'
import { hasActiveRuntime, pathExists, validateLocalPathTarget } from './local-path-target-guard'
import { registerShellOpenWithHandlers } from './shell-open-with-handlers'
import { MAX_REPO_ICON_UPLOAD_BYTES } from '../../shared/repo-icon'
import type { Store } from '../persistence'
import {
Expand All @@ -23,32 +25,6 @@ const REPO_ICON_IMAGE_MIME_TYPES: Record<string, string> = {
'.png': 'image/png'
}

async function pathExists(pathValue: string): Promise<boolean> {
try {
await stat(pathValue)
return true
} catch {
return false
}
}

async function validateLocalPathTarget(
pathValue: string
): Promise<{ ok: true; path: string } | { ok: false; reason: 'not-absolute' | 'not-found' }> {
const normalizedPath = normalize(pathValue)
if (!isAbsolute(normalizedPath)) {
return { ok: false, reason: 'not-absolute' }
}
if (!(await pathExists(normalizedPath))) {
return { ok: false, reason: 'not-found' }
}
return { ok: true, path: normalizedPath }
}

function hasActiveRuntime(store: Store): boolean {
return Boolean(store.getSettings().activeRuntimeEnvironmentId?.trim())
}

async function openInFileManager(
store: Store,
pathValue: string
Expand Down Expand Up @@ -172,6 +148,8 @@ export function registerShellHandlers(store: Store): void {
return openWithSystemDefault(filePath)
})

registerShellOpenWithHandlers(store)

ipcMain.handle('shell:openFileUri', async (_event, rawUri: string) => {
let parsed: URL
try {
Expand Down
Loading