Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(remote-desktop): preserve setup diagnostics across UAC

Lizie4fbb1ad3e67
diff --git a/apps/desktop/native/remote-desktop/windows-host/src/main.rs b/apps/desktop/native/remote-desktop/windows-host/src/main.rs
index 22d3307b63..3c5d91dd28 100644
--- a/apps/desktop/native/remote-desktop/windows-host/src/main.rs
+++ b/apps/desktop/native/remote-desktop/windows-host/src/main.rs
@@ -104,6 +104,6 @@ fn main() {
// One line for the Desktop log, and an exit code the unelevated parent
// can decode when this process is the hidden elevated child.
println!("{}", failure.line());
- std::process::exit(failure.step.exit() as i32);
+ std::process::exit(failure.exit_code() as i32);
}
}
diff --git a/apps/desktop/native/remote-desktop/windows-host/src/service.rs b/apps/desktop/native/remote-desktop/windows-host/src/service.rs
index 9af2c53299..c115e4fd83 100644
--- a/apps/desktop/native/remote-desktop/windows-host/src/service.rs
+++ b/apps/desktop/native/remote-desktop/windows-host/src/service.rs
@@ -167,6 +167,31 @@ pub fn uninstall(name: &str) -> Staged<()> {
))
}
};
+ // SERVICE_STOPPED is reported by the service entry point immediately
+ // before it returns. Keep a wait handle for the service process so the
+ // staged executable is no longer loaded before its files are replaced.
+ let process_handle = {
+ let mut process_status: SERVICE_STATUS_PROCESS = unsafe { mem::zeroed() };
+ let mut needed = 0;
+ let queried = unsafe {
+ QueryServiceStatusEx(
+ service.0,
+ SC_STATUS_PROCESS_INFO,
+ (&mut process_status as *mut SERVICE_STATUS_PROCESS).cast(),
+ mem::size_of_val(&process_status) as u32,
+ &mut needed,
+ )
+ };
+ if queried != 0
+ && process_status.dwCurrentState != SERVICE_STOPPED
+ && process_status.dwProcessId != 0
+ {
+ let raw = unsafe { OpenProcess(SYNCHRONIZE, 0, process_status.dwProcessId) };
+ Some(Handle::new(raw).stage(Step::ServiceStop)?)
+ } else {
+ None
+ }
+ };
let mut status: SERVICE_STATUS = unsafe { mem::zeroed() };
if unsafe { ControlService(service.0, SERVICE_CONTROL_STOP, &mut status) } == 0 {
let code = unsafe { GetLastError() };
@@ -187,6 +212,13 @@ pub fn uninstall(name: &str) -> Staged<()> {
}
std::thread::sleep(Duration::from_millis(100));
}
+ if let Some(process) = process_handle {
+ match unsafe { WaitForSingleObject(process.0, 5000) } {
+ WAIT_OBJECT_0 => {}
+ WAIT_FAILED => return Err(Failure::new(Step::ServiceStop, last_error())),
+ _ => return Err(Failure::new(Step::ServiceStop, ERROR_TIMEOUT as i32)),
+ }
+ }
if unsafe { DeleteService(service.0) } == 0 {
return Err(Failure::new(Step::ServiceDelete, last_error()));
}
@@ -232,10 +264,14 @@ pub fn elevate(command: &str) -> Staged<()> {
if code != 0 {
// The elevated child runs hidden, so its own failed step only reaches
// us through its exit code.
+ let (child, os) = match Failure::from_exit_code(code) {
+ Some((child, os)) => (Some(child), os),
+ None => (None, code as i32),
+ };
return Err(Failure {
step: Step::ElevateChild,
- os: code as i32,
- child: Step::from_exit(code),
+ os,
+ child,
});
}
Ok(())
diff --git a/apps/desktop/native/remote-desktop/windows-host/src/win.rs b/apps/desktop/native/remote-desktop/windows-host/src/win.rs
index d11f569836..6afc7b98d8 100644
--- a/apps/desktop/native/remote-desktop/windows-host/src/win.rs
+++ b/apps/desktop/native/remote-desktop/windows-host/src/win.rs
@@ -15,9 +15,11 @@ pub fn denied<T>() -> Result<T> {
Err(io::Error::from(io::ErrorKind::PermissionDenied))
}
-/// Setup exit codes start above the generic failure exit, so an ordinary crash
-/// is never decoded as one of the steps below.
-const EXIT_BASE: u32 = 16;
+/// The elevated child is hidden, so its step and raw Win32 error have to cross
+/// the UAC process boundary in the one value Windows gives us: the exit code.
+/// The low byte is the step (plus one); the remaining 24 bits carry the usual
+/// Win32 error range. A zero exit code remains success.
+const EXIT_STEP_MASK: u32 = 0xff;
/// Declares every step that can fail during lock-screen setup, keeping the
/// textual code and the numeric form in one list so the two cannot drift apart.
@@ -28,20 +30,18 @@ macro_rules! steps {
/// "failed". The numeric form travels back from the elevated child as
/// its process exit code, because the child's console output is hidden
/// from the parent. Codes carry no path, account or machine content.
- #[derive(Clone, Copy, PartialEq, Eq)]
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Step { $($variant,)* }
impl Step {
pub fn code(self) -> &'static str {
match self { $(Step::$variant => $code,)* }
}
- pub fn exit(self) -> u32 {
- self as u32 + EXIT_BASE
- }
- /// Maps an elevated child's exit code back to the step it failed at.
+ /// Maps the low byte of an elevated child's exit code back to its
+ /// failed step.
pub fn from_exit(value: u32) -> Option<Step> {
const ALL: &[Step] = &[$(Step::$variant,)*];
- value
- .checked_sub(EXIT_BASE)
+ (value & EXIT_STEP_MASK)
+ .checked_sub(1)
.and_then(|index| ALL.get(index as usize))
.copied()
}
@@ -108,6 +108,19 @@ impl Failure {
pub fn line(&self) -> String {
format!("error {}", self.detail())
}
+
+ /// Encodes the failed step and raw OS error for a hidden elevated child.
+ /// Win32 errors used by setup fit in the upper 24 bits; keeping the step in
+ /// the low byte makes the value independently decodable by the unelevated
+ /// parent without exposing paths or account names.
+ pub fn exit_code(&self) -> u32 {
+ (((self.os.max(0) as u32) & 0x00ff_ffff) << 8) | (self.step as u32 + 1)
+ }
+
+ pub fn from_exit_code(value: u32) -> Option<(Step, i32)> {
+ let step = Step::from_exit(value)?;
+ Some((step, (value >> 8) as i32))
+ }
}
impl std::fmt::Debug for Failure {
@@ -133,6 +146,29 @@ pub fn refuse<T>(step: Step) -> Staged<T> {
pub fn wide(value: &str) -> Vec<u16> {
value.encode_utf16().chain(Some(0)).collect()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn elevated_exit_code_round_trips_step_and_os_error() {
+ let failure = Failure::new(Step::StageWrite, 5);
+ assert_eq!(
+ Failure::from_exit_code(failure.exit_code()),
+ Some((Step::StageWrite, 5))
+ );
+ }
+
+ #[test]
+ fn elevated_exit_code_keeps_validation_failures_decodable() {
+ let failure = Failure::new(Step::ProtectedRoot, 0);
+ assert_eq!(
+ Failure::from_exit_code(failure.exit_code()),
+ Some((Step::ProtectedRoot, 0))
+ );
+ }
+}
pub struct Handle(pub HANDLE);
unsafe impl Send for Handle {}
impl Handle {
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/windowsLockScreenSetup.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/windowsLockScreenSetup.test.ts
index f0fa3aced9..a28c268e8f 100644
--- a/apps/desktop/src/main/remote-desktop/__tests__/windowsLockScreenSetup.test.ts
+++ b/apps/desktop/src/main/remote-desktop/__tests__/windowsLockScreenSetup.test.ts
@@ -27,6 +27,7 @@ import {
configureWindowsDesktopSupport,
readWindowsDesktopDetail,
readWindowsDesktopSupport,
+ windowsCargoTarget,
WindowsDesktopSetupError,
} from '../windowsHost';
@@ -54,6 +55,12 @@ Object.defineProperty(process, 'resourcesPath', {
});
describe('windows lock-screen setup diagnostics', () => {
+ it('builds source helpers for the running Electron architecture', () => {
+ expect(windowsCargoTarget('x64')).toBe('x86_64-pc-windows-msvc');
+ expect(windowsCargoTarget('arm64')).toBe('aarch64-pc-windows-msvc');
+ expect(() => windowsCargoTarget('ia32')).toThrow('Unsupported Windows desktop architecture');
+ });
+
it('reads the failed step from a status line and from an error line', () => {
expect(readWindowsDesktopDetail('installRequired protected-root 0')).toBe('protected-root 0');
expect(readWindowsDesktopDetail('error service-create 5')).toBe('service-create 5');
diff --git a/apps/desktop/src/main/remote-desktop/windowsHost.ts b/apps/desktop/src/main/remote-desktop/windowsHost.ts
index 0d6cef3f6b..f4e68f55c6 100644
--- a/apps/desktop/src/main/remote-desktop/windowsHost.ts
+++ b/apps/desktop/src/main/remote-desktop/windowsHost.ts
@@ -20,6 +20,19 @@ const packagedInput = () =>
path.join(process.resourcesPath, 'tools', 'remote-desktop', 'cindy-windows-desktop-input.exe');
type WindowsDesktopArtifacts = { binary: string; addon: string; input: string };
let build: Promise<WindowsDesktopArtifacts> | null = null;
+class WindowsDesktopArtifactsMissing extends Error {
+ constructor() {
+ super('WINDOWS_DESKTOP_ARTIFACTS_NOT_BUILT');
+ this.name = 'WindowsDesktopArtifactsMissing';
+ }
+}
+
+/** Match Cargo's Windows target to the architecture of the running Electron. */
+export function windowsCargoTarget(arch: NodeJS.Architecture = process.arch): string {
+ if (arch === 'arm64') return 'aarch64-pc-windows-msvc';
+ if (arch === 'x64') return 'x86_64-pc-windows-msvc';
+ throw new Error('Unsupported Windows desktop architecture: ' + arch);
+}
/**
* The packaged helper is already present in resources. In source mode, build
@@ -28,10 +41,16 @@ let build: Promise<WindowsDesktopArtifacts> | null = null;
* Main-only addon derive the same installation identity. The cache directory is
* stable across source edits; its source digest decides when it needs rebuilding.
*/
-async function resolveArtifacts(): Promise<WindowsDesktopArtifacts> {
+async function resolveArtifacts(
+ options: { allowBuild?: boolean } = {},
+): Promise<WindowsDesktopArtifacts> {
+ const allowBuild = options.allowBuild !== false;
if (app.isPackaged)
return { binary: packagedBinary(), addon: packagedAddon(), input: packagedInput() };
- if (build) return build;
+ if (build) {
+ if (!allowBuild) throw new WindowsDesktopArtifactsMissing();
+ return build;
+ }
const resolve = async (): Promise<WindowsDesktopArtifacts> => {
const nativeRoot = path.join(app.getAppPath(), 'native', 'remote-desktop');
const hostRoot = path.join(nativeRoot, 'windows-host');
@@ -109,8 +128,10 @@ async function resolveArtifacts(): Promise<WindowsDesktopArtifacts> {
// Build below. A partial cache is disposable and never becomes visible
// until both final files and the stamp have been written.
}
+ if (!allowBuild) throw new WindowsDesktopArtifactsMissing();
await fs.mkdir(helperDir, { recursive: true });
const buildDir = path.join(installRoot, 'build');
+ const cargoTarget = windowsCargoTarget();
const buildCargo = (
root: string,
targetDir: string,
@@ -123,6 +144,8 @@ async function resolveArtifacts(): Promise<WindowsDesktopArtifacts> {
'build',
'--release',
'--locked',
+ '--target',
+ cargoTarget,
'--manifest-path',
path.join(root, 'Cargo.toml'),
'--target-dir',
@@ -143,9 +166,9 @@ async function resolveArtifacts(): Promise<WindowsDesktopArtifacts> {
);
await buildCargo(hostRoot, path.join(buildDir, 'host-addon'), '--lib');
await buildCargo(inputRoot, path.join(buildDir, 'input'));
- const hostBinaryOutput = path.join(buildDir, 'host-bin', 'release');
- const hostAddonOutput = path.join(buildDir, 'host-addon', 'release');
- const inputOutput = path.join(buildDir, 'input', 'release');
+ const hostBinaryOutput = path.join(buildDir, 'host-bin', cargoTarget, 'release');
+ const hostAddonOutput = path.join(buildDir, 'host-addon', cargoTarget, 'release');
+ const inputOutput = path.join(buildDir, 'input', cargoTarget, 'release');
const temporaryBinary = binary + '.' + process.pid + '.tmp';
const temporaryAddon = versionedAddon + '.' + process.pid + '.tmp';
const temporaryInput = input + '.' + process.pid + '.tmp';
@@ -210,13 +233,17 @@ export async function readWindowsDesktopSupport(): Promise<WindowsDesktopSupport
if (process.platform !== 'win32') return undefined;
let stdout: string;
try {
- const { binary } = await resolveArtifacts();
+ // Status is queried by ordinary remote-desktop capability reads. Do not
+ // make those reads compile three Rust targets; an explicit setup action
+ // below is the point where a missing or stale source cache is built.
+ const { binary } = await resolveArtifacts({ allowBuild: false });
({ stdout } = await exec(binary, ['--status'], {
timeout: REMOTE_DESKTOP_OFFER_BUDGET.platformStatusMs,
maxBuffer: 1024,
windowsHide: true,
}));
} catch (error) {
+ if (error instanceof WindowsDesktopArtifactsMissing) return 'missing';
log.warn(
'status failed',
readWindowsDesktopDetail((error as { stdout?: unknown })?.stdout) ?? error,
diff --git a/docs/remote-desktop.md b/docs/remote-desktop.md
index 6318638762..5206bd0967 100644
--- a/docs/remote-desktop.md
+++ b/docs/remote-desktop.md
@@ -972,7 +972,8 @@ transport, a session-scoped SYSTEM GDI capture worker and the SendInput helper.
The settings page installs/removes the service through Windows administrator
consent. Any packaged installation is eligible, including Cindy's default
per-user one. Source-mode development runs build the same two host helpers in
-the per-user userData cache, then use the same protected staging path; their
+the per-user userData cache for the running Electron architecture, then use the
+same protected staging path; their
Electron process is accepted only for the exact PID approved by that setup's
administrator prompt.