Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(remote-desktop): guard Linux clipboard and window actions while locked
Dash Huang3c1687e9b827
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/linuxClipboard.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/linuxClipboard.test.tsindex a7771ef058..4e799152d3 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/linuxClipboard.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/linuxClipboard.test.ts@@ -1,10 +1,5 @@import { beforeEach, expect, it, vi } from 'vitest';-const h = vi.hoisted(() => ({ locked: false, text: 'text', supported: true, read: vi.fn() }));-vi.mock('node:child_process', () => ({ execFile: vi.fn() }));-vi.mock('node:util', () => ({- promisify: () => async () => ({ stdout: h.locked ? 'yes' : 'no' }),-}));-vi.mock('../linuxDesktop', () => ({ supportsLinuxLock: () => h.supported }));+const h = vi.hoisted(() => ({ text: 'text', read: vi.fn() }));vi.mock('../linuxClipboardNative', () => ({readLinuxClipboardSnapshot: async () => {h.read();@@ -14,8 +9,6 @@ vi.mock('../linuxClipboardNative', () => ({}));import { linuxClipboardVersion } from '../linuxClipboard';beforeEach(() => {- h.locked = false;- h.supported = true;h.text = 'text';h.read.mockClear();});@@ -26,11 +19,6 @@ it('changes the opaque generation when clipboard contents change', async () => {h.text = 'different';expect(await linuxClipboardVersion()).not.toBe(before);});-it('does not read clipboard content while the session is locked', async () => {- h.locked = true;- await expect(linuxClipboardVersion()).rejects.toThrow('DESKTOP_CLIPBOARD_UNAVAILABLE');- expect(h.read).not.toHaveBeenCalled();-});it('bounds content and returns no sampled text in an error', async () => {h.text = 'private'.repeat(100000);await expect(linuxClipboardVersion()).rejects.toThrow('CLIPBOARD_TOO_LONG');diff --git a/apps/desktop/src/main/remote-desktop/__tests__/linuxClipboardNative.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/linuxClipboardNative.test.tsindex f6d9c632db..b23e86760f 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/linuxClipboardNative.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/linuxClipboardNative.test.ts@@ -1,19 +1,65 @@+import { EventEmitter } from 'node:events';import { afterEach, beforeEach, expect, it, vi } from 'vitest';-const h = vi.hoisted(() => ({ exec: vi.fn() }));-vi.mock('electron', () => ({ app: {} }));-vi.mock('node:child_process', () => ({ execFile: vi.fn(), spawn: vi.fn() }));+const h = vi.hoisted(() => ({ exec: vi.fn(), unlocked: vi.fn(), spawn: vi.fn() }));+vi.mock('../linuxSessionLock', () => ({ isLinuxDesktopUnlocked: h.unlocked }));+vi.mock('electron', () => ({ app: { isPackaged: true } }));+vi.mock('node:child_process', () => ({ execFile: vi.fn(), spawn: h.spawn }));vi.mock('node:util', () => ({ promisify: () => h.exec }));vi.mock('node:fs', () => ({ accessSync: vi.fn(), constants: { X_OK: 1 } }));-import { readLinuxClipboardSnapshot } from '../linuxClipboardNative';+import { readLinuxClipboardSnapshot, writeLinuxClipboard } from '../linuxClipboardNative';beforeEach(() => {h.exec.mockReset();- vi.stubGlobal('process', { ...process, platform: 'linux' });+ h.spawn.mockReset();+ h.unlocked.mockReset().mockResolvedValue(true);+ vi.stubGlobal('process', { ...process, platform: 'linux', resourcesPath: '/runtime' });vi.stubEnv('HYPRLAND_INSTANCE_SIGNATURE', 'test');});+it('refuses clipboard writes while locked without starting an owner', async () => {+ h.unlocked.mockResolvedValue(false);+ await expect(writeLinuxClipboard({ text: 'private' }, () => true)).rejects.toThrow(+ 'DESKTOP_CLIPBOARD_UNAVAILABLE',+ );+ expect(h.spawn).not.toHaveBeenCalled();+});+it('kills the new clipboard owner if the compositor locks during its handshake', async () => {+ const stdout = new EventEmitter();+ const kill = vi.fn();+ const child = Object.assign(new EventEmitter(), {+ stdout,+ stderr: { resume: vi.fn() },+ stdin: {+ on: vi.fn(),+ write: vi.fn(() => {+ h.unlocked.mockResolvedValue(false);+ stdout.emit('data', Buffer.from('ready\n'));+ }),+ },+ kill,+ });+ h.spawn.mockReturnValue(child);+ await expect(writeLinuxClipboard({ text: 'private' }, () => true)).rejects.toThrow(+ 'DESKTOP_CLIPBOARD_UNAVAILABLE',+ );+ expect(kill).toHaveBeenCalledOnce();+});afterEach(() => {vi.unstubAllEnvs();vi.unstubAllGlobals();});+it.each([false, true])('refuses clipboard reads when locked (primary=%s)', async (primary) => {+ h.unlocked.mockResolvedValue(false);+ await expect(readLinuxClipboardSnapshot(primary)).rejects.toThrow(+ 'DESKTOP_CLIPBOARD_UNAVAILABLE',+ );+ expect(h.exec).not.toHaveBeenCalled();+});+it('discards clipboard content if the compositor locks during a native read', async () => {+ h.exec.mockImplementation(async () => {+ h.unlocked.mockResolvedValue(false);+ return { stdout: Buffer.from('private text') };+ });+ await expect(readLinuxClipboardSnapshot()).rejects.toThrow('DESKTOP_CLIPBOARD_UNAVAILABLE');+});it('reads all offered portable text alternatives while Cindy is unfocused', async () => {h.exec.mockImplementation(async (_tool, args: string[]) => ({stdout: Buffer.from(diff --git a/apps/desktop/src/main/remote-desktop/__tests__/linuxSessionLock.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/linuxSessionLock.test.tsnew file mode 100644index 0000000000..96ee7ad4e3--- /dev/null+++ b/apps/desktop/src/main/remote-desktop/__tests__/linuxSessionLock.test.ts@@ -0,0 +1,25 @@+import { beforeEach, expect, it, vi } from 'vitest';+const h = vi.hoisted(() => ({ exec: vi.fn() }));+vi.mock('node:child_process', () => ({ execFile: vi.fn() }));+vi.mock('node:util', () => ({ promisify: () => h.exec }));+import { isLinuxDesktopUnlocked } from '../linuxSessionLock';+beforeEach(() => h.exec.mockReset());+it.each([+ [[{ solitaryBlockedBy: [] }], true],+ [[{ solitaryBlockedBy: ['LOCK'] }], false],+ [[{ solitaryBlockedBy: [] }, { solitaryBlockedBy: ['LOCK'] }], false],+ [[{ solitaryBlockedBy: ['WORKSPACE'] }], false],+ [[{}], false],+ [[{ solitaryBlockedBy: [1] }], false],+ [[], false],+ [null, false],+])('uses actual compositor lock evidence: %j', async (monitors, expected) => {+ h.exec.mockResolvedValue({ stdout: JSON.stringify(monitors) });+ expect(await isLinuxDesktopUnlocked()).toBe(expected);+ expect(h.exec).toHaveBeenCalledWith('/usr/bin/hyprctl', ['-j', 'monitors'], expect.any(Object));+});+it('refuses unreadable or malformed compositor state', async () => {+ h.exec.mockRejectedValueOnce(new Error('timeout')).mockResolvedValueOnce({ stdout: 'bad json' });+ expect(await isLinuxDesktopUnlocked()).toBe(false);+ expect(await isLinuxDesktopUnlocked()).toBe(false);+});diff --git a/apps/desktop/src/main/remote-desktop/__tests__/linuxWindowActions.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/linuxWindowActions.test.tsindex 001a25f3cc..224717760d 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/linuxWindowActions.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/linuxWindowActions.test.ts@@ -26,6 +26,7 @@ function fixture(lua = false) {return 'ok';});const openMenu = vi.fn(async () => {});+ const unlocked = vi.fn(async () => true);const windows = new LinuxWindowActions(run,async () => ({@@ -40,11 +41,13 @@ function fixture(lua = false) {availableModes: [],}),openMenu,+ unlocked,);return {windows,run,openMenu,+ unlocked,workspace: () => workspace,navigate: (next: string) => {workspace = next;@@ -231,3 +234,35 @@ it.each(['workspaceLeft', 'workspaceRight', 'omarchyMenu'] as const)(expect(h.openMenu).not.toHaveBeenCalled();},);++it.each(['list', 'activate', 'desktop', 'workspaceLeft', 'workspaceRight', 'omarchyMenu'] as const)(+ 'refuses %s without reading titles or dispatching when locked',+ async (action) => {+ const h = fixture();+ h.unlocked.mockResolvedValue(false);+ await expect(h.windows.request(action, '0xabc', 'hyprland:eDP-2', () => true)).rejects.toThrow(+ 'DESKTOP_INPUT_UNAVAILABLE',+ );+ expect(h.run).not.toHaveBeenCalled();+ expect(h.openMenu).not.toHaveBeenCalled();+ },+);+it('discards titles if the session locks while clients are read', async () => {+ const h = fixture();+ h.unlocked.mockResolvedValueOnce(true).mockResolvedValue(false);+ await expect(h.windows.request('list', undefined, 'hyprland:eDP-2', () => true)).rejects.toThrow(+ 'DESKTOP_INPUT_UNAVAILABLE',+ );+});+it('does not dispatch after a syntax probe overlaps a local lock', async () => {+ const h = fixture();+ const run = h.run.getMockImplementation()!;+ h.run.mockImplementation(async (args) => {+ if (args[0] === 'eval') h.unlocked.mockResolvedValue(false);+ return run(args);+ });+ await expect(+ h.windows.request('activate', '0xabc', 'hyprland:eDP-2', () => true),+ ).rejects.toThrow('DESKTOP_INPUT_UNAVAILABLE');+ expect(h.run.mock.calls.some(([args]) => args[0] === 'dispatch')).toBe(false);+});diff --git a/apps/desktop/src/main/remote-desktop/linuxClipboard.ts b/apps/desktop/src/main/remote-desktop/linuxClipboard.tsindex 7729193981..85213096e2 100644--- a/apps/desktop/src/main/remote-desktop/linuxClipboard.ts+++ b/apps/desktop/src/main/remote-desktop/linuxClipboard.ts@@ -1,36 +1,15 @@import { createHash } from 'node:crypto';-import { execFile } from 'node:child_process';-import { promisify } from 'node:util';-import { supportsLinuxLock } from './linuxDesktop';import { readLinuxClipboardSnapshot } from './linuxClipboardNative';-const exec = promisify(execFile);/** Linux has no portable clipboard generation counter. Fingerprint only the* portable formats that our existing transfer path can expose, never file URLs.* This is called within the controlling lease, never as an application watcher. */-async function unlocked(): Promise<void> {- if (!supportsLinuxLock()) throw new Error('DESKTOP_CLIPBOARD_UNAVAILABLE');- try {- const { stdout } = await exec(- '/usr/bin/loginctl',- ['show-session', process.env.XDG_SESSION_ID!, '-p', 'LockedHint', '--value'],- { timeout: 1000, maxBuffer: 128 },- );- if (stdout.trim() !== 'no') throw new Error('DESKTOP_CLIPBOARD_UNAVAILABLE');- } catch {- throw new Error('DESKTOP_CLIPBOARD_UNAVAILABLE');- }-}export async function linuxClipboardVersion(): Promise<string> {- await unlocked();const snapshot = await readLinuxClipboardSnapshot();- await unlocked();return createHash('sha256').update(JSON.stringify(snapshot)).digest('hex');}export async function linuxSelection(): Promise<string> {- await unlocked();const text = (await readLinuxClipboardSnapshot(true)).content.text ?? '';- await unlocked();if (text.length > 16384) throw new Error('DESKTOP_CLIPBOARD_COPY_FAILED');return text;}diff --git a/apps/desktop/src/main/remote-desktop/linuxClipboardNative.ts b/apps/desktop/src/main/remote-desktop/linuxClipboardNative.tsindex 6b60469e34..e9c3bb5fda 100644--- a/apps/desktop/src/main/remote-desktop/linuxClipboardNative.ts+++ b/apps/desktop/src/main/remote-desktop/linuxClipboardNative.ts@@ -6,6 +6,7 @@ import fs from 'node:fs/promises';import { accessSync, constants } from 'node:fs';import path from 'node:path';import type { RemoteClipboardContent } from '@cindy/device-link';+import { isLinuxDesktopUnlocked } from './linuxSessionLock';const exec = promisify(execFile);export function supportsLinuxClipboard(): boolean {@@ -18,12 +19,14 @@ export function supportsLinuxClipboard(): boolean {}}async function read(args: string[], maxBuffer: number): Promise<Buffer> {+ if (!(await isLinuxDesktopUnlocked())) throw new Error('DESKTOP_CLIPBOARD_UNAVAILABLE');try {const result = await exec('/usr/bin/wl-paste', args, {timeout: 2000,maxBuffer,encoding: 'buffer',});+ if (!(await isLinuxDesktopUnlocked())) throw new Error('DESKTOP_CLIPBOARD_UNAVAILABLE');return result.stdout;} catch (error) {// Empty selection is distinct from failed compositor access. Never propagate@@ -136,6 +139,7 @@ export async function writeLinuxClipboard(current: () => boolean,): Promise<void> {const executable = await binary();+ if (!(await isLinuxDesktopUnlocked())) throw new Error('DESKTOP_CLIPBOARD_UNAVAILABLE');if (!current()) throw new Error('DESKTOP_LEASE_EXPIRED');const child = spawn(executable, [], { stdio: 'pipe' });child.stderr.resume();@@ -168,6 +172,7 @@ export async function writeLinuxClipboard(}) + '\n',);});+ if (!(await isLinuxDesktopUnlocked())) throw new Error('DESKTOP_CLIPBOARD_UNAVAILABLE');if (!current()) throw new Error('DESKTOP_LEASE_EXPIRED');writer?.kill();writer = child;diff --git a/apps/desktop/src/main/remote-desktop/linuxSessionLock.ts b/apps/desktop/src/main/remote-desktop/linuxSessionLock.tsnew file mode 100644index 0000000000..f874eabcb3--- /dev/null+++ b/apps/desktop/src/main/remote-desktop/linuxSessionLock.ts@@ -0,0 +1,27 @@+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';++const exec = promisify(execFile);++/** Read compositor lock ownership, not logind's advisory LockedHint. Mirrors the+ * credential helper's session probe without requiring an unlock-capable locker. */+export async function isLinuxDesktopUnlocked(): Promise<boolean> {+ try {+ const { stdout } = await exec('/usr/bin/hyprctl', ['-j', 'monitors'], {+ timeout: 1000,+ maxBuffer: 128000,+ });+ const monitors: unknown = JSON.parse(stdout);+ if (!Array.isArray(monitors) || !monitors.length || monitors.length > 32) return false;+ const blockers = monitors.map((monitor) => monitor?.solitaryBlockedBy);+ return (+ blockers.every(+ (items) => Array.isArray(items) && items.every((item) => typeof item === 'string'),+ ) &&+ !blockers.some((items) => items.includes('LOCK')) &&+ blockers.some((items) => !items.includes('WORKSPACE'))+ );+ } catch {+ return false;+ }+}diff --git a/apps/desktop/src/main/remote-desktop/linuxWindowActions.ts b/apps/desktop/src/main/remote-desktop/linuxWindowActions.tsindex ee8e1762b1..dfcdbad0cf 100644--- a/apps/desktop/src/main/remote-desktop/linuxWindowActions.ts+++ b/apps/desktop/src/main/remote-desktop/linuxWindowActions.ts@@ -4,6 +4,7 @@ import { accessSync, constants } from 'node:fs';import { promisify } from 'node:util';import type { RemoteDesktopWindow } from '@cindy/device-link';import { linuxMonitor } from './linuxDesktop';+import { isLinuxDesktopUnlocked } from './linuxSessionLock';const exec = promisify(execFile);export function supportsOmarchyMenu(): boolean {@@ -37,7 +38,11 @@ export class LinuxWindowActions {private readonly run = invoke,private readonly monitor = linuxMonitor,private readonly openMenu = openOmarchyMenu,+ private readonly unlocked = isLinuxDesktopUnlocked,) {}+ private async requireUnlocked(): Promise<void> {+ if (!(await this.unlocked())) throw new Error('DESKTOP_INPUT_UNAVAILABLE');+ }private async clients(): Promise<RemoteDesktopWindow[]> {const value: unknown = JSON.parse(await this.run(['-j', 'clients']));if (!Array.isArray(value) || value.length > 2048) throw new Error('DESKTOP_INPUT_UNAVAILABLE');@@ -56,7 +61,7 @@ export class LinuxWindowActions {private async dispatch(name: 'focuswindow' | 'focusmonitor' | 'workspace',value: string,- check: () => void = () => {},+ check: () => Promise<void> = () => this.requireUnlocked(),): Promise<void> {// Hyprland 0.55+ uses typed Lua dispatchers. Probe syntax without changing// configuration; never retry an already-issued action with another syntax.@@ -64,7 +69,7 @@ export class LinuxWindowActions {(value) => value === 'ok',() => false,);- check();+ await check();const field = { focuswindow: 'window', focusmonitor: 'monitor', workspace: 'workspace' }[name];if (!field || !/^[A-Za-z0-9_.:+-]{1,128}$/.test(value))throw new Error('DESKTOP_INPUT_UNAVAILABLE');@@ -82,50 +87,52 @@ export class LinuxWindowActions {current: () => boolean,): Promise<RemoteDesktopWindow[] | null> {const generation = this.generation;- const check = () => {+ const check = async () => {+ if (generation !== this.generation || !current()) throw new Error('DESKTOP_LEASE_EXPIRED');+ await this.requireUnlocked();if (generation !== this.generation || !current()) throw new Error('DESKTOP_LEASE_EXPIRED');};const operation = this.tail.catch(() => {}).then(async () => {- check();+ await check();if (action === 'list') {const windows = await this.clients();- check();+ await check();return windows;}if (action === 'activate') {const windows = await this.clients();- check();+ await check();if (!windows.some((window) => window.id === id))throw new Error('DESKTOP_INPUT_UNAVAILABLE');await this.restore(check);- check();+ await check();await this.dispatch('focuswindow', `address:${id}`, check);- check();+ await check();return null;}if (action === 'workspaceLeft' || action === 'workspaceRight' || action === 'omarchyMenu') {await this.restore(check);- check();+ await check();const selected = await this.monitor(displayId);- check();+ await check();await this.dispatch('focusmonitor', selected.name, check);- check();+ await check();if (action === 'omarchyMenu') await this.openMenu();else await this.dispatch('workspace', action === 'workspaceLeft' ? 'm-1' : 'm+1', check);- check();+ await check();return null;}if (this.desktop) {await this.restore(check);- check();+ await check();return null;}const selected = await this.monitor(displayId);- check();+ await check();const monitors: Monitor[] = JSON.parse(await this.run(['-j', 'monitors']));- check();+ await check();const target = monitors.find((m) => m.name === selected.name);if (!target ||@@ -139,19 +146,19 @@ export class LinuxWindowActions {temporary: `cindy-desktop-${randomBytes(8).toString('hex')}`,};await this.dispatch('focusmonitor', target.name, check);- check();+ await check();await this.dispatch('workspace', `name:${this.desktop.temporary}`, check);- check();+ await check();return null;});this.tail = operation;return operation;}- private async restore(check: () => void = () => {}): Promise<void> {+ private async restore(check: () => Promise<void> = () => this.requireUnlocked()): Promise<void> {const saved = this.desktop;if (!saved) return;const monitors: Monitor[] = JSON.parse(await this.run(['-j', 'monitors']));- check();+ await check();const selected = monitors.find((m) => m.name === saved.monitor);if (selected?.activeWorkspace.name === saved.temporary) {await this.dispatch('focusmonitor', saved.monitor, check);diff --git a/docs/remote-desktop.md b/docs/remote-desktop.mdindex 0eca689cad..c3b22429b4 100644--- a/docs/remote-desktop.md+++ b/docs/remote-desktop.md@@ -543,7 +543,12 @@ configurations are rejected rather than being silently replaced. Live scratchoutput tests cover resize, EOF, heartbeat timeout and SIGTERM cleanup.Linux clipboard transfer uses the existing bounded portable-format path and an-opaque content generation. Reads refuse a locked or unknown login session.+opaque content generation. Native reads and writes refuse a locked or unknown+compositor session; logind's advisory `LockedHint` does not prove it is unlocked.+Clipboard reads recheck after each subprocess result. Window lists and actions+use the same compositor probe, including after asynchronous dispatch preparation+and before returning titles. These checks also apply to Quickshell, independently+of whether its locker supports automatic password unlock.Hyprland reads use bounded `wl-paste` calls, so an unfocused Cindy window canread the actual system clipboard. A bundled data-control writer offers text,HTML, RTF and PNG together, without subprocess arguments or temporary files