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): protect Windows lock-screen service setup
Lizid96af935e074
diff --git a/apps/desktop/native/remote-desktop/windows-host/src/cursor.rs b/apps/desktop/native/remote-desktop/windows-host/src/cursor.rsindex 8f75614bf7..1ab6dab545 100644--- a/apps/desktop/native/remote-desktop/windows-host/src/cursor.rs+++ b/apps/desktop/native/remote-desktop/windows-host/src/cursor.rs@@ -205,13 +205,23 @@ unsafe fn raster(handle: HCURSOR) -> Option<(i32, i32, u32, u32, Vec<u8>)> {fn standard_shape(handle: HCURSOR) -> &'static str {for (id, shape) in [- (IDC_ARROW, "default"), (IDC_IBEAM, "text"), (IDC_HAND, "pointer"),- (IDC_CROSS, "crosshair"), (IDC_WAIT, "wait"), (IDC_APPSTARTING, "progress"),- (IDC_SIZEWE, "ew-resize"), (IDC_SIZENS, "ns-resize"),- (IDC_SIZENWSE, "nwse-resize"), (IDC_SIZENESW, "nesw-resize"),- (IDC_SIZEALL, "move"), (IDC_NO, "not-allowed"), (IDC_HELP, "help"),+ (IDC_ARROW, "default"),+ (IDC_IBEAM, "text"),+ (IDC_HAND, "pointer"),+ (IDC_CROSS, "crosshair"),+ (IDC_WAIT, "wait"),+ (IDC_APPSTARTING, "progress"),+ (IDC_SIZEWE, "ew-resize"),+ (IDC_SIZENS, "ns-resize"),+ (IDC_SIZENWSE, "nwse-resize"),+ (IDC_SIZENESW, "nesw-resize"),+ (IDC_SIZEALL, "move"),+ (IDC_NO, "not-allowed"),+ (IDC_HELP, "help"),] {- if unsafe { LoadCursorW(ptr::null_mut(), id) } == handle { return shape; }+ if unsafe { LoadCursorW(ptr::null_mut(), id) } == handle {+ return shape;+ }}"default"}@@ -243,8 +253,12 @@ mod tests {#[test]fn identifies_standard_native_shapes() {- for (id, expected) in [(IDC_ARROW, "default"), (IDC_IBEAM, "text"),- (IDC_HAND, "pointer"), (IDC_SIZEWE, "ew-resize")] {+ for (id, expected) in [+ (IDC_ARROW, "default"),+ (IDC_IBEAM, "text"),+ (IDC_HAND, "pointer"),+ (IDC_SIZEWE, "ew-resize"),+ ] {let handle = unsafe { LoadCursorW(ptr::null_mut(), id) };assert!(!handle.is_null());assert_eq!(standard_shape(handle), expected);diff --git a/apps/desktop/native/remote-desktop/windows-host/src/lib.rs b/apps/desktop/native/remote-desktop/windows-host/src/lib.rsindex d6fafcbdf6..283691a60f 100644--- a/apps/desktop/native/remote-desktop/windows-host/src/lib.rs+++ b/apps/desktop/native/remote-desktop/windows-host/src/lib.rs@@ -1,10 +1,11 @@//! Main-only Node-API transport: the OS sees the actual Cindy PID opening the//! pipe. A child process or a self-reported parent PID is never authorization.mod capture_protocol;+mod naming;mod pipe;mod win;+use naming::Installation;use napi_derive::napi;-use sha2::{Digest, Sha256};use std::{path::PathBuf,sync::{@@ -27,24 +28,20 @@ impl DesktopConnection {#[napi(factory)]pub async fn open(binary: String, init: String) -> napi::Result<Self> {tokio::task::spawn_blocking(move || {- let path = PathBuf::from(binary).canonicalize().map_err(failure)?;- let name = format!(- "CindyRemoteDesktop-{:x}",- Sha256::digest(path.to_string_lossy().to_lowercase().as_bytes())- )[..35]- .to_string();- let mut pipe = pipe::Pipe::client(&format!(r"\\.\pipe\{}", name)).map_err(failure)?;- let pid = pipe.server_pid().map_err(failure)?;- let server = win::process(pid).map_err(failure)?;- if !win::system(win::token(server.0).map_err(failure)?.0).map_err(failure)?- || win::image(server.0)- .map_err(failure)?- .canonicalize()- .map_err(failure)?- != path- {- return Err(failure("identity"));- }+ // `binary` is the helper shipped inside this installation. The+ // service runs the protected copy of it, so the pipe name is+ // derived from the installation rather than taken from a caller+ // supplied service name. The service itself checks the client PID+ // and the elevated setup flow checks the protected image.+ let bundled = PathBuf::from(binary)+ .canonicalize()+ .map_err(|e| failure(("bundled", e)))?;+ let installation =+ Installation::of_bundled(&bundled).map_err(|e| failure(e.detail()))?;+ let name = installation.service();+ let mut pipe = pipe::Pipe::client(&installation.pipe())+ .map_err(|e| failure(("pipe-client", e)))?;+ let pid = pipe.server_pid().map_err(|e| failure(("server-pid", e)))?;unsafe {let manager =OpenSCManagerW(std::ptr::null(), std::ptr::null(), SC_MANAGER_CONNECT);@@ -78,8 +75,8 @@ impl DesktopConnection {let parsed: serde_json::Value = serde_json::from_str(&init).map_err(failure)?;let response_limit = capture_protocol::response_limit(&parsed);pipe.write(format!("{init}\n").as_bytes())- .map_err(failure)?;- if pipe.line(1024).map_err(failure)? != b"ready\n" {+ .map_err(|e| failure(("write-init", e)))?;+ if pipe.line(1024).map_err(|e| failure(("read-ready", e)))? != b"ready\n" {return Err(failure("ready"));}let cancel = pipe.cancel.clone();diff --git a/apps/desktop/native/remote-desktop/windows-host/src/main.rs b/apps/desktop/native/remote-desktop/windows-host/src/main.rsindex 1a99e0c7ab..22d3307b63 100644--- a/apps/desktop/native/remote-desktop/windows-host/src/main.rs+++ b/apps/desktop/native/remote-desktop/windows-host/src/main.rs@@ -1,59 +1,109 @@mod capture;mod capture_protocol;mod cursor;+mod naming;mod pipe;mod security;mod service;+mod staging;mod win;+use naming::Installation;use sha2::{Digest, Sha256};use win::*;-fn service_name() -> Result<String> {+/// The service name used before the executable moved into a protected+/// directory: a hash of this bundled helper's own path. Removal still looks+/// for it, so a machine that enabled the feature under an older build is not+/// left with a stale registration no one deletes.+fn legacy_service_name() -> Result<String> {let path = std::env::current_exe()?.canonicalize()?.to_string_lossy().to_lowercase();Ok(format!("CindyRemoteDesktop-{:x}", Sha256::digest(path.as_bytes()))[..35].to_string())}-fn pipe_name() -> Result<String> {- Ok(format!(r"\\.\pipe\{}", service_name()?))++/// This executable's own installation, for the modes that run from inside one.+fn bundled() -> Staged<Installation> {+ Installation::of_bundled(&std::env::current_exe().stage(Step::ProtectedOpen)?)}-fn run() -> Result<()> {++fn run() -> Staged<()> {let args: Vec<String> = std::env::args().skip(1).collect();match args.first().map(String::as_str) {- Some("--service") => service::run(),- Some("--worker") if args.len() == 2 => service::worker(&args[1]),- Some("--install") if args.len() == 2 => {- let pid = args[1].parse::<u32>().map_err(|_| error())?;- service::install()?;- service::authorize(pid)+ Some("--service") => service::run().stage(Step::Service),+ Some("--worker") if args.len() == 2 => service::worker(&args[1]).stage(Step::Worker),+ Some("--install") if args.len() == 2 || args.len() == 3 => {+ let pid = args[1]+ .parse::<u32>()+ .map_err(|_| Failure::new(Step::Args, 0))?;+ let development = args.get(2).is_some_and(|arg| arg == "--development");+ if args.len() == 3 && !development {+ return refuse(Step::Args);+ }+ let installation = if development {+ bundled()?.for_development()+ } else {+ bundled()?+ };+ // Stop first: setup also runs for an upgrade, and the staged files+ // cannot be replaced while the service it starts still holds them.+ service::uninstall(&installation.service())?;+ service::install(&installation)?;+ service::authorize(&installation, pid)+ }+ Some("--uninstall") => {+ let installation = bundled()?;+ service::uninstall(&installation.service())?;+ if let Ok(legacy) = legacy_service_name() {+ service::uninstall(&legacy)?;+ }+ staging::unstage(&installation)}- Some("--uninstall") => service::uninstall(),- Some("--elevate-install") if args.len() == 2 => {- let pid = args[1].parse::<u32>().map_err(|_| error())?;- let (_main, _) = security::authorize_client(pid)?;- service::elevate(&format!("--install {pid}"))+ Some("--elevate-install") if args.len() == 2 || args.len() == 3 => {+ let pid = args[1]+ .parse::<u32>()+ .map_err(|_| Failure::new(Step::Args, 0))?;+ let development = args.get(2).is_some_and(|arg| arg == "--development");+ if args.len() == 3 && !development {+ return refuse(Step::Args);+ }+ let installation = if development {+ bundled()?.for_development()+ } else {+ bundled()?+ };+ let (_main, _) = security::authorize_client(pid, &installation.install, development)+ .stage(Step::ClientIdentity)?;+ let command = if development {+ format!("--install {pid} --development")+ } else {+ format!("--install {pid}")+ };+ service::elevate(&command)}Some("--elevate-uninstall") => service::elevate("--uninstall"),Some("--status") => {- println!(- "{}",- if service::pid().is_ok() {- "ready"- } else if security::protected_install().is_err() {- "installRequired"- } else {- "missing"+ let status = match bundled() {+ Ok(installation) if service::pid(&installation.service()).is_ok() => {+ "ready".to_string()}- );+ Ok(_) => "missing".to_string(),+ // Setup cannot run at all on this machine. Name the step, so+ // the settings page does not have to guess behind a bare word.+ Err(failure) => format!("installRequired {}", failure.detail()),+ };+ println!("{status}");Ok(())}- _ => denied(),+ _ => refuse(Step::Args),}}fn main() {- if run().is_err() {- println!("error");- std::process::exit(1);+ if let Err(failure) = run() {+ // 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);}}diff --git a/apps/desktop/native/remote-desktop/windows-host/src/naming.rs b/apps/desktop/native/remote-desktop/windows-host/src/naming.rsnew file mode 100644index 0000000000..1b4fc04335--- /dev/null+++ b/apps/desktop/native/remote-desktop/windows-host/src/naming.rs@@ -0,0 +1,252 @@+//! Names and locations derived from the Cindy installation that asked for+//! lock-screen control.+//!+//! The SYSTEM service runs from a copy in a protected directory rather than+//! from the installation, which may sit somewhere the current user can write.+//! Its own path therefore cannot be the shared identity. Every participant —+//! the copy inside the installation, the staged copy, and the Main-only+//! library — derives the same identity from the installation directory+//! instead, so none of them has to be told where the others are.+#![allow(dead_code)]+use crate::win::*;+use sha2::{Digest, Sha256};+use std::path::{Path, PathBuf};+use std::ptr;+use windows_sys::Win32::{System::Com::CoTaskMemFree, UI::Shell::*};++pub const HOST_EXE: &str = "cindy-windows-desktop-host.exe";+pub const INPUT_EXE: &str = "cindy-windows-desktop-input.exe";+/// Records which installation this staged copy serves. It lives in the+/// protected directory, so the service reads an administrator-written value+/// rather than trusting a path handed to it over the pipe.+pub const INSTALL_RECORD: &str = "install.txt";+/// One subdirectory per installation lives under this Program Files folder.+pub const STAGING_ROOT: &str = "Cindy Remote Desktop";++/// The installation directory a bundled helper belongs to. The helper ships at+/// `<install>/resources/tools/remote-desktop/<exe>`.+pub fn install_of(bundled_exe: &Path) -> Option<&Path> {+ bundled_exe+ .parent()+ .and_then(Path::parent)+ .and_then(Path::parent)+ .and_then(Path::parent)+}++/// A stable id for one installation. Two installations — Cindy and CindyDev,+/// or two copies of the same edition — never share a service, a pipe or a+/// staged executable.+pub fn install_id(install: &Path) -> String {+ let path = install.to_string_lossy().to_lowercase();+ format!("{:x}", Sha256::digest(path.as_bytes()))[..32].to_string()+}++pub fn service_name(id: &str) -> String {+ format!("CindyRemoteDesktop-{id}")+}++pub fn pipe_name(service: &str) -> String {+ format!(r"\\.\pipe\{service}")+}++/// Where this installation's staged copy of the helpers lives.+pub fn staged_dir(program_files: &Path, id: &str) -> PathBuf {+ program_files.join(STAGING_ROOT).join(id)+}++/// The machine's Program Files directory — the only place this host accepts a+/// SYSTEM service executable from.+pub fn program_files() -> Staged<PathBuf> {+ let mut raw = ptr::null_mut();+ if unsafe { SHGetKnownFolderPath(&FOLDERID_ProgramFiles, 0, ptr::null_mut(), &mut raw) } < 0+ || raw.is_null()+ {+ return refuse(Step::ProtectedRoot);+ }+ Ok(unsafe {+ let mut len = 0;+ while *raw.add(len) != 0 {+ len += 1;+ }+ let result = PathBuf::from(String::from_utf16_lossy(std::slice::from_raw_parts(+ raw, len,+ )));+ CoTaskMemFree(raw.cast());+ result+ })+}++/// Everything a helper inside the installation needs to address its own+/// staged copy.+pub struct Installation {+ pub install: PathBuf,+ pub id: String,+ pub staged: PathBuf,+ pub development: bool,+}++impl Installation {+ /// Derived by a helper running from inside the installation.+ ///+ /// The path is canonicalized first: the service, the setup command and the+ /// Main-only library each arrive here with a path of their own, and they+ /// have to agree on one id or they address different services.+ pub fn of_bundled(bundled_exe: &Path) -> Staged<Self> {+ let program_files = program_files()?;+ let bundled = bundled_exe.canonicalize().stage(Step::ProtectedOpen)?;+ let install = install_of(&bundled).ok_or(Failure::new(Step::ProtectedRoot, 0))?;+ let id = install_id(install);+ Ok(Self {+ staged: staged_dir(&program_files, &id),+ install: install.to_owned(),+ id,+ development: false,+ })+ }+ pub fn for_development(mut self) -> Self {+ self.development = true;+ self+ }+ pub fn service(&self) -> String {+ service_name(&self.id)+ }+ pub fn pipe(&self) -> String {+ pipe_name(&self.service())+ }+ pub fn host(&self) -> PathBuf {+ self.staged.join(HOST_EXE)+ }+}++/// What the staged copy can work out about itself from its own location,+/// before anything has been verified. The service manager starts it by path,+/// so its directory is the staging directory and that directory's name is the+/// installation id.+pub struct StagedCopy {+ pub dir: PathBuf,+ pub id: String,+}++#[derive(Clone)]+pub struct InstallRecord {+ pub path: PathBuf,+ pub development: bool,+}++impl StagedCopy {+ pub fn of(staged_exe: &Path) -> Staged<Self> {+ let dir = staged_exe+ .parent()+ .ok_or(Failure::new(Step::ProtectedRoot, 0))?+ .to_owned();+ let id = dir+ .file_name()+ .map(|name| name.to_string_lossy().into_owned())+ .filter(|name| {+ name.len() == 32+ && name+ .bytes()+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))+ })+ .ok_or(Failure::new(Step::ProtectedRoot, 0))?;+ Ok(Self { dir, id })+ }+ pub fn service(&self) -> String {+ service_name(&self.id)+ }+ pub fn pipe(&self) -> String {+ pipe_name(&self.service())+ }+ /// The installation this copy serves. Read only after the directory has+ /// been proven writable by administrators alone, since the answer decides+ /// which process may drive the service.+ pub fn install(&self) -> Staged<InstallRecord> {+ let record =+ std::fs::read_to_string(self.dir.join(INSTALL_RECORD)).stage(Step::StageRecord)?;+ let mut lines = record.lines();+ let install = PathBuf::from(lines.next().unwrap_or_default().trim());+ let development = match lines.next().map(str::trim) {+ None | Some("") => false,+ Some("development") => true,+ Some(_) => return refuse(Step::StageRecord),+ };+ if lines.next().is_some() {+ return refuse(Step::StageRecord);+ }+ // The directory name is the hash of the installation path, so a record+ // naming a different installation cannot redirect this service.+ if !install.is_absolute() || install_id(&install) != self.id {+ return refuse(Step::StageRecord);+ }+ Ok(InstallRecord {+ path: install,+ development,+ })+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// The service name is agreed on by three processes that each know a+ /// different path: the helper inside the installation, the staged copy the+ /// service manager starts, and the Node-API library in Cindy's main+ /// process. If these two derivations ever disagree, the setup command and+ /// the service it just installed address different pipes, and every+ /// connection fails with an identity error that names nothing useful.+ #[test]+ fn staged_copy_and_installation_agree_on_one_service_name() {+ let install = Path::new(r"C:\Users\someone\AppData\Local\Programs\Cindy");+ let id = install_id(install);+ let staged = staged_dir(Path::new(r"C:\Program Files"), &id);+ let copy = StagedCopy::of(&staged.join(HOST_EXE)).expect("staged layout is recognized");+ assert_eq!(copy.id, id);+ assert_eq!(copy.service(), service_name(&id));+ assert_eq!(copy.dir, staged);+ }++ #[test]+ fn installation_id_ignores_path_case_but_separates_installations() {+ let lower = install_id(Path::new(r"c:\program files\cindy"));+ let upper = install_id(Path::new(r"C:\Program Files\Cindy"));+ assert_eq!(+ lower, upper,+ "Windows paths differing only in case are one installation"+ );+ assert_ne!(+ upper,+ install_id(Path::new(r"C:\Program Files\CindyDev")),+ "separate installations must not share a service"+ );+ assert_eq!(upper.len(), 32);+ }++ /// The directory name becomes a service name and a pipe name, so a copy+ /// sitting somewhere unexpected must be refused rather than used to build+ /// those names out of arbitrary text.+ #[test]+ fn staged_copy_refuses_a_directory_that_is_not_an_installation_id() {+ for directory in [+ r"C:\Program Files\Cindy Remote Desktop\not-a-hash",+ r"C:\Program Files\Cindy Remote Desktop\ABCDEF0123456789abcdef0123456789",+ r"C:\Program Files\Cindy Remote Desktop\abc",+ ] {+ assert!(+ StagedCopy::of(&Path::new(directory).join(HOST_EXE)).is_err(),+ "{directory} should not be accepted as a staged copy"+ );+ }+ }++ #[test]+ fn installation_directory_is_found_above_the_bundled_helper() {+ let install = Path::new(r"C:\Program Files\Cindy");+ let bundled = install+ .join("resources")+ .join("tools")+ .join("remote-desktop")+ .join(HOST_EXE);+ assert_eq!(install_of(&bundled), Some(install));+ }+}diff --git a/apps/desktop/native/remote-desktop/windows-host/src/pipe.rs b/apps/desktop/native/remote-desktop/windows-host/src/pipe.rsindex 6f88ccfbb7..43a7a5b699 100644--- a/apps/desktop/native/remote-desktop/windows-host/src/pipe.rs+++ b/apps/desktop/native/remote-desktop/windows-host/src/pipe.rs@@ -84,22 +84,45 @@ impl Pipe {shutdown: None,})}+ /// Connects within the documented three-second open budget.+ ///+ /// The service drops and recreates its listening instance after every+ /// accept timeout, and reports RUNNING just before the first instance+ /// exists. `WaitNamedPipeW` returns immediately when no instance exists at+ /// all, so a single attempt can fail with `ERROR_FILE_NOT_FOUND` purely for+ /// landing in one of those gaps. Retry until the deadline, and keep waiting+ /// out `ERROR_PIPE_BUSY` the ordinary way.pub fn client(name: &str) -> Result<Self> {let name = wide(name);- unsafe {- WaitNamedPipeW(name.as_ptr(), 3000);- }- let handle = Handle::new(unsafe {- CreateFileW(- name.as_ptr(),- FILE_READ_DATA | FILE_WRITE_DATA | FILE_READ_ATTRIBUTES | SYNCHRONIZE,- 0,- ptr::null(),- OPEN_EXISTING,- FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION,- ptr::null_mut(),- )- })?;+ let deadline = Instant::now() + Duration::from_millis(3000);+ let handle = loop {+ let raw = unsafe {+ CreateFileW(+ name.as_ptr(),+ FILE_READ_DATA | FILE_WRITE_DATA | FILE_READ_ATTRIBUTES | SYNCHRONIZE,+ 0,+ ptr::null(),+ OPEN_EXISTING,+ FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION,+ ptr::null_mut(),+ )+ };+ if !raw.is_null() && raw != INVALID_HANDLE_VALUE {+ break Handle::new(raw)?;+ }+ let code = unsafe { GetLastError() };+ let remaining = deadline.saturating_duration_since(Instant::now());+ if remaining.is_zero() || (code != ERROR_FILE_NOT_FOUND && code != ERROR_PIPE_BUSY) {+ return Err(io::Error::from_raw_os_error(code as i32));+ }+ if code == ERROR_PIPE_BUSY {+ unsafe {+ WaitNamedPipeW(name.as_ptr(), remaining.as_millis() as u32);+ }+ } else {+ std::thread::sleep(Duration::from_millis(25).min(remaining));+ }+ };Ok(Self {handle,buffered: Vec::new(),diff --git a/apps/desktop/native/remote-desktop/windows-host/src/security.rs b/apps/desktop/native/remote-desktop/windows-host/src/security.rsindex 8a43987a4a..17933218f3 100644--- a/apps/desktop/native/remote-desktop/windows-host/src/security.rs+++ b/apps/desktop/native/remote-desktop/windows-host/src/security.rs@@ -1,17 +1,12 @@use crate::win::*;-use std::os::windows::fs::MetadataExt;use std::{mem,path::{Path, PathBuf},ptr,};use windows_sys::Win32::{- Foundation::*,- Security::Authorization::*,- Security::*,- Storage::FileSystem::*,- System::{Com::*, SystemServices::*},- UI::Shell::*,+ Foundation::*, Security::Authorization::*, Security::*, Storage::FileSystem::*,+ System::SystemServices::*,};pub fn same_file(a: &Path, b: &Path) -> bool {@@ -24,35 +19,51 @@ pub fn same_file(a: &Path, b: &Path) -> bool {}}-// Retain non-delete-sharing handles through caller authorization / worker spawn.-// Reject ACLs that we cannot prove safe rather than interpreting a path prefix as-// an integrity boundary. Installation does not silently repair administrator ACLs.-pub fn protected_install() -> Result<Vec<Handle>> {- let mut raw = ptr::null_mut();- if unsafe { SHGetKnownFolderPath(&FOLDERID_ProgramFiles, 0, ptr::null_mut(), &mut raw) } < 0 || raw.is_null() {- return denied();+/// The OS error number of the call that just failed.+fn last_os() -> i32 {+ unsafe { GetLastError() as i32 }+}++/// Proves the staged directory still holds what the service may run: the two+/// executables, the record naming the installation they serve, the directory+/// itself and every directory up to Program Files.+///+/// Only this directory is checked. The installation that Cindy itself runs+/// from is deliberately outside the boundary — it is writable by the account+/// that installed Cindy, which is why the service runs from a copy rather than+/// from there.+pub fn protected_staging(staged: &Path) -> Staged<Vec<Handle>> {+ let root = crate::naming::program_files()?;+ if !staged.starts_with(&root) || staged == root {+ return refuse(Step::ProtectedRoot);}- let root = unsafe {- let mut len = 0;- while *raw.add(len) != 0 {- len += 1;+ let mut paths = vec![+ staged.join(crate::naming::HOST_EXE),+ staged.join(crate::naming::INPUT_EXE),+ staged.join(crate::naming::INSTALL_RECORD),+ staged.to_owned(),+ ];+ ancestors(&mut paths, staged, &root);+ verify_protected(paths)+}++/// Adds every directory between `from` and the Program Files root: a writable+/// parent would let an attacker replace the whole subtree.+pub fn ancestors(paths: &mut Vec<PathBuf>, from: &Path, root: &Path) {+ let mut directory = from.parent();+ while let Some(path) = directory {+ paths.push(path.to_owned());+ if path == root {+ break;}- let result = PathBuf::from(String::from_utf16_lossy(std::slice::from_raw_parts(- raw, len,- )));- CoTaskMemFree(raw.cast());- result- };- let executable = std::env::current_exe()?;- let install = executable- .parent()- .and_then(Path::parent)- .and_then(Path::parent)- .and_then(Path::parent)- .ok_or_else(error)?;- if !install.starts_with(&root) || install == root {- return denied();+ directory = path.parent();}+}++/// Proves every path is owned by, and writable only by, SYSTEM, Administrators+/// or TrustedInstaller. The returned handles deny deletion for as long as the+/// caller holds them, so the files cannot be swapped after being checked.+pub fn verify_protected(paths: Vec<PathBuf>) -> Staged<Vec<Handle>> {let mut trusted_installer = ptr::null_mut();// Exact Windows servicing identity, not all service SIDs.if unsafe {@@ -62,7 +73,7 @@ pub fn protected_install() -> Result<Vec<Handle>> {)} == 0{- return Err(error());+ return Err(Failure::new(Step::ProtectedOpen, last_os()));}struct LocalSid(PSID);impl Drop for LocalSid {@@ -73,51 +84,6 @@ pub fn protected_install() -> Result<Vec<Handle>> {}}let trusted_installer = LocalSid(trusted_installer);- let mut paths = vec![- install.join("resources/app.asar"),- executable.clone(),- executable.with_file_name("cindy-windows-desktop-host.node"),- executable.with_file_name("cindy-windows-desktop-input.exe"),- ];- // Packaged exe identity is discovered only from the protected app directory.- // No caller-selected executable or command line is accepted by the broker.- for item in std::fs::read_dir(install)? {- let path = item?.path();- if path- .extension()- .is_some_and(|e| e.eq_ignore_ascii_case("exe") || e.eq_ignore_ascii_case("dll"))- {- paths.push(path);- }- }- // Unpacked native code is part of the executable trust boundary too.- let unpacked = install.join("resources/app.asar.unpacked");- if unpacked.exists() {- let mut pending = vec![unpacked];- while let Some(path) = pending.pop() {- let metadata = std::fs::symlink_metadata(&path)?;- if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {- return denied();- }- if metadata.is_dir() {- for item in std::fs::read_dir(&path)? {- pending.push(item?.path());- }- }- paths.push(path);- if paths.len() + pending.len() > 100_000 {- return denied();- }- }- }- let mut directory = executable.parent();- while let Some(path) = directory {- paths.push(path.to_owned());- if path == root {- break;- }- directory = path.parent();- }let mut handles = Vec::new();for path in paths {let handle = Handle::new(unsafe {@@ -130,12 +96,14 @@ pub fn protected_install() -> Result<Vec<Handle>> {FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,ptr::null_mut(),)- })?;+ })+ .stage(Step::ProtectedOpen)?;let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { mem::zeroed() };- if unsafe { GetFileInformationByHandle(handle.0, &mut info) } == 0- || info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0- {- return denied();+ if unsafe { GetFileInformationByHandle(handle.0, &mut info) } == 0 {+ return Err(Failure::new(Step::ProtectedOpen, last_os()));+ }+ if info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 {+ return refuse(Step::ProtectedReparse);}let mut owner = ptr::null_mut();let mut acl = ptr::null_mut();@@ -153,18 +121,23 @@ pub fn protected_install() -> Result<Vec<Handle>> {)};if code != ERROR_SUCCESS {- return denied();+ return Err(Failure::new(Step::ProtectedOpen, code as i32));}if acl.is_null() || owner.is_null() || unsafe { IsValidAcl(acl) } == 0 {- unsafe { LocalFree(descriptor); }- return denied();+ unsafe {+ LocalFree(descriptor);+ }+ return refuse(Step::ProtectedAcl);}let trusted = |sid| unsafe {IsWellKnownSid(sid, WinLocalSystemSid) != 0|| IsWellKnownSid(sid, WinBuiltinAdministratorsSid) != 0|| EqualSid(sid, trusted_installer.0) != 0};- let mut safe = trusted(owner);+ // Separate codes: an untrusted owner and a stray writable ACE need+ // different answers from whoever reads the log.+ let mut failed = (!trusted(owner)).then_some(Step::ProtectedOwner);+ let mut safe = failed.is_none();if safe {unsafe {for i in 0..(*acl).AceCount as u32 {@@ -212,14 +185,22 @@ pub fn protected_install() -> Result<Vec<Handle>> {LocalFree(descriptor);}if !safe {- return denied();+ return refuse(failed.take().unwrap_or(Step::ProtectedAcl));}handles.push(handle);}Ok(handles)}-pub fn authorize_client(pid: u32) -> Result<(Handle, u32)> {+/// Accepts a Cindy process as the owner of this service's lease.+///+/// `install` is the directory the staged copy records as its installation.+/// That directory is writable by the account that installed Cindy, so the+/// image check below is a consistency check, not a trust boundary: what keeps+/// an arbitrary process from driving the service is that the caller must be+/// the exact process an administrator approved during setup, still alive and+/// still on the active console session.+pub fn authorize_client(pid: u32, install: &Path, development: bool) -> Result<(Handle, u32)> {let client = process(pid)?;let session = session(token(client.0)?.0)?;if session == 0@@ -229,19 +210,28 @@ pub fn authorize_client(pid: u32) -> Result<(Handle, u32)> {return denied();}let client_image = image(client.0)?;- let executable = std::env::current_exe()?;- let install = executable- .parent()- .and_then(Path::parent)- .and_then(Path::parent)- .and_then(Path::parent)- .ok_or_else(error)?;- if !client_image.parent().is_some_and(|p| same_file(p, install))- || !client_image.file_name().is_some_and(|n| {+ let packaged = client_image.parent().is_some_and(|p| same_file(p, install))+ && client_image.file_name().is_some_and(|n| {n.eq_ignore_ascii_case("Cindy.exe") || n.eq_ignore_ascii_case("CindyDev.exe")- })- {+ });+ // Source-mode Electron is named electron.exe and lives under+ // node_modules, so it cannot satisfy the packaged installation-parent+ // check. The PID is still the one explicitly approved by the elevated+ // setup flow and is retained by the service for every later pipe client.+ let development_electron = development+ && client_image+ .file_name()+ .is_some_and(|n| n.eq_ignore_ascii_case("electron.exe"));+ if !packaged && !development_electron {return denied();}Ok((client, session))}++/// Whether two files hold exactly the same bytes. Used to confirm that the+/// elevated process asking the service to register a Cindy process is running+/// the very same helper build the service itself was started from.+pub fn same_contents(a: &Path, b: &Path) -> Result<bool> {+ let (a, b) = (std::fs::read(a)?, std::fs::read(b)?);+ Ok(a == b)+}diff --git a/apps/desktop/native/remote-desktop/windows-host/src/service.rs b/apps/desktop/native/remote-desktop/windows-host/src/service.rsindex 80f5def279..9af2c53299 100644--- a/apps/desktop/native/remote-desktop/windows-host/src/service.rs+++ b/apps/desktop/native/remote-desktop/windows-host/src/service.rs@@ -1,3 +1,4 @@+use crate::naming::{InstallRecord, Installation, StagedCopy};use crate::{pipe::Pipe, win::*};use std::{io::{self, BufRead, Write},@@ -19,6 +20,18 @@ static AUTHORIZED: Mutex<Option<Handle>> = Mutex::new(None);static STOP: AtomicBool = AtomicBool::new(false);static CLIENTS: AtomicUsize = AtomicUsize::new(0);static STATUS: Mutex<usize> = Mutex::new(0);+/// The installation this running service accepts clients from, taken from the+/// record in its own protected directory once that directory has been checked.+static INSTALL: Mutex<Option<InstallRecord>> = Mutex::new(None);++/// The installation the running service serves, or a refusal if it never+/// finished validating one.+fn approved_install() -> Result<InstallRecord> {+ match INSTALL.lock().map_err(|_| error())?.as_ref() {+ Some(install) => Ok(install.clone()),+ None => denied(),+ }+}struct ServiceHandle(SC_HANDLE);impl Drop for ServiceHandle {fn drop(&mut self) {@@ -35,17 +48,17 @@ fn manager(access: u32) -> Result<ServiceHandle> {Ok(ServiceHandle(value))}}-fn service(manager: &ServiceHandle, access: u32) -> Result<ServiceHandle> {- let value = unsafe { OpenServiceW(manager.0, wide(&crate::service_name()?).as_ptr(), access) };+fn service(manager: &ServiceHandle, name: &str, access: u32) -> Result<ServiceHandle> {+ let value = unsafe { OpenServiceW(manager.0, wide(name).as_ptr(), access) };if value.is_null() {Err(error())} else {Ok(ServiceHandle(value))}}-pub fn pid() -> Result<u32> {+pub fn pid(name: &str) -> Result<u32> {let manager = manager(SC_MANAGER_CONNECT)?;- let service = service(&manager, SERVICE_QUERY_STATUS)?;+ let service = service(&manager, name, SERVICE_QUERY_STATUS)?;let mut status: SERVICE_STATUS_PROCESS = unsafe { mem::zeroed() };let mut size = 0;if unsafe {@@ -64,12 +77,13 @@ pub fn pid() -> Result<u32> {}Ok(status.dwProcessId)}-pub fn install() -> Result<()> {- let _guard = crate::security::protected_install()?;- let manager = manager(SC_MANAGER_CREATE_SERVICE | SC_MANAGER_CONNECT)?;- let name = wide(&crate::service_name()?);- let executable = std::env::current_exe()?;- let command = wide(&format!("\"{}\" --service", executable.display()));+/// Registers and starts the service for one installation, running the staged+/// copy rather than the executable inside the installation.+pub fn install(installation: &Installation) -> Staged<()> {+ let staged = crate::staging::stage(installation)?;+ let manager = manager(SC_MANAGER_CREATE_SERVICE | SC_MANAGER_CONNECT).stage(Step::ScmOpen)?;+ let name = wide(&installation.service());+ let command = wide(&format!("\"{}\" --service", staged.display()));let raw = unsafe {CreateServiceW(manager.0,@@ -88,61 +102,113 @@ pub fn install() -> Result<()> {)};let installed = if raw.is_null() {- if unsafe { GetLastError() } != ERROR_SERVICE_EXISTS {- return Err(error());+ let code = unsafe { GetLastError() };+ if code != ERROR_SERVICE_EXISTS {+ return Err(Failure::new(Step::ServiceCreate, code as i32));}- service(&manager, SERVICE_START | SERVICE_QUERY_STATUS)?+ // An existing registration may still point at an older staged copy, so+ // update its command line before starting it.+ let existing = service(+ &manager,+ &installation.service(),+ SERVICE_START | SERVICE_QUERY_STATUS | SERVICE_CHANGE_CONFIG,+ )+ .stage(Step::ServiceCreate)?;+ if unsafe {+ ChangeServiceConfigW(+ existing.0,+ SERVICE_NO_CHANGE,+ SERVICE_NO_CHANGE,+ SERVICE_NO_CHANGE,+ command.as_ptr(),+ ptr::null(),+ ptr::null_mut(),+ ptr::null(),+ ptr::null(),+ ptr::null(),+ ptr::null(),+ )+ } == 0+ {+ return Err(Failure::new(Step::ServiceCreate, last_error()));+ }+ existing} else {ServiceHandle(raw)};- if unsafe { StartServiceW(installed.0, 0, ptr::null()) } == 0- && unsafe { GetLastError() } != ERROR_SERVICE_ALREADY_RUNNING- {- return Err(error());+ if unsafe { StartServiceW(installed.0, 0, ptr::null()) } == 0 {+ let code = unsafe { GetLastError() };+ if code != ERROR_SERVICE_ALREADY_RUNNING {+ return Err(Failure::new(Step::ServiceStart, code as i32));+ }}+ // The service validates its own executable before reporting RUNNING, so a+ // refusal there shows up here as a start that never completes.let deadline = Instant::now() + Duration::from_secs(8);while Instant::now() < deadline {- if pid().is_ok() {+ if pid(&installation.service()).is_ok() {return Ok(());}std::thread::sleep(Duration::from_millis(100));}- Err(io::Error::from(io::ErrorKind::TimedOut))+ refuse(Step::ServiceReady)}-pub fn uninstall() -> Result<()> {- let manager = manager(SC_MANAGER_CONNECT)?;- let service = match service(&manager, SERVICE_STOP | DELETE | SERVICE_QUERY_STATUS) {+/// Stops and deregisters one service by name. The staged files are removed+/// separately, after the service that runs them has stopped.+pub fn uninstall(name: &str) -> Staged<()> {+ let manager = manager(SC_MANAGER_CONNECT).stage(Step::ScmOpen)?;+ let service = match service(&manager, name, SERVICE_STOP | DELETE | SERVICE_QUERY_STATUS) {Ok(s) => s,Err(e) if e.raw_os_error() == Some(ERROR_SERVICE_DOES_NOT_EXIST as i32) => return Ok(()),- Err(e) => return Err(e),+ Err(e) => {+ return Err(Failure::new(+ Step::ServiceStop,+ e.raw_os_error().unwrap_or(0),+ ))+ }};let mut status: SERVICE_STATUS = unsafe { mem::zeroed() };- if unsafe { ControlService(service.0, SERVICE_CONTROL_STOP, &mut status) } == 0- && unsafe { GetLastError() } != ERROR_SERVICE_NOT_ACTIVE- {- return Err(error());+ if unsafe { ControlService(service.0, SERVICE_CONTROL_STOP, &mut status) } == 0 {+ let code = unsafe { GetLastError() };+ if code != ERROR_SERVICE_NOT_ACTIVE {+ return Err(Failure::new(Step::ServiceStop, code as i32));+ }}let deadline = Instant::now() + Duration::from_secs(20);loop {if unsafe { QueryServiceStatus(service.0, &mut status) } == 0 {- return Err(error());+ return Err(Failure::new(Step::ServiceStop, last_error()));}if status.dwCurrentState == SERVICE_STOPPED {break;}if Instant::now() >= deadline {- return Err(io::Error::from(io::ErrorKind::TimedOut));+ return refuse(Step::ServiceStop);}std::thread::sleep(Duration::from_millis(100));}if unsafe { DeleteService(service.0) } == 0 {- return Err(error());+ return Err(Failure::new(Step::ServiceDelete, last_error()));}Ok(())}-pub fn elevate(command: &str) -> Result<()> {- let _guard = crate::security::protected_install()?;- let executable = wide(&std::env::current_exe()?.to_string_lossy());+/// The OS error number of the call that just failed.+fn last_error() -> i32 {+ unsafe { GetLastError() as i32 }+}+/// Relaunches this executable elevated, to run one setup command.+///+/// There is deliberately no check on where this executable lives: Cindy+/// installs per user by default, so it normally sits in a directory the+/// current user can write. What the elevated child does with that is the+/// subject of `staging` — it copies the helpers somewhere only administrators+/// can write before registering anything as SYSTEM.+pub fn elevate(command: &str) -> Staged<()> {+ let executable = wide(+ &std::env::current_exe()+ .stage(Step::ElevateLaunch)?+ .to_string_lossy(),+ );let verb = wide("runas");let parameters = wide(command);let mut info: SHELLEXECUTEINFOW = unsafe { mem::zeroed() };@@ -153,15 +219,24 @@ pub fn elevate(command: &str) -> Result<()> {info.lpParameters = parameters.as_ptr();info.nShow = SW_HIDE;if unsafe { ShellExecuteExW(&mut info) } == 0 {- return Err(error());+ return Err(Failure::new(Step::ElevateLaunch, last_error()));}- let process = Handle::new(info.hProcess)?;+ let process = Handle::new(info.hProcess).stage(Step::ElevateLaunch)?;if unsafe { WaitForSingleObject(process.0, 120000) } != WAIT_OBJECT_0 {- return Err(io::Error::from(io::ErrorKind::TimedOut));+ return refuse(Step::ElevateTimeout);}let mut code = 1;- if unsafe { GetExitCodeProcess(process.0, &mut code) } == 0 || code != 0 {- return denied();+ if unsafe { GetExitCodeProcess(process.0, &mut code) } == 0 {+ return Err(Failure::new(Step::ElevateChild, last_error()));+ }+ if code != 0 {+ // The elevated child runs hidden, so its own failed step only reaches+ // us through its exit code.+ return Err(Failure {+ step: Step::ElevateChild,+ os: code as i32,+ child: Step::from_exit(code),+ });}Ok(())}@@ -204,19 +279,40 @@ unsafe extern "system" fn control(0}unsafe extern "system" fn entry(_argc: u32, _argv: *mut *mut u16) {- let Ok(name) = crate::service_name() else {+ let Ok(copy) = std::env::current_exe()+ .map_err(drop)+ .and_then(|exe| StagedCopy::of(&exe).map_err(drop))+ else {return;};- let handle =- RegisterServiceCtrlHandlerExW(wide(&name).as_ptr(), Some(control), ptr::null_mut());+ let handle = RegisterServiceCtrlHandlerExW(+ wide(©.service()).as_ptr(),+ Some(control),+ ptr::null_mut(),+ );if handle.is_null() {return;}*STATUS.lock().unwrap() = handle as usize;- let Ok(_installation) = crate::security::protected_install() else {+ // Prove this copy is still administrator-owned before acting as SYSTEM,+ // and only then read which installation it was staged for. The handles+ // stay held for the service's lifetime so the files cannot be swapped+ // after the check.+ let Ok(_staged) = crate::security::protected_staging(©.dir) else {status(SERVICE_STOPPED);return;};+ let Ok(install) = copy.install() else {+ status(SERVICE_STOPPED);+ return;+ };+ match INSTALL.lock() {+ Ok(mut approved) => *approved = Some(install),+ Err(_) => {+ status(SERVICE_STOPPED);+ return;+ }+ }status(SERVICE_RUNNING);let registration_deadline = Instant::now() + Duration::from_secs(30);while !STOP.load(Ordering::SeqCst) {@@ -237,7 +333,7 @@ unsafe extern "system" fn entry(_argc: u32, _argv: *mut *mut u16) {std::thread::sleep(Duration::from_millis(100));continue;}- let Ok(mut pipe) = Pipe::server(&crate::pipe_name().unwrap(), false) else {+ let Ok(mut pipe) = Pipe::server(©.pipe(), false) else {std::thread::sleep(Duration::from_millis(500));continue;};@@ -263,7 +359,8 @@ unsafe extern "system" fn entry(_argc: u32, _argv: *mut *mut u16) {status(SERVICE_STOPPED);}pub fn run() -> Result<()> {- let name = wide(&crate::service_name()?);+ let copy = StagedCopy::of(&std::env::current_exe()?).map_err(|_| error())?;+ let name = wide(©.service());let table = [SERVICE_TABLE_ENTRYW {lpServiceName: name.as_ptr().cast_mut(),@@ -408,11 +505,14 @@ fn serve(mut client: Pipe) -> Result<()> {let init = client.line(1024)?;let parsed: serde_json::Value = serde_json::from_slice(&init)?;if parsed["mode"] == "authorize" {- // Only the fixed UAC-elevated setup executable may register a process.+ // Only an elevated run of this same helper build may register a+ // process. The caller runs from the installation while this service+ // runs from its protected copy, so their paths differ by design and+ // identical contents is what proves they are the same build.let caller_token = token(caller.0)?;let mut elevation: TOKEN_ELEVATION = unsafe { mem::zeroed() };let mut needed = 0;- if !crate::security::same_file(&image(caller.0)?, &std::env::current_exe()?)+ if !crate::security::same_contents(&image(caller.0)?, &std::env::current_exe()?)?|| unsafe {GetTokenInformation(caller_token.0,@@ -430,7 +530,9 @@ fn serve(mut client: Pipe) -> Result<()> {.as_u64().filter(|p| *p <= u32::MAX as u64).ok_or_else(error)? as u32;- let (main, _) = crate::security::authorize_client(main_pid)?;+ let install = approved_install()?;+ let (main, _) =+ crate::security::authorize_client(main_pid, &install.path, install.development)?;*AUTHORIZED.lock().map_err(|_| error())? = Some(main);return client.write(b"ready\n");}@@ -443,7 +545,12 @@ fn serve(mut client: Pipe) -> Result<()> {return denied();}}- let (owner, session) = crate::security::authorize_client(client.client_pid()?)?;+ let install = approved_install()?;+ let (owner, session) = crate::security::authorize_client(+ client.client_pid()?,+ &install.path,+ install.development,+ )?;if parsed["mode"] == "probe" {return client.write(b"ready\n");}@@ -456,7 +563,9 @@ fn serve(mut client: Pipe) -> Result<()> {}let name = format!(r"\\.\pipe\{}-{:08x}{:04x}{:04x}{:02x?}",- crate::service_name()?,+ StagedCopy::of(&std::env::current_exe()?)+ .map_err(|_| error())?+ .service(),guid.data1,guid.data2,guid.data3,@@ -593,13 +702,14 @@ impl Drop for InputChild {}}pub fn worker(name: &str) -> Result<()> {+ let copy = StagedCopy::of(&std::env::current_exe()?).map_err(|_| error())?;if !system(token(unsafe { GetCurrentProcess() })?.0)?- || !name.starts_with(&format!(r"\\.\pipe\{}-", crate::service_name()?))+ || !name.starts_with(&format!(r"\\.\pipe\{}-", copy.service())){return denied();}let mut pipe = Pipe::client(name)?;- if pipe.server_pid()? != pid()? {+ if pipe.server_pid()? != pid(©.service())? {return denied();}let init: serde_json::Value = serde_json::from_slice(&pipe.line(1024)?)?;@@ -651,18 +761,25 @@ pub fn worker(name: &str) -> Result<()> {}}-pub fn authorize(main_pid: u32) -> Result<()> {- let mut pipe = Pipe::client(&crate::pipe_name()?)?;- let server = process(pipe.server_pid()?)?;- if !system(token(server.0)?.0)?- || !crate::security::same_file(&image(server.0)?, &std::env::current_exe()?)- || pipe.server_pid()? != pid()?- {- return denied();- }- pipe.write(format!("{{\"mode\":\"authorize\",\"pid\":{main_pid}}}\n").as_bytes())?;- if pipe.line(1024)? != b"ready\n" {- return denied();+/// Registers the Cindy process this setup run was started for, from the+/// elevated child. The service must be running as SYSTEM from the staged copy+/// this installation just wrote.+pub fn authorize(installation: &Installation, main_pid: u32) -> Staged<()> {+ let mut pipe = Pipe::client(&installation.pipe()).stage(Step::AuthorizeConnect)?;+ let identity = (|| -> Result<bool> {+ let server = process(pipe.server_pid()?)?;+ Ok(system(token(server.0)?.0)?+ && crate::security::same_file(&image(server.0)?, &installation.host())+ && pipe.server_pid()? == pid(&installation.service())?)+ })()+ .stage(Step::AuthorizeIdentity)?;+ if !identity {+ return refuse(Step::AuthorizeIdentity);+ }+ pipe.write(format!("{{\"mode\":\"authorize\",\"pid\":{main_pid}}}\n").as_bytes())+ .stage(Step::AuthorizeReply)?;+ if pipe.line(1024).stage(Step::AuthorizeReply)? != b"ready\n" {+ return refuse(Step::AuthorizeReply);}Ok(())}diff --git a/apps/desktop/native/remote-desktop/windows-host/src/staging.rs b/apps/desktop/native/remote-desktop/windows-host/src/staging.rsnew file mode 100644index 0000000000..c2fe584a80--- /dev/null+++ b/apps/desktop/native/remote-desktop/windows-host/src/staging.rs@@ -0,0 +1,254 @@+//! Places the SYSTEM service's executables in a protected directory.+//!+//! Cindy installs per user by default, so its own directory is writable by the+//! account that installed it. A service started from there would let any+//! ordinary process on the machine replace a SYSTEM executable — permanently,+//! and without a prompt. Running the installer from Program Files is one way+//! to avoid that, but it makes every update ask for an administrator, so this+//! module takes the other route: while the user is already confirming the+//! administrator prompt for setup, copy the two helpers into a directory under+//! Program Files that only administrators and SYSTEM can write, and point the+//! service at that copy.+//!+//! What this does and does not protect:+//!+//! * It removes the standing risk. After setup, no ordinary process can reach+//! the executable the service starts, so there is no unprompted path to+//! SYSTEM.+//! * It does not make the one-time elevation itself trustworthy. The copy is+//! made by this executable, which was launched from the installation+//! directory and elevated by the user's confirmation. Anything that could+//! already replace files there could have replaced this one too, and+//! verifying our own signature from inside the same executable would prove+//! nothing. That exposure is the same one the Cindy updater already accepts+//! when it elevates to write into a protected directory.+use crate::naming::*;+use crate::security;+use crate::win::*;+use std::io::{Read, Write};+use std::os::windows::io::FromRawHandle;+use std::path::{Path, PathBuf};+use std::{mem, ptr};+use windows_sys::Win32::{+ Foundation::*, Security::Authorization::*, Security::*, Storage::FileSystem::*,+};++/// Owned by Administrators, written only by Administrators and SYSTEM, read+/// and executed by everyone. `P` blocks inheritance from Program Files, and+/// an explicit owner matters as much as the entries: an owner can always+/// rewrite the entries, so leaving the installing account as owner would hand+/// that account unprompted write access to a SYSTEM executable.+const DIRECTORY_RIGHTS: &str = "O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;BU)";+const FILE_RIGHTS: &str = "O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;BU)";+/// Refuse anything far larger than the helpers, rather than reading without a+/// limit from a directory the current user can write.+const MAX_HELPER_BYTES: u64 = 64 * 1024 * 1024;++/// A security descriptor built from SDDL, freed when it goes out of scope.+struct Descriptor(PSECURITY_DESCRIPTOR);+impl Drop for Descriptor {+ fn drop(&mut self) {+ unsafe {+ LocalFree(self.0);+ }+ }+}+impl Descriptor {+ fn parse(sddl: &str) -> Staged<Self> {+ let mut raw = ptr::null_mut();+ if unsafe {+ ConvertStringSecurityDescriptorToSecurityDescriptorW(+ wide(sddl).as_ptr(),+ 1,+ &mut raw,+ ptr::null_mut(),+ )+ } == 0+ {+ return Err(Failure::new(Step::StagePrepare, last_error()));+ }+ Ok(Self(raw))+ }+ fn attributes(&self) -> SECURITY_ATTRIBUTES {+ SECURITY_ATTRIBUTES {+ nLength: mem::size_of::<SECURITY_ATTRIBUTES>() as u32,+ lpSecurityDescriptor: self.0,+ bInheritHandle: 0,+ }+ }+ /// Applies this descriptor to an existing path, replacing whatever owner+ /// and entries it had. Only used on the staging directory itself, which+ /// this feature creates and owns.+ fn apply(&self, path: &Path) -> Staged<()> {+ let mut owner = ptr::null_mut();+ let mut defaulted = 0;+ let mut acl = ptr::null_mut();+ let mut present = 0;+ if unsafe { GetSecurityDescriptorOwner(self.0, &mut owner, &mut defaulted) } == 0+ || unsafe { GetSecurityDescriptorDacl(self.0, &mut present, &mut acl, &mut defaulted) }+ == 0+ || present == 0+ {+ return Err(Failure::new(Step::StagePrepare, last_error()));+ }+ let code = unsafe {+ SetNamedSecurityInfoW(+ wide(&path.to_string_lossy()).as_ptr().cast_mut(),+ SE_FILE_OBJECT,+ OWNER_SECURITY_INFORMATION+ | DACL_SECURITY_INFORMATION+ | PROTECTED_DACL_SECURITY_INFORMATION,+ owner,+ ptr::null_mut(),+ acl,+ ptr::null_mut(),+ )+ };+ if code != ERROR_SUCCESS {+ return Err(Failure::new(Step::StagePrepare, code as i32));+ }+ Ok(())+ }+}++fn last_error() -> i32 {+ unsafe { GetLastError() as i32 }+}++/// Reads a helper from the installation while denying every other writer.+/// Holding the handle across the read means the bytes that land in the+/// protected copy are the bytes that were checked, not a replacement swapped+/// in afterwards.+fn read_exclusively(path: &Path) -> Staged<Vec<u8>> {+ let handle = Handle::new(unsafe {+ CreateFileW(+ wide(&path.to_string_lossy()).as_ptr(),+ FILE_GENERIC_READ,+ FILE_SHARE_READ,+ ptr::null(),+ OPEN_EXISTING,+ FILE_ATTRIBUTE_NORMAL,+ ptr::null_mut(),+ )+ })+ .stage(Step::StageRead)?;+ let mut file = unsafe { std::fs::File::from_raw_handle(handle.0.cast()) };+ mem::forget(handle);+ let length = file.metadata().stage(Step::StageRead)?.len();+ if length == 0 || length > MAX_HELPER_BYTES {+ return refuse(Step::StageRead);+ }+ let mut bytes = Vec::with_capacity(length as usize);+ file.read_to_end(&mut bytes).stage(Step::StageRead)?;+ if bytes.len() as u64 != length {+ return refuse(Step::StageRead);+ }+ Ok(bytes)+}++/// Writes `bytes` to a file created with the fixed descriptor above. The old+/// file is removed first: Windows ignores the descriptor supplied to an open+/// of an existing file, so reusing one would silently keep its old owner.+fn write_protected(path: &Path, bytes: &[u8], rights: &Descriptor) -> Staged<()> {+ match std::fs::remove_file(path) {+ Ok(()) => {}+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}+ Err(e) => {+ return Err(Failure::new(+ Step::StageWrite,+ e.raw_os_error().unwrap_or(0),+ ))+ }+ }+ let attributes = rights.attributes();+ let handle = Handle::new(unsafe {+ CreateFileW(+ wide(&path.to_string_lossy()).as_ptr(),+ FILE_GENERIC_WRITE,+ 0,+ &attributes,+ CREATE_NEW,+ FILE_ATTRIBUTE_NORMAL,+ ptr::null_mut(),+ )+ })+ .stage(Step::StageWrite)?;+ let mut file = unsafe { std::fs::File::from_raw_handle(handle.0.cast()) };+ mem::forget(handle);+ file.write_all(bytes).stage(Step::StageWrite)?;+ file.sync_all().stage(Step::StageWrite)+}++/// Copies this installation's helpers into its protected directory and returns+/// the staged host executable. Runs in the elevated setup child, with the+/// service already stopped so the files it uses can be replaced.+pub fn stage(installation: &Installation) -> Staged<PathBuf> {+ let bundled = std::env::current_exe().stage(Step::StageRead)?;+ let host = read_exclusively(&bundled)?;+ let input = read_exclusively(&bundled.with_file_name(INPUT_EXE))?;++ let directory_rights = Descriptor::parse(DIRECTORY_RIGHTS)?;+ let attributes = directory_rights.attributes();+ for directory in [+ installation.staged.parent().unwrap_or(&installation.staged),+ &installation.staged,+ ] {+ if unsafe { CreateDirectoryW(wide(&directory.to_string_lossy()).as_ptr(), &attributes) }+ == 0+ {+ let code = unsafe { GetLastError() };+ if code != ERROR_ALREADY_EXISTS {+ return Err(Failure::new(Step::StagePrepare, code as i32));+ }+ // A directory that already exists kept the descriptor it was+ // created with. Reassert ours rather than inheriting whatever an+ // earlier version, or a repaired Program Files, left behind.+ directory_rights.apply(directory)?;+ }+ }++ let file_rights = Descriptor::parse(FILE_RIGHTS)?;+ write_protected(&installation.host(), &host, &file_rights)?;+ write_protected(&installation.staged.join(INPUT_EXE), &input, &file_rights)?;+ write_protected(+ &installation.staged.join(INSTALL_RECORD),+ format!(+ "{}{}",+ installation.install.to_string_lossy(),+ if installation.development {+ "\ndevelopment"+ } else {+ ""+ }+ )+ .as_bytes(),+ &file_rights,+ )?;++ // Prove the result before anything is registered with the service manager.+ drop(security::protected_staging(&installation.staged)?);+ Ok(installation.host())+}++/// Removes a staged copy. Leaving a few megabytes behind is better than+/// refusing to finish a removal, so a file that will not go is reported but+/// does not abort the rest.+pub fn unstage(installation: &Installation) -> Staged<()> {+ match std::fs::remove_dir_all(&installation.staged) {+ Ok(()) => {}+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}+ Err(e) => {+ return Err(Failure::new(+ Step::StageRemove,+ e.raw_os_error().unwrap_or(0),+ ))+ }+ }+ // Take the shared folder with it once the last installation has gone.+ // Plain `remove_dir` fails while another installation still has a copy+ // there, which is exactly the wanted behaviour.+ if let Some(root) = installation.staged.parent() {+ let _ = std::fs::remove_dir(root);+ }+ Ok(())+}diff --git a/apps/desktop/native/remote-desktop/windows-host/src/win.rs b/apps/desktop/native/remote-desktop/windows-host/src/win.rsindex 25085a4e10..d11f569836 100644--- a/apps/desktop/native/remote-desktop/windows-host/src/win.rs+++ b/apps/desktop/native/remote-desktop/windows-host/src/win.rs@@ -1,3 +1,8 @@+//! Win32 helpers shared by this crate's two targets: the setup/service+//! executable and the Main-only Node-API library. Each target uses a different+//! subset — the setup steps below belong to the executable — so items unused by+//! one of them are expected here rather than dead.+#![allow(dead_code)]use std::{io, ptr};use windows_sys::Win32::{Foundation::*, Security::*, Storage::FileSystem::SYNCHRONIZE, System::Threading::*,@@ -9,6 +14,122 @@ pub fn error() -> io::Error {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;++/// 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.+macro_rules! steps {+ ($($variant:ident => $code:literal,)*) => {+ /// A named setup step. The code reaches the Desktop log and the settings+ /// page, so a failed setup says which step failed instead of only+ /// "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)]+ 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.+ pub fn from_exit(value: u32) -> Option<Step> {+ const ALL: &[Step] = &[$(Step::$variant,)*];+ value+ .checked_sub(EXIT_BASE)+ .and_then(|index| ALL.get(index as usize))+ .copied()+ }+ }+ };+}++steps! {+ Args => "args",+ Service => "service",+ Worker => "worker",+ ProtectedRoot => "protected-root",+ ProtectedOpen => "protected-open",+ ProtectedReparse => "protected-reparse",+ ProtectedOwner => "protected-owner",+ ProtectedAcl => "protected-acl",+ StagePrepare => "stage-prepare",+ StageRead => "stage-read",+ StageWrite => "stage-write",+ StageRemove => "stage-remove",+ StageRecord => "stage-record",+ ScmOpen => "scm-open",+ ServiceCreate => "service-create",+ ServiceStart => "service-start",+ ServiceReady => "service-ready",+ ServiceStop => "service-stop",+ ServiceDelete => "service-delete",+ AuthorizeConnect => "authorize-connect",+ AuthorizeIdentity => "authorize-identity",+ AuthorizeReply => "authorize-reply",+ ClientIdentity => "client-identity",+ ElevateLaunch => "elevate-launch",+ ElevateTimeout => "elevate-timeout",+ ElevateChild => "elevate-child",+}++/// A failed step plus the raw OS error number — the part that distinguishes+/// "access denied" from "not found" on an otherwise identical step.+pub struct Failure {+ pub step: Step,+ pub os: i32,+ /// Set when the failure actually happened inside the elevated child.+ pub child: Option<Step>,+}+pub type Staged<T> = std::result::Result<T, Failure>;++impl Failure {+ pub fn new(step: Step, os: i32) -> Self {+ Self {+ step,+ os,+ child: None,+ }+ }+ /// The step, the elevated child's own step when it came from there, and the+ /// OS error number. Appended to a status word, or printed after `error`.+ pub fn detail(&self) -> String {+ match self.child {+ Some(child) => format!("{}/{} {}", self.step.code(), child.code(), self.os),+ None => format!("{} {}", self.step.code(), self.os),+ }+ }+ /// The single line the process prints before exiting on failure.+ pub fn line(&self) -> String {+ format!("error {}", self.detail())+ }+}++impl std::fmt::Debug for Failure {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str(&self.detail())+ }+}++/// Attaches a step name to an ordinary OS failure.+pub trait Stage<T> {+ fn stage(self, step: Step) -> Staged<T>;+}+impl<T> Stage<T> for Result<T> {+ fn stage(self, step: Step) -> Staged<T> {+ self.map_err(|e| Failure::new(step, e.raw_os_error().unwrap_or(0)))+ }+}+/// Rejects a step that failed a validation rule rather than an OS call.+pub fn refuse<T>(step: Step) -> Staged<T> {+ Err(Failure::new(step, 0))+}+pub fn wide(value: &str) -> Vec<u16> {value.encode_utf16().chain(Some(0)).collect()}diff --git a/apps/desktop/src/main/remote-desktop/__tests__/windowsLockScreenSetup.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/windowsLockScreenSetup.test.tsnew file mode 100644index 0000000000..f0fa3aced9--- /dev/null+++ b/apps/desktop/src/main/remote-desktop/__tests__/windowsLockScreenSetup.test.ts@@ -0,0 +1,89 @@+// Protects the diagnosis path for Windows lock-screen setup. Before this, the+// helper printed a bare "error", Main threw a generic failure and the settings+// page said only "authorization was not completed" — so a failed setup gave+// nobody anything to act on. These cases assert the production entry points+// carry the helper's step code through, and that a helper which cannot work out+// where it would install is not offered to the user as a setup they can finish.+import { afterEach, describe, expect, it, vi } from 'vitest';++const execFile = vi.hoisted(() => vi.fn());+vi.mock('node:child_process', async (importOriginal) => ({+ ...(await importOriginal<typeof import('node:child_process')>()),+ execFile,+}));+vi.mock('electron', () => ({ app: { isPackaged: true } }));+vi.mock('../../logger', () => ({+ createLogger: () => ({+ trace: vi.fn(),+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ fatal: vi.fn(),+ }),+}));++import {+ configureWindowsDesktopSupport,+ readWindowsDesktopDetail,+ readWindowsDesktopSupport,+ WindowsDesktopSetupError,+} from '../windowsHost';++/** `promisify(execFile)` calls the callback form, so replies go through it. */+function helperPrints(stdout: string, exitCode = 0): void {+ execFile.mockImplementation((_binary, _args, _options, callback) => {+ if (exitCode === 0) {+ callback(null, { stdout, stderr: '' });+ return;+ }+ callback(Object.assign(new Error('exit'), { code: exitCode, stdout, stderr: '' }));+ });+}++const platform = process.platform;+afterEach(() => {+ Object.defineProperty(process, 'platform', { value: platform });+ execFile.mockReset();+});+Object.defineProperty(process, 'platform', { value: 'win32' });+// Set by Electron in a packaged app; the helper path is built from it.+Object.defineProperty(process, 'resourcesPath', {+ value: 'C:\\Program Files\\Cindy\\resources',+ configurable: true,+});++describe('windows lock-screen setup diagnostics', () => {+ 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');+ expect(readWindowsDesktopDetail('error elevate-child/stage-write 5')).toBe(+ 'elevate-child/stage-write 5',+ );+ // Nothing that is not a step code may reach the log or the settings page,+ // since a path or account name there would leak machine content.+ expect(readWindowsDesktopDetail('error C:\\Users\\someone\\Cindy failed')).toBeUndefined();+ expect(readWindowsDesktopDetail('ready')).toBeUndefined();+ expect(readWindowsDesktopDetail(undefined)).toBeUndefined();+ });++ it('keeps the step code on the error a failed setup throws', async () => {+ helperPrints('error elevate-child/stage-write 5', 21);+ const failure = await configureWindowsDesktopSupport(true).catch((error: unknown) => error);+ expect(failure).toBeInstanceOf(WindowsDesktopSetupError);+ expect((failure as WindowsDesktopSetupError).detail).toBe('elevate-child/stage-write 5');+ });++ it('offers setup when the service is simply not installed yet', async () => {+ helperPrints('missing');+ expect(await readWindowsDesktopSupport()).toBe('missing');+ });++ it('does not offer setup when the helper cannot locate an installation', async () => {+ // `installRequired` from the helper means it could not work out where it+ // would install at all. Reporting that as a pending setup would leave the+ // user pressing a button that can never succeed.+ helperPrints('installRequired protected-root 0');+ expect(await readWindowsDesktopSupport()).toBe('unavailable');+ });+});diff --git a/apps/desktop/src/main/remote-desktop/index.ts b/apps/desktop/src/main/remote-desktop/index.tsindex b40b8ed737..62445cbae0 100644--- a/apps/desktop/src/main/remote-desktop/index.ts+++ b/apps/desktop/src/main/remote-desktop/index.ts@@ -79,7 +79,11 @@ import { ControlledOverlay } from './controlledOverlay';import { LinuxPrivacyScreen, supportsLinuxPrivacy, prepareLinuxPrivacy } from './linuxPrivacy';import { LinuxWindowActions, supportsOmarchyMenu } from './linuxWindowActions';import { systemAudioMuteGuard } from '../voice-input/SystemAudioMuteGuard.js';-import { readWindowsDesktopSupport, configureWindowsDesktopSupport } from './windowsHost';+import {+ readWindowsDesktopSupport,+ configureWindowsDesktopSupport,+ WindowsDesktopSetupError,+} from './windowsHost';import {DesktopInputHost,readDesktopDisplayModes,@@ -1173,8 +1177,11 @@ export function registerRemoteDesktopIpc(remoteDesktop.stop(undefined, undefined, 'disabled');try {await configureWindowsDesktopSupport(enabled);- } catch {- throwIpcError('PERMISSION_DENIED', 'Windows desktop support setup failed');+ } catch (error) {+ // Carry the helper's step code so settings can name the failed step.+ // It holds no path or account name, only a fixed code and OS number.+ const detail = error instanceof WindowsDesktopSetupError ? error.detail : undefined;+ throwIpcError('PERMISSION_DENIED', detail ?? 'Windows desktop support setup failed');} finally {windowsSetupBusy = false;}diff --git a/apps/desktop/src/main/remote-desktop/windowsHost.ts b/apps/desktop/src/main/remote-desktop/windowsHost.tsindex f7169aff38..0d6cef3f6b 100644--- a/apps/desktop/src/main/remote-desktop/windowsHost.ts+++ b/apps/desktop/src/main/remote-desktop/windowsHost.ts@@ -1,66 +1,282 @@import { app } from 'electron';import { REMOTE_DESKTOP_OFFER_BUDGET } from '@cindy/device-link';import { execFile } from 'node:child_process';+import { createHash } from 'node:crypto';+import fs from 'node:fs/promises';import { createRequire } from 'node:module';import path from 'node:path';import { promisify } from 'node:util';+import { createLogger } from '../logger';import type { WindowsDesktopSupport } from '../../shared/remoteDesktop';const exec = promisify(execFile);+const log = createLogger('remote-desktop:windows');const requireNative = createRequire(import.meta.url);-const binary = () =>+const packagedBinary = () =>path.join(process.resourcesPath, 'tools', 'remote-desktop', 'cindy-windows-desktop-host.exe');+const packagedAddon = () =>+ path.join(process.resourcesPath, 'tools', 'remote-desktop', 'cindy-windows-desktop-host.node');+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;++/**+ * The packaged helper is already present in resources. In source mode, build+ * both targets into a private userData cache, then arrange the executable under+ * a stable `resources/tools/remote-desktop` shape so the Rust service and the+ * 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> {+ if (app.isPackaged)+ return { binary: packagedBinary(), addon: packagedAddon(), input: packagedInput() };+ if (build) return build;+ const resolve = async (): Promise<WindowsDesktopArtifacts> => {+ const nativeRoot = path.join(app.getAppPath(), 'native', 'remote-desktop');+ const hostRoot = path.join(nativeRoot, 'windows-host');+ const inputRoot = path.join(nativeRoot, 'windows-input');+ const sourceFiles = [+ 'Cargo.toml',+ 'Cargo.lock',+ 'build.rs',+ 'src/capture.rs',+ 'src/capture_protocol.rs',+ 'src/cursor.rs',+ 'src/lib.rs',+ 'src/main.rs',+ 'src/naming.rs',+ 'src/pipe.rs',+ 'src/security.rs',+ 'src/service.rs',+ 'src/staging.rs',+ 'src/win.rs',+ ].map((file) => path.join('windows-host', file));+ sourceFiles.push(+ ...[+ 'Cargo.toml',+ 'Cargo.lock',+ 'src/desktop.rs',+ 'src/main.rs',+ 'src/privacy.rs',+ 'src/selection.rs',+ ].map((file) => path.join('windows-input', file)),+ );+ const installHash = createHash('sha256')+ .update(process.arch)+ .update(path.resolve(app.getAppPath()).toLowerCase())+ .digest('hex');+ const digest = createHash('sha256')+ .update(process.arch)+ .update(path.resolve(app.getAppPath()).toLowerCase());+ for (const file of sourceFiles) {+ digest.update(file);+ digest.update(await fs.readFile(path.join(nativeRoot, file)));+ }+ const sourceHash = digest.digest('hex');+ const installRoot = path.join(+ app.getPath('userData'),+ 'remote-desktop',+ 'development',+ installHash.slice(0, 32),+ );+ const helperDir = path.join(installRoot, 'resources', 'tools', 'remote-desktop');+ const binary = path.join(helperDir, 'cindy-windows-desktop-host.exe');+ const input = path.join(helperDir, 'cindy-windows-desktop-input.exe');+ const stamp = path.join(installRoot, 'source.sha256');+ // Windows keeps a loaded Node-API addon open. Give each source revision+ // its own addon filename so a running dev process can rebuild without+ // trying to unlink the addon it currently has loaded.+ const versionedAddon = path.join(+ helperDir,+ `cindy-windows-desktop-host-${sourceHash.slice(0, 16)}.node`,+ );+ const legacyAddon = path.join(helperDir, 'cindy-windows-desktop-host.node');+ try {+ if ((await fs.readFile(stamp, 'utf8')).trim() === sourceHash) {+ await Promise.all([fs.access(binary), fs.access(input)]);+ try {+ await fs.access(versionedAddon);+ return { binary, addon: versionedAddon, input };+ } catch {+ // Existing caches used the fixed addon name. Keep them usable until+ // the next source build creates a revisioned name.+ await fs.access(legacyAddon);+ return { binary, addon: legacyAddon, input };+ }+ }+ } catch {+ // Build below. A partial cache is disposable and never becomes visible+ // until both final files and the stamp have been written.+ }+ await fs.mkdir(helperDir, { recursive: true });+ const buildDir = path.join(installRoot, 'build');+ const buildCargo = (+ root: string,+ targetDir: string,+ target?: '--bin' | '--lib',+ name?: string,+ ) =>+ exec(+ 'cargo',+ [+ 'build',+ '--release',+ '--locked',+ '--manifest-path',+ path.join(root, 'Cargo.toml'),+ '--target-dir',+ targetDir,+ ...(target ? [target, ...(name ? [name] : [])] : []),+ ],+ { timeout: 180_000, windowsHide: true },+ );+ // The host package exposes both a binary and a cdylib. Building both in+ // one Cargo target collides on Windows because the linker gives them the+ // same PDB filename. Keep their target directories separate so source+ // mode can build deterministically even when the cache is cold.+ await buildCargo(+ hostRoot,+ path.join(buildDir, 'host-bin'),+ '--bin',+ 'cindy-windows-desktop-host',+ );+ 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 temporaryBinary = binary + '.' + process.pid + '.tmp';+ const temporaryAddon = versionedAddon + '.' + process.pid + '.tmp';+ const temporaryInput = input + '.' + process.pid + '.tmp';+ await Promise.all([+ fs.copyFile(path.join(hostBinaryOutput, 'cindy-windows-desktop-host.exe'), temporaryBinary),+ fs.copyFile(path.join(hostAddonOutput, 'cindy_windows_desktop_host.dll'), temporaryAddon),+ fs.copyFile(path.join(inputOutput, 'cindy-windows-desktop-input.exe'), temporaryInput),+ ]);+ await Promise.all([fs.rm(binary, { force: true }), fs.rm(input, { force: true })]);+ await Promise.all([fs.rename(temporaryBinary, binary), fs.rename(temporaryInput, input)]);+ // A previous run may already have produced this revision while its stamp+ // write was interrupted. Reuse that file rather than unlinking a loaded+ // addon; otherwise a live Electron process would turn recovery into EPERM.+ try {+ await fs.access(versionedAddon);+ await fs.rm(temporaryAddon, { force: true });+ } catch {+ await fs.rename(temporaryAddon, versionedAddon);+ }+ await fs.writeFile(stamp, `${sourceHash}\n`, 'utf8');+ return { binary, addon: versionedAddon, input };+ };+ build = resolve().finally(() => {+ build = null;+ });+ return build;+}export interface WindowsDesktopConnection {request(line: string): Promise<string>;close(): void;}++/**+ * The helper's own name for the setup step that failed, plus an OS error+ * number — `service-create 5`, or `elevate-child/protected-acl 0` when the+ * failure happened inside the hidden elevated child. It carries no path,+ * account name or other machine content, so it is safe to log and to show in+ * settings. Without it every failure looks the same from outside.+ */+export type WindowsDesktopDetail = string;+const DETAIL = /^[a-z-]+(?:\/[a-z-]+)? -?\d+$/;++/** Reads the diagnostic the helper appends to a status word or an error line. */+export function readWindowsDesktopDetail(output: unknown): WindowsDesktopDetail | undefined {+ if (typeof output !== 'string') return undefined;+ const line = output.trim().split('\n').at(-1)?.trim() ?? '';+ const detail = line.startsWith('error ')+ ? line.slice('error '.length)+ : line.split(' ').slice(1).join(' ');+ return DETAIL.test(detail) ? detail : undefined;+}++/** A setup failure that kept the helper's step code, for the caller to report. */+export class WindowsDesktopSetupError extends Error {+ constructor(readonly detail?: WindowsDesktopDetail) {+ super('DESKTOP_SYSTEM_SERVICE_UNAVAILABLE');+ this.name = 'WindowsDesktopSetupError';+ }+}+export async function readWindowsDesktopSupport(): Promise<WindowsDesktopSupport | undefined> {if (process.platform !== 'win32') return undefined;- if (!app.isPackaged) return 'installRequired';+ let stdout: string;try {- const { stdout } = await exec(binary(), ['--status'], {+ const { binary } = await resolveArtifacts();+ ({ stdout } = await exec(binary, ['--status'], {timeout: REMOTE_DESKTOP_OFFER_BUDGET.platformStatusMs,maxBuffer: 1024,windowsHide: true,- });- const status = stdout.trim();- if (status === 'ready') {- try {- const connection = await openWindowsDesktopConnection({ mode: 'probe' });- connection.close();- } catch {- return 'missing';- }- }- return status === 'ready' || status === 'missing' || status === 'installRequired'- ? status- : 'unavailable';- } catch {+ }));+ } catch (error) {+ log.warn(+ 'status failed',+ readWindowsDesktopDetail((error as { stdout?: unknown })?.stdout) ?? error,+ );return 'unavailable';}+ const status = stdout.trim().split(' ')[0];+ if (status === 'ready') {+ try {+ const connection = await openWindowsDesktopConnection({ mode: 'probe' });+ connection.close();+ } catch (error) {+ log.warn('service is running but refused a pipe probe', error);+ return 'missing';+ }+ return 'ready';+ }+ if (status === 'missing') return 'missing';+ // Anything else means the helper could not even work out where it would+ // install — a broken or incomplete copy of Cindy rather than a setup the+ // user can complete, so it reads as unavailable with the step in the log.+ log.warn('lock-screen setup unavailable:', readWindowsDesktopDetail(stdout) ?? status);+ return 'unavailable';}+export async function configureWindowsDesktopSupport(enabled: boolean): Promise<void> {- if (process.platform !== 'win32' || !app.isPackaged)- throw new Error('DESKTOP_SYSTEM_SERVICE_UNAVAILABLE');- await exec(- binary(),- enabled ? ['--elevate-install', String(process.pid)] : ['--elevate-uninstall'],- { timeout: 130_000, maxBuffer: 1024, windowsHide: true },- );- if (enabled && (await readWindowsDesktopSupport()) !== 'ready')- throw new Error('DESKTOP_SYSTEM_SERVICE_UNAVAILABLE');+ if (process.platform !== 'win32') throw new WindowsDesktopSetupError();+ log.info(enabled ? 'installing the lock-screen service' : 'removing the lock-screen service');+ try {+ const { binary } = await resolveArtifacts();+ const args = enabled+ ? ['--elevate-install', String(process.pid), ...(app.isPackaged ? [] : ['--development'])]+ : ['--elevate-uninstall'];+ await exec(binary, args, { timeout: 130_000, maxBuffer: 1024, windowsHide: true });+ } catch (error) {+ const detail = readWindowsDesktopDetail((error as { stdout?: unknown })?.stdout);+ log.warn('lock-screen setup failed:', detail ?? error);+ throw new WindowsDesktopSetupError(detail);+ }+ if (enabled) {+ const support = await readWindowsDesktopSupport();+ if (support !== 'ready') {+ log.warn('lock-screen setup finished but the service reports', support);+ throw new WindowsDesktopSetupError();+ }+ }+ log.info('lock-screen service', enabled ? 'installed' : 'removed');}+export async function openWindowsDesktopConnection(- init: { mode: 'input' | 'probe' } | { mode: 'capture'; rect: number[]; cursorOverlay?: boolean; bitrate?: number },+ init:+ | { mode: 'input' | 'probe' }+ | { mode: 'capture'; rect: number[]; cursorOverlay?: boolean; bitrate?: number },): Promise<WindowsDesktopConnection> {- if (process.platform !== 'win32' || !app.isPackaged)- throw new Error('DESKTOP_SYSTEM_SERVICE_UNAVAILABLE');+ if (process.platform !== 'win32') throw new Error('DESKTOP_SYSTEM_SERVICE_UNAVAILABLE');+ const { binary, addon } = await resolveArtifacts();// Fixed packaged Node-API addon, loaded only by Main. It opens the pipe in- // this process and authenticates SCM/SYSTEM identity before sending anything.- const native = requireNative(- path.join(process.resourcesPath, 'tools', 'remote-desktop', 'cindy-windows-desktop-host.node'),- ) as {+ // this process and checks the SCM service identity before sending anything.+ const native = requireNative(addon) as {DesktopConnection: { open(binary: string, init: string): Promise<WindowsDesktopConnection> };};- return native.DesktopConnection.open(binary(), JSON.stringify(init));+ return native.DesktopConnection.open(binary, JSON.stringify(init));}diff --git a/apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx b/apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsxindex e5404cc65b..dd369d9ea6 100644--- a/apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx+++ b/apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx@@ -3,12 +3,17 @@ import { useTranslation } from 'react-i18next';import type { WindowsDesktopSupport } from '../../../shared/remoteDesktop';import { Button } from '@/components/ui/button';import { Switch } from '@/components/ui/switch';+import { extractIpcError } from '../../utils/ipcError';import { RemoteDesktopPermissions } from './RemoteDesktopPermissions';+/** The failed setup step the helper reported, such as `service-create 5`. */+const SETUP_DETAIL = /^[a-z-]+(?:\/[a-z-]+)? -?\d+$/;+export function RemoteDesktopSetting() {const { t } = useTranslation();const [windowsSupport, setWindowsSupport] = useState<WindowsDesktopSupport>();const [serviceError, setServiceError] = useState(false);+ const [serviceErrorDetail, setServiceErrorDetail] = useState<string>();const [enabled, setEnabled] = useState(false);const [busy, setBusy] = useState(false);const [error, setError] = useState(false);@@ -95,6 +100,12 @@ export function RemoteDesktopSetting() {{serviceError && (<p role="alert" className="text-12 text-[var(--text-primary)]">{t('remoteDesktop.windowsError')}+ {serviceErrorDetail && (+ <span className="text-[var(--text-tertiary)]">+ {' '}+ {t('remoteDesktop.windowsErrorDetail', { code: serviceErrorDetail })}+ </span>+ )}</p>)}</div>@@ -107,11 +118,18 @@ export function RemoteDesktopSetting() {changing.current = true;setBusy(true);setServiceError(false);+ setServiceErrorDetail(undefined);void window.electronAPI.remoteDesktop.windowsSupport(windowsSupport !== 'ready').then(() => window.electronAPI.remoteDesktop.state(true)).then((state) => setWindowsSupport(state.windowsSupport))- .catch(() => setServiceError(true))+ .catch((err: unknown) => {+ const message = extractIpcError(err)?.message;+ setServiceErrorDetail(+ message && SETUP_DETAIL.test(message) ? message : undefined,+ );+ setServiceError(true);+ }).finally(() => {changing.current = false;setBusy(false);diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 370ab24fea..ef84ebd6a3 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -805,11 +805,12 @@"windowsTitle": "Lock screen control","windowsready": "Enabled for this Cindy process. Restarting Cindy requires administrator authorization again.","windowsmissing": "Allow control of the lock screen and administrator prompts. Administrator authorization is required.",- "windowsinstallRequired": "Install Cindy for all users in Program Files to enable this feature.",+ "windowsinstallRequired": "Cindy could not find its installation directory. Restart Cindy and try again.","windowsunavailable": "The system service is unavailable. Reinstall Cindy and try again.","windowsEnable": "Authorize","windowsDisable": "Remove service","windowsError": "Authorization was not completed. Try again on this computer.",+ "windowsErrorDetail": "Error code {{code}}","permissionsTitle": "Remote desktop permissions","permissionsIntro": "Screen recording lets you view the desktop. Accessibility also enables control. Complete authorization on the computer; status updates automatically.","permissionsReady": "System permissions are ready. You can reconnect.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 1c740369a7..8c104d303f 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -793,11 +793,12 @@"windowsTitle": "ロック画面の操作","windowsready": "現在の Cindy で有効です。Cindy を再起動すると管理者の再承認が必要です。","windowsmissing": "ロック画面と管理者の確認画面を操作するには管理者の承認が必要です。",- "windowsinstallRequired": "Cindy を Program Files に全ユーザー向けにインストールしてください。",+ "windowsinstallRequired": "Cindy のインストール場所を確認できません。Cindy を再起動してもう一度お試しください。","windowsunavailable": "システムサービスを利用できません。Cindy を再インストールしてください。","windowsEnable": "承認して有効化","windowsDisable": "サービスを削除","windowsError": "承認が完了していません。このコンピューターで再試行してください。",+ "windowsErrorDetail": "エラーコード {{code}}","permissionsTitle": "リモートデスクトップの権限","permissionsIntro": "画面の表示には画面収録、操作にはアクセシビリティの権限も必要です。コンピューターで許可すると、状態が自動更新されます。","permissionsReady": "システム権限の準備ができました。再接続できます。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 770bff1bff..a3c17058e3 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -793,11 +793,12 @@"windowsTitle": "잠금 화면 제어","windowsready": "현재 Cindy 실행에 허용되었습니다. Cindy를 다시 시작하면 관리자 승인이 다시 필요합니다.","windowsmissing": "잠금 화면과 관리자 확인 창을 제어하려면 관리자 승인이 필요합니다.",- "windowsinstallRequired": "Cindy를 Program Files에 모든 사용자용으로 설치하세요.",+ "windowsinstallRequired": "Cindy의 설치 위치를 찾을 수 없습니다. Cindy를 다시 시작한 후 다시 시도하세요.","windowsunavailable": "시스템 서비스를 사용할 수 없습니다. Cindy를 다시 설치하세요.","windowsEnable": "승인 후 활성화","windowsDisable": "서비스 제거","windowsError": "승인이 완료되지 않았습니다. 이 컴퓨터에서 다시 시도하세요.",+ "windowsErrorDetail": "오류 코드 {{code}}","permissionsTitle": "원격 데스크톱 권한","permissionsIntro": "데스크톱을 보려면 화면 기록 권한이, 조작하려면 손쉬운 사용 권한도 필요합니다. 컴퓨터에서 허용하면 상태가 자동으로 갱신됩니다.","permissionsReady": "시스템 권한이 준비되었습니다. 다시 연결할 수 있습니다.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex a523824835..37a5460aa7 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -793,11 +793,12 @@"windowsTitle": "锁屏控制","windowsready": "已为本次运行的 Cindy 开启。重新启动 Cindy 后需要再次由管理员授权。","windowsmissing": "允许操作锁屏界面和管理员提示,需要管理员授权。",- "windowsinstallRequired": "请将 Cindy 安装到 Program Files 并选择为所有用户安装,再启用此功能。",+ "windowsinstallRequired": "找不到 Cindy 的安装位置,请重新启动 Cindy 后重试。","windowsunavailable": "系统服务不可用,请重新安装 Cindy 后重试。","windowsEnable": "授权开启","windowsDisable": "移除服务","windowsError": "未完成授权,请在这台电脑上重试。",+ "windowsErrorDetail": "错误码 {{code}}","permissionsTitle": "远程桌面权限","permissionsIntro": "查看桌面需要屏幕录制权限;操作桌面还需要辅助功能权限。请在电脑上完成授权,结果会自动更新。","permissionsReady": "系统权限已就绪,可以重新连接。",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex fe9ae80478..0ac421bcf4 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -793,11 +793,12 @@"windowsTitle": "鎖定畫面控制","windowsready": "已為本次執行的 Cindy 啟用。重新啟動 Cindy 後需要再次由管理員授權。","windowsmissing": "允許操作鎖定畫面和管理員提示,需要管理員授權。",- "windowsinstallRequired": "請將 Cindy 安裝到 Program Files 並選擇為所有使用者安裝,再啟用此功能。",+ "windowsinstallRequired": "找不到 Cindy 的安裝位置,請重新啟動 Cindy 後重試。","windowsunavailable": "系統服務無法使用,請重新安裝 Cindy 後重試。","windowsEnable": "授權啟用","windowsDisable": "移除服務","windowsError": "尚未完成授權,請在這台電腦上重試。",+ "windowsErrorDetail": "錯誤碼 {{code}}","permissionsTitle": "遠端桌面權限","permissionsIntro": "檢視桌面需要螢幕錄製權限;操作桌面還需要輔助使用權限。請在電腦上完成授權,結果會自動更新。","permissionsReady": "系統權限已就緒,可以重新連線。",diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.mdindex 17c6bdeed7..921bc88183 100644--- a/docs/dev-rules/credentials-and-local-storage.md+++ b/docs/dev-rules/credentials-and-local-storage.md@@ -228,6 +228,7 @@ refresh 与 relay 自救节流。在途 refresh 尚未返回时收到的恢复| 语音输入声纹识别模型 | `userData/voice-models/<哈希前缀>-<文件名>.onnx`,按内容哈希从区域 CDN 下载并在可见前校验 SHA-256;不含个人数据,本机所有账号共用。新版本模型下载完成后删除旧版本文件 || Mobile 语音输入声纹(生物特征) | SecureStore(iOS 钥匙串 / Android Keystore)键 `xdt.voiceSpeakerProfile.v1.<账号 key 的 SHA-256 前 32 位>`,内容同 Desktop:声纹向量、录入时间与模型哈希;开关与灵敏度 override 在 AsyncStorage `cindy.mobile.voice-speaker-filter.v1.<账号 key>`。只在本机,不同步、不上传、不进日志;退出登录时随该账号的其他本机数据一起删除(模型文件保留)。删除前写 AsyncStorage `cindy.mobile.voice-speaker-filter.cleanup.v1.<账号 key>` 重试标记,不含声纹;失败时保留标记,启动、回到前台及该账号下次读写前重试,全部删除成功后才移除。标记落盘也失败时保留进程内重试,无法保证进程终止后的恢复;不因声纹删除失败阻止退出凭证清除。朗读音频只在内存中处理 || Mobile 语音输入声纹识别模型 | `cacheDirectory/voice-models/`,与 Desktop 同一组按内容哈希下载、校验 SHA-256 后才可见的文件;放缓存目录以免进入 iCloud / Android 备份。系统清理缓存后,下次语音输入发现缺失会在后台重新下载,本次不过滤 |+| Windows 锁屏控制的系统服务程序 | `%ProgramFiles%\Cindy Remote Desktop\<安装目录哈希>\`,由「授权开启」的管理员提权步骤写入:两个原生 helper 与记录所属安装目录的 `install.txt`。目录与文件的所有者是 Administrators,只有 Administrators 与 SYSTEM 可写——SYSTEM 服务不能从用户可写的安装目录启动,否则本机任何普通进程都能换掉它。不含凭证、账号或对话。源码运行的开发版另将构建缓存放在 `userData/remote-desktop/development/<安装身份哈希>/`,只含本机编译产物与源码摘要;它仍复制到上述受保护目录后才注册服务。只有设置页的「移除服务」(同样需要管理员确认)会删除它;按安装目录分子目录,多份安装互不影响。见 `native/remote-desktop/windows-host/src/staging.rs`、`apps/desktop/src/main/remote-desktop/windowsHost.ts` 与 [`../remote-desktop.md`](../remote-desktop.md) || 用户明确导出的文件 | 用户选择或任务明确指定的目标路径 |- 内置 Skill 的官方身份只授予当前 manifest 已提交且指纹匹配的 bundle:`.active` 必须是diff --git a/docs/remote-desktop.md b/docs/remote-desktop.mdindex 8b3a11e614..6318638762 100644--- a/docs/remote-desktop.md+++ b/docs/remote-desktop.md@@ -965,13 +965,65 @@ Remaining platform adapters are explicitly separate:The macOS pre-login and Linux service adapters remain unimplemented. The remote business protocol and shared relay are unchanged. Recoveryaffects only this desktop lease/video track, not other connected peers.-### Windows system service (implementation awaiting Windows runtime validation)+### Windows system service-Packaged Windows builds include a native SCM service, a Main-only Node-API pipe+Windows builds include a native SCM service, a Main-only Node-API pipetransport, a session-scoped SYSTEM GDI capture worker and the SendInput helper.The settings page installs/removes the service through Windows administrator-consent. Only a protected all-users Program Files installation is eligible;-per-user/development installations retain the ordinary desktop path.+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+Electron process is accepted only for the exact PID approved by that setup's+administrator prompt.++#### Where the service executable comes from++The service must not start an executable that ordinary processes can replace,+or any process running as the user would reach SYSTEM permanently and without a+prompt. Requiring an all-users Program Files installation was one way to get+that, at the cost of an administrator prompt on every update, so setup takes the+other route: while the user is already confirming the administrator prompt, the+elevated setup child copies `cindy-windows-desktop-host.exe` and+`cindy-windows-desktop-input.exe` into+`%ProgramFiles%\Cindy Remote Desktop\<installation id>\`, creates that directory+owned by Administrators and writable only by Administrators and SYSTEM, and+registers the service against the copy. The copies are read from the+installation through a handle opened without write or delete sharing, so the+bytes that are checked are the bytes that land.++The installation id is a hash of the installation directory, so two+installations — Cindy and CindyDev, or two copies of one edition — never share a+service, a pipe or a staged executable. Every participant derives that id from+the installation directory rather than from its own path, because they run from+different places: `naming.rs` holds the single derivation, and+`naming::tests::staged_copy_and_installation_agree_on_one_service_name` pins the+two sides together.++Setup always stops the service, restages and restarts, so an upgraded Cindy does+not keep running the previous version's copy. Removal deletes the service, the+staged directory, and a service registered under the pre-staging name.++What this does not cover: the elevated setup child itself is launched from the+installation directory, which the installing account can write. Anything able to+replace files there before the user confirms the prompt could have replaced that+child too, and a program checking its own signature proves nothing about itself.+This is the same exposure the Cindy updater already accepts when it elevates to+write into a protected directory. What staging removes is the standing risk: the+executable the service starts afterwards is out of reach.++Because Cindy's own uninstaller runs per user without administrator rights, it+cannot delete the staged directory or the service registration. Removing them is+the settings page's "remove service" action, which asks for administrator+consent. A leftover registration is inert — the service is demand-start and+exits with the Cindy process it was authorized for.++Both helpers import `VCRUNTIME140.dll` and the UCRT api-sets, as the shipped+helpers already did before staging; the UCRT is part of Windows, and+`VCRUNTIME140.dll` comes from the Visual C++ redistributable, which setup does+not install. Where it is missing the service cannot start, which surfaces as the+`service-ready` step rather than silently.++#### Authorization and validationAuthorization records a live process handle for the Cindy process explicitlyapproved through the elevated setup helper. Executable path alone is insufficient:@@ -979,12 +1031,42 @@ plugin utility processes share Cindy.exe. The service starts on demand and exitsRestarting Cindy or the service requires fresh administrator approval. This is a current limitation, not unattendedpost-reboot support. No authorization secrets or screenshots are persisted.+Registration is accepted only from an elevated process whose image has the same+contents as the running service's own image: the setup child runs from the+installation and the service from its protected copy, so their paths differ by+design and identical contents is what shows they are one build. Which+installation may then drive the service comes from `install.txt` in the+protected directory — an administrator-written value rather than a path handed+over the pipe — and it is accepted only if it hashes back to the directory's own+name, so a rewritten record cannot redirect the service elsewhere. That path is+user-writable, so the Cindy.exe check against it is a consistency check; what+actually gates the service is the approved process handle and the active console+session.+The broker validates file/directory ownership, writable ACLs, reparse points,-SCM identity, peer PIDs and active console session. It retains installation-handles for its lifetime. Workers are fixed-purpose children in kill-on-close jobs+SCM identity, peer PIDs and active console session over the staged directory and+its parents up to Program Files, and retains those handles for its lifetime.+Workers are fixed-purpose children in kill-on-close jobswith local-only, bounded, timed pipes. Uninstall/upgrade waits for the service tostop before removing binaries. Upgrade clears the authorization.+#### Diagnosing a failed setup++Every setup step has a fixed code — `stage-write`, `service-create`,+`authorize-connect` and so on — carrying the OS error number and nothing else:+no path, account name or other machine content. The elevated child is hidden, so+its console output never reaches the parent; it returns its step as its exit+code instead, and the parent reports it as `elevate-child/<step>`. Main logs the+code under `remote-desktop:windows` and the settings page shows it beside the+failure, so a report says which step failed rather than only that setup failed.+`windowsLockScreenSetup.test.ts` covers that path end to end in Main.++The service drops and recreates its listening pipe instance after every accept+timeout, and reports RUNNING just before the first instance exists.+`WaitNamedPipeW` returns immediately when no instance exists at all, so+`Pipe::client` retries within its three-second budget rather than failing on a+connection that merely landed in one of those gaps.+Desktop transitions terminate the old input helper, including pending batchesand long text input; Main then recovers only the remote desktop lease. Ctrl+Alt+Delis routed through service-side SendSAS impersonating the approved user's session.@@ -992,9 +1074,10 @@ Windows policy decides whether software SAS is allowed; Cindy never changes it.Capture follows the input desktop and validates the selected monitor's geometry.The GDI compatibility stream is capped at a 1280-pixel long edge and 180 KB JPEG.-Validation available on macOS: Windows-target Rust compilation checks and Desktop-TypeScript checking. Still required on Windows 10/11: signed package linking and-installation, administrator consent/cancellation, lock/unlock, UAC, policy-enabled+Validation so far: native release build and unit tests on Windows 11, Desktop+TypeScript checking, and the Main-side setup tests above. Still required on+Windows 10/11: signed package linking and installation, administrator+consent/cancellation, lock/unlock, UAC, policy-enabledSAS, mixed-DPI displays, worker cleanup, upgrade/uninstall, and plugin rejection.Windows display-mode changes and pre-login/unattended post-reboot control are notimplemented. A Linux pre-login service remains deferred. Do not present this as fully validated