Skip to content

armgit / muxin

Public Imported from GitHub
0

All your machines, one app. For you and your AI agents: agent sessions, desktops, files, logs and GitHub across your Macs, Linux and Windows machines, with an MCP server.

PowerShell strings: double every quote PowerShell reads as one

Adib Hanna84f2ff5ba1c7
diff --git a/agent/src/sys.rs b/agent/src/sys.rs
index 768968a..2eb28aa 100644
--- a/agent/src/sys.rs
+++ b/agent/src/sys.rs
@@ -155,11 +155,11 @@ pub fn spawn_background(args: &[&str], log: PathBuf) -> io::Result<()> {
if direct.is_ok() {
return Ok(());
}
- let quote = |s: &str| s.replace('\'', "''");
+ let quote = crate::win::quote;
let line = std::iter::once(format!("\"{}\"", exe.display())).chain(args.iter().map(|a| a.to_string())).collect::<Vec<_>>().join(" ");
// Hidden (ShowWindow 0), should this be a desktop session.
let script = format!(
- "$startup = New-CimInstance -ClassName Win32_ProcessStartup -ClientOnly -Property @{{ ShowWindow = [uint16]0 }}; $r = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{{ CommandLine = '{}'; CurrentDirectory = '{}'; ProcessStartupInformation = $startup }}; exit $r.ReturnValue",
+ "$startup = New-CimInstance -ClassName Win32_ProcessStartup -ClientOnly -Property @{{ ShowWindow = [uint16]0 }}; $r = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{{ CommandLine = {}; CurrentDirectory = {}; ProcessStartupInformation = $startup }}; exit $r.ReturnValue",
quote(&line),
quote(&home.display().to_string())
);
diff --git a/agent/src/win.rs b/agent/src/win.rs
index faf56d4..4b7105f 100644
--- a/agent/src/win.rs
+++ b/agent/src/win.rs
@@ -49,9 +49,19 @@ fn clixml_error(stderr: &str) -> Option<String> {
Some(text.trim().to_string()).filter(|t| !t.is_empty())
}
-/// A PowerShell string literal.
+/// A PowerShell string literal. PowerShell takes ‘ ’ ‚ ‛ for single quotes
+/// too, so each is doubled like ' is (else one would end the string).
pub fn quote(s: &str) -> String {
- format!("'{}'", s.replace('\'', "''"))
+ let mut out = String::with_capacity(s.len() + 2);
+ out.push('\'');
+ for c in s.chars() {
+ if matches!(c, '\'' | '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}') {
+ out.push(c);
+ }
+ out.push(c);
+ }
+ out.push('\'');
+ out
}
// --- Processes --------------------------------------------------------------
@@ -299,5 +309,7 @@ mod tests {
let err = "#< CLIXML\r\n<Objs Version=\"1.1.0.1\"><S S=\"Error\">Cannot find any service with service name 'nope'._x000D__x000A_</S></Objs>";
assert_eq!(clixml_error(err).as_deref(), Some("Cannot find any service with service name 'nope'."));
assert_eq!(quote("it's"), "'it''s'");
+ // PowerShell's other single quotes are doubled too.
+ assert_eq!(quote("don\u{2019}t \u{2018}x\u{201A}\u{201B}"), "'don\u{2019}\u{2019}t \u{2018}\u{2018}x\u{201A}\u{201A}\u{201B}\u{201B}'");
}
}
diff --git a/src/fleet/command.rs b/src/fleet/command.rs
index 157ae25..068a31a 100644
--- a/src/fleet/command.rs
+++ b/src/fleet/command.rs
@@ -28,7 +28,7 @@ fn sh_script(command: &str) -> String {
/// output formatted as text, its `exit` its exit status).
fn ps_script(command: &str) -> String {
format!(
- "$OR_CMD = '{}'\n\
+ "$OR_CMD = {}\n\
$f = Join-Path ([IO.Path]::GetTempPath()) (\"muxen-run-$PID.ps1\")\n\
Set-Content -LiteralPath $f -Value $OR_CMD -Encoding UTF8\n\
Set-Location $env:USERPROFILE\n\
@@ -36,7 +36,7 @@ fn ps_script(command: &str) -> String {
$c = $LASTEXITCODE\n\
Remove-Item -LiteralPath $f -Force -ErrorAction SilentlyContinue\n\
[Console]::Error.WriteLine(\"${{OR_MARK}}:exit=$c\")\n",
- command.replace('\'', "''")
+ crate::ops::remote::ps_quote(command)
)
}
diff --git a/src/fleet/workspaces/scripts/exec.ps1 b/src/fleet/workspaces/scripts/exec.ps1
index e88ce6a..76b41da 100644
--- a/src/fleet/workspaces/scripts/exec.ps1
+++ b/src/fleet/workspaces/scripts/exec.ps1
@@ -16,7 +16,9 @@ $env:GIT_TERMINAL_PROMPT = '0'
$runs = Join-Path $OR_DIR '.muxen'
New-Item -ItemType Directory -Force -Path (Join-Path $runs 'logs') | Out-Null
$f = Join-Path $runs ('run-' + [guid]::NewGuid().ToString('N').Substring(0, 8) + '.ps1')
-$q = { param($s) "'" + $s.Replace("'", "''") + "'" }
+# A string literal: PowerShell takes U+2018, U+2019, U+201A and U+201B for
+# single quotes too, so all five are doubled (as \u escapes: this file stays ASCII).
+$q = { param($s) "'" + ($s -replace '[\u0027\u2018\u2019\u201A\u201B]', '$0$0') + "'" }
if ($OR_BG) {
# Started through WMI, so it outlives this ssh session (sshd ends what a
diff --git a/src/ops/remote.rs b/src/ops/remote.rs
index cb396b7..806ed13 100644
--- a/src/ops/remote.rs
+++ b/src/ops/remote.rs
@@ -77,8 +77,20 @@ pub(crate) fn sh_quote(s: &str) -> String {
format!("'{}'", s.replace('\'', r"'\''"))
}
+/// A PowerShell single-quoted string. PowerShell takes ‘ ’ ‚ ‛ for single
+/// quotes too, so each of those is doubled like ' is, or text with one (a
+/// typographic "don’t") would end the string and run the rest as commands.
pub(crate) fn ps_quote(s: &str) -> String {
- format!("'{}'", s.replace('\'', "''"))
+ let mut out = String::with_capacity(s.len() + 2);
+ out.push('\'');
+ for c in s.chars() {
+ if matches!(c, '\'' | '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}') {
+ out.push(c);
+ }
+ out.push(c);
+ }
+ out.push('\'');
+ out
}
/// Runs `script` on the machine, forwarding every output line (secrets masked) to
@@ -289,6 +301,37 @@ mod tests {
assert_eq!(ps, "$OR_TOKEN = 'it''s'\n$OR_NAMES = @('a-01', 'b-02')\n$OR_SERVICE = $false\n");
}
+ /// How PowerShell reads a single-quoted string (its tokenizer): any of
+ /// ' ‘ ’ ‚ ‛ ends it, unless another one follows, which stands for that
+ /// second one. Returns the text and whatever comes after the string.
+ fn ps_read(quoted: &str) -> (String, String) {
+ let is_quote = |c: char| matches!(c, '\'' | '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}');
+ let mut chars = quoted.chars().peekable();
+ assert!(chars.next().is_some_and(is_quote));
+ let mut text = String::new();
+ while let Some(c) = chars.next() {
+ if is_quote(c) {
+ match chars.peek() {
+ Some(&n) if is_quote(n) => text.push(chars.next().unwrap()),
+ _ => return (text, chars.collect()),
+ }
+ } else {
+ text.push(c);
+ }
+ }
+ panic!("unterminated string: {quoted}");
+ }
+
+ #[test]
+ fn powershell_strings_hold_any_quote() {
+ for s in ["it's", "don’t", "‘quoted’", "a‚b‛c", "x’; Remove-Item -Recurse ~; ’", "''’’", "", "$(whoami) `n"] {
+ let (text, rest) = ps_read(&ps_quote(s));
+ assert_eq!(text, s);
+ assert_eq!(rest, "", "{s:?} leaked out of its string");
+ }
+ assert_eq!(ps_quote("don’t"), "'don’’t'");
+ }
+
#[test]
fn cleans_lines() {
let secrets = vec!["AABBCCDDEEFF".to_string()];
diff --git a/src/probe/mod.rs b/src/probe/mod.rs
index f18e8c2..0b29c04 100644
--- a/src/probe/mod.rs
+++ b/src/probe/mod.rs
@@ -458,7 +458,7 @@ fn script_for(spec: &MachineSpec, shell: Shell) -> String {
format!("OR_DIRS='{dirs}'\n{PROBE_SH}")
}
Shell::Powershell => {
- let dirs: Vec<String> = spec.runner_dirs.iter().map(|d| format!("'{}'", d.replace('\'', "''"))).collect();
+ let dirs: Vec<String> = spec.runner_dirs.iter().map(|d| crate::ops::remote::ps_quote(d)).collect();
format!("$OR_DIRS = @({})\n{PROBE_PS1}", dirs.join(", "))
}
}