Bläddra i källkod

Run host queries without a shell

The screen, compositor and tray queries in platform.ts built shell strings (execSync + "2>/dev/null"). They now run the program directly through execFileSync, via flatpak-spawn --host inside a Flatpak, and drop stderr with stdio instead. This removes the CodeQL indirect-command-line-injection findings there.

hostShell had no callers left and is removed together with its tests.
UwU 4 veckor sedan
förälder
incheckning
e2f20e91f6

+ 0 - 8
src/main/utils/flatpak-host.test.ts

@@ -57,14 +57,6 @@ describe('isHostCommandAvailable', () => {
   })
 })
 
-describe('hostShell quoting', () => {
-  it('escapes single quotes in the passed session variables', async () => {
-    process.env.WAYLAND_DISPLAY = "a'b"
-    const { hostShell } = await load(true)
-    expect(hostShell('true')).toContain(`'--env=WAYLAND_DISPLAY=a'\\''b'`)
-  })
-})
-
 describe('sandbox info', () => {
   const info = '[Application]\nname=io.example.app\n\n[Instance]\ninstance-id=1234567\napp-path=/home/u/.local/share/flatpak/app/io.example.app/x86_64/stable/abc/files\n'
 

+ 3 - 7
src/main/utils/flatpak.test.ts

@@ -28,29 +28,25 @@ function setSession(values: Record<string, string>): void {
 
 describe('hostCommand', () => {
   it('runs the program itself outside a Flatpak', async () => {
-    const { hostCommand, hostShell, isFlatpak } = await load()
+    const { hostCommand, isFlatpak } = await load()
     expect(isFlatpak()).toBe(false)
     expect(hostCommand('kscreen-doctor', ['--outputs'])).toEqual(['kscreen-doctor', ['--outputs']])
-    expect(hostShell('xrandr --query 2>/dev/null')).toBe('xrandr --query 2>/dev/null')
   })
 
   it('goes through flatpak-spawn inside one', async () => {
     setSession({})
-    const { hostCommand, hostShell, isFlatpak } = await load('io.github.WallpaperEngineLover.we_manager')
+    const { hostCommand, isFlatpak } = await load('io.github.WallpaperEngineLover.we_manager')
     expect(isFlatpak()).toBe(true)
     expect(hostCommand('qdbus', ['org.kde.plasmashell'])).toEqual(['flatpak-spawn', ['--host', 'qdbus', 'org.kde.plasmashell']])
-    expect(hostShell('wlr-randr 2>/dev/null')).toBe('flatpak-spawn --host sh -c "wlr-randr 2>/dev/null"')
   })
 })
 
 describe('session variables for host programs', () => {
   it('passes the session to the host, whose helper may not have it', async () => {
     setSession({ WAYLAND_DISPLAY: 'wayland-1', HYPRLAND_INSTANCE_SIGNATURE: 'abc_1_2', XDG_CURRENT_DESKTOP: 'Hyprland' })
-    const { hostCommand, hostShell } = await load('io.github.WallpaperEngineLover.we_manager')
+    const { hostCommand } = await load('io.github.WallpaperEngineLover.we_manager')
     expect(hostCommand('hyprctl', ['monitors', '-j'])).toEqual(['flatpak-spawn', ['--host', '--env=WAYLAND_DISPLAY=wayland-1',
       '--env=XDG_CURRENT_DESKTOP=Hyprland', '--env=HYPRLAND_INSTANCE_SIGNATURE=abc_1_2', 'hyprctl', 'monitors', '-j']])
-    expect(hostShell('hyprctl monitors -j')).toBe("flatpak-spawn --host '--env=WAYLAND_DISPLAY=wayland-1' " +
-      "'--env=XDG_CURRENT_DESKTOP=Hyprland' '--env=HYPRLAND_INSTANCE_SIGNATURE=abc_1_2' sh -c \"hyprctl monitors -j\"")
   })
 
   it("keeps the sandbox's X display away from the host", async () => {

+ 0 - 6
src/main/utils/flatpak.ts

@@ -21,12 +21,6 @@ export function hostCommand(cmd: string, args: string[] = []): [string, string[]
   return isFlatpak() ? ['flatpak-spawn', ['--host', ...sessionEnvArgs(), cmd, ...args]] : [cmd, args]
 }
 
-export function hostShell(command: string): string {
-  if (!isFlatpak()) return command
-  const env = sessionEnvArgs().map((arg) => `'${arg.replace(/'/g, `'\\''`)}'`)
-  return ['flatpak-spawn --host', ...env, `sh -c ${JSON.stringify(command)}`].join(' ')
-}
-
 const hostCommandCache = new Map<string, boolean>()
 
 export function isHostCommandAvailable(cmd: string): boolean {

+ 5 - 2
src/main/utils/platform-session.test.ts

@@ -4,7 +4,10 @@ import * as path from 'path'
 import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
 
 const execSync = vi.fn<(command: string, options?: Record<string, unknown>) => string>()
-vi.mock('child_process', () => ({ execSync: (command: string, options?: Record<string, unknown>) => execSync(command, options) }))
+vi.mock('child_process', () => ({
+  execSync: (command: string, options?: Record<string, unknown>) => execSync(command, options),
+  execFileSync: (file: string, args: string[], options?: Record<string, unknown>) => execSync([file, ...args].join(' '), options)
+}))
 
 const platform = await import('./platform')
 
@@ -141,7 +144,7 @@ describe.skipIf(process.platform !== 'linux')('getMirroredScreens', () => {
     vi.stubEnv('XDG_CURRENT_DESKTOP', 'KDE')
     answer({ 'kscreen-doctor -j': kscreen })
     expect(platform.getMirroredScreens()).toEqual(['HDMI-A-1'])
-    expect(execSync.mock.calls[0][1]).toEqual({ encoding: 'utf8', timeout: 5000 })
+    expect(execSync.mock.calls[0][1]).toEqual({ encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] })
   })
 
   it('stays out of other sessions and survives a failing tool', () => {

+ 4 - 1
src/main/utils/platform.test.ts

@@ -3,7 +3,10 @@ import { join } from 'path'
 import { afterEach, describe, expect, it, vi } from 'vitest'
 
 const execSync = vi.fn<(command: string) => string>()
-vi.mock('child_process', () => ({ execSync: (command: string) => execSync(command) }))
+vi.mock('child_process', () => ({
+  execSync: (command: string) => execSync(command),
+  execFileSync: (file: string, args: string[]) => execSync([file, ...args].join(' '))
+}))
 
 const {
   getConnectedScreens,

+ 19 - 12
src/main/utils/platform.ts

@@ -1,8 +1,15 @@
 import fs from 'fs'
 import path from 'path'
-import { execSync } from 'child_process'
+import { execFileSync, execSync } from 'child_process'
 import { parseDesktopEnv, type DesktopEnvironment } from '@shared/desktop'
-import { hostShell } from './flatpak'
+import { hostCommand } from './flatpak'
+
+/** stdout of a program on the host, stderr dropped; the words are the program and its arguments */
+function hostOutput(commandLine: string, timeout: number): string {
+  const [program, ...args] = commandLine.split(' ')
+  const [file, fileArgs] = hostCommand(program, args)
+  return execFileSync(file, fileArgs, { encoding: 'utf8', timeout, stdio: ['ignore', 'pipe', 'ignore'] })
+}
 
 export type DisplayServer = 'wayland' | 'x11' | 'unknown'
 export type { DesktopEnvironment }
@@ -113,7 +120,7 @@ export function parseKscreenMirrors(json: string): string[] {
 export function getMirroredScreens(): string[] {
   if (process.platform !== 'linux' || !isWaylandSession() || detectDesktopEnv() !== 'kde') return []
   try {
-    return parseKscreenMirrors(execSync(hostShell('kscreen-doctor -j 2>/dev/null'), { encoding: 'utf8', timeout: 5000 }))
+    return parseKscreenMirrors(hostOutput('kscreen-doctor -j', 5000))
   } catch {
     return []
   }
@@ -128,14 +135,14 @@ export function getConnectedScreens(): string[] {
     for (const { marker, command, parse } of COMPOSITOR_QUERIES) {
       if (!process.env[marker]) continue
       try {
-        const output = execSync(hostShell(`${command} 2>/dev/null`), { encoding: 'utf8', timeout: 5000 })
+        const output = hostOutput(command, 5000)
         const screens = parse(output)
         if (screens.length > 0) return screens
       } catch { }
     }
 
     try {
-      const output = execSync(hostShell('wlr-randr 2>/dev/null'), { encoding: 'utf8', timeout: 5000 })
+      const output = hostOutput('wlr-randr', 5000)
       const screens = output
         .split('\n')
         .filter(line => /^[A-Za-z]/.test(line) && !line.startsWith(' '))
@@ -145,7 +152,7 @@ export function getConnectedScreens(): string[] {
     } catch { }
 
     try {
-      const output = execSync(hostShell('kscreen-doctor --outputs 2>/dev/null'), { encoding: 'utf8', timeout: 5000 })
+      const output = hostOutput('kscreen-doctor --outputs', 5000)
       const clean = output.replace(/\x1b\[[0-9;]*m/g, '')
       const screens = clean
         .split('\n')
@@ -158,9 +165,9 @@ export function getConnectedScreens(): string[] {
     } catch { }
 
     try {
-      const output = execSync(
-        hostShell("gdbus call --session --dest org.gnome.Mutter.DisplayConfig --object-path /org/gnome/Mutter/DisplayConfig --method org.gnome.Mutter.DisplayConfig.GetCurrentState 2>/dev/null"),
-        { encoding: 'utf8', timeout: 5000 }
+      const output = hostOutput(
+        'gdbus call --session --dest org.gnome.Mutter.DisplayConfig --object-path /org/gnome/Mutter/DisplayConfig --method org.gnome.Mutter.DisplayConfig.GetCurrentState',
+        5000
       )
       // gdbus prints the monitors as ('connector', 'vendor', 'product', 'serial') tuples
       const screens = [...new Set([...output.matchAll(/\(\('([^']+)',\s*'[^']*',\s*'[^']*',\s*'[^']*'\)/g)].map(m => m[1]))]
@@ -169,7 +176,7 @@ export function getConnectedScreens(): string[] {
   }
 
   try {
-    const output = execSync(hostShell('xrandr --query 2>/dev/null'), { encoding: 'utf8', timeout: 5000 })
+    const output = hostOutput('xrandr --query', 5000)
     const screens = output
       .split('\n')
       .filter(line => / connected/i.test(line))
@@ -194,7 +201,7 @@ export function parseXrandrGeometries(output: string): Map<string, string> {
 /** Geometry of the named screen, else of the first one */
 export function getScreenGeometry(screen?: string): string | null {
   try {
-    const output = execSync(hostShell('xrandr --query 2>/dev/null'), { encoding: 'utf8', timeout: 5000 })
+    const output = hostOutput('xrandr --query', 5000)
     const geometries = parseXrandrGeometries(output)
     return (screen && geometries.get(screen)) || geometries.values().next().value || null
   } catch {
@@ -227,7 +234,7 @@ export function hasStatusNotifierHost(maxAgeMs = TRAY_HOST_CACHE_MS): boolean {
   let value = true
   for (const command of NAME_HAS_OWNER_COMMANDS) {
     try {
-      const output = execSync(hostShell(`${command} 2>/dev/null`), { encoding: 'utf8', timeout: 2000 })
+      const output = hostOutput(command, 2000)
       const owned = parseNameHasOwner(output)
       if (owned !== null) {
         value = owned