Skip to content

armgit / Wake

Public Imported from GitHub
0

All your AI agent sessions in one place — browse, search, resume. Rust + GPUI.

Rust

fix(terminal): validate session ids before resuming

Corey Chiu30abeb89a153
diff --git a/crates/wake-core/src/services/terminal/cmd.rs b/crates/wake-core/src/services/terminal/cmd.rs
new file mode 100644
index 0000000..8439453
--- /dev/null
+++ b/crates/wake-core/src/services/terminal/cmd.rs
@@ -0,0 +1,81 @@
+//! Command Prompt command construction, kept independent of Win32 so its
+//! rejection rules can be tested on every platform.
+
+/// cmd always needs double quotes here; callers must reject inputs containing
+/// quotes, percent expansion or line/control delimiters before using this.
+fn quote(s: &str) -> String {
+ format!("\"{s}\"")
+}
+
+/// Unlike paths, database-backed session ids can contain `"`. It breaks out of
+/// quotes; `%VAR%` expands even inside them. Reject instead of rewriting either
+/// value, including in the clipboard fallback. Newlines and NUL are not valid
+/// parts of the single command passed to cmd.exe either.
+fn hostile(cli: &str, args: &[String], cwd: Option<&str>) -> bool {
+ std::iter::once(cli)
+ .chain(args.iter().map(|s| s.as_str()))
+ .chain(cwd)
+ .any(|s| s.contains(['%', '"', '\r', '\n', '\0']))
+}
+
+/// `call` keeps the first word unquoted, avoiding cmd's legacy `/K` rule that
+/// strips the first and last quotes when the payload starts with a quote.
+/// `/d` makes cd switch drives as well as directories.
+pub(super) fn command_line(
+ cli: &str,
+ args: &[String],
+ cwd: Option<&str>,
+) -> anyhow::Result<String> {
+ if hostile(cli, args, cwd) {
+ anyhow::bail!("path or argument contains a double quote, '%', or a control delimiter that Command Prompt cannot safely quote — pick another terminal");
+ }
+ let mut line = String::new();
+ if let Some(dir) = cwd {
+ line.push_str(&format!("cd /d {} && ", quote(dir)));
+ }
+ line.push_str("call ");
+ line.push_str(&quote(cli));
+ for arg in args {
+ line.push(' ');
+ line.push_str(&quote(arg));
+ }
+ Ok(line)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::command_line;
+
+ #[test]
+ fn rejects_unsafe_inputs_before_producing_a_command() {
+ for value in [
+ r#"x" & echo BREAKOUT_MARKER & rem"#,
+ "a\"b",
+ "%COMSPEC%",
+ "a\rb",
+ "a\nb",
+ "a\0b",
+ ] {
+ assert!(command_line("claude", &["--resume".into(), value.into()], None).is_err());
+ assert!(command_line(value, &["--resume".into(), "abc-123".into()], None).is_err());
+ assert!(command_line("claude", &[], Some(value)).is_err());
+ }
+ }
+
+ #[test]
+ fn preserves_quoted_paths_and_arguments() {
+ assert_eq!(
+ command_line(
+ r"C:\Program Files\agent.cmd",
+ &["--resume".into(), "abc-123".into()],
+ Some(r"D:\工作 & (test)^"),
+ )
+ .unwrap(),
+ r#"cd /d "D:\工作 & (test)^" && call "C:\Program Files\agent.cmd" "--resume" "abc-123""#
+ );
+ assert_eq!(
+ command_line("copilot", &["--resume=abc-123".into()], None).unwrap(),
+ r#"call "copilot" "--resume=abc-123""#
+ );
+ }
+}
diff --git a/crates/wake-core/src/services/terminal/macos.rs b/crates/wake-core/src/services/terminal/macos.rs
index d70e1d3..434fd83 100644
--- a/crates/wake-core/src/services/terminal/macos.rs
+++ b/crates/wake-core/src/services/terminal/macos.rs
@@ -437,17 +437,7 @@ fn launch_kooky(meta: &SessionMeta) -> ResumeOutcome {
if !KOOKY_ROSTER.contains(&meta.agent) {
return launch_kooky_cli(meta);
}
- let id_ok = meta
- .id
- .chars()
- .next()
- .is_some_and(|c| c.is_ascii_alphanumeric())
- && meta.id.len() <= 200
- && meta
- .id
- .chars()
- .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-'));
- if id_ok {
+ if super::is_resume_id(&meta.id) {
let mut url = format!(
"kooky://resume?agent={}&id={}",
meta.agent.as_str(),
diff --git a/crates/wake-core/src/services/terminal/mod.rs b/crates/wake-core/src/services/terminal/mod.rs
index 23e776a..e948f91 100644
--- a/crates/wake-core/src/services/terminal/mod.rs
+++ b/crates/wake-core/src/services/terminal/mod.rs
@@ -15,6 +15,10 @@ use std::path::Path;
use std::process::Command;
use std::sync::Mutex;
+// cmd 命令构建不依赖 Win32,在各平台测试拒绝危险输入的边界。
+#[cfg(any(target_os = "windows", test))]
+mod cmd;
+
#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "macos")]
@@ -152,8 +156,23 @@ pub fn agent_bin(agent: AgentId) -> Option<&'static str> {
}
}
+/// Native ids may come from database columns or transcript contents, not just
+/// filenames. Quoting protects shell syntax, but cannot stop a leading `-`
+/// from becoming a CLI option. Share Kooky's conservative id grammar across
+/// local terminals, deep links and copied SSH commands.
+fn is_resume_id(id: &str) -> bool {
+ id.len() <= 200
+ && id.as_bytes().first().is_some_and(u8::is_ascii_alphanumeric)
+ && id
+ .bytes()
+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'.' | b'-'))
+}
+
fn resume_args(meta: &SessionMeta) -> Option<(Vec<String>, bool)> {
let id = meta.id.as_str();
+ if !is_resume_id(id) {
+ return None;
+ }
match meta.agent {
AgentId::ClaudeCode => Some((vec!["--resume".into(), id.into()], true)),
AgentId::Codex => Some((vec!["resume".into(), id.into()], false)),
@@ -280,8 +299,7 @@ pub enum ResumeTarget {
}
pub fn resume_targets(meta: &SessionMeta) -> Vec<ResumeTarget> {
- // 没有 resume 形制的 agent(OpenClaw)不列任何目标——否则菜单里每一项都是
- // 点了才报 "isn't supported" 的死项;本地/远程两条路同源于 resume_args
+ // 不支持恢复或 id 不安全的会话不列目标;本地/远程同源于 resume_args。
if resume_args(meta).is_none() {
return Vec::new();
}
@@ -304,15 +322,7 @@ pub fn resume_target(meta: &SessionMeta, target: ResumeTarget) -> ResumeOutcome
fn copy_ssh_outcome(meta: &SessionMeta) -> ResumeOutcome {
let Some(command) = ssh_resume_command(meta) else {
- // OpenClaw 之外全有 resume_args;护栏语义同 resume_session_in
- return ResumeOutcome {
- ok: false,
- command: String::new(),
- error: Some(format!(
- "Resume isn't supported for {} yet",
- meta.agent.display_name()
- )),
- };
+ return resume_unavailable(meta);
};
if platform::copy_to_clipboard(&command) {
ResumeOutcome {
@@ -331,7 +341,26 @@ fn copy_ssh_outcome(meta: &SessionMeta) -> ResumeOutcome {
}
}
+fn resume_unavailable(meta: &SessionMeta) -> ResumeOutcome {
+ ResumeOutcome {
+ ok: false,
+ command: String::new(),
+ error: Some(if is_resume_id(&meta.id) {
+ format!(
+ "Resume isn't supported for {} yet",
+ meta.agent.display_name()
+ )
+ } else {
+ "Cannot resume: invalid session id (expected 1–200 ASCII letters, digits, '_', '.' or '-', starting with a letter or digit)".into()
+ }),
+ }
+}
+
pub fn resume_session_in(meta: &SessionMeta, term: TerminalApp) -> ResumeOutcome {
+ // Reject before any deep-link dispatch, CLI lookup or clipboard fallback.
+ if !is_resume_id(&meta.id) {
+ return resume_unavailable(meta);
+ }
// 深链类目标(macOS 的 Kooky / Claude Desktop / Codex Desktop)由平台
// 整锅接管,不走 shell 命令构建;新增非 shell 目标在平台的
// deep_link_resume 里声明,这里无需加旁路
@@ -339,14 +368,7 @@ pub fn resume_session_in(meta: &SessionMeta, term: TerminalApp) -> ResumeOutcome
return outcome;
}
let Some((args, requires_cwd)) = resume_args(meta) else {
- return ResumeOutcome {
- ok: false,
- command: String::new(),
- error: Some(format!(
- "Resume isn't supported for {} yet",
- meta.agent.display_name()
- )),
- };
+ return resume_unavailable(meta);
};
let bin = session_bin(meta);
let Some(cli) = bin.and_then(resolve_cli) else {
@@ -360,7 +382,17 @@ pub fn resume_session_in(meta: &SessionMeta, term: TerminalApp) -> ResumeOutcome
let cwd = cwd_ok.then(|| meta.project_path.as_str());
// 按用户选的宿主取方言:command 既是成功 toast 的展示面,也是失败时
// 塞进剪贴板的那条,必须与真正跑的一致(Windows 的 cmd 宿主方言不同)
- let command = compose_command(term, &cli, &args, cwd);
+ let command = match compose_command(term, &cli, &args, cwd) {
+ Ok(command) => command,
+ Err(e) => {
+ // An unsafe command must never become the manual/clipboard fallback.
+ return ResumeOutcome {
+ ok: false,
+ command: String::new(),
+ error: Some(format!("Cannot resume: {e}")),
+ };
+ }
+ };
if requires_cwd && !cwd_ok {
let hint = clipboard_fallback(&command);
return ResumeOutcome {
@@ -374,9 +406,7 @@ pub fn resume_session_in(meta: &SessionMeta, term: TerminalApp) -> ResumeOutcome
}
// 起终端:POSIX 直接投喂拼好的 command;Windows 的 launch_shell 另收
- // 结构化件按宿主重拼方言(cmd 宿主 cmd 方言、其余复用 command 的
- // PowerShell 形态)——一条字符串塞不进两种引号规则,平台差异只摊在
- // 这一处调用点上。
+ // 结构化件供 wt 拆分工作目录与调用段;其余宿主复用各自方言的 command。
#[cfg(not(target_os = "windows"))]
let result = platform::launch_shell(term, &command);
#[cfg(target_os = "windows")]
@@ -577,6 +607,112 @@ mod tests {
}
}
+ #[test]
+ fn resume_id_grammar_and_length_boundaries() {
+ for id in [
+ "a",
+ "0",
+ "ses_A1.b-2",
+ "01937a56-3a2c-43af-af68-a8d4e00d60ed",
+ ] {
+ assert!(super::is_resume_id(id), "{id:?}");
+ }
+ assert!(super::is_resume_id(&"a".repeat(200)));
+ assert!(!super::is_resume_id(&"a".repeat(201)));
+ for id in [
+ "", "-", "_abc", ".abc", "a b", "a/b", "a\\b", "a:b", "é", "a\0b",
+ ] {
+ assert!(!super::is_resume_id(id), "{id:?}");
+ }
+ }
+
+ #[test]
+ fn unsafe_ids_never_reach_resume_targets_or_commands() {
+ use super::{ResumeTarget, TerminalApp};
+ #[cfg(target_os = "macos")]
+ let terminals = [
+ TerminalApp::Terminal,
+ TerminalApp::Kooky,
+ TerminalApp::ClaudeDesktop,
+ TerminalApp::CodexDesktop,
+ ];
+ #[cfg(target_os = "linux")]
+ let terminals = [TerminalApp::GnomeTerminal];
+ #[cfg(target_os = "windows")]
+ let terminals = [TerminalApp::Cmd, TerminalApp::WindowsPowershell];
+
+ for agent in AgentId::ALL {
+ for id in [
+ "--dangerously-skip-permissions",
+ "--mcp-config=evil.json",
+ "-x",
+ r#"x" & echo BREAKOUT_MARKER & rem"#,
+ "%COMSPEC%",
+ "a\nb",
+ "a\rb",
+ "",
+ ] {
+ let mut meta = remote_meta(agent, id, "");
+ assert!(super::resume_args(&meta).is_none(), "{agent:?}: {id:?}");
+ assert!(super::resume_targets(&meta).is_empty());
+ assert!(super::ssh_resume_command(&meta).is_none());
+ let copied = super::resume_target(&meta, ResumeTarget::CopySshCommand);
+ assert!(!copied.ok);
+ assert!(copied.command.is_empty());
+ assert!(copied.error.unwrap().contains("invalid session id"));
+
+ meta.host.clear();
+ assert!(super::resume_targets(&meta).is_empty());
+ for term in terminals {
+ let outcome = super::resume_session_in(&meta, term);
+ assert!(!outcome.ok);
+ assert!(outcome.command.is_empty());
+ assert!(outcome.error.unwrap().contains("invalid session id"));
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn valid_resume_ids_preserve_agent_arguments() {
+ let id = "a0_B.c-123";
+ for (agent, expected, requires_cwd) in [
+ (AgentId::ClaudeCode, vec!["--resume", id], true),
+ (AgentId::Codex, vec!["resume", id], false),
+ (AgentId::Qoder, vec!["--resume", id], true),
+ (AgentId::Copilot, vec!["--resume=a0_B.c-123"], false),
+ (AgentId::Cursor, vec!["--resume", id], false),
+ (AgentId::Opencode, vec!["--session", id], false),
+ (AgentId::Pi, vec!["--session", id], false),
+ (AgentId::Omp, vec!["--resume", id], false),
+ (AgentId::Grok, vec!["--resume", id], false),
+ (AgentId::Kimi, vec!["--session", id], false),
+ (
+ AgentId::Antigravity,
+ vec!["--conversation=a0_B.c-123"],
+ false,
+ ),
+ (AgentId::Dsh, vec!["@deepseek-ai/dsh", "web"], true),
+ (
+ AgentId::Hermes,
+ vec!["--profile", "default", "--resume", id],
+ false,
+ ),
+ (AgentId::Codebuddy, vec!["--resume", id], true),
+ (AgentId::Devin, vec!["--resume", id], true),
+ ] {
+ let meta = remote_meta(agent, id, "");
+ let (args, cwd) = super::resume_args(&meta).unwrap();
+ assert_eq!(args, expected, "{agent:?}");
+ assert_eq!(cwd, requires_cwd, "{agent:?}");
+ assert_eq!(
+ super::resume_targets(&meta),
+ vec![super::ResumeTarget::CopySshCommand]
+ );
+ assert!(super::ssh_resume_command(&meta).is_some());
+ }
+ }
+
#[test]
fn ssh_resume_command_quotes_nested_layers() {
let meta = remote_meta(AgentId::Codex, "abc-123", "/home/dev/my project");
diff --git a/crates/wake-core/src/services/terminal/posix.rs b/crates/wake-core/src/services/terminal/posix.rs
index d931751..8e20346 100644
--- a/crates/wake-core/src/services/terminal/posix.rs
+++ b/crates/wake-core/src/services/terminal/posix.rs
@@ -74,8 +74,8 @@ pub(super) fn compose_command(
cli: &str,
args: &[String],
cwd: Option<&str>,
-) -> String {
- super::sh_command_line(cli, args, cwd)
+) -> anyhow::Result<String> {
+ Ok(super::sh_command_line(cli, args, cwd))
}
/// 保守 percent-encode(RFC 3986 unreserved 之外全编;keep_slash 供
diff --git a/crates/wake-core/src/services/terminal/windows.rs b/crates/wake-core/src/services/terminal/windows.rs
index 58315ad..5a655f0 100644
--- a/crates/wake-core/src/services/terminal/windows.rs
+++ b/crates/wake-core/src/services/terminal/windows.rs
@@ -139,47 +139,6 @@ fn ps_quote(s: &str) -> String {
format!("'{}'", s.replace('\'', "''"))
}
-/// cmd 方言 quote:一律双引号包裹(Windows 文件名不允许 `"`,无内层转义面)。
-/// 不留裸词快路径——cmd 的引号保全规则按"整行引号个数 + 首字符是否引号"
-/// 分支,让引号数随内容浮动等于让 mangling 随机出现;定长形制配合 cmd_line
-/// 的 `call` 前缀,行首恒为裸词,规则可预测。
-///
-/// `%` 无法在此中和:命令行(非批处理)语境下 `%%` 不折叠、引号内 `^` 是
-/// 字面量,故含 `%` 的会话交由 launch_shell 拒绝走 cmd 宿主,不静默改写
-fn cmd_quote(s: &str) -> String {
- format!("\"{s}\"")
-}
-
-/// cmd 方言整行。`call` 前缀让行首恒为裸词:cmd 对 `/K` 载荷有一条遗留
-/// 规则——首字符是引号且全行引号数不为二时,砍掉首尾各一个引号——路径
-/// 带空格(`C:\Program Files\…`)时整条命令会被腰斩成 `C:\Program`,而
-/// spawn 成功、Wake 照报 ok(2026-08-25 review)。`call` 对 exe 与
-/// bat/cmd 同样是同步调用,语义不变。
-/// `/d`:跨盘符 cd 也生效(会话在 D: 而 cmd 起在 C: 的情形)。
-fn cmd_line(cli: &str, args: &[String], cwd: Option<&str>) -> String {
- let mut line = String::new();
- if let Some(dir) = cwd {
- line.push_str(&format!("cd /d {} && ", cmd_quote(dir)));
- }
- line.push_str("call ");
- line.push_str(&cmd_quote(cli));
- for a in args {
- line.push(' ');
- line.push_str(&cmd_quote(a));
- }
- line
-}
-
-/// cmd 宿主无法安全承载的内容:`%VAR%` 在双引号内照样展开,而命令行语境
-/// 下没有任何转义能关掉它——含 `%` 就会静默跑成另一条命令。会话 id 取自
-/// 文件名(parse_utils),用户目录更是任意,概率并非零。
-fn cmd_hostile(cli: &str, args: &[String], cwd: Option<&str>) -> bool {
- std::iter::once(cli)
- .chain(args.iter().map(|s| s.as_str()))
- .chain(cwd)
- .any(|s| s.contains('%'))
-}
-
/// PowerShell 方言:`Set-Location -LiteralPath 'dir' -ErrorAction Stop;
/// & 'cli' 'args…'`。-LiteralPath 防路径里的 `[ ]` 被当通配符;
/// **-ErrorAction Stop 不可省**:Windows PowerShell 5.1 不认 `&&`,而
@@ -209,10 +168,10 @@ pub(super) fn compose_command(
cli: &str,
args: &[String],
cwd: Option<&str>,
-) -> String {
+) -> anyhow::Result<String> {
match term {
- TerminalApp::Cmd => cmd_line(cli, args, cwd),
- _ => ps_line(cli, args, cwd),
+ TerminalApp::Cmd => super::cmd::command_line(cli, args, cwd),
+ _ => Ok(ps_line(cli, args, cwd)),
}
}
@@ -293,8 +252,8 @@ const PS_SESSION: [&str; 3] = ["-NoLogo", "-NoExit", "-Command"];
/// 按宿主方言起终端。keep-open 与 POSIX 的 `exec $SHELL` 同位:cmd 用
/// `/K`,PowerShell 用 `-NoExit`,命令跑完留在交互提示符。command 即
-/// mod.rs 经 compose_command 拼好的 PowerShell 形态,PowerShell 系宿主
-/// 直接复用;cmd 宿主方言不同,只能从结构化件重拼。
+/// mod.rs 经 compose_command 校验、按宿主拼好的命令。wt 另用结构化件
+/// 拆分工作目录和调用段,避免其分号语义。
pub(super) fn launch_shell(
term: TerminalApp,
cli: &str,
@@ -307,14 +266,9 @@ pub(super) fn launch_shell(
let mut cmd = Command::new(&exe);
match term {
TerminalApp::Cmd => {
- if cmd_hostile(cli, args, cwd) {
- // 拒绝而非静默改写:调用方会把 command(此刻已是 cmd 方言)
- // 送进剪贴板兜底,用户仍拿得到可手动执行的那条
- anyhow::bail!("path or session id contains '%', which Command Prompt would expand — pick another terminal");
- }
// raw_arg 绕过 std 的 argv 引号规则——cmd 不做 argv 解析,std 把
// 整串再包一层引号反而会毁掉内层结构。command 即 compose_command
- // 给的 cmd 方言原文(见 cmd_line 的 `call` 前缀说明)
+ // 给的已校验 cmd 方言原文(见 cmd::command_line 的 `call` 前缀)
cmd.raw_arg(format!("/K {command}"));
}
TerminalApp::Pwsh | TerminalApp::WindowsPowershell => {
@@ -512,3 +466,31 @@ pub(super) fn reveal_path(path: &str) {
cmd.raw_arg(format!("/select,\"{}\"", win_path(path)));
let _ = spawn_and_reap(cmd);
}
+
+#[cfg(test)]
+mod tests {
+ use super::{compose_command, TerminalApp};
+
+ #[test]
+ fn cmd_rejects_unsafe_input_before_clipboard_fallback() {
+ for value in [r#"x" & echo BREAKOUT_MARKER & rem"#, "%COMSPEC%"] {
+ assert!(compose_command(TerminalApp::Cmd, "claude", &[value.into()], None).is_err());
+ assert!(compose_command(TerminalApp::Cmd, value, &[], None).is_err());
+ assert!(compose_command(TerminalApp::Cmd, "claude", &[], Some(value)).is_err());
+ }
+ }
+
+ #[test]
+ fn powershell_still_quotes_paths_that_cmd_cannot_carry() {
+ assert_eq!(
+ compose_command(
+ TerminalApp::WindowsPowershell,
+ r"C:\Tools\agent.cmd",
+ &["--resume".into(), "abc-123".into()],
+ Some(r"D:\O'Brien\100%"),
+ )
+ .unwrap(),
+ r"Set-Location -LiteralPath 'D:\O''Brien\100%' -ErrorAction Stop; & 'C:\Tools\agent.cmd' '--resume' 'abc-123'"
+ );
+ }
+}