|
| 1 | +//! CLI invocation and owned shell registration rules; native adapters perform all I/O. |
| 2 | +
|
| 3 | +use crate::{RuleError, RuleErrorCode}; |
| 4 | +use serde::Deserialize; |
| 5 | +use serde_json::{json, Value}; |
| 6 | + |
| 7 | +/// Parses bounded launch arguments without probing native paths. |
| 8 | +pub const PLAN_LAUNCH: &str = "application.cli.planLaunch"; |
| 9 | +/// Classifies a native path observation into an isolated editor or a project. |
| 10 | +pub const OPEN_TARGET: &str = "application.cli.openTarget"; |
| 11 | +/// Produces an idempotent edit of only Lithe's owned registration. |
| 12 | +pub const EDIT_REGISTRATION: &str = "application.cli.editRegistration"; |
| 13 | +const BEGIN: &str = "# >>> Lithe CLI >>>"; |
| 14 | +const END: &str = "# <<< Lithe CLI <<<"; |
| 15 | +const MAX_SOURCE: usize = 1024 * 1024; |
| 16 | + |
| 17 | +fn invalid(reason: &str) -> RuleError { |
| 18 | + RuleError::new(RuleErrorCode::InvalidRequest, reason) |
| 19 | +} |
| 20 | + |
| 21 | +#[derive(Deserialize)] |
| 22 | +#[serde(rename_all = "camelCase", deny_unknown_fields)] |
| 23 | +struct LaunchRequest { |
| 24 | + args: Vec<String>, |
| 25 | +} |
| 26 | + |
| 27 | +/// Resolves help, version, a single path and the launcher's internal detach marker. |
| 28 | +pub fn plan_launch_json(payload: Value) -> Result<Value, RuleError> { |
| 29 | + let request: LaunchRequest = |
| 30 | + serde_json::from_value(payload).map_err(|_| invalid("Invalid CLI arguments"))?; |
| 31 | + if request.args.len() > 4 |
| 32 | + || request |
| 33 | + .args |
| 34 | + .iter() |
| 35 | + .any(|s| s.len() > 32768 || s.contains('\0')) |
| 36 | + { |
| 37 | + return Err(invalid("CLI arguments exceed their bounds")); |
| 38 | + } |
| 39 | + let mut args = request.args.as_slice(); |
| 40 | + let detach = args.first().is_some_and(|s| s == "--cli"); |
| 41 | + if detach { |
| 42 | + args = &args[1..]; |
| 43 | + } |
| 44 | + let literal = args.first().is_some_and(|s| s == "--"); |
| 45 | + if literal { |
| 46 | + args = &args[1..]; |
| 47 | + } |
| 48 | + let (action, path) = match args { |
| 49 | + [] => ("welcome", ""), |
| 50 | + [arg] if !literal && (arg == "--help" || arg == "-h") => ("help", ""), |
| 51 | + [arg] if !literal && (arg == "--version" || arg == "-v") => ("version", ""), |
| 52 | + [arg] if !arg.is_empty() && (literal || !arg.starts_with('-')) => ("open", arg.as_str()), |
| 53 | + _ => return Err(invalid("Expected one file or folder path")), |
| 54 | + }; |
| 55 | + Ok(json!({"action": action, "path": path, "detach": detach})) |
| 56 | +} |
| 57 | + |
| 58 | +#[derive(Deserialize)] |
| 59 | +#[serde(rename_all = "camelCase", deny_unknown_fields)] |
| 60 | +struct TargetRequest { |
| 61 | + /// Native observation; never inferred from the filename or extension. |
| 62 | + kind: String, |
| 63 | +} |
| 64 | + |
| 65 | +/// No project services are permitted for a standalone regular file. |
| 66 | +pub fn open_target_json(payload: Value) -> Result<Value, RuleError> { |
| 67 | + let request: TargetRequest = serde_json::from_value(payload) |
| 68 | + .map_err(|_| invalid("Invalid native target observation"))?; |
| 69 | + let (mode, plugins) = match request.kind.as_str() { |
| 70 | + "directory" => ("project", true), |
| 71 | + "file" => ("file", false), |
| 72 | + _ => return Err(invalid("Target must be a regular file or directory")), |
| 73 | + }; |
| 74 | + // Commands outside this list cannot enter project services from an editor-only session. |
| 75 | + let commands = if plugins { |
| 76 | + Vec::new() |
| 77 | + } else { |
| 78 | + [ |
| 79 | + "settings.open", |
| 80 | + "logs.open", |
| 81 | + "theme.system", |
| 82 | + "theme.light", |
| 83 | + "theme.dark", |
| 84 | + "window.fullscreen", |
| 85 | + "language.en", |
| 86 | + "language.zh", |
| 87 | + "editor.vimMode", |
| 88 | + "project.open", |
| 89 | + "document.open", |
| 90 | + "documents.saveAll", |
| 91 | + "tab.close", |
| 92 | + "terminal.new", |
| 93 | + "tool.terminal", |
| 94 | + "editor.find", |
| 95 | + "editor.replace", |
| 96 | + "editor.fold", |
| 97 | + "editor.unfold", |
| 98 | + "editor.foldAll", |
| 99 | + "editor.unfoldAll", |
| 100 | + "editor.addNextOccurrence", |
| 101 | + "editor.unselectOccurrence", |
| 102 | + "editor.selectAllOccurrences", |
| 103 | + "editor.cloneCaretAbove", |
| 104 | + "editor.cloneCaretBelow", |
| 105 | + ] |
| 106 | + .into_iter() |
| 107 | + .collect::<Vec<_>>() |
| 108 | + }; |
| 109 | + Ok(json!({"mode": mode, "plugins": plugins, "commands": commands})) |
| 110 | +} |
| 111 | + |
| 112 | +#[derive(Deserialize)] |
| 113 | +#[serde(rename_all = "camelCase", deny_unknown_fields)] |
| 114 | +struct RegistrationRequest { |
| 115 | + /// zsh, bash, sh, fish or windows; shell discovery belongs to the native adapter. |
| 116 | + shell: String, |
| 117 | + source: String, |
| 118 | + #[serde(default)] |
| 119 | + launcher_source: String, |
| 120 | + directory: String, |
| 121 | + executable: String, |
| 122 | + /// inspect never changes the returned source; install/remove require an explicit click. |
| 123 | + action: String, |
| 124 | +} |
| 125 | + |
| 126 | +fn quote(value: &str) -> String { |
| 127 | + format!("'{}'", value.replace('\'', "'\"'\"'")) |
| 128 | +} |
| 129 | + |
| 130 | +fn fish_quote(value: &str) -> String { |
| 131 | + format!("'{}'", value.replace('\\', "\\\\").replace('\'', "\\'")) |
| 132 | +} |
| 133 | + |
| 134 | +/// Keeps unrelated configuration byte-for-byte, rejecting malformed owned blocks. |
| 135 | +pub fn edit_registration_json(payload: Value) -> Result<Value, RuleError> { |
| 136 | + let request: RegistrationRequest = |
| 137 | + serde_json::from_value(payload).map_err(|_| invalid("Invalid CLI registration request"))?; |
| 138 | + let r = &request; |
| 139 | + if r.source.len() > MAX_SOURCE |
| 140 | + || r.launcher_source.len() > MAX_SOURCE |
| 141 | + || r.directory.is_empty() |
| 142 | + || r.executable.is_empty() |
| 143 | + || [&r.directory, &r.executable] |
| 144 | + .iter() |
| 145 | + .any(|s| s.len() > 32768 || s.contains(['\0', '\r', '\n'])) |
| 146 | + || !matches!(r.action.as_str(), "inspect" | "install" | "remove") |
| 147 | + { |
| 148 | + return Err(invalid("Invalid CLI registration values")); |
| 149 | + } |
| 150 | + let windows = r.shell == "windows"; |
| 151 | + if !windows && !matches!(r.shell.as_str(), "zsh" | "bash" | "sh" | "fish") { |
| 152 | + return Err(invalid("Unsupported login shell")); |
| 153 | + } |
| 154 | + let platform = if windows { |
| 155 | + lithe_platform::Platform::Windows |
| 156 | + } else { |
| 157 | + lithe_platform::Platform::Unix |
| 158 | + }; |
| 159 | + let launcher = lithe_platform::cli::launcher(&r.executable, platform) |
| 160 | + .ok_or_else(|| invalid("Invalid launcher path"))?; |
| 161 | + let owned = lithe_platform::cli::is_managed_launcher(&r.launcher_source, platform); |
| 162 | + if windows { |
| 163 | + if r.directory.contains([';', '"']) { |
| 164 | + return Err(invalid("Invalid Windows PATH entry")); |
| 165 | + } |
| 166 | + let same = |s: &str| lithe_platform::cli::same_path_entry(s, &r.directory, platform); |
| 167 | + let installed = r.source.split(';').any(same); |
| 168 | + let source = match r.action.as_str() { |
| 169 | + "install" if !installed => format!( |
| 170 | + "{}{}{}", |
| 171 | + r.source, |
| 172 | + if r.source.is_empty() || r.source.ends_with(';') { |
| 173 | + "" |
| 174 | + } else { |
| 175 | + ";" |
| 176 | + }, |
| 177 | + r.directory |
| 178 | + ), |
| 179 | + "remove" => r |
| 180 | + .source |
| 181 | + .split(';') |
| 182 | + .filter(|s| !same(s)) |
| 183 | + .collect::<Vec<_>>() |
| 184 | + .join(";"), |
| 185 | + _ => r.source.clone(), |
| 186 | + }; |
| 187 | + return Ok( |
| 188 | + json!({"installed": installed, "source": source, "launcher": launcher, "owned": owned}), |
| 189 | + ); |
| 190 | + } |
| 191 | + let newline = if r.source.contains("\r\n") { |
| 192 | + "\r\n" |
| 193 | + } else { |
| 194 | + "\n" |
| 195 | + }; |
| 196 | + let command = if r.shell == "fish" { |
| 197 | + format!( |
| 198 | + "if not contains -- {} $PATH; set -gx PATH {} $PATH; end", |
| 199 | + fish_quote(&r.directory), |
| 200 | + fish_quote(&r.directory) |
| 201 | + ) |
| 202 | + } else { |
| 203 | + format!("export PATH={}:\"$PATH\"", quote(&r.directory)) |
| 204 | + }; |
| 205 | + let block = format!("{BEGIN}{newline}{command}{newline}{END}{newline}"); |
| 206 | + let starts: Vec<_> = r.source.match_indices(BEGIN).collect(); |
| 207 | + let ends: Vec<_> = r.source.match_indices(END).collect(); |
| 208 | + if starts.len() > 1 || ends.len() > 1 || starts.len() != ends.len() { |
| 209 | + return Err(invalid("Conflicting Lithe CLI registration markers")); |
| 210 | + } |
| 211 | + let range = if let (Some(&(start, _)), Some(&(end, _))) = (starts.first(), ends.first()) { |
| 212 | + if end < start || (start > 0 && !r.source[..start].ends_with('\n')) { |
| 213 | + return Err(invalid("Malformed Lithe CLI registration block")); |
| 214 | + } |
| 215 | + let tail = end + END.len(); |
| 216 | + let suffix = &r.source[tail..]; |
| 217 | + let length = if suffix.starts_with("\r\n") { |
| 218 | + 2 |
| 219 | + } else if suffix.starts_with('\n') { |
| 220 | + 1 |
| 221 | + } else if suffix.is_empty() { |
| 222 | + 0 |
| 223 | + } else { |
| 224 | + return Err(invalid("Malformed Lithe CLI registration block")); |
| 225 | + }; |
| 226 | + Some(start..tail + length) |
| 227 | + } else { |
| 228 | + None |
| 229 | + }; |
| 230 | + let installed = range.as_ref().is_some_and(|range| { |
| 231 | + r.source[range.clone()].trim_end_matches(['\r', '\n']) |
| 232 | + == block.trim_end_matches(['\r', '\n']) |
| 233 | + }); |
| 234 | + let mut source = r.source.clone(); |
| 235 | + match r.action.as_str() { |
| 236 | + "install" => { |
| 237 | + if let Some(range) = range { |
| 238 | + source.replace_range(range, &block); |
| 239 | + } else { |
| 240 | + if !source.is_empty() && !source.ends_with('\n') { |
| 241 | + source.push_str(newline); |
| 242 | + } |
| 243 | + source.push_str(&block); |
| 244 | + } |
| 245 | + } |
| 246 | + "remove" => { |
| 247 | + if let Some(range) = range { |
| 248 | + source.replace_range(range, ""); |
| 249 | + } |
| 250 | + } |
| 251 | + _ => {} |
| 252 | + } |
| 253 | + Ok(json!({"installed": installed, "source": source, "launcher": launcher, "owned": owned})) |
| 254 | +} |
| 255 | + |
| 256 | +#[cfg(test)] |
| 257 | +mod tests { |
| 258 | + use super::*; |
| 259 | + |
| 260 | + #[test] |
| 261 | + fn launch_rejects_ambiguous_inputs_and_preserves_literal_paths() { |
| 262 | + assert!(plan_launch_json(json!({"args": ["a", "b"]})).is_err()); |
| 263 | + assert!(plan_launch_json(json!({"args": ["--unknown"]})).is_err()); |
| 264 | + let plan = plan_launch_json(json!({"args": ["--cli", "--", "-file.txt"]})).unwrap(); |
| 265 | + assert_eq!(plan["path"], "-file.txt"); |
| 266 | + assert_eq!(plan["detach"], true); |
| 267 | + let target = open_target_json(json!({"kind": "file"})).unwrap(); |
| 268 | + assert_eq!(target["plugins"], false); |
| 269 | + let commands = target["commands"].as_array().unwrap(); |
| 270 | + assert!(commands.contains(&json!("editor.find"))); |
| 271 | + assert!(commands.contains(&json!("terminal.new"))); |
| 272 | + assert!(commands.contains(&json!("tool.terminal"))); |
| 273 | + assert!(!commands.contains(&json!("search.files"))); |
| 274 | + } |
| 275 | + |
| 276 | + #[test] |
| 277 | + fn shell_registration_is_idempotent_and_preserves_unrelated_content() { |
| 278 | + for shell in ["zsh", "bash", "sh", "fish", "windows"] { |
| 279 | + let original = if shell == "windows" { |
| 280 | + "C:\\Tools;%USERPROFILE%\\bin" |
| 281 | + } else { |
| 282 | + "# personal settings\r\nexport EDITOR=vi\r\n" |
| 283 | + }; |
| 284 | + let mut request = json!({"shell": shell, "source": original, "directory": "/User Space/bin", "executable": "/Apps/Lithe's.app/lithe", "action": "install"}); |
| 285 | + let first = edit_registration_json(request.clone()).unwrap(); |
| 286 | + request["source"] = first["source"].clone(); |
| 287 | + let second = edit_registration_json(request.clone()).unwrap(); |
| 288 | + assert_eq!(first["source"], second["source"]); |
| 289 | + assert_eq!(second["installed"], true); |
| 290 | + request["action"] = json!("remove"); |
| 291 | + assert_eq!(edit_registration_json(request).unwrap()["source"], original); |
| 292 | + } |
| 293 | + } |
| 294 | + |
| 295 | + #[test] |
| 296 | + fn malformed_markers_never_overwrite_shell_configuration() { |
| 297 | + let request = json!({"shell": "zsh", "source": BEGIN, "directory": "/bin", "executable": "/app", "action": "install"}); |
| 298 | + assert!(edit_registration_json(request).is_err()); |
| 299 | + } |
| 300 | +} |
0 commit comments