diff --git a/README.en.md b/README.en.md index 7b429f6..dcecb40 100644 --- a/README.en.md +++ b/README.en.md @@ -546,6 +546,19 @@ GNOME-to-official-Mac bidirectional clipboard synchronization is still unverifie - CLI: `connect DEVICE false - echo legacy [--view-only]` (desktop), `files DEVICE ls|get|put …`, `terminal DEVICE [SESSION]`, `terminal-ui DEVICE NAME`, `portmap DEVICE LOCAL_PORT HOST PORT` (listens on 127.0.0.1 only), `power DEVICE reboot|shutdown`, `unbind DEVICE` (remove a device from the account; also under "More tools" in the launcher), `assist CONNECT_ID` (the code is read from one stdin line, never an argument). See `uuremote-viewer --help`. +- **Secure `type` input** (inject keystrokes into an open desktop session — lock-screen PIN/password; never put secrets on argv): + ```sh + # Preferred: open desktop via ui/connect first, then type (reuses the session; does not kick the live view) + UU_INPUT_ENV=UU_SECRET UU_SECRET='…' \ + uuremote-viewer type DEVICE [--delay-ms 40] [--omit-last 1] [--snapshot /path/out.png] + # Or: printf '%s' '…' | uuremote-viewer type DEVICE + # Validate only, no network: uuremote-viewer type DEVICE --dry-run + # If no desktop viewer is running you must pass --new-session (opens a new peer and replaces any already-open desktop window; upstream #30) + ``` + Brace tokens: `{Enter}` `{Tab}` `{Esc}` `{Backspace}` `{Ctrl+Alt+Del}` …; `{{` is a literal `{`. + **Layout**: characters are mapped for **US QWERTY** only (non-US layouts may mistype symbols/letters). + **Windows numeric PIN**: Windows often submits automatically once enough digits are entered — usually no `{Enter}` needed. Use `--omit-last N` to omit the last N characters when you want to fill without signing in. + Logs and `--dry-run` report lengths/event counts only. When reusing a session, about one second after sending, a PNG frame is saved (default under `$XDG_RUNTIME_DIR/uu-viewer-type/`, mode 0600); the path is logged and printed as `snapshot=…`. - Ctrl+Alt+F in the desktop window opens the files window on the same connection. `UU_VIEWER_AUDIO=0` disables sound, `UU_VIEWER_CLIPBOARD=0` the clipboard, `UU_VIEWER_VIEW_ONLY=1` input; `UU_VIEWER_FFMPEG` selects the ffmpeg binary. - Desktop offers H.264 / H.265; the host chooses the codec. `UU_VIEWER_CODEC=h264` limits both SDP and decoder capabilities to H.264. diff --git a/README.md b/README.md index d70de13..f94d9b1 100644 --- a/README.md +++ b/README.md @@ -486,6 +486,19 @@ GNOME 与官方 Mac 被控端的双向剪贴板尚未验证通过;此修改不 - 命令行:`connect DEVICE false - echo legacy [--view-only]`(桌面)、`files DEVICE ls|get|put …`、`terminal DEVICE [SESSION]`、 `terminal-ui DEVICE NAME`、`portmap DEVICE LOCAL_PORT HOST PORT`(只监听 127.0.0.1)、`power DEVICE reboot|shutdown`、`unbind DEVICE`(从账号删除设备,启动窗口「更多工具」里也有)、 `assist CONNECT_ID`(验证码从 stdin 读取一行,不能作为参数传入)。`uuremote-viewer --help` 查看全部参数。 +- **安全输入 `type`**(向已打开的桌面会话注入键盘,适合锁屏 PIN / 密码;文本永不进 argv): + ```sh + # 推荐:先 ui/connect 打开桌面,再 type(复用会话,不顶掉当前画面) + UU_INPUT_ENV=UU_SECRET UU_SECRET='……' \ + uuremote-viewer type DEVICE [--delay-ms 40] [--omit-last 1] [--snapshot /path/out.png] + # 或:printf '%s' '……' | uuremote-viewer type DEVICE + # 只检查、不连网:uuremote-viewer type DEVICE --dry-run + # 没有正在运行的桌面会话时必须显式:--new-session(会新开连接,并顶掉已打开的桌面窗口,见上游 #30) + ``` + 特殊键用花括号:`{Enter}` `{Tab}` `{Esc}` `{Backspace}` `{Ctrl+Alt+Del}` 等;`{{` 表示字面 `{`。 + **布局**:字符按 **US QWERTY** 物理键位映射(非美式布局的符号/字母可能对不上)。 + **Windows 数字 PIN**:输满位数后系统常会自动提交,一般不必再发 `{Enter}`;若只想填入、不登录,用 `--omit-last N` 省略最后 N 个字符。 + 日志与 `--dry-run` 输出只含长度/事件数,不含明文。复用会话时,发送约 1 秒后会保存一帧 PNG(默认写在 `$XDG_RUNTIME_DIR/uu-viewer-type/`,权限 0600),路径打在日志并打印 `snapshot=…`。 - 桌面窗口中按 Ctrl+Alt+F 打开文件窗口(复用同一连接)。`UU_VIEWER_AUDIO=0` 关闭声音,`UU_VIEWER_CLIPBOARD=0` 关闭剪贴板, `UU_VIEWER_VIEW_ONLY=1` 只看不控,`UU_VIEWER_FFMPEG` 指定 ffmpeg 路径。 - 桌面同时提供 H.264 / H.265,由主机协商选择;`UU_VIEWER_CODEC=h264` 将 SDP 和解码能力限制为 H.264。 diff --git a/src/viewer/mod.rs b/src/viewer/mod.rs index e559402..42b79c1 100644 --- a/src/viewer/mod.rs +++ b/src/viewer/mod.rs @@ -21,6 +21,8 @@ pub mod tools; pub mod clipboard; pub mod power; +pub mod secure_input; +pub mod type_ipc; fn device_label(name:Option<&str>)->&str{ name.filter(|name|!name.is_empty()).unwrap_or("远端设备") diff --git a/src/viewer/sdl.rs b/src/viewer/sdl.rs index 6330d31..7b7f91f 100644 --- a/src/viewer/sdl.rs +++ b/src/viewer/sdl.rs @@ -1,7 +1,9 @@ use super::{desktop::{Frame,FrameSink},input::{Input,Viewport},session::Session}; use sdl2::{event::{Event,WindowEvent},mouse::MouseButton,pixels::PixelFormatEnum,rect::Rect}; +#[derive(Debug)] enum Command { Files, Type } pub struct Window { canvas:sdl2::render::Canvas, events:sdl2::EventPump, _sdl:sdl2::Sdl, frame:(u32,u32), focused:bool, files:bool, mac:bool, - clipboard:sdl2::clipboard::ClipboardUtil, clipboard_dirty:bool, clipboard_tx:tokio::sync::mpsc::Sender, clipboard_requests:tokio::sync::mpsc::Receiver } + clipboard:sdl2::clipboard::ClipboardUtil, clipboard_dirty:bool, clipboard_tx:tokio::sync::mpsc::Sender, clipboard_requests:tokio::sync::mpsc::Receiver, + pub last_frame:Option } impl Window { pub fn new()->Result{ let sdl=sdl2::init()?;let video=sdl.video()?; @@ -9,7 +11,7 @@ impl Window { let canvas=window.into_canvas().build().map_err(|_|"Renderer creation failed")?; let events=sdl.event_pump()?;let clipboard=video.clipboard(); let(clipboard_tx,clipboard_requests)=tokio::sync::mpsc::channel(16); - Ok(Self{canvas,events,_sdl:sdl,frame:(1920,1080),focused:true,files:false,mac:false,clipboard,clipboard_dirty:true,clipboard_tx,clipboard_requests}) + Ok(Self{canvas,events,_sdl:sdl,frame:(1920,1080),focused:true,files:false,mac:false,clipboard,clipboard_dirty:true,clipboard_tx,clipboard_requests,last_frame:None}) } pub fn clipboard_bridge(&self)->super::clipboard::Bridge{super::clipboard::Bridge::sdl(self.clipboard_tx.clone())} pub fn set_mac(&mut self,mac:bool){self.mac=mac;} @@ -87,6 +89,7 @@ fn translate_actions(events:impl IntoIterator,input:&mut Input,viewp fn button(b:MouseButton)->Option{match b{MouseButton::Left=>Some(1),MouseButton::Right=>Some(2),MouseButton::Middle=>Some(4),_=>None}} impl FrameSink for Window { fn present(&mut self,frame:&Frame)->Result<(),String>{ + self.last_frame=Some(Frame{width:frame.width,height:frame.height,rgb:frame.rgb.clone()}); self.frame=(frame.width,frame.height);let v=self.viewport();let creator=self.canvas.texture_creator(); let mut texture=creator.create_texture_streaming(PixelFormatEnum::RGB24,frame.width,frame.height).map_err(|_|"Texture creation failed")?; texture.update(None,&frame.rgb,frame.width as usize*3).map_err(|_|"Texture update failed")?; @@ -94,21 +97,34 @@ impl FrameSink for Window { self.canvas.copy(&texture,None,Some(Rect::new(v.x as i32,v.y as i32,v.width as u32,v.height as u32)))?;self.canvas.present();Ok(()) } } -pub async fn run(session:&mut Session,window:&mut Window,decoder:&mut dyn super::desktop::Decoder,view_only:bool)->Result<(),String>{ +pub async fn run(session:&mut Session,window:&mut Window,decoder:&mut dyn super::desktop::Decoder,view_only:bool,device:&str)->Result<(),String>{ #[cfg(uu_gtk)] let mut files:Option>>=None; - let(tx,mut commands)=tokio::sync::mpsc::channel(8); + let(tx,mut commands)=tokio::sync::mpsc::channel::(8); if std::env::var("UU_VIEWER_COMMANDS").as_deref()==Ok("1") { std::thread::spawn(move||{ use std::io::Read; let mut input=std::io::stdin().lock();let mut line=Vec::new();let mut byte=[0]; while input.read(&mut byte).ok()==Some(1){ - if byte[0]==b'\n'{if line==b"files" && tx.blocking_send(()).is_err(){break}line.clear();} + if byte[0]==b'\n'{ + let cmd=match line.as_slice(){b"files"=>Some(Command::Files),b"type"=>Some(Command::Type),_=>None}; + line.clear(); + if let Some(cmd)=cmd { if tx.blocking_send(cmd).is_err(){break} } + } else if line.len()<32{line.push(byte[0]);}else{break} } }); }else{drop(tx);} - let mut command_open=true;let mut requested=false; + let(type_tx,mut type_rx)=tokio::sync::mpsc::channel::(4); + let type_ipc=match super::type_ipc::Server::bind(device).await { + Ok(server)=>{ + log::info!("Type IPC ready for device key {}", &super::type_ipc::device_key(device)[..12]); + Some(tokio::spawn(async move { server.run(type_tx).await; })) + } + Err(e)=>{ log::warn!("Type IPC not started: {e}"); None } + }; + let mut command_open=true;let mut requested=false;let mut type_requested=false; + let mut type_job:Option=None; let mut terminate=tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).map_err(|_|"Cannot watch termination")?; let mut audio=super::audio::Playback::new(&window._sdl,session.peer.audio.clone()); let mut input=Input::new(view_only);input.set_mac(window.mac);let mut tick=tokio::time::interval(std::time::Duration::from_millis(8)); @@ -116,7 +132,32 @@ pub async fn run(session:&mut Session,window:&mut Window,decoder:&mut dyn super: let deadline=tokio::time::sleep(std::time::Duration::from_secs(30));tokio::pin!(deadline); let result=async { loop {tokio::select!{ - command=commands.recv(),if command_open=>{if command.is_some(){requested=true}else{command_open=false}}, + command=commands.recv(),if command_open=>{ + match command { + Some(Command::Files)=>{requested=true}, + Some(Command::Type)=>{type_requested=true}, + None=>{command_open=false}, + } + }, + pending=type_rx.recv()=>{ + if let Some(mut pending)=pending { + if type_job.is_some() { + let _=pending.reply.send(super::type_ipc::TypeResponse{ok:false,events:0,chars:0,snapshot:None,error:Some("Secure input busy".into())}); + } else { + let mut snapshot_create_new=false; + if pending.request.snapshot.as_ref().map_or(true, |s| s.is_empty()) { + if let Ok(path)=super::type_ipc::default_snapshot_path(device) { + pending.request.snapshot=Some(path.display().to_string()); + snapshot_create_new=true; + } + } + match start_type_job(pending, window.mac, input.enabled(), snapshot_create_new) { + Ok(job)=>type_job=Some(job), + Err(())=>{}, + } + } + } + }, _=terminate.recv()=>return Ok(()), _=tokio::signal::ctrl_c()=>return Ok(()), result=session.step()=>result?, @@ -145,6 +186,34 @@ pub async fn run(session:&mut Session,window:&mut Window,decoder:&mut dyn super: } } #[cfg(not(uu_gtk))] {if requested{log::warn!("File window requires GTK3");requested=false;}} + if type_requested { + type_requested=false; + if type_job.is_some() { + log::warn!("Secure type command ignored: busy"); + } else if !input.enabled() { + log::warn!("Secure type command ignored: view-only session"); + } else if std::env::var_os("UU_INPUT_ENV").is_none() { + log::warn!("Secure type command ignored: set UU_INPUT_ENV (stdin is the command channel)"); + } else { + match super::secure_input::load_secret(std::io::Cursor::new([] as [u8;0])) { + Ok(mut secret)=>{ + match enqueue_local_type(&mut type_job, &mut secret, window.mac, None, 0, std::time::Duration::ZERO, None) { + Ok(())=>{}, + Err(e)=>log::warn!("Secure type failed: {e}"), + } + } + Err(e)=>log::warn!("Secure type load failed: {e}"), + } + } + } + if let Some(job)=type_job.as_mut() { + if let Err(e)=pump_type_job(job, session, window).await { + log::warn!("Secure type job failed: {e}"); + type_job=None; + } else if job.done { + type_job=None; + } + } if session.peer.ready(super::rtc::ReadyPolicy::EchoOnly,false){for m in messages{session.peer.send_input(&m).await?;}} else {input.release_all();} if quit{return Ok(())} @@ -157,10 +226,150 @@ pub async fn run(session:&mut Session,window:&mut Window,decoder:&mut dyn super: }} }.await; #[cfg(uu_gtk)] if let Some(f)=files {f.abort();let _=f.await;super::tools_ui::hide();session.peer.tools.lock().unwrap().take();} + if let Some(t)=type_ipc {t.abort();let _=t.await;} for m in input.release_all(){let _=session.peer.send_input(&m).await;} result } +struct TypeJob { + actions: super::secure_input::ActionList, + index: usize, + delay: std::time::Duration, + next_at: tokio::time::Instant, + chars: usize, + snapshot_path: Option, + snapshot_create_new: bool, + phase: TypePhase, + reply: Option>, + done: bool, +} +enum TypePhase { Sending, WaitSnap(tokio::time::Instant) } + +fn start_type_job(mut pending: super::type_ipc::PendingType, mac: bool, enabled: bool, snapshot_create_new: bool) -> Result { + let reply = pending.reply; + let respond_err = |reply: tokio::sync::oneshot::Sender, msg: String| { + let _ = reply.send(super::type_ipc::TypeResponse{ok:false,events:0,chars:0,snapshot:None,error:Some(msg)}); + }; + if !enabled { + respond_err(reply, "view-only session".into()); + return Err(()); + } + let mut secret = super::secure_input::Secret::new(std::mem::take(&mut pending.request.secret)); + if let Err(e) = secret.omit_last_chars(pending.request.omit_last) { + respond_err(reply, e); + return Err(()); + } + let chars = secret.chars_count(); + let actions = match super::secure_input::expand(secret.as_str(), mac) { + Ok(a) => a, + Err(e) => { respond_err(reply, e); return Err(()); } + }; + drop(secret); + log::info!("Secure input prepared: chars={} events={} delay_ms={}", chars, actions.len(), pending.request.delay_ms); + let snapshot_path = pending.request.snapshot.as_ref().filter(|s| !s.is_empty()).map(std::path::PathBuf::from); + Ok(TypeJob { + actions, + index: 0, + delay: std::time::Duration::from_millis(pending.request.delay_ms.min(5_000)), + next_at: tokio::time::Instant::now(), + chars, + snapshot_path, + snapshot_create_new, + phase: TypePhase::Sending, + reply: Some(reply), + done: false, + }) +} + +fn enqueue_local_type( + slot: &mut Option, + secret: &mut super::secure_input::Secret, + mac: bool, + snapshot: Option, + omit_last: usize, + delay: std::time::Duration, + reply: Option>, +) -> Result<(), String> { + secret.omit_last_chars(omit_last)?; + let chars = secret.chars_count(); + let actions = super::secure_input::expand(secret.as_str(), mac)?; + drop(std::mem::replace(secret, super::secure_input::Secret::new(String::new()))); + log::info!("Secure input prepared: chars={} events={}", chars, actions.len()); + *slot = Some(TypeJob { + actions, + index: 0, + delay, + next_at: tokio::time::Instant::now(), + chars, + snapshot_path: snapshot, + snapshot_create_new: false, + phase: TypePhase::Sending, + reply, + done: false, + }); + Ok(()) +} + +async fn pump_type_job(job: &mut TypeJob, session: &mut Session, window: &mut Window) -> Result<(), String> { + use super::type_ipc::TypeResponse; + match job.phase { + TypePhase::Sending => { + if !session.peer.ready(super::rtc::ReadyPolicy::EchoOnly, false) { + return Ok(()); + } + if tokio::time::Instant::now() < job.next_at { + return Ok(()); + } + if job.index >= job.actions.len() { + let wait = tokio::time::Instant::now() + std::time::Duration::from_secs(1); + job.phase = TypePhase::WaitSnap(wait); + return Ok(()); + } + let action = &job.actions[job.index]; + session.peer.send_input(&action.to_json()).await?; + job.index += 1; + if !job.delay.is_zero() { + job.next_at = tokio::time::Instant::now() + job.delay; + } + Ok(()) + } + TypePhase::WaitSnap(deadline) => { + if tokio::time::Instant::now() < deadline { + return Ok(()); + } + let mut snap = None; + if let Some(path) = job.snapshot_path.clone() { + if let Some(frame) = window.last_frame.as_ref() { + match super::type_ipc::write_png_rgb(&path, frame.width, frame.height, &frame.rgb, job.snapshot_create_new) { + Ok(()) => { + log::info!("Secure input snapshot written: {}", path.display()); + snap = Some(path.display().to_string()); + } + Err(e) => log::warn!("Secure input snapshot failed: {e}"), + } + } else { + log::warn!("Secure input snapshot skipped: no decoded frame yet"); + } + } + let events = job.actions.len(); + let chars = job.chars; + if let Some(reply) = job.reply.take() { + let _ = reply.send(TypeResponse { + ok: true, + events, + chars, + snapshot: snap, + error: None, + }); + } else { + log::info!("Secure input finished: chars={} events={}", chars, events); + } + job.done = true; + Ok(()) + } + } +} + #[cfg(test)] mod tests { use super::*; // macOS: SDL video must start on the main thread, which the test harness does not use; CI runs it on Linux. diff --git a/src/viewer/secure_input.rs b/src/viewer/secure_input.rs new file mode 100644 index 0000000..87deef6 --- /dev/null +++ b/src/viewer/secure_input.rs @@ -0,0 +1,731 @@ +//! Compose CONTROL keyboard JSON for scripted typing. Secrets never appear in logs or Debug. +use serde_json::{json, Value}; +use std::fmt; +use std::io::{BufRead, Read}; +use std::ops::{Deref, DerefMut}; +#[cfg(test)] +use std::sync::Mutex; +use std::time::Duration; + +/// Serializes tests that mutate process environment. +#[cfg(test)] +pub static ENV_LOCK: Mutex<()> = Mutex::new(()); + +/// Holds secret text; Debug/Display only show length. +pub struct Secret(String); + +impl Secret { + pub fn new(value: String) -> Self { + Self(value) + } + pub fn as_str(&self) -> &str { + &self.0 + } + pub fn len(&self) -> usize { + self.0.len() + } + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + pub fn chars_count(&self) -> usize { + self.0.chars().count() + } + /// Drop the last `n` Unicode scalars (fill-without-submit for Windows PIN). + pub fn omit_last_chars(&mut self, n: usize) -> Result<(), String> { + let count = self.0.chars().count(); + if n > count { + return Err("omit-last exceeds secret length".into()); + } + if n == 0 { + return Ok(()); + } + let keep = count - n; + let truncated: String = self.0.chars().take(keep).collect(); + zeroize_str(&mut self.0); + self.0 = truncated; + Ok(()) + } +} + +impl fmt::Debug for Secret { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Secret(len={})", self.0.len()) + } +} + +impl fmt::Display for Secret { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "*** ({} bytes)", self.0.len()) + } +} + +impl Drop for Secret { + fn drop(&mut self) { + zeroize_str(&mut self.0); + } +} + +fn zeroize_str(s: &mut String) { + let bytes = unsafe { s.as_bytes_mut() }; + for b in bytes.iter_mut() { + *b = 0; + } + s.clear(); +} + +/// One CONTROL keyboard action (Windows VK or Mac keycode in `key`). +#[derive(Clone, Debug, PartialEq)] +pub enum KeyAction { + Press(i32), + Release(i32), +} + +impl KeyAction { + pub fn to_json(&self) -> Value { + match self { + Self::Press(k) => json!({"action":"kbd_press","key":k}), + Self::Release(k) => json!({"action":"kbd_release","key":k}), + } + } + fn zeroize(&mut self) { + match self { + Self::Press(k) | Self::Release(k) => *k = 0, + } + } +} + +/// Key event list that wipes key codes on drop. +pub struct ActionList(Vec); + +impl std::fmt::Debug for ActionList { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "ActionList(len={})", self.0.len()) + } +} + +impl ActionList { + pub fn new(actions: Vec) -> Self { + Self(actions) + } + pub fn len(&self) -> usize { + self.0.len() + } + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + pub fn as_slice(&self) -> &[KeyAction] { + &self.0 + } +} + +impl Deref for ActionList { + type Target = [KeyAction]; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for ActionList { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl Drop for ActionList { + fn drop(&mut self) { + for a in &mut self.0 { + a.zeroize(); + } + self.0.clear(); + } +} + +pub fn parse_delay_ms(raw: Option<&str>) -> Result { + let Some(raw) = raw else { + return Ok(Duration::ZERO); + }; + let ms: u64 = raw + .parse() + .map_err(|_| String::from("delay must be a non-negative integer (milliseconds)"))?; + if ms > 5_000 { + return Err("delay must be at most 5000 ms".into()); + } + Ok(Duration::from_millis(ms)) +} + +pub fn parse_omit_last(raw: Option<&str>) -> Result { + let Some(raw) = raw else { + return Ok(0); + }; + let n: usize = raw + .parse() + .map_err(|_| String::from("omit-last must be a non-negative integer"))?; + if n > 64 { + return Err("omit-last must be at most 64".into()); + } + Ok(n) +} + +/// `UU_INPUT_ENV` names another variable that holds the secret; otherwise one stdin line. +/// After reading a named secret variable, that variable is removed from the environment. +pub fn load_secret(stdin: impl BufRead) -> Result { + if let Ok(name) = std::env::var("UU_INPUT_ENV") { + validate_env_name(&name)?; + let value = std::env::var(&name) + .map_err(|_| "Environment variable named by UU_INPUT_ENV is not set".to_string())?; + std::env::remove_var(&name); + if value.is_empty() { + return Err("Secret environment variable is empty".into()); + } + if value.len() > 16 * 1024 { + return Err("Secret exceeds 16 KiB".into()); + } + return Ok(Secret::new(value)); + } + let mut line = String::new(); + stdin + .take(16 * 1024 + 1) + .read_to_string(&mut line) + .map_err(|_| "Cannot read secret from stdin")?; + if line.len() > 16 * 1024 { + return Err("Secret exceeds 16 KiB".into()); + } + if line.ends_with('\n') { + line.pop(); + if line.ends_with('\r') { + line.pop(); + } + } + if line.is_empty() { + return Err("Secret stdin is empty (set UU_INPUT_ENV or pipe text)".into()); + } + Ok(Secret::new(line)) +} + +fn validate_env_name(name: &str) -> Result<(), String> { + if name.is_empty() || name.len() > 128 { + return Err("UU_INPUT_ENV must be a non-empty variable name".into()); + } + if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { + return Err("UU_INPUT_ENV must be an alphanumeric variable name".into()); + } + Ok(()) +} + +/// Expand template text into key actions. Brace tokens: `{Enter}`, `{Tab}`, `{Esc}`, +/// `{Backspace}`, `{Delete}`, `{Space}`, `{Ctrl+Alt+Del}`, arrows, `{Home}`, `{End}`, `{F1}`…`{F12}`. +/// Plain characters use a US QWERTY VK/Mac mapping (Shift for uppercase/symbols). +/// Errors never include the offending character or token text — only a 0-based char index. +pub fn expand(text: &str, mac: bool) -> Result { + let mut out = Vec::new(); + let mut chars = text.chars().peekable(); + let mut index = 0usize; + while let Some(c) = chars.next() { + if c == '{' { + if chars.peek() == Some(&'{') { + chars.next(); + push_char(&mut out, '{', mac, index)?; + index += 1; + continue; + } + let start = index; + let mut name = String::new(); + let mut closed = false; + for n in chars.by_ref() { + if n == '}' { + closed = true; + break; + } + if n == '{' || name.len() > 32 { + zeroize_str(&mut name); + return Err(format!("Invalid special-key token at index {start}")); + } + name.push(n); + } + if !closed { + zeroize_str(&mut name); + return Err(format!("Unclosed special-key token at index {start}")); + } + // Advance index past '{' + name + '}' + index += 1 + name.chars().count() + 1; + let result = push_special(&mut out, &name, mac, start); + zeroize_str(&mut name); + result?; + continue; + } + if c.is_control() && c != '\t' && c != '\n' && c != '\r' { + return Err(format!("Control character at index {index}")); + } + match c { + '\n' | '\r' => push_special(&mut out, "Enter", mac, index)?, + '\t' => push_special(&mut out, "Tab", mac, index)?, + _ => push_char(&mut out, c, mac, index)?, + } + index += 1; + } + Ok(ActionList::new(out)) +} + +fn push_special( + out: &mut Vec, + name: &str, + mac: bool, + index: usize, +) -> Result<(), String> { + let key = match name { + "Enter" | "Return" => Some(vk_or_mac(0x0d, 36, mac)), + "Tab" => Some(vk_or_mac(0x09, 48, mac)), + "Esc" | "Escape" => Some(vk_or_mac(0x1b, 53, mac)), + "Backspace" => Some(vk_or_mac(0x08, 51, mac)), + "Delete" | "Del" => Some(vk_or_mac(0x2e, 117, mac)), + "Space" => Some(vk_or_mac(0x20, 49, mac)), + "Up" => Some(vk_or_mac(0x26, 126, mac)), + "Down" => Some(vk_or_mac(0x28, 125, mac)), + "Left" => Some(vk_or_mac(0x25, 123, mac)), + "Right" => Some(vk_or_mac(0x27, 124, mac)), + "Home" => Some(vk_or_mac(0x24, 115, mac)), + "End" => Some(vk_or_mac(0x23, 119, mac)), + "Ctrl+Alt+Del" | "CAD" => { + let ctrl = vk_or_mac(0xa2, 59, mac); + let alt = vk_or_mac(0xa4, 58, mac); + let del = vk_or_mac(0x2e, 117, mac); + out.push(KeyAction::Press(ctrl)); + out.push(KeyAction::Press(alt)); + out.push(KeyAction::Press(del)); + out.push(KeyAction::Release(del)); + out.push(KeyAction::Release(alt)); + out.push(KeyAction::Release(ctrl)); + return Ok(()); + } + other if other.len() >= 2 && other.as_bytes()[0] == b'F' => { + let n: u32 = other[1..] + .parse() + .map_err(|_| format!("Unknown special key at index {index}"))?; + if !(1..=12).contains(&n) { + return Err(format!("Unknown special key at index {index}")); + } + let vk = 0x70 + (n as i32 - 1); + let mac_code = match n { + 1 => 122, + 2 => 120, + 3 => 99, + 4 => 118, + 5 => 96, + 6 => 97, + 7 => 98, + 8 => 100, + 9 => 101, + 10 => 109, + 11 => 103, + 12 => 111, + _ => unreachable!(), + }; + Some(vk_or_mac(vk, mac_code, mac)) + } + _ => return Err(format!("Unknown special key at index {index}")), + }; + let Some(key) = key else { + return Ok(()); + }; + out.push(KeyAction::Press(key)); + out.push(KeyAction::Release(key)); + Ok(()) +} + +fn vk_or_mac(vk: i32, mac: i32, is_mac: bool) -> i32 { + if is_mac { + mac + } else { + vk + } +} + +fn push_char(out: &mut Vec, c: char, mac: bool, index: usize) -> Result<(), String> { + let (vk, shift) = us_qwerty_vk(c) + .ok_or_else(|| format!("Unsupported character at index {index}"))?; + let key = if mac { + mac_from_vk(vk).ok_or_else(|| format!("Unsupported character at index {index}"))? + } else { + vk + }; + let shift_key = vk_or_mac(0xa0, 56, mac); + if shift { + out.push(KeyAction::Press(shift_key)); + } + out.push(KeyAction::Press(key)); + out.push(KeyAction::Release(key)); + if shift { + out.push(KeyAction::Release(shift_key)); + } + Ok(()) +} + +fn us_qwerty_vk(c: char) -> Option<(i32, bool)> { + match c { + 'a'..='z' => Some((0x41 + (c as i32 - 'a' as i32), false)), + 'A'..='Z' => Some((0x41 + (c as i32 - 'A' as i32), true)), + '0' => Some((0x30, false)), + '1'..='9' => Some((0x30 + (c as i32 - '0' as i32), false)), + ' ' => Some((0x20, false)), + '-' => Some((0xbd, false)), + '_' => Some((0xbd, true)), + '=' => Some((0xbb, false)), + '+' => Some((0xbb, true)), + '[' => Some((0xdb, false)), + '{' => Some((0xdb, true)), + ']' => Some((0xdd, false)), + '}' => Some((0xdd, true)), + '\\' => Some((0xdc, false)), + '|' => Some((0xdc, true)), + ';' => Some((0xba, false)), + ':' => Some((0xba, true)), + '\'' => Some((0xde, false)), + '"' => Some((0xde, true)), + '`' => Some((0xc0, false)), + '~' => Some((0xc0, true)), + ',' => Some((0xbc, false)), + '<' => Some((0xbc, true)), + '.' => Some((0xbe, false)), + '>' => Some((0xbe, true)), + '/' => Some((0xbf, false)), + '?' => Some((0xbf, true)), + '!' => Some((0x31, true)), + '@' => Some((0x32, true)), + '#' => Some((0x33, true)), + '$' => Some((0x34, true)), + '%' => Some((0x35, true)), + '^' => Some((0x36, true)), + '&' => Some((0x37, true)), + '*' => Some((0x38, true)), + '(' => Some((0x39, true)), + ')' => Some((0x30, true)), + _ => None, + } +} + +fn mac_from_vk(vk: i32) -> Option { + let scan = match vk { + 0x41..=0x5a => 4 + (vk - 0x41), + 0x31..=0x39 => 30 + (vk - 0x31), + 0x30 => 39, + 0x0d => 40, + 0x1b => 41, + 0x08 => 42, + 0x09 => 43, + 0x20 => 44, + 0xbd => 45, + 0xbb => 46, + 0xdb => 47, + 0xdd => 48, + 0xdc => 49, + 0xba => 51, + 0xde => 52, + 0xc0 => 53, + 0xbc => 54, + 0xbe => 55, + 0xbf => 56, + 0xa0 => 225, + _ => return None, + }; + super::input::mac_keycode(scan) +} + +pub async fn send_actions( + send: impl Fn(Value) -> std::pin::Pin> + Send>>, + actions: &[KeyAction], + delay: Duration, +) -> Result<(), String> { + for (i, action) in actions.iter().enumerate() { + send(action.to_json()).await?; + if !delay.is_zero() && i + 1 != actions.len() { + tokio::time::sleep(delay).await; + } + } + Ok(()) +} + +/// Wait for CONTROL echo on an open desktop session, then send key actions. +pub async fn run_session( + session: &mut super::session::Session, + actions: &[KeyAction], + delay: Duration, +) -> Result<(), String> { + use std::sync::atomic::Ordering; + let ready = async { + loop { + if session.peer.observed.control_open.load(Ordering::Acquire) + && session.peer.observed.echo_received.load(Ordering::Acquire) + { + return Ok::<_, String>(()); + } + tokio::select! { + r = session.step() => r?, + _ = tokio::time::sleep(Duration::from_millis(20)) => {} + } + } + }; + tokio::time::timeout(Duration::from_secs(30), ready) + .await + .map_err(|_| "CONTROL echo timed out")??; + for (i, action) in actions.iter().enumerate() { + session.peer.send_input(&action.to_json()).await?; + if !delay.is_zero() && i + 1 != actions.len() { + tokio::time::sleep(delay).await; + } + } + Ok(()) +} + +/// Dry-run summary: lengths only, never the secret or key codes. +pub fn dry_run_report(secret: &Secret, omit_last: usize, mac: bool) -> Result { + let mut owned = Secret::new(secret.as_str().to_owned()); + owned.omit_last_chars(omit_last)?; + let actions = expand(owned.as_str(), mac)?; + Ok(format!( + "dry-run: chars={} omit_last={} events={} mac={}", + owned.chars_count(), + omit_last, + actions.len(), + mac + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + #[test] + fn secret_debug_and_display_never_leak() { + let s = Secret::new("hunter2".into()); + let d = format!("{s:?}"); + let p = format!("{s}"); + assert!(d.contains("len=7")); + assert!(!d.contains("hunter")); + assert!(!p.contains("hunter")); + assert!(p.contains("***")); + } + + #[test] + fn action_list_debug_shows_len_only() { + let list = ActionList::new(vec![ + KeyAction::Press(0x41), + KeyAction::Release(0x41), + KeyAction::Press(0x42), + KeyAction::Release(0x42), + ]); + let d = format!("{list:?}"); + assert_eq!(d, "ActionList(len=4)"); + assert!(!d.contains("0x41")); + assert!(!d.contains("Press")); + assert!(!d.contains("41")); + } + + #[test] + fn letters_digits_and_shift_symbols_map_to_windows_vk() { + let actions = expand("Ab1!", false).unwrap(); + assert_eq!( + &actions[0..4], + &[ + KeyAction::Press(0xa0), + KeyAction::Press(0x41), + KeyAction::Release(0x41), + KeyAction::Release(0xa0), + ] + ); + assert_eq!( + &actions[4..6], + &[KeyAction::Press(0x42), KeyAction::Release(0x42)] + ); + assert_eq!( + &actions[6..8], + &[KeyAction::Press(0x31), KeyAction::Release(0x31)] + ); + assert_eq!( + &actions[8..12], + &[ + KeyAction::Press(0xa0), + KeyAction::Press(0x31), + KeyAction::Release(0x31), + KeyAction::Release(0xa0), + ] + ); + } + + #[test] + fn special_keys_and_ctrl_alt_del() { + let a = expand("{Enter}{Tab}{Esc}{Backspace}{Ctrl+Alt+Del}", false).unwrap(); + assert!(a + .windows(2) + .any(|w| w == [KeyAction::Press(0x0d), KeyAction::Release(0x0d)])); + let cad: Vec<_> = a.iter().rev().take(6).rev().cloned().collect(); + assert_eq!( + cad, + vec![ + KeyAction::Press(0xa2), + KeyAction::Press(0xa4), + KeyAction::Press(0x2e), + KeyAction::Release(0x2e), + KeyAction::Release(0xa4), + KeyAction::Release(0xa2), + ] + ); + } + + #[test] + fn unknown_special_key_errors_without_echoing_payload() { + let err = expand("{NotAKey}", false).unwrap_err(); + assert!(err.contains("Unknown special key at index")); + assert!(!err.contains("NotAKey")); + assert!(!err.contains("password")); + } + + #[test] + fn unsupported_char_errors_without_codepoint_or_char() { + let err = expand("a中", false).unwrap_err(); + assert!(err.contains("Unsupported character at index 1")); + assert!(!err.contains('中')); + assert!(!err.contains("4E2D")); + assert!(!err.contains("U+")); + } + + #[test] + fn unclosed_token_and_control_char_rejected() { + assert!(expand("{Enter", false).is_err()); + assert!(expand("a\u{0001}b", false).is_err()); + } + + #[test] + fn load_from_named_env_and_stdin() { + let _g = ENV_LOCK.lock().unwrap(); + std::env::set_var("UU_INPUT_ENV", "UU_SECRET"); + std::env::set_var("UU_SECRET", "pin-value"); + let s = load_secret(Cursor::new(b"")).unwrap(); + assert_eq!(s.as_str(), "pin-value"); + assert!(!format!("{s:?}").contains("pin")); + assert!(std::env::var("UU_SECRET").is_err()); + std::env::remove_var("UU_INPUT_ENV"); + let s = load_secret(Cursor::new(b"from-stdin\n")).unwrap(); + assert_eq!(s.as_str(), "from-stdin"); + } + + #[test] + fn invalid_env_name_and_empty_secret() { + let _g = ENV_LOCK.lock().unwrap(); + std::env::set_var("UU_INPUT_ENV", "bad-name!"); + assert!(load_secret(Cursor::new(b"")).is_err()); + std::env::remove_var("UU_INPUT_ENV"); + std::env::set_var("UU_INPUT_ENV", "EMPTY_SECRET_TEST"); + std::env::set_var("EMPTY_SECRET_TEST", ""); + assert!(load_secret(Cursor::new(b"")).is_err()); + std::env::remove_var("UU_INPUT_ENV"); + std::env::remove_var("EMPTY_SECRET_TEST"); + assert!(load_secret(Cursor::new(b"\n")).is_err()); + } + + #[test] + fn delay_and_omit_bounds() { + assert_eq!(parse_delay_ms(None).unwrap(), Duration::ZERO); + assert_eq!( + parse_delay_ms(Some("50")).unwrap(), + Duration::from_millis(50) + ); + assert!(parse_delay_ms(Some("-1")).is_err()); + assert!(parse_delay_ms(Some("5001")).is_err()); + assert_eq!(parse_omit_last(None).unwrap(), 0); + assert_eq!(parse_omit_last(Some("2")).unwrap(), 2); + assert!(parse_omit_last(Some("65")).is_err()); + } + + #[test] + fn omit_last_and_dry_run() { + let mut s = Secret::new("1234567".into()); + s.omit_last_chars(1).unwrap(); + assert_eq!(s.as_str(), "123456"); + let report = dry_run_report(&Secret::new("1234567".into()), 1, false).unwrap(); + assert!(report.contains("chars=6")); + assert!(report.contains("omit_last=1")); + assert!(report.contains("events=")); + assert!(report.contains("omit_last=1")); + assert!(!report.contains("123456")); + assert!(!report.contains("1234567")); + } + + #[test] + fn brace_escape_types_literal_brace() { + let a = expand("{{a", false).unwrap(); + assert_eq!( + &a[0..4], + &[ + KeyAction::Press(0xa0), + KeyAction::Press(0xdb), + KeyAction::Release(0xdb), + KeyAction::Release(0xa0), + ] + ); + assert_eq!( + &a[4..6], + &[KeyAction::Press(0x41), KeyAction::Release(0x41)] + ); + } + + #[test] + fn password_with_enter_suffix() { + let a = expand("secret{Enter}", false).unwrap(); + assert_eq!(a.last(), Some(&KeyAction::Release(0x0d))); + assert_eq!(a[a.len() - 2], KeyAction::Press(0x0d)); + } + + #[test] + fn action_list_zeroizes_on_drop() { + let mut a = KeyAction::Press(0x41); + a.zeroize(); + assert_eq!(a, KeyAction::Press(0)); + let list = ActionList::new(vec![KeyAction::Press(7), KeyAction::Release(7)]); + assert_eq!(list.len(), 2); + drop(list); + } + + #[tokio::test] + async fn send_actions_respects_delay_and_order() { + use std::sync::{Arc, Mutex}; + let log = Arc::new(Mutex::new(Vec::new())); + let recorded = log.clone(); + let actions = expand("a{Enter}", false).unwrap(); + let start = std::time::Instant::now(); + send_actions( + |v| { + let recorded = recorded.clone(); + Box::pin(async move { + recorded.lock().unwrap().push(v); + Ok(()) + }) + }, + actions.as_slice(), + Duration::from_millis(20), + ) + .await + .unwrap(); + assert!(start.elapsed() >= Duration::from_millis(50)); + let keys: Vec<_> = log + .lock() + .unwrap() + .iter() + .map(|v| { + ( + v["action"].as_str().unwrap().to_owned(), + v["key"].as_i64().unwrap(), + ) + }) + .collect(); + assert_eq!( + keys, + vec![ + ("kbd_press".into(), 0x41), + ("kbd_release".into(), 0x41), + ("kbd_press".into(), 0x0d), + ("kbd_release".into(), 0x0d), + ] + ); + } +} diff --git a/src/viewer/type_ipc.rs b/src/viewer/type_ipc.rs new file mode 100644 index 0000000..326d2cc --- /dev/null +++ b/src/viewer/type_ipc.rs @@ -0,0 +1,627 @@ +//! Local Unix-socket bridge: `uuremote-viewer type` hands secrets to a running desktop session. +//! Frames are length-prefixed JSON; secrets never appear in logs. Peer UID must match. +use serde::{Deserialize, Serialize}; +use std::{ + os::unix::fs::DirBuilderExt, + path::{Path, PathBuf}, +}; +use tokio::{ + io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}, + net::{UnixListener, UnixStream}, + sync::mpsc, +}; + +/// Max JSON frame (header + secret). 16 KiB secret + margin. +pub const MAX_FRAME: usize = 20 * 1024; + +#[derive(Serialize, Deserialize)] +pub struct TypeRequest { + pub delay_ms: u64, + pub omit_last: usize, + pub snapshot: Option, + /// Secret text; Debug only exposes length. + pub secret: String, +} + +impl std::fmt::Debug for TypeRequest { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TypeRequest") + .field("delay_ms", &self.delay_ms) + .field("omit_last", &self.omit_last) + .field( + "snapshot", + &self.snapshot.as_ref().map(|s| format!("len={}", s.len())), + ) + .field("secret_len", &self.secret.len()) + .finish() + } +} + +impl Drop for TypeRequest { + fn drop(&mut self) { + zeroize_string(&mut self.secret); + if let Some(s) = self.snapshot.as_mut() { + zeroize_string(s); + } + } +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct TypeResponse { + pub ok: bool, + pub events: usize, + pub chars: usize, + pub snapshot: Option, + pub error: Option, +} + +fn zeroize_string(s: &mut String) { + // Best-effort wipe before drop. + let bytes = unsafe { s.as_bytes_mut() }; + for b in bytes.iter_mut() { + *b = 0; + } + s.clear(); +} + +/// Ensure `dir` is a real directory owned by us with mode & 0o077 == 0 (no symlink). +pub fn validate_private_dir(dir: &Path) -> Result<(), String> { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + let meta = std::fs::symlink_metadata(dir).map_err(|_| "Cannot inspect type-ipc directory")?; + if meta.file_type().is_symlink() { + return Err("Type-ipc path is a symlink".into()); + } + if !meta.file_type().is_dir() { + return Err("Type-ipc path is not a directory".into()); + } + let me = unsafe { libc::getuid() }; + if meta.uid() != me { + return Err("Type-ipc directory owner mismatch".into()); + } + if meta.permissions().mode() & 0o077 != 0 { + return Err("Type-ipc directory permissions too open".into()); + } + Ok(()) +} + +pub fn runtime_dir() -> Result { + let base = std::env::var_os("XDG_RUNTIME_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| { + PathBuf::from(format!( + "{}/uu-viewer-type-{}", + std::env::temp_dir().display(), + unsafe { libc::getuid() } + )) + }); + let dir = if base.ends_with("uu-viewer-type") || base.file_name().is_some_and(|n| { + n.to_string_lossy().starts_with("uu-viewer-type") + }) { + base + } else { + base.join("uu-viewer-type") + }; + // Use symlink_metadata so a pre-planted symlink is not followed before we decide. + match std::fs::symlink_metadata(&dir) { + Ok(_) => { + validate_private_dir(&dir)?; + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + std::fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(&dir) + .map_err(|_| "Cannot create private type-ipc directory")?; + validate_private_dir(&dir)?; + } + Err(_) => return Err("Cannot inspect type-ipc directory".into()), + } + Ok(dir) +} + +pub fn device_key(device: &str) -> String { + use sha2::{Digest, Sha256}; + hex::encode(Sha256::digest(device.as_bytes())) +} + +pub fn socket_path(device: &str) -> Result { + Ok(runtime_dir()?.join(format!("{}.sock", device_key(device)))) +} + +pub fn default_snapshot_path(device: &str) -> Result { + let ts = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis()) + .unwrap_or(0); + Ok(runtime_dir()?.join(format!("snap-{}-{ts}.png", &device_key(device)[..12]))) +} + +pub async fn read_frame(r: &mut (impl AsyncRead + Unpin)) -> Result, String> { + let n = r.read_u32().await.map_err(|_| "Type IPC closed")? as usize; + if n > MAX_FRAME { + return Err("Type IPC frame exceeds size limit".into()); + } + let mut b = vec![0; n]; + r.read_exact(&mut b) + .await + .map_err(|_| "Type IPC closed")?; + Ok(b) +} + +pub async fn write_frame(w: &mut (impl AsyncWrite + Unpin), body: &[u8]) -> Result<(), String> { + if body.len() > MAX_FRAME { + return Err("Type IPC frame exceeds size limit".into()); + } + w.write_u32(body.len() as u32) + .await + .map_err(|_| "Type IPC closed")?; + w.write_all(body).await.map_err(|_| "Type IPC closed")?; + Ok(()) +} + +fn check_peer(stream: &UnixStream) -> Result<(), String> { + let cred = stream + .peer_cred() + .map_err(|_| "Type IPC peer credentials unavailable")?; + let uid = cred.uid(); + let me = unsafe { libc::getuid() }; + if uid != me { + return Err("Type IPC peer uid mismatch".into()); + } + Ok(()) +} + +pub struct Server { + pub path: PathBuf, + listener: Option, +} + +impl Drop for Server { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.path); + } +} + +impl Server { + pub async fn bind(device: &str) -> Result { + let path = socket_path(device)?; + if path.exists() { + match UnixStream::connect(&path).await { + Ok(_) => return Err("A desktop viewer is already listening for this device".into()), + Err(_) => { + let _ = std::fs::remove_file(&path); + } + } + } + let listener = UnixListener::bind(&path).map_err(|_| "Cannot bind type IPC socket")?; + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)); + Ok(Self { path, listener: Some(listener) }) + } + + /// Accept connections and forward validated TypeRequests to `tx`. + pub async fn run(mut self, tx: mpsc::Sender) { + let path = self.path.clone(); + let listener = self.listener.take().expect("type IPC listener"); + // Prevent Drop from removing the socket twice while we still hold `path` in a guard. + self.path = PathBuf::new(); + struct Guard(PathBuf); + impl Drop for Guard { + fn drop(&mut self) { + if !self.0.as_os_str().is_empty() { + let _ = std::fs::remove_file(&self.0); + } + } + } + let _guard = Guard(path); + loop { + let accepted = listener.accept().await; + let Ok((stream, _)) = accepted else { break }; + if check_peer(&stream).is_err() { + continue; + } + let tx = tx.clone(); + tokio::spawn(async move { + let _ = serve_client(stream, tx).await; + }); + } + } +} + +pub struct PendingType { + pub request: TypeRequest, + pub reply: tokio::sync::oneshot::Sender, +} + +async fn serve_client(mut stream: UnixStream, tx: mpsc::Sender) -> Result<(), String> { + let body = read_frame(&mut stream).await?; + let request: TypeRequest = + serde_json::from_slice(&body).map_err(|_| "Invalid type IPC request")?; + let mut body = body; + for b in &mut body { + *b = 0; + } + let (reply_tx, reply_rx) = tokio::sync::oneshot::channel(); + // Move request into PendingType; zeroize on drop if send fails. + if tx + .send(PendingType { + request, + reply: reply_tx, + }) + .await + .is_err() + { + return Err("Desktop session is gone".into()); + } + let response = reply_rx.await.map_err(|_| "Desktop session is gone")?; + let out = serde_json::to_vec(&response).map_err(|_| "Type IPC encode failed")?; + write_frame(&mut stream, &out).await +} + +/// Client: deliver a type request to a running viewer. Returns response or connection error. +pub async fn send_to_viewer(device: &str, mut request: TypeRequest) -> Result { + let path = socket_path(device)?; + let mut stream = UnixStream::connect(&path) + .await + .map_err(|_| "No running desktop viewer for this device")?; + check_peer(&stream)?; + let body = serde_json::to_vec(&request).map_err(|_| "Type IPC encode failed")?; + // Clear serde copy in request early — response path still needs omit metadata only. + zeroize_string(&mut request.secret); + write_frame(&mut stream, &body).await?; + // Wipe encoded body + let mut body = body; + for b in &mut body { + *b = 0; + } + let resp_body = read_frame(&mut stream).await?; + let response: TypeResponse = + serde_json::from_slice(&resp_body).map_err(|_| "Invalid type IPC response")?; + Ok(response) +} + +/// Encode an RGB24 frame as a minimal PNG (8-bit RGB, no filtering beyond None). +/// Write RGB24 as PNG. Always uses O_NOFOLLOW + mode 0600. +/// `create_new`: true for default runtime paths (refuse overwrite); false for user `--snapshot`. +pub fn write_png_rgb( + path: &Path, + width: u32, + height: u32, + rgb: &[u8], + create_new: bool, +) -> Result<(), String> { + let expected = width as usize * height as usize * 3; + if rgb.len() != expected || width == 0 || height == 0 { + return Err("Snapshot frame size mismatch".into()); + } + use flate2::{write::ZlibEncoder, Compression}; + use std::io::Write; + let mut raw = Vec::with_capacity((width as usize * 3 + 1) * height as usize); + for row in 0..height as usize { + raw.push(0); // filter None + let start = row * width as usize * 3; + raw.extend_from_slice(&rgb[start..start + width as usize * 3]); + } + let mut enc = ZlibEncoder::new(Vec::new(), Compression::fast()); + enc.write_all(&raw).map_err(|_| "Snapshot zlib failed")?; + for b in &mut raw { + *b = 0; + } + let compressed = enc.finish().map_err(|_| "Snapshot zlib failed")?; + + fn chunk(tag: &[u8; 4], data: &[u8], out: &mut Vec) { + out.extend_from_slice(&(data.len() as u32).to_be_bytes()); + out.extend_from_slice(tag); + out.extend_from_slice(data); + let mut crc = crc32_ieee_update(0xffff_ffff, tag); + crc = crc32_ieee_update(crc, data); + out.extend_from_slice(&(crc ^ 0xffff_ffff).to_be_bytes()); + } + let mut png = Vec::with_capacity(compressed.len() + 128); + png.extend_from_slice(&[137, 80, 78, 71, 13, 10, 26, 10]); + let mut ihdr = Vec::with_capacity(13); + ihdr.extend_from_slice(&width.to_be_bytes()); + ihdr.extend_from_slice(&height.to_be_bytes()); + ihdr.extend_from_slice(&[8, 2, 0, 0, 0]); // 8-bit RGB + chunk(b"IHDR", &ihdr, &mut png); + chunk(b"IDAT", &compressed, &mut png); + chunk(b"IEND", &[], &mut png); + + use std::os::unix::fs::OpenOptionsExt; + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).mode(0o600).custom_flags(libc::O_NOFOLLOW); + if create_new { + opts.create_new(true); + } else { + opts.create(true).truncate(true); + } + let mut file = opts + .open(path) + .map_err(|_| "Cannot write snapshot file")?; + file.write_all(&png).map_err(|_| "Cannot write snapshot file")?; + Ok(()) +} + +fn crc32_ieee(data: &[u8]) -> u32 { + crc32_ieee_update(0xffff_ffff, data) ^ 0xffff_ffff +} +fn crc32_ieee_update(mut crc: u32, data: &[u8]) -> u32 { + for &b in data { + crc ^= u32::from(b); + for _ in 0..8 { + let mask = (!(crc & 1)).wrapping_add(1); // 0 or 0xFFFFFFFF + crc = (crc >> 1) ^ (0xEDB8_8320 & mask); + } + } + crc +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn frame_limit_rejects_oversized_length() { + // Unit-level: MAX_FRAME constant is the contract used by read_frame. + assert!(MAX_FRAME >= 16 * 1024); + assert!(MAX_FRAME < 1024 * 1024); + } + + #[test] + fn device_key_is_stable_hex() { + let a = device_key("device-1"); + let b = device_key("device-1"); + assert_eq!(a, b); + assert_eq!(a.len(), 64); + assert!(a.chars().all(|c| c.is_ascii_hexdigit())); + assert_ne!(device_key("device-1"), device_key("device-2")); + } + + #[test] + fn png_roundtrip_header_and_mode() { + let dir = tempfile_dir(); + let path = dir.join("t.png"); + write_png_rgb(&path, 2, 2, &[255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255], true).unwrap(); + let meta = std::fs::metadata(&path).unwrap(); + use std::os::unix::fs::PermissionsExt; + assert_eq!(meta.permissions().mode() & 0o777, 0o600); + let bytes = std::fs::read(&path).unwrap(); + assert_eq!(&bytes[..8], &[137, 80, 78, 71, 13, 10, 26, 10]); + let _ = std::fs::remove_dir_all(dir); + } + + fn tempfile_dir() -> PathBuf { + use std::os::unix::fs::DirBuilderExt; + let dir = std::env::temp_dir().join(format!("uu-type-ipc-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::DirBuilder::new() + .mode(0o700) + .create(&dir) + .unwrap(); + dir + } + + #[tokio::test] + async fn server_client_roundtrip_and_uid_gate() { + let device = format!("ipc-test-{}", uuidish()); + let server = Server::bind(&device).await.unwrap(); + let path = server.path.clone(); + let (tx, mut rx) = mpsc::channel::(4); + let run = tokio::spawn(async move { server.run(tx).await }); + // Handle one request in background + let worker = tokio::spawn(async move { + if let Some(pending) = rx.recv().await { + assert_eq!(pending.request.secret, "sentinel-SECRET-9f3a"); + assert_eq!(pending.request.delay_ms, 10); + assert_eq!(pending.request.omit_last, 1); + let _ = pending.reply.send(TypeResponse { + ok: true, + events: 12, + chars: 6, + snapshot: Some("/tmp/fake.png".into()), + error: None, + }); + } + }); + let response = send_to_viewer( + &device, + TypeRequest { + delay_ms: 10, + omit_last: 1, + snapshot: None, + secret: "sentinel-SECRET-9f3a".into(), + }, + ) + .await + .unwrap(); + assert!(response.ok); + assert_eq!(response.events, 12); + assert_eq!(response.snapshot.as_deref(), Some("/tmp/fake.png")); + worker.abort(); + run.abort(); + let _ = std::fs::remove_file(path); + } + + #[tokio::test] + async fn connect_without_server_errors_without_secret() { + let device = format!("missing-{}", uuidish()); + let err = send_to_viewer( + &device, + TypeRequest { + delay_ms: 0, + omit_last: 0, + snapshot: None, + secret: "sentinel-SECRET-9f3a".into(), + }, + ) + .await + .unwrap_err(); + assert!(err.contains("No running desktop viewer")); + assert!(!err.contains("sentinel")); + } + + #[tokio::test] + async fn oversized_frame_rejected() { + let device = format!("oversize-{}", uuidish()); + let server = Server::bind(&device).await.unwrap(); + let path = server.path.clone(); + let (tx, mut rx) = mpsc::channel::(1); + let run = tokio::spawn(async move { server.run(tx).await }); + // Drain so accept happens + let _drain = tokio::spawn(async move { while rx.recv().await.is_some() {} }); + let mut stream = UnixStream::connect(&path).await.unwrap(); + let huge = vec![0u8; MAX_FRAME + 1]; + let result = write_frame(&mut stream, &huge).await; + // Client-side write_frame rejects before send + assert!(result.is_err()); + assert!(!format!("{result:?}").contains("sentinel")); + run.abort(); + let _ = std::fs::remove_file(path); + } + + #[test] + fn validate_private_dir_rejects_symlink_and_open_mode() { + use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; + let base = std::env::temp_dir().join(format!( + "uu-type-ipc-val-{}-{}", + std::process::id(), + uuidish() + )); + let _ = std::fs::remove_dir_all(&base); + std::fs::DirBuilder::new().mode(0o700).create(&base).unwrap(); + + let open = base.join("open"); + std::fs::DirBuilder::new().mode(0o755).create(&open).unwrap(); + let err = validate_private_dir(&open).unwrap_err(); + assert!(err.contains("permissions"), "{err}"); + assert!(!err.contains("sentinel")); + + let good = base.join("good"); + std::fs::DirBuilder::new().mode(0o700).create(&good).unwrap(); + validate_private_dir(&good).unwrap(); + + let link = base.join("link"); + std::os::unix::fs::symlink(&good, &link).unwrap(); + let err = validate_private_dir(&link).unwrap_err(); + assert!(err.contains("symlink"), "{err}"); + + let file = base.join("file"); + std::fs::write(&file, b"x").unwrap(); + let err = validate_private_dir(&file).unwrap_err(); + assert!(err.contains("not a directory"), "{err}"); + + let _ = std::fs::remove_dir_all(&base); + } + + #[test] + fn runtime_dir_rejects_preexisting_open_or_symlink() { + use std::os::unix::fs::DirBuilderExt; + // Serialize against other tests that read/write process environment. + let _env = crate::viewer::secure_input::ENV_LOCK.lock().unwrap(); + let base = std::env::temp_dir().join(format!( + "uu-type-ipc-rt-{}-{}", + std::process::id(), + uuidish() + )); + let _ = std::fs::remove_dir_all(&base); + std::fs::DirBuilder::new().mode(0o700).create(&base).unwrap(); + + // Point XDG_RUNTIME_DIR at a private base; plant a bad uu-viewer-type child. + let child = base.join("uu-viewer-type"); + std::fs::DirBuilder::new().mode(0o755).create(&child).unwrap(); + let _guard = EnvGuard::set("XDG_RUNTIME_DIR", base.to_str().unwrap()); + let err = runtime_dir().unwrap_err(); + assert!(err.contains("permissions"), "{err}"); + let _ = std::fs::remove_dir_all(&child); + + let target = base.join("target"); + std::fs::DirBuilder::new().mode(0o700).create(&target).unwrap(); + std::os::unix::fs::symlink(&target, &child).unwrap(); + let err = runtime_dir().unwrap_err(); + assert!(err.contains("symlink"), "{err}"); + let _ = std::fs::remove_file(&child); + + // Fresh create succeeds and validates. + let dir = runtime_dir().unwrap(); + assert!(dir.ends_with("uu-viewer-type")); + validate_private_dir(&dir).unwrap(); + let _ = std::fs::remove_dir_all(&base); + } + + #[test] + fn write_png_refuses_symlink_target() { + let dir = tempfile_dir(); + let real = dir.join("real.png"); + let link = dir.join("link.png"); + std::fs::write(&real, b"old").unwrap(); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let err = write_png_rgb( + &link, + 1, + 1, + &[1, 2, 3], + false, + ) + .unwrap_err(); + assert!(err.contains("Cannot write snapshot"), "{err}"); + // Original untouched + assert_eq!(std::fs::read(&real).unwrap(), b"old"); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn write_png_create_new_refuses_existing() { + let dir = tempfile_dir(); + let path = dir.join("exists.png"); + std::fs::write(&path, b"old").unwrap(); + let err = write_png_rgb(&path, 1, 1, &[1, 2, 3], true).unwrap_err(); + assert!(err.contains("Cannot write snapshot"), "{err}"); + assert_eq!(std::fs::read(&path).unwrap(), b"old"); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn type_request_debug_shows_secret_len_only() { + let req = TypeRequest { + delay_ms: 40, + omit_last: 1, + snapshot: Some("/tmp/out.png".into()), + secret: "sentinel-SECRET-9f3a".into(), + }; + let d = format!("{req:?}"); + assert!(d.contains("secret_len: 20") || d.contains("secret_len: 20,"), "{d}"); + assert!(!d.contains("sentinel")); + assert!(!d.contains("SECRET")); + assert!(!d.contains("9f3a")); + } + + struct EnvGuard { + key: &'static str, + prev: Option, + } + impl EnvGuard { + fn set(key: &'static str, val: &str) -> Self { + let prev = std::env::var_os(key); + std::env::set_var(key, val); + Self { key, prev } + } + } + impl Drop for EnvGuard { + fn drop(&mut self) { + match &self.prev { + Some(v) => std::env::set_var(self.key, v), + None => std::env::remove_var(self.key), + } + } + } + + fn uuidish() -> String { + format!( + "{:x}", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + ) + } +} diff --git a/src/viewer_main.rs b/src/viewer_main.rs index ace0547..f0b11eb 100644 --- a/src/viewer_main.rs +++ b/src/viewer_main.rs @@ -13,7 +13,7 @@ use viewer::clipboard; #[cfg(test)] #[path="initialization.rs"] mod initialization; use viewer::{api::Api,rtc::ReadyPolicy,session::{Options,Session},wire::Shape}; use std::time::Duration; -const HELP:&str="Experimental native viewer.\n uuremote-viewer ui (GTK window: sign-in, devices, sessions) Desktop UI requires viewer-sdl (decodes with the ffmpeg CLI, or FFmpeg 6.x libraries with viewer-ffmpeg).\n uuremote-viewer power DEVICE reboot|shutdown\n uuremote-viewer unbind DEVICE [--shared] (从账号删除设备 / remove a device from the account)\n uuremote-viewer terminal DEVICE [SESSION]\n uuremote-viewer files DEVICE ls PATH | get REMOTE LOCAL | put LOCAL REMOTE\n uuremote-viewer portmap DEVICE LOCAL_PORT HOST PORT\n uuremote-viewer files-ui|portmap-ui|terminal-ui DEVICE NAME (GTK tool windows)\n uuremote-viewer login [--no-gui]\n uuremote-viewer devices METHOD ARRAY_POINTER ID_POINTER NAME_POINTER\n uuremote-viewer assist CONNECT_ID (验证码从 stdin 读取一行)\n uuremote-viewer connect DEVICE true|false SHAPE_JSON echo|manual raw|legacy [--view-only]\nVideo: UU_VIEWER_CODEC=h264 forces H.264; UU_VIEWER_CHROMA=444 requests true color (default 4:2:0).\nAudio: UU_VIEWER_AUDIO=0 disables playback. UU_VIEWER_VIEW_ONLY=1 disables desktop input.\nDevice-list method/JSON pointers and compatibility shape require verified operator configuration.\nQR login reuses the sibling uuremote-server login command. Never run login in a captured log.\nEcho readiness is transport observation only; no sendVideoTrack RPC is emitted."; +const HELP:&str="Experimental native viewer.\n uuremote-viewer ui (GTK window: sign-in, devices, sessions) Desktop UI requires viewer-sdl (decodes with the ffmpeg CLI, or FFmpeg 6.x libraries with viewer-ffmpeg).\n uuremote-viewer power DEVICE reboot|shutdown\n uuremote-viewer type DEVICE [options] (secret from UU_INPUT_ENV or stdin; reuses running viewer)\n options: --delay-ms MS --omit-last N --snapshot PATH --dry-run --new-session\n uuremote-viewer unbind DEVICE [--shared] (从账号删除设备 / remove a device from the account)\n uuremote-viewer terminal DEVICE [SESSION]\n uuremote-viewer files DEVICE ls PATH | get REMOTE LOCAL | put LOCAL REMOTE\n uuremote-viewer portmap DEVICE LOCAL_PORT HOST PORT\n uuremote-viewer files-ui|portmap-ui|terminal-ui DEVICE NAME (GTK tool windows)\n uuremote-viewer login [--no-gui]\n uuremote-viewer devices METHOD ARRAY_POINTER ID_POINTER NAME_POINTER\n uuremote-viewer assist CONNECT_ID (验证码从 stdin 读取一行)\n uuremote-viewer connect DEVICE true|false SHAPE_JSON echo|manual raw|legacy [--view-only]\nVideo: UU_VIEWER_CODEC=h264 forces H.264; UU_VIEWER_CHROMA=444 requests true color (default 4:2:0).\nAudio: UU_VIEWER_AUDIO=0 disables playback. UU_VIEWER_VIEW_ONLY=1 disables desktop input.\nDevice-list method/JSON pointers and compatibility shape require verified operator configuration.\nQR login reuses the sibling uuremote-server login command. Never run login in a captured log.\nEcho readiness is transport observation only; no sendVideoTrack RPC is emitted."; const DEFAULT_SHAPE:&str=r#"{"capture_type":1,"platform":3,"client_version":"4.42.0","width":1920,"height":1080,"fps":60,"chroma":1, "decoders":[{"fps":60,"codec":1,"width":3840,"height":2160,"chroma":1}],"display_modes":[[1920,1080,60]], "displays":[{"id":1,"fps":60,"type":0,"hdr":0}], @@ -60,6 +60,7 @@ async fn run(args:&[String])->Result<(),String> { println!("已从账号删除设备");Ok(()) } Some("power")=>power_command(args).await, + Some("type")=>type_command(args).await, Some("terminal-local") if args.len()==2 || args.len()==3=>{ let session=if args.len()==3{Some(args[2].parse::().ok().filter(|n|*n!=0).ok_or("Invalid terminal session id")?)}else{None}; viewer::tools::terminal_ipc::client(std::path::Path::new(&args[1]),session).await @@ -111,11 +112,93 @@ async fn desktop_command(args:&[String],code:Option)->Result<(),String> let options=Options{timeout:Duration::from_secs(12),legacy_prefix:legacy,ready_policy:policy,clipboard}; let mut session=Session::open(&room,&shape,&creds.device_id,&creds.client_id,options,Default::default()).await?; #[cfg(feature="viewer-sdl")] - let result=if let Some((window,decoder))=desktop.as_mut(){viewer::sdl::run(&mut session,window,decoder.as_mut(),view_only).await}else{session.run().await}; + let result=if let Some((window,decoder))=desktop.as_mut(){viewer::sdl::run(&mut session,window,decoder.as_mut(),view_only,&args[1]).await}else{session.run().await}; #[cfg(not(feature="viewer-sdl"))] let result=session.run().await; session.close().await;result } +async fn type_command(args:&[String])->Result<(),String>{ + // type DEVICE [--delay-ms MS] [--omit-last N] [--snapshot PATH] [--dry-run] [--new-session] + if args.len()<2 || args[1].trim().is_empty() { return Err(HELP.into()) } + let device=&args[1]; + let mut delay_ms:Option<&str>=None; + let mut omit_last:Option<&str>=None; + let mut snapshot:Option=None; + let mut dry_run=false; + let mut new_session=false; + let mut i=2; + while i { + i+=1; delay_ms=Some(args.get(i).map(String::as_str).ok_or_else(||HELP.to_string())?); + } + "--omit-last" => { + i+=1; omit_last=Some(args.get(i).map(String::as_str).ok_or_else(||HELP.to_string())?); + } + "--snapshot" => { + i+=1; snapshot=Some(args.get(i).cloned().ok_or_else(||HELP.to_string())?); + } + "--dry-run" => { dry_run=true; } + "--new-session" => { new_session=true; } + _ => return Err(HELP.into()), + } + i+=1; + } + let delay=viewer::secure_input::parse_delay_ms(delay_ms)?; + let omit=viewer::secure_input::parse_omit_last(omit_last)?; + let mut secret=viewer::secure_input::load_secret(std::io::stdin().lock())?; + if dry_run { + let report=viewer::secure_input::dry_run_report(&secret, omit, false)?; + drop(secret); + println!("{report}"); + return Ok(()); + } + secret.omit_last_chars(omit)?; + // Prefer a running desktop viewer (avoids force-replacing the live session, upstream #30). + match viewer::type_ipc::socket_path(device) { + Ok(path) if path.exists() && !new_session => { + let req=viewer::type_ipc::TypeRequest{ + delay_ms: delay.as_millis() as u64, + omit_last: 0, // already applied locally + snapshot, + secret: secret.as_str().to_owned(), + }; + drop(secret); + let response=viewer::type_ipc::send_to_viewer(device, req).await?; + if !response.ok { + return Err(response.error.unwrap_or_else(||"Secure input failed on running viewer".into())); + } + println!("安全输入已发送({} 个按键事件,{} 字符)。", response.events, response.chars); + if let Some(path)=response.snapshot { + println!("snapshot={path}"); + log::info!("Secure input snapshot: {path}"); + } + return Ok(()); + } + _ => {} + } + if !new_session { + drop(secret); + return Err("No running desktop viewer for this device; open a connect/ui session first, or pass --new-session".into()); + } + let mut shape:Shape=serde_json::from_str(DEFAULT_SHAPE).map_err(|_|"Invalid built-in type shape")?; + shape.capture_type=1; + let creds=credentials()?;let api=Api::new(auth::UUAuthClient::new(creds.clone()),auth::BASE_URL); + let room=api.join(device,false,true).await.map_err(|e|e.to_string())?; + let mac=api.target_is_mac(&room,Some(device)).await.map_err(|e|e.to_string())?; + let actions=viewer::secure_input::expand(secret.as_str(),mac)?; + let event_count=actions.len(); + let char_count=secret.chars_count(); + drop(secret); + log::info!("Secure input prepared (new session): chars={} events={} delay_ms={} mac={}", char_count, event_count, delay.as_millis(), mac); + let options=Options{timeout:Duration::from_secs(12),legacy_prefix:true,ready_policy:ReadyPolicy::EchoOnly,clipboard:clipboard::Bridge::new(false)}; + let mut session=Session::open(&room,&shape,&creds.device_id,&creds.client_id,options,Default::default()).await?; + let result=viewer::secure_input::run_session(&mut session,actions.as_slice(),delay).await; + session.close().await; + if result.is_ok(){println!("安全输入已发送({event_count} 个按键事件);新会话路径无截图。");} + result +} + fn credentials()->Result {auth::Credentials::load(config::read_fresh().map_err(|_|"Cannot read credential configuration")?.as_ref())} fn api()->Result {Ok(Api::new(auth::UUAuthClient::new(credentials()?),auth::BASE_URL))} @@ -128,11 +211,34 @@ mod cli_tests { use super::*; #[tokio::test] async fn invalid_commands_never_fall_through_to_login_or_host_service() { - for args in [vec!["invalid"],vec!["power"],vec!["power","device","logout"],vec!["power","device","reboot","extra"],vec!["login","--invalid"],vec!["connect"],vec!["assist"],vec!["assist","id","forbidden-code-argument"],vec!["terminal"],vec!["terminal","device","extra"],vec!["terminal","device","0"],vec!["terminal","device","4294967296"],vec!["terminal-ui","device"],vec!["files","device","bad","path"],vec!["portmap","device","bad","host","80"],vec!["portmap","device","8000","host","0"],vec!["devices","DELETE","/data","/id","/name"],vec!["unbind"],vec!["unbind",""],vec!["unbind","device","--other"],vec!["unbind","device","--shared","extra"]] { + for args in [vec!["invalid"],vec!["power"],vec!["power","device","logout"],vec!["power","device","reboot","extra"],vec!["type"],vec!["type","device","--delay-ms"],vec!["type","device","--delay-ms","x"],vec!["type","device","extra"],vec!["type","device","--omit-last"],vec!["type","device","--snapshot"],vec!["login","--invalid"],vec!["connect"],vec!["assist"],vec!["assist","id","forbidden-code-argument"],vec!["terminal"],vec!["terminal","device","extra"],vec!["terminal","device","0"],vec!["terminal","device","4294967296"],vec!["terminal-ui","device"],vec!["files","device","bad","path"],vec!["portmap","device","bad","host","80"],vec!["portmap","device","8000","host","0"],vec!["devices","DELETE","/data","/id","/name"],vec!["unbind"],vec!["unbind",""],vec!["unbind","device","--other"],vec!["unbind","device","--shared","extra"]] { assert!(run(&args.into_iter().map(str::to_owned).collect::>()).await.is_err()); } } #[tokio::test] + async fn type_dry_run_and_no_viewer_paths_are_redacted() { + let _g = viewer::secure_input::ENV_LOCK.lock().unwrap(); + std::env::set_var("UU_INPUT_ENV", "UU_TYPE_SENTINEL_ENV"); + std::env::set_var("UU_TYPE_SENTINEL_ENV", "sentinel-SECRET-9f3a"); + let out = { + // dry-run + let args: Vec = ["type","missing-device-id","--dry-run"].into_iter().map(str::to_owned).collect(); + // reload env for dry-run — previous load_secret removed the var + std::env::set_var("UU_INPUT_ENV", "UU_TYPE_SENTINEL_ENV"); + std::env::set_var("UU_TYPE_SENTINEL_ENV", "sentinel-SECRET-9f3a"); + run(&args).await + }; + assert!(out.is_ok(), "{out:?}"); + std::env::set_var("UU_INPUT_ENV", "UU_TYPE_SENTINEL_ENV"); + std::env::set_var("UU_TYPE_SENTINEL_ENV", "sentinel-SECRET-9f3a"); + let err = run(&["type".into(),"missing-device-id".into()]).await.unwrap_err(); + assert!(err.contains("No running desktop viewer") || err.contains("--new-session"), "{err}"); + assert!(!err.contains("sentinel")); + assert!(!err.contains("SECRET")); + std::env::remove_var("UU_INPUT_ENV"); + std::env::remove_var("UU_TYPE_SENTINEL_ENV"); + } + #[tokio::test] async fn login_reuses_companion_subcommand_with_a_local_process_mock() { use std::os::unix::fs::PermissionsExt; let path=std::env::temp_dir().join(format!("uu-viewer-login-mock-{}",viewer::wire::uuid()));