From a1980156cf58662abe247bbfe429abca3c4ea913 Mon Sep 17 00:00:00 2001 From: reamd7 Date: Sun, 19 Apr 2026 23:53:52 +0800 Subject: [PATCH 01/15] chore: rename app title to 'Bitwarden Agent' and show main window on launch --- src-tauri/tauri.conf.json | 4 ++-- src/pages/DashboardPage.tsx | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 1be2c3c..d4bf6e5 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -13,8 +13,8 @@ "windows": [ { "label": "main", - "title": "bw-agent", - "visible": false, + "title": "Bitwarden Agent", + "visible": true, "width": 480, "height": 640, "resizable": true, diff --git a/src/pages/DashboardPage.tsx b/src/pages/DashboardPage.tsx index 9eca7c7..7e0ee51 100644 --- a/src/pages/DashboardPage.tsx +++ b/src/pages/DashboardPage.tsx @@ -155,7 +155,7 @@ export default function DashboardPage() {
-

Bitwarden SSH Agent

+

Bitwarden Agent

{store.email} From 29de90c2572efb8ef56a846c155d6d8baa48239a Mon Sep 17 00:00:00 2001 From: reamd7 Date: Mon, 20 Apr 2026 00:38:25 +0800 Subject: [PATCH 02/15] feat: add clap CLI with git-sign subcommand stub --- crates/bw-agent/Cargo.toml | 1 + crates/bw-agent/src/git_sign.rs | 14 +++++++ crates/bw-agent/src/lib.rs | 1 + crates/bw-agent/src/main.rs | 73 ++++++++++++++++++++++++++++++--- 4 files changed, 84 insertions(+), 5 deletions(-) create mode 100644 crates/bw-agent/src/git_sign.rs diff --git a/crates/bw-agent/Cargo.toml b/crates/bw-agent/Cargo.toml index 8565a39..c2b7791 100644 --- a/crates/bw-agent/Cargo.toml +++ b/crates/bw-agent/Cargo.toml @@ -29,6 +29,7 @@ serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" uuid = { version = "1.23", features = ["v4"] } rusqlite = { version = "0.35", features = ["bundled"] } +clap = { version = "4", features = ["derive"] } [lints] workspace = true diff --git a/crates/bw-agent/src/git_sign.rs b/crates/bw-agent/src/git_sign.rs new file mode 100644 index 0000000..a4466ac --- /dev/null +++ b/crates/bw-agent/src/git_sign.rs @@ -0,0 +1,14 @@ +//! Git SSH signing program — drop-in replacement for ssh-keygen -Y. + +/// Entry point for the git-sign subcommand. +pub fn run( + action: &str, + _namespace: Option<&str>, + _key_file: Option<&str>, + _principal: Option<&str>, + _signature_file: Option<&str>, + _data_file: Option<&str>, +) -> anyhow::Result<()> { + eprintln!("error: unsupported action: {action}"); + std::process::exit(1); +} diff --git a/crates/bw-agent/src/lib.rs b/crates/bw-agent/src/lib.rs index e87ad23..d3c89af 100644 --- a/crates/bw-agent/src/lib.rs +++ b/crates/bw-agent/src/lib.rs @@ -3,6 +3,7 @@ pub mod approval; pub mod auth; pub mod config; pub mod git_context; +pub mod git_sign; #[cfg(windows)] pub mod pipe; pub mod process; diff --git a/crates/bw-agent/src/main.rs b/crates/bw-agent/src/main.rs index 43f9ea3..c86220b 100644 --- a/crates/bw-agent/src/main.rs +++ b/crates/bw-agent/src/main.rs @@ -1,9 +1,72 @@ +use clap::{Parser, Subcommand}; + +#[derive(Parser)] +#[command(name = "bw-agent", about = "Bitwarden-backed SSH agent")] +struct Cli { + #[command(subcommand)] + command: Option, +} + +#[derive(Subcommand)] +enum Commands { + /// Act as Git SSH signing program (gpg.ssh.program) + GitSign { + /// Action to perform (sign, verify, find-principals, check-novalidate) + #[arg(short = 'Y', long)] + action: String, + /// Namespace (e.g. "git") + #[arg(short = 'n', long)] + namespace: Option, + /// Key file or allowed_signers file + #[arg(short = 'f', long)] + key_file: Option, + /// Principal identity + #[arg(short = 'I', long)] + principal: Option, + /// Signature file + #[arg(short = 's', long)] + signature_file: Option, + /// Use SSH agent for signing + #[arg(short = 'U')] + use_agent: bool, + /// Options (e.g. -Overify-time=...) + #[arg(short = 'O', number_of_values = 1)] + options: Vec, + /// Data file (positional, for sign) + data_file: Option, + }, +} + #[tokio::main] async fn main() -> anyhow::Result<()> { env_logger::init(); - let mut config = bw_agent::config::Config::load(); - config.apply_env_overrides(); - config.validate()?; - let ui = bw_agent::StubUiCallback; - bw_agent::start_agent(config, ui).await + let cli = Cli::parse(); + + match cli.command { + None => { + // Default: start SSH agent daemon + let mut config = bw_agent::config::Config::load(); + config.apply_env_overrides(); + config.validate()?; + let ui = bw_agent::StubUiCallback; + bw_agent::start_agent(config, ui).await + } + Some(Commands::GitSign { + action, + namespace, + key_file, + principal, + signature_file, + use_agent: _, + options: _, + data_file, + }) => bw_agent::git_sign::run( + &action, + namespace.as_deref(), + key_file.as_deref(), + principal.as_deref(), + signature_file.as_deref(), + data_file.as_deref(), + ), + } } From 41fbef883b7fd8ad3ff0cbdc7f0515c2d41c4510 Mon Sep 17 00:00:00 2001 From: reamd7 Date: Mon, 20 Apr 2026 00:55:15 +0800 Subject: [PATCH 03/15] feat: implement git-sign with sign/verify/find-principals/check-novalidate --- crates/bw-agent/src/git_sign.rs | 466 +++++++++++++++++++++++++++++++- 1 file changed, 458 insertions(+), 8 deletions(-) diff --git a/crates/bw-agent/src/git_sign.rs b/crates/bw-agent/src/git_sign.rs index a4466ac..652bcb0 100644 --- a/crates/bw-agent/src/git_sign.rs +++ b/crates/bw-agent/src/git_sign.rs @@ -1,14 +1,464 @@ //! Git SSH signing program — drop-in replacement for ssh-keygen -Y. +use anyhow::{Context, anyhow, bail}; +use ssh_agent_lib::proto::{Identity, SignRequest}; +use ssh_key::{HashAlg, PublicKey, SshSig}; +use std::{ + collections::BTreeSet, + fs, + path::{Path, PathBuf}, + process, +}; + +const DEFAULT_NAMESPACE: &str = "git"; +const RSA_SHA2_512_FLAG: u32 = 0x04; + +#[cfg(windows)] +const DEFAULT_PIPE_NAME: &str = r"\\.\pipe\openssh-ssh-agent"; + +#[derive(Clone, Debug, Eq, PartialEq)] +struct AllowedSigner { + principals: Vec, + public_key: PublicKey, +} + /// Entry point for the git-sign subcommand. pub fn run( action: &str, - _namespace: Option<&str>, - _key_file: Option<&str>, - _principal: Option<&str>, - _signature_file: Option<&str>, - _data_file: Option<&str>, -) -> anyhow::Result<()> { - eprintln!("error: unsupported action: {action}"); - std::process::exit(1); + namespace: Option<&str>, + key_file: Option<&str>, + principal: Option<&str>, + signature_file: Option<&str>, + data_file: Option<&str>, +) -> anyhow::Result<()> { + let namespace = namespace.unwrap_or(DEFAULT_NAMESPACE); + + let result = match action { + "sign" => sign_action(namespace, key_file, data_file), + "verify" => verify_action(namespace, key_file, principal, signature_file, data_file), + "find-principals" => find_principals_action(namespace, key_file, signature_file, data_file), + "check-novalidate" => check_novalidate_action(namespace, signature_file, data_file), + _ => Err(anyhow!("unsupported action: {action}")), + }; + + if let Err(error) = result { + eprintln!("error: {error}"); + process::exit(255); + } + + Ok(()) +} + +fn sign_action( + namespace: &str, + key_file: Option<&str>, + data_file: Option<&str>, +) -> anyhow::Result<()> { + let key_path = required_path(key_file, "-f/--key-file")?; + let data_path = required_path(data_file, "data file")?; + let public_key = read_signing_public_key(&key_path)?; + let data = fs::read(&data_path) + .with_context(|| format!("failed to read data file {}", data_path.display()))?; + let signed_data = SshSig::signed_data(namespace, HashAlg::Sha512, &data)?; + + let mut agent = connect_agent()?; + let agent_key = find_agent_identity(&mut agent, &public_key)?; + let signature = agent.sign(SignRequest { + pubkey: agent_key.key_data().clone(), + data: signed_data, + flags: signature_flags(&public_key), + })?; + + let sshsig = SshSig::new( + public_key.key_data().clone(), + namespace, + HashAlg::Sha512, + signature, + )?; + let pem = sshsig.to_pem(ssh_key::LineEnding::LF)?; + + let output_path = signature_output_path(&data_path); + eprintln!("Signing file {}", data_path.display()); + fs::write(&output_path, pem) + .with_context(|| format!("failed to write signature file {}", output_path.display()))?; + eprintln!("Write signature to {}", output_path.display()); + + Ok(()) +} + +fn verify_action( + namespace: &str, + key_file: Option<&str>, + principal: Option<&str>, + signature_file: Option<&str>, + data_file: Option<&str>, +) -> anyhow::Result<()> { + let allowed_signers_path = required_path(key_file, "-f/--key-file")?; + let principal = + principal.ok_or_else(|| anyhow!("missing required principal (-I/--principal)"))?; + let sshsig = read_signature(required_path(signature_file, "-s/--signature-file")?)?; + let data_path = required_path(data_file, "data file")?; + let data = fs::read(&data_path) + .with_context(|| format!("failed to read data file {}", data_path.display()))?; + let allowed_signers = parse_allowed_signers_file(&allowed_signers_path)?; + + let signer = allowed_signers + .iter() + .find(|entry| { + entry.public_key.key_data() == sshsig.public_key() + && entry + .principals + .iter() + .any(|candidate| candidate == principal) + }) + .ok_or_else(|| anyhow!("principal {principal} is not allowed for this signature"))?; + + if let Err(error) = signer.public_key.verify(namespace, &data, &sshsig) { + println!("Could not verify signature."); + eprintln!("error: Signature verification failed: {error}"); + process::exit(255); + } + + println!( + "Good \"{}\" signature for {} with {} key {}", + namespace, + principal, + key_type_string(&signer.public_key), + signer.public_key.fingerprint(Default::default()) + ); + + Ok(()) +} + +fn find_principals_action( + namespace: &str, + key_file: Option<&str>, + signature_file: Option<&str>, + data_file: Option<&str>, +) -> anyhow::Result<()> { + let allowed_signers_path = required_path(key_file, "-f/--key-file")?; + let sshsig = read_signature(required_path(signature_file, "-s/--signature-file")?)?; + let data_path = required_path(data_file, "data file")?; + let data = fs::read(&data_path) + .with_context(|| format!("failed to read data file {}", data_path.display()))?; + let allowed_signers = parse_allowed_signers_file(&allowed_signers_path)?; + + let matched_principals = matching_principals(namespace, &data, &sshsig, &allowed_signers); + if matched_principals.is_empty() { + eprintln!("No principal matched."); + process::exit(255); + } + + for matched in matched_principals { + println!("{matched}"); + } + + Ok(()) +} + +fn check_novalidate_action( + namespace: &str, + signature_file: Option<&str>, + data_file: Option<&str>, +) -> anyhow::Result<()> { + let sshsig = read_signature(required_path(signature_file, "-s/--signature-file")?)?; + let data_path = required_path(data_file, "data file")?; + let data = fs::read(&data_path) + .with_context(|| format!("failed to read data file {}", data_path.display()))?; + let public_key = PublicKey::from(sshsig.public_key().clone()); + + if let Err(error) = public_key.verify(namespace, &data, &sshsig) { + println!("Could not verify signature."); + eprintln!("error: Signature verification failed: {error}"); + process::exit(255); + } + + println!( + "Good \"{}\" signature with {} key {}", + namespace, + key_type_string(&public_key), + public_key.fingerprint(Default::default()) + ); + + Ok(()) +} + +fn matching_principals( + namespace: &str, + data: &[u8], + sshsig: &SshSig, + allowed_signers: &[AllowedSigner], +) -> Vec { + let mut principals = BTreeSet::new(); + + for entry in allowed_signers { + if entry.public_key.key_data() != sshsig.public_key() { + continue; + } + + if entry.public_key.verify(namespace, data, sshsig).is_ok() { + for principal in &entry.principals { + principals.insert(principal.clone()); + } + } + } + + principals.into_iter().collect() +} + +fn required_path(value: Option<&str>, label: &str) -> anyhow::Result { + value + .map(PathBuf::from) + .ok_or_else(|| anyhow!("missing required {label}")) +} + +fn read_signing_public_key(path: &Path) -> anyhow::Result { + let contents = fs::read_to_string(path) + .with_context(|| format!("failed to read key file {}", path.display()))?; + + if let Ok(public_key) = PublicKey::from_openssh(&contents) { + return Ok(public_key); + } + + let private_key = ssh_key::PrivateKey::from_openssh(&contents).with_context(|| { + format!( + "failed to parse key file {} as SSH public or private key", + path.display() + ) + })?; + + Ok(private_key.public_key().clone()) +} + +fn read_signature(path: PathBuf) -> anyhow::Result { + let pem = fs::read(&path) + .with_context(|| format!("failed to read signature file {}", path.display()))?; + SshSig::from_pem(pem) + .with_context(|| format!("failed to parse signature file {}", path.display())) +} + +fn signature_output_path(data_path: &Path) -> PathBuf { + let mut display = data_path.as_os_str().to_os_string(); + display.push(".sig"); + PathBuf::from(display) +} + +fn signature_flags(public_key: &PublicKey) -> u32 { + if matches!(public_key.algorithm(), ssh_key::Algorithm::Rsa { .. }) { + RSA_SHA2_512_FLAG + } else { + 0 + } +} + +fn key_type_string(public_key: &PublicKey) -> &'static str { + match public_key.algorithm() { + ssh_key::Algorithm::Ed25519 => "ED25519", + ssh_key::Algorithm::Rsa { .. } => "RSA", + _ => "UNKNOWN", + } +} + +fn parse_allowed_signers_file(path: &Path) -> anyhow::Result> { + let contents = fs::read_to_string(path) + .with_context(|| format!("failed to read allowed signers file {}", path.display()))?; + + parse_allowed_signers(&contents) +} + +fn parse_allowed_signers(contents: &str) -> anyhow::Result> { + let mut allowed_signers = Vec::new(); + + for (index, raw_line) in contents.lines().enumerate() { + let line = raw_line.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + + let mut parts = line.split_whitespace(); + let principals = parts + .next() + .ok_or_else(|| anyhow!("invalid allowed_signers line {}", index + 1))?; + let algorithm = parts + .next() + .ok_or_else(|| anyhow!("invalid allowed_signers line {}", index + 1))?; + let key_blob = parts + .next() + .ok_or_else(|| anyhow!("invalid allowed_signers line {}", index + 1))?; + + let normalized_algorithm = normalize_allowed_signers_algorithm(algorithm); + let public_key = PublicKey::from_openssh(&format!("{normalized_algorithm} {key_blob}")) + .with_context(|| format!("invalid public key on allowed_signers line {}", index + 1))?; + + let principals = principals + .split(',') + .filter(|principal| !principal.is_empty()) + .map(ToOwned::to_owned) + .collect::>(); + + if principals.is_empty() { + bail!("invalid allowed_signers line {}", index + 1); + } + + allowed_signers.push(AllowedSigner { + principals, + public_key, + }); + } + + Ok(allowed_signers) +} + +fn normalize_allowed_signers_algorithm(algorithm: &str) -> &str { + match algorithm { + "rsa-sha2-256" | "rsa-sha2-512" => "ssh-rsa", + other => other, + } +} + +fn find_agent_identity( + client: &mut ssh_agent_lib::blocking::Client, + public_key: &PublicKey, +) -> anyhow::Result +where + S: std::io::Read + std::io::Write, +{ + let identities = client.request_identities()?; + find_matching_identity(public_key, &identities) +} + +fn find_matching_identity( + public_key: &PublicKey, + identities: &[Identity], +) -> anyhow::Result { + identities + .iter() + .find(|identity| identity.pubkey == *public_key.key_data()) + .map(|identity| PublicKey::from(identity.pubkey.clone())) + .ok_or_else(|| anyhow!("requested key is not available in SSH agent")) +} + +#[cfg(unix)] +fn connect_agent() -> anyhow::Result> +{ + use std::os::unix::net::UnixStream; + + let socket_path = if let Ok(path) = std::env::var("SSH_AUTH_SOCK") { + path + } else { + let runtime_dir = std::env::var("XDG_RUNTIME_DIR") + .map_err(|_| anyhow!("SSH_AUTH_SOCK is unset and XDG_RUNTIME_DIR is unavailable"))?; + format!("{runtime_dir}/bw-agent.sock") + }; + + let stream = UnixStream::connect(&socket_path) + .with_context(|| format!("failed to connect to SSH agent at {socket_path}"))?; + Ok(ssh_agent_lib::blocking::Client::new(stream)) +} + +#[cfg(windows)] +fn connect_agent() -> anyhow::Result> { + let pipe_path = std::env::var("BW_PIPE_NAME").unwrap_or_else(|_| DEFAULT_PIPE_NAME.to_string()); + let stream = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(&pipe_path) + .with_context(|| format!("failed to connect to SSH agent named pipe {pipe_path}"))?; + + Ok(ssh_agent_lib::blocking::Client::new(stream)) +} + +#[cfg(test)] +mod tests { + use super::*; + + const ED25519_PRIVATE_KEY: &str = r#"-----BEGIN OPENSSH PRIVATE KEY----- +b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW +QyNTUxOQAAACCzPq7zfqLffKoBDe/eo04kH2XxtSmk9D7RQyf1xUqrYgAAAJgAIAxdACAM +XQAAAAtzc2gtZWQyNTUxOQAAACCzPq7zfqLffKoBDe/eo04kH2XxtSmk9D7RQyf1xUqrYg +AAAEC2BsIi0QwW2uFscKTUUXNHLsYX4FxlaSDSblbAj7WR7bM+rvN+ot98qgEN796jTiQf +ZfG1KaT0PtFDJ/XFSqtiAAAAEHVzZXJAZXhhbXBsZS5jb20BAgMEBQ== +-----END OPENSSH PRIVATE KEY-----"#; + + const RSA_PRIVATE_KEY: &str = r#"-----BEGIN OPENSSH PRIVATE KEY----- +b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABFwAAAAdzc2gtcn +NhAAAAAwEAAQAAAQEAyng6J3IE5++Ji7EfVNTANDnhYH46LnZW+bwW45etzKswQkc/AvSA +9ih2VAhE8FFUR0Z6pyl4hEn/878x50pGt1FHplbbe4wZ5aornT1hcGGYy313Glt+zyn96M +BTAjO0yULa1RrhBBmeY3yXIEAApUIVdvxcLOvJgltSFmFURtbY5cZkweuspwnHBE/JUPBX +9/Njb+z2R4BTnf0UrudxRKA/TJx9mL3Pb2JjkXfQ07pZqp+oEiUoGMvdfN9vYW4J5LTbXo +n20kRt5UKSxKggBBa0rzGabF+P/BTd39ZrI27WRYhDAzeYJoLq/xfO6qCgAM3TKxe0tDeT +gV4akFJ9CwAAA7hN/dPaTf3T2gAAAAdzc2gtcnNhAAABAQDKeDoncgTn74mLsR9U1MA0Oe +Fgfjoudlb5vBbjl63MqzBCRz8C9ID2KHZUCETwUVRHRnqnKXiESf/zvzHnSka3UUemVtt7 +jBnlqiudPWFwYZjLfXcaW37PKf3owFMCM7TJQtrVGuEEGZ5jfJcgQAClQhV2/Fws68mCW1 +IWYVRG1tjlxmTB66ynCccET8lQ8Ff382Nv7PZHgFOd/RSu53FEoD9MnH2Yvc9vYmORd9DT +ulmqn6gSJSgYy918329hbgnktNteifbSRG3lQpLEqCAEFrSvMZpsX4/8FN3f1msjbtZFiE +MDN5gmgur/F87qoKAAzdMrF7S0N5OBXhqQUn0LAAAAAwEAAQAAAQAxxSgWdjK6iOl4y0t2 +YO32aJv8SksnDLQIo7HEtI5ml1Y/lJ/qrAvfdsbPlVDM+lELTEnuOYWEj2Q5mLA9uMZ1Xa +eNPiCp2CCtkg0yk9oV9AfJTcgvVHpxllLyGgTNr8QrDSIZ7IePqHSE5CWKKfF+riX0n8hQ +yo04XBZrpfU/jDQV8ENKiNQd3Aiy6ppSbnDhyTzZEYIxtvnh1FmvU0Ct1jQRd8p42gurEn +sq6nAPE9pnn0otKmjRdfGCnM9X/ZbUcaUcU/X8pPYG1pW0GZR7eTO+1f9s8TS5LIqz2Eru +L4gBQweASh9mhatsMqJX/ZRrdHvdIuH8N1VDSahf1ZTxAAAAgF1+qA6ZVBEaoCj+fAJZyU +EYf7NMI/nPqEVxiIjg4WKmRYKC9Pb9cuGehOs/XTi3KMEHzYJIKT1K+uO0OG025XVH06qk +9qyWcBwtRbCPVFJPSkKyGBPaUIxMI07x1+434vig6z7iwVROxy3vyhslgiJNpIkaWVUhQN +EGEHX0oWLfAAAAgQDLd25QLAb1kngTsuwQ+xo3S6UcQvOTiDnVRvxWPaW4yn/3qO55+esd +dzxUujFXhUO/POeUJiHv0B1QlDm/sHYL6YVI5+XRaWAst/z0T93mM4ts63Z1OoJbAtE5qH +yGlKVPQ5ZG8SUVElbX+SZE2CcnsPx53trW8qQu/R2bPdDN7QAAAIEA/r7nlgz6D93vMVkn +wq38d49h+PTfyBQ1bum8AhxCEfTaK94YrH9BeizO6Ma5MIjY6WHWbq7Co93J3fl8f4eTCo +CpHJYWfbBqrf/5PUoOIjdMdfFHK6GpUCQNxhbSpnL4l75sxrhkEXtBHVKRXCNR5T4JnOcx +R6qbyo6hPuCiV9cAAAAAAQID +-----END OPENSSH PRIVATE KEY-----"#; + + const ED25519_PUBLIC_KEY: &str = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILM+rvN+ot98qgEN796jTiQfZfG1KaT0PtFDJ/XFSqti user@example.com"; + + #[test] + fn sshsig_roundtrip() { + let private_key = ssh_key::PrivateKey::from_openssh(ED25519_PRIVATE_KEY).unwrap(); + let data = b"hello from git-sign"; + let sshsig = private_key + .sign(DEFAULT_NAMESPACE, HashAlg::Sha512, data) + .unwrap(); + + let pem = sshsig.to_pem(ssh_key::LineEnding::LF).unwrap(); + let reparsed = SshSig::from_pem(pem).unwrap(); + + private_key + .public_key() + .verify(DEFAULT_NAMESPACE, data, &reparsed) + .unwrap(); + } + + #[test] + fn parses_allowed_signers() { + let rsa_public_key = ssh_key::PrivateKey::from_openssh(RSA_PRIVATE_KEY) + .unwrap() + .public_key() + .to_openssh() + .unwrap(); + let mut rsa_parts = rsa_public_key.split_whitespace(); + let _ = rsa_parts.next().unwrap(); + let rsa_blob = rsa_parts.next().unwrap(); + + let allowed_signers = parse_allowed_signers(&format!( + "alice,bob ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILM+rvN+ot98qgEN796jTiQfZfG1KaT0PtFDJ/XFSqti\ncarol rsa-sha2-512 {rsa_blob}\n" + )) + .unwrap(); + + assert_eq!(allowed_signers.len(), 2); + assert_eq!(allowed_signers[0].principals, vec!["alice", "bob"]); + assert_eq!(allowed_signers[1].principals, vec!["carol"]); + assert_eq!(key_type_string(&allowed_signers[0].public_key), "ED25519"); + assert_eq!(key_type_string(&allowed_signers[1].public_key), "RSA"); + } + + #[test] + fn key_type_string_mapping() { + let ed25519 = PublicKey::from_openssh(ED25519_PUBLIC_KEY).unwrap(); + let rsa = ssh_key::PrivateKey::from_openssh(RSA_PRIVATE_KEY) + .unwrap() + .public_key() + .clone(); + + assert_eq!(key_type_string(&ed25519), "ED25519"); + assert_eq!(key_type_string(&rsa), "RSA"); + } } From 4fa1af403d02bc40e925631ddd86488f101f785f Mon Sep 17 00:00:00 2001 From: reamd7 Date: Mon, 20 Apr 2026 01:02:30 +0800 Subject: [PATCH 04/15] feat: add git signing Tauri commands and settings UI Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus --- src-tauri/src/commands.rs | 66 +++++++++++++++++++++++++ src-tauri/src/main.rs | 2 + src/lib/tauri.ts | 8 ++++ src/pages/SettingsPage.tsx | 98 +++++++++++++++++++++++++++++++++++++- 4 files changed, 172 insertions(+), 2 deletions(-) diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 49dc4ff..ed1838e 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -18,6 +18,13 @@ pub enum UnlockResult { TwoFactorRequired { providers: Vec }, } +#[derive(serde::Serialize)] +pub struct GitSigningStatus { + pub ssh_program: Option, + pub gpg_format: Option, + pub commit_gpgsign: bool, +} + /// Spawn background sync + vault unlock after successful login. /// Shared by `unlock` and `unlock_with_two_factor` to avoid duplication. fn spawn_sync_and_unlock( @@ -230,6 +237,34 @@ pub async fn unlock_with_two_factor( } } +#[tauri::command] +pub async fn get_git_signing_status() -> Result { + let ssh_program = git_config_get("gpg.ssh.program").ok(); + let gpg_format = git_config_get("gpg.format").ok(); + let commit_gpgsign = git_config_get("commit.gpgsign") + .map(|v| v == "true") + .unwrap_or(false); + + Ok(GitSigningStatus { + ssh_program, + gpg_format, + commit_gpgsign, + }) +} + +#[tauri::command] +pub async fn configure_git_signing() -> Result<(), String> { + let exe_path = + std::env::current_exe().map_err(|e| format!("Cannot determine executable path: {e}"))?; + let program = format!("{} git-sign", exe_path.display()); + + git_config_set("gpg.ssh.program", &program)?; + git_config_set("gpg.format", "ssh")?; + git_config_set("commit.gpgsign", "true")?; + + Ok(()) +} + /// Clear any pending 2FA login state. Call this everywhere the vault is locked. fn clear_pending_two_factor(state: &AppState) { if let Ok(mut pending) = state.pending_two_factor.lock() { @@ -239,6 +274,37 @@ fn clear_pending_two_factor(state: &AppState) { } } +fn git_config_get(key: &str) -> Result { + let output = std::process::Command::new("git") + .args(["config", "--global", "--get", key]) + .output() + .map_err(|e| format!("Failed to run git: {e}"))?; + + if output.status.success() { + Ok(String::from_utf8_lossy(&output.stdout).trim().to_string()) + } else { + Err(format!("git config --get {key} failed")) + } +} + +fn git_config_set(key: &str, value: &str) -> Result<(), String> { + let output = std::process::Command::new("git") + .args(["config", "--global", key, value]) + .output() + .map_err(|e| format!("Failed to run git: {e}"))?; + + if output.status.success() { + Ok(()) + } else { + Err(format!( + "git config --global {} {} failed: {}", + key, + value, + String::from_utf8_lossy(&output.stderr) + )) + } +} + /// Background sync + unlock. Runs after login succeeds. async fn sync_and_unlock( client: bw_core::api::Client, diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 27d7e57..26096a7 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -240,6 +240,8 @@ fn main() { commands::get_config, commands::save_config, commands::update_lock_mode, + commands::get_git_signing_status, + commands::configure_git_signing, ]) .run(tauri::generate_context!()) .expect("error while running tauri application"); diff --git a/src/lib/tauri.ts b/src/lib/tauri.ts index e564494..b04fb65 100644 --- a/src/lib/tauri.ts +++ b/src/lib/tauri.ts @@ -54,6 +54,12 @@ export interface Config { proxy: string | null; } +export interface GitSigningStatus { + ssh_program: string | null; + gpg_format: string | null; + commit_gpgsign: boolean; +} + export const unlock = (password: string) => invoke("unlock", { password }); export const submitPassword = (password: string | null) => invoke("submit_password", { password }); export const submitTwoFactor = (provider: number, code: string) => invoke("submit_two_factor", { provider, code }); @@ -68,3 +74,5 @@ export const manualSync = () => invoke("manual_sync"); export const getConfig = () => invoke("get_config"); export const saveConfig = (config: Config) => invoke("save_config", { config }); export const updateLockMode = (lockMode: LockMode) => invoke("update_lock_mode", { lockMode }); +export const getGitSigningStatus = () => invoke("get_git_signing_status"); +export const configureGitSigning = () => invoke("configure_git_signing"); diff --git a/src/pages/SettingsPage.tsx b/src/pages/SettingsPage.tsx index e5b51af..177a32b 100644 --- a/src/pages/SettingsPage.tsx +++ b/src/pages/SettingsPage.tsx @@ -1,5 +1,15 @@ import { createSignal, onMount, Show } from "solid-js"; -import { getConfig, saveConfig, lockVault, updateLockMode, type Config, type LockMode } from "../lib/tauri"; +import { + getConfig, + saveConfig, + lockVault, + updateLockMode, + getGitSigningStatus, + configureGitSigning, + type Config, + type LockMode, + type GitSigningStatus, +} from "../lib/tauri"; import { store } from "../lib/store"; function navigate(path: string) { @@ -22,6 +32,8 @@ export default function SettingsPage() { const [saving, setSaving] = createSignal(false); const [toast, setToast] = createSignal<{ message: string; type: "success" | "error" } | null>(null); let originalConfig: Config | null = null; + const [gitSigningStatus, setGitSigningStatus] = createSignal(null); + const [configuring, setConfiguring] = createSignal(false); const [lockPreset, setLockPreset] = createSignal("15m"); @@ -51,6 +63,13 @@ export default function SettingsPage() { } else if (mode.type === "never") { setLockPreset("never"); } + + try { + const status = await getGitSigningStatus(); + setGitSigningStatus(status); + } catch (e) { + console.error("Failed to get git signing status:", e); + } } catch (e) { console.error("Failed to load config:", e); setToast({ message: "Failed to load settings", type: "error" }); @@ -117,6 +136,24 @@ export default function SettingsPage() { setConfig(prev => ({ ...prev, lock_mode: newMode })); }; + const handleConfigureGitSigning = async () => { + setConfiguring(true); + setToast(null); + + try { + await configureGitSigning(); + const status = await getGitSigningStatus(); + setGitSigningStatus(status); + setToast({ message: "Git SSH signing configured successfully", type: "success" }); + setTimeout(() => setToast(null), 3000); + } catch (e) { + console.error("Failed to configure git signing:", e); + setToast({ message: "Failed to configure git signing", type: "error" }); + } finally { + setConfiguring(false); + } + }; + const updateField = (field: keyof Config, value: string | number | null) => { setConfig((prev) => ({ ...prev, [field]: value })); }; @@ -324,6 +361,63 @@ export default function SettingsPage() { />
+ +
+

Git Signing

+

+ Configure git to use bw-agent for SSH commit signing. +

+
+ +
+ +
+
+ + + +
+
+

+ Git SSH signing is not configured. +

+
+ +
+
+
+
+ } + > +
+
+
+ + + +
+
+

+ Git SSH signing is configured +

+

+ gpg.ssh.program: {gitSigningStatus()?.ssh_program} +

+
+
+
+ +
@@ -341,4 +435,4 @@ export default function SettingsPage() {
); -} \ No newline at end of file +} From 0507c3c93358170cab44737beb88595494ac9fb0 Mon Sep 17 00:00:00 2001 From: reamd7 Date: Mon, 20 Apr 2026 10:29:39 +0800 Subject: [PATCH 05/15] fix: align Unix socket path resolution with server (BW_SOCKET_PATH priority) --- crates/bw-agent/src/git_sign.rs | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/crates/bw-agent/src/git_sign.rs b/crates/bw-agent/src/git_sign.rs index 652bcb0..7ddb5ac 100644 --- a/crates/bw-agent/src/git_sign.rs +++ b/crates/bw-agent/src/git_sign.rs @@ -343,13 +343,18 @@ fn connect_agent() -> anyhow::Result Date: Mon, 20 Apr 2026 10:41:11 +0800 Subject: [PATCH 06/15] feat: implement match-principals for complete -Y subcommand coverage --- crates/bw-agent/src/git_sign.rs | 69 +++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/crates/bw-agent/src/git_sign.rs b/crates/bw-agent/src/git_sign.rs index 7ddb5ac..e154f6f 100644 --- a/crates/bw-agent/src/git_sign.rs +++ b/crates/bw-agent/src/git_sign.rs @@ -37,6 +37,7 @@ pub fn run( "sign" => sign_action(namespace, key_file, data_file), "verify" => verify_action(namespace, key_file, principal, signature_file, data_file), "find-principals" => find_principals_action(namespace, key_file, signature_file, data_file), + "match-principals" => match_principals_action(key_file, principal), "check-novalidate" => check_novalidate_action(namespace, signature_file, data_file), _ => Err(anyhow!("unsupported action: {action}")), }; @@ -156,6 +157,33 @@ fn find_principals_action( Ok(()) } +fn match_principals_action(key_file: Option<&str>, principal: Option<&str>) -> anyhow::Result<()> { + let allowed_signers_path = required_path(key_file, "-f/--key-file")?; + let principal = + principal.ok_or_else(|| anyhow!("missing required principal (-I/--principal)"))?; + let allowed_signers = parse_allowed_signers_file(&allowed_signers_path)?; + + let matched: Vec<&str> = allowed_signers + .iter() + .filter(|entry| entry.principals.iter().any(|p| p == principal)) + .flat_map(|entry| entry.principals.iter().map(String::as_str)) + .collect(); + + if matched.is_empty() { + eprintln!("No principal matched."); + process::exit(255); + } + + let mut seen = BTreeSet::new(); + for p in matched { + if seen.insert(p) { + println!("{p}"); + } + } + + Ok(()) +} + fn check_novalidate_action( namespace: &str, signature_file: Option<&str>, @@ -466,4 +494,45 @@ R6qbyo6hPuCiV9cAAAAAAQID assert_eq!(key_type_string(&ed25519), "ED25519"); assert_eq!(key_type_string(&rsa), "RSA"); } + + #[test] + fn match_principals_finds_entries() { + let rsa_public_key = ssh_key::PrivateKey::from_openssh(RSA_PRIVATE_KEY) + .unwrap() + .public_key() + .to_openssh() + .unwrap(); + let mut rsa_parts = rsa_public_key.split_whitespace(); + let _ = rsa_parts.next().unwrap(); + let rsa_blob = rsa_parts.next().unwrap(); + + let allowed_signers = parse_allowed_signers(&format!( + "alice,bob ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILM+rvN+ot98qgEN796jTiQfZfG1KaT0PtFDJ/XFSqti\ncarol rsa-sha2-512 {rsa_blob}\n" + )) + .unwrap(); + + // "alice" matches the first entry, which has principals ["alice", "bob"] + let matched: Vec<&str> = allowed_signers + .iter() + .filter(|entry| entry.principals.iter().any(|p| p == "alice")) + .flat_map(|entry| entry.principals.iter().map(String::as_str)) + .collect(); + assert_eq!(matched, vec!["alice", "bob"]); + + // "carol" matches the second entry + let matched: Vec<&str> = allowed_signers + .iter() + .filter(|entry| entry.principals.iter().any(|p| p == "carol")) + .flat_map(|entry| entry.principals.iter().map(String::as_str)) + .collect(); + assert_eq!(matched, vec!["carol"]); + + // "unknown" matches nothing + let matched: Vec<&str> = allowed_signers + .iter() + .filter(|entry| entry.principals.iter().any(|p| p == "unknown")) + .flat_map(|entry| entry.principals.iter().map(String::as_str)) + .collect(); + assert!(matched.is_empty()); + } } From 8b94f218ce8645bb378c189a941025b4364ef372 Mon Sep 17 00:00:00 2001 From: reamd7 Date: Mon, 20 Apr 2026 12:46:29 +0800 Subject: [PATCH 07/15] fix: resolve bw-agent.exe path for git signing instead of using current_exe MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit configure_git_signing() was using std::env::current_exe() which returns bw-agent-desktop.exe — the wrong binary for git-sign. Now looks for bw-agent(.exe) as a sibling, with a dev-workspace fallback to the parent target/ directory. --- Cargo.lock | 41 +++++++++++++++++++++++++++++++++++++ src-tauri/src/commands.rs | 43 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 81 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e234b06..6170011 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -459,6 +459,7 @@ version = "0.1.0" dependencies = [ "anyhow", "bw-core", + "clap", "env_logger", "log", "rand 0.10.1", @@ -722,6 +723,46 @@ dependencies = [ "inout 0.2.2", ] +[[package]] +name = "clap" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + [[package]] name = "cmake" version = "0.1.58" diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index ed1838e..bbe5e1a 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -254,9 +254,8 @@ pub async fn get_git_signing_status() -> Result { #[tauri::command] pub async fn configure_git_signing() -> Result<(), String> { - let exe_path = - std::env::current_exe().map_err(|e| format!("Cannot determine executable path: {e}"))?; - let program = format!("{} git-sign", exe_path.display()); + let cli_path = resolve_git_sign_program_path()?; + let program = format!("{} git-sign", cli_path.display()); git_config_set("gpg.ssh.program", &program)?; git_config_set("gpg.format", "ssh")?; @@ -305,6 +304,44 @@ fn git_config_set(key: &str, value: &str) -> Result<(), String> { } } +fn resolve_git_sign_program_path() -> Result { + let current_exe = + std::env::current_exe().map_err(|e| format!("Cannot determine executable path: {e}"))?; + + let current_dir = current_exe.parent().ok_or_else(|| { + format!( + "Executable has no parent directory: {}", + current_exe.display() + ) + })?; + + let cli_name = if cfg!(windows) { + "bw-agent.exe" + } else { + "bw-agent" + }; + + let sibling_cli = current_dir.join(cli_name); + if sibling_cli.exists() { + return Ok(sibling_cli); + } + + // Dev-workspace fallback: target//bw-agent(.exe) next to src-tauri target output. + if let Some(target_dir) = current_dir.parent() { + let target_cli = target_dir.join(cli_name); + if target_cli.exists() { + return Ok(target_cli); + } + } + + Err(format!( + "Could not locate {} next to desktop executable {}; looked for {}", + cli_name, + current_exe.display(), + sibling_cli.display() + )) +} + /// Background sync + unlock. Runs after login succeeds. async fn sync_and_unlock( client: bw_core::api::Client, From ee03ca4438992e94f79602bb42e068aa9939cb2f Mon Sep 17 00:00:00 2001 From: reamd7 Date: Mon, 20 Apr 2026 12:49:47 +0800 Subject: [PATCH 08/15] feat: bundle bw-agent CLI as Tauri sidecar for git signing - Add externalBin to tauri.conf.json pointing to binaries/bw-agent - Add scripts/stage-sidecar.mjs to copy CLI binary with target-triple suffix that Tauri requires (must run before cargo build) - Add release CI step: build CLI + copy to src-tauri/binaries/ with target triple suffix before tauri-action runs - Add pnpm stage-sidecar and tauri:dev scripts for local dev - Add .gitignore for src-tauri/binaries/ (build artifacts) --- .github/workflows/release.yml | 14 ++++ package.json | 2 + scripts/stage-sidecar.mjs | 49 ++++++++++++++ scripts/test-git-sign-cli.ps1 | 116 ++++++++++++++++++++++++++++++++++ src-tauri/binaries/.gitignore | 4 ++ src-tauri/tauri.conf.json | 5 +- 6 files changed, 188 insertions(+), 2 deletions(-) create mode 100644 scripts/stage-sidecar.mjs create mode 100644 scripts/test-git-sign-cli.ps1 create mode 100644 src-tauri/binaries/.gitignore diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cfbab74..b3b6279 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -94,6 +94,20 @@ jobs: # follow-up task. # ----------------------------------------------------------------------- + - name: Build CLI sidecar + shell: bash + run: | + cargo build --release -p bw-agent --target ${{ matrix.target }} + TRIPLE="${{ matrix.target }}" + mkdir -p src-tauri/binaries + if [ "$RUNNER_OS" = "Windows" ]; then + cp "target/${TRIPLE}/release/bw-agent.exe" "src-tauri/binaries/bw-agent-${TRIPLE}.exe" + else + cp "target/${TRIPLE}/release/bw-agent" "src-tauri/binaries/bw-agent-${TRIPLE}" + fi + echo "--- Sidecar binary ---" + ls -la src-tauri/binaries/ + - name: Build Tauri bundles uses: tauri-apps/tauri-action@v0 with: diff --git a/package.json b/package.json index ca30527..c14a01c 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,9 @@ "scripts": { "dev": "rsbuild dev", "build": "rsbuild build", + "stage-sidecar": "node scripts/stage-sidecar.mjs", "tauri": "tauri", + "tauri:dev": "pnpm stage-sidecar && tauri dev", "test": "cargo test --workspace", "test:unit": "echo \"[placeholder] frontend unit tests not yet implemented (owned by task2)\" && exit 0", "check": "cargo fmt --all -- --check && cargo clippy --workspace --all-targets -- -D warnings", diff --git a/scripts/stage-sidecar.mjs b/scripts/stage-sidecar.mjs new file mode 100644 index 0000000..73d3c31 --- /dev/null +++ b/scripts/stage-sidecar.mjs @@ -0,0 +1,49 @@ +#!/usr/bin/env node +// Stages the bw-agent CLI binary as a Tauri sidecar. +// Run after `cargo build` — copies the binary to src-tauri/binaries/ with +// the target-triple suffix that Tauri's externalBin expects. +// +// Usage: +// node scripts/stage-sidecar.mjs [target-triple] +// +// If target-triple is omitted, defaults to the host triple from `rustc`. + +import { execSync } from "node:child_process"; +import { existsSync, mkdirSync, copyFileSync } from "node:fs"; +import { join, resolve } from "node:path"; + +const root = resolve(import.meta.dirname, ".."); +const binariesDir = join(root, "src-tauri", "binaries"); + +const triple = process.argv[2] || execSync("rustc --print host-tuple", { encoding: "utf-8" }).trim(); +const isWindows = triple.includes("windows"); +const ext = isWindows ? ".exe" : ""; + +const srcName = `bw-agent${ext}`; +const dstName = `bw-agent-${triple}${ext}`; + +// Check debug first, then release +const candidates = [ + join(root, "target", "debug", srcName), + join(root, "target", triple, "debug", srcName), + join(root, "target", "release", srcName), + join(root, "target", triple, "release", srcName), +]; + +let srcPath = null; +for (const candidate of candidates) { + if (existsSync(candidate)) { + srcPath = candidate; + break; + } +} + +if (!srcPath) { + console.error(`Error: ${srcName} not found. Run 'cargo build -p bw-agent' first.`); + process.exit(1); +} + +mkdirSync(binariesDir, { recursive: true }); +const dstPath = join(binariesDir, dstName); +copyFileSync(srcPath, dstPath); +console.log(`Staged sidecar: ${dstPath}`); diff --git a/scripts/test-git-sign-cli.ps1 b/scripts/test-git-sign-cli.ps1 new file mode 100644 index 0000000..784ab4b --- /dev/null +++ b/scripts/test-git-sign-cli.ps1 @@ -0,0 +1,116 @@ +$ErrorActionPreference = 'Stop' + +function Assert-Success($Result, $Message) { + if ($Result.ExitCode -ne 0) { + throw "$Message`nSTDOUT:`n$($Result.StdOut)`nSTDERR:`n$($Result.StdErr)" + } +} + +function Assert-Contains($Text, $Expected, $Message) { + if (-not $Text.Contains($Expected)) { + throw "$Message`nExpected to contain: $Expected`nActual:`n$Text" + } +} + +function Run-Command { + param( + [string]$FilePath, + [string[]]$Arguments, + [string]$WorkingDirectory = (Get-Location).Path + ) + + $stdoutFile = [System.IO.Path]::GetTempFileName() + $stderrFile = [System.IO.Path]::GetTempFileName() + + try { + $startInfo = [System.Diagnostics.ProcessStartInfo]::new() + $startInfo.FileName = $FilePath + $startInfo.WorkingDirectory = $WorkingDirectory + $startInfo.UseShellExecute = $false + $startInfo.RedirectStandardOutput = $true + $startInfo.RedirectStandardError = $true + + foreach ($argument in $Arguments) { + [void]$startInfo.ArgumentList.Add($argument) + } + + $process = [System.Diagnostics.Process]::Start($startInfo) + $process.WaitForExit() + + [System.IO.File]::WriteAllText($stdoutFile, $process.StandardOutput.ReadToEnd()) + [System.IO.File]::WriteAllText($stderrFile, $process.StandardError.ReadToEnd()) + + return [pscustomobject]@{ + ExitCode = $process.ExitCode + StdOut = [System.IO.File]::ReadAllText($stdoutFile) + StdErr = [System.IO.File]::ReadAllText($stderrFile) + } + } + finally { + Remove-Item $stdoutFile, $stderrFile -ErrorAction SilentlyContinue + } +} + +$repoRoot = Split-Path -Parent $PSScriptRoot +$bwAgentExe = Join-Path $repoRoot 'target\debug\bw-agent.exe' + +Write-Host '==> Building bw-agent binary' +$build = Run-Command -FilePath 'cargo' -Arguments @('build', '--package', 'bw-agent') -WorkingDirectory $repoRoot +Assert-Success $build 'cargo build failed' + +if (-not (Test-Path $bwAgentExe)) { + throw "Expected binary not found: $bwAgentExe" +} + +$tempDir = Join-Path ([System.IO.Path]::GetTempPath()) ("bw-agent-git-sign-" + [System.Guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $tempDir | Out-Null + +try { + $keyBase = Join-Path $tempDir 'test_key' + $dataFile = Join-Path $tempDir 'test_data.txt' + $allowedSigners = Join-Path $tempDir 'allowed_signers' + $signatureFile = "$dataFile.sig" + + Write-Host '==> Generating temporary SSH keypair' + $keygen = Run-Command -FilePath 'ssh-keygen' -Arguments @('-t', 'ed25519', '-f', $keyBase, '-N', '', '-C', 'test@example.com') -WorkingDirectory $tempDir + Assert-Success $keygen 'ssh-keygen key generation failed' + + Set-Content -Path $dataFile -Value 'hello git signing' -NoNewline + + Write-Host '==> Signing test data with ssh-keygen' + $sign = Run-Command -FilePath 'ssh-keygen' -Arguments @('-Y', 'sign', '-n', 'git', '-f', $keyBase, $dataFile) -WorkingDirectory $tempDir + Assert-Success $sign 'ssh-keygen signing failed' + + if (-not (Test-Path $signatureFile)) { + throw "Signature file not created: $signatureFile" + } + + $pubKey = Get-Content "$keyBase.pub" -Raw + Set-Content -Path $allowedSigners -Value ("test@example.com " + $pubKey.Trim()) + + Write-Host '==> Testing check-novalidate' + $checkNoValidate = Run-Command -FilePath $bwAgentExe -Arguments @('git-sign', '-Y', 'check-novalidate', '-n', 'git', '-s', $signatureFile, $dataFile) -WorkingDirectory $repoRoot + Assert-Success $checkNoValidate 'check-novalidate failed' + Assert-Contains $checkNoValidate.StdOut 'Good "git" signature with ED25519 key SHA256:' 'check-novalidate output mismatch' + + Write-Host '==> Testing find-principals' + $findPrincipals = Run-Command -FilePath $bwAgentExe -Arguments @('git-sign', '-Y', 'find-principals', '-f', $allowedSigners, '-s', $signatureFile, $dataFile) -WorkingDirectory $repoRoot + Assert-Success $findPrincipals 'find-principals failed' + Assert-Contains $findPrincipals.StdOut 'test@example.com' 'find-principals output mismatch' + + Write-Host '==> Testing verify' + $verify = Run-Command -FilePath $bwAgentExe -Arguments @('git-sign', '-Y', 'verify', '-n', 'git', '-f', $allowedSigners, '-I', 'test@example.com', '-s', $signatureFile, $dataFile) -WorkingDirectory $repoRoot + Assert-Success $verify 'verify failed' + Assert-Contains $verify.StdOut 'Good "git" signature for test@example.com with ED25519 key SHA256:' 'verify output mismatch' + + Write-Host '==> Testing match-principals' + $matchPrincipals = Run-Command -FilePath $bwAgentExe -Arguments @('git-sign', '-Y', 'match-principals', '-f', $allowedSigners, '-I', 'test@example.com') -WorkingDirectory $repoRoot + Assert-Success $matchPrincipals 'match-principals failed' + Assert-Contains $matchPrincipals.StdOut 'test@example.com' 'match-principals output mismatch' + + Write-Host '' + Write-Host 'All git-sign CLI checks passed.' -ForegroundColor Green +} +finally { + Remove-Item $tempDir -Recurse -Force -ErrorAction SilentlyContinue +} diff --git a/src-tauri/binaries/.gitignore b/src-tauri/binaries/.gitignore new file mode 100644 index 0000000..58c9192 --- /dev/null +++ b/src-tauri/binaries/.gitignore @@ -0,0 +1,4 @@ +# Sidecar binaries are built and staged here by CI / local build scripts. +# They must not be committed — they are platform-specific build artifacts. +* +!.gitignore diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index d4bf6e5..dd87572 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -6,7 +6,7 @@ "build": { "devUrl": "http://localhost:1420", "beforeDevCommand": "pnpm dev", - "beforeBuildCommand": "pnpm build", + "beforeBuildCommand": "pnpm build && pnpm stage-sidecar", "frontendDist": "../dist" }, "app": { @@ -38,6 +38,7 @@ "icons/128x128@2x.png", "icons/icon.icns", "icons/icon.ico" - ] + ], + "externalBin": ["binaries/bw-agent"] } } From 12d71f378584c5d345aecd66a491f0f67769294e Mon Sep 17 00:00:00 2001 From: reamd7 Date: Mon, 20 Apr 2026 15:14:48 +0800 Subject: [PATCH 09/15] fix: use hardlink for gpg.ssh.program instead of space-separated args MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Git's gpg.ssh.program is a single pathname — it does not split on spaces. Using 'bw-agent.exe git-sign' caused 'No such file or directory'. Solution: create a hardlink named bw-agent-git-sign(.exe) that points to bw-agent(.exe). The binary detects 'git-sign' in argv[0] and routes to the signing code path automatically (busybox pattern). - main.rs: argv[0] detection before clap parsing - git_sign.rs: add run_from_args() for positional arg parsing - commands.rs: ensure_git_sign_binary() creates hardlink at configure time - tauri.conf.json: externalBin includes both binaries - stage-sidecar.mjs & CI: create git-sign hardlink alongside sidecar --- .github/workflows/release.yml | 10 ++-- crates/bw-agent/src/git_sign.rs | 56 +++++++++++++++++++++ crates/bw-agent/src/main.rs | 15 ++++++ scripts/stage-sidecar.mjs | 12 ++++- src-tauri/src/commands.rs | 88 ++++++++++++++++++++++++--------- src-tauri/tauri.conf.json | 2 +- src/lib/tauri.ts | 6 +++ src/pages/SettingsPage.tsx | 43 ++++++++++++---- 8 files changed, 195 insertions(+), 37 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b3b6279..ad38d66 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -101,11 +101,15 @@ jobs: TRIPLE="${{ matrix.target }}" mkdir -p src-tauri/binaries if [ "$RUNNER_OS" = "Windows" ]; then - cp "target/${TRIPLE}/release/bw-agent.exe" "src-tauri/binaries/bw-agent-${TRIPLE}.exe" + EXT=".exe" else - cp "target/${TRIPLE}/release/bw-agent" "src-tauri/binaries/bw-agent-${TRIPLE}" + EXT="" fi - echo "--- Sidecar binary ---" + cp "target/${TRIPLE}/release/bw-agent${EXT}" "src-tauri/binaries/bw-agent-${TRIPLE}${EXT}" + # Hardlink for gpg.ssh.program — git calls it as a single executable, + # so we use argv[0] detection instead of passing arguments. + ln "src-tauri/binaries/bw-agent-${TRIPLE}${EXT}" "src-tauri/binaries/bw-agent-git-sign-${TRIPLE}${EXT}" + echo "--- Sidecar binaries ---" ls -la src-tauri/binaries/ - name: Build Tauri bundles diff --git a/crates/bw-agent/src/git_sign.rs b/crates/bw-agent/src/git_sign.rs index e154f6f..bbb4519 100644 --- a/crates/bw-agent/src/git_sign.rs +++ b/crates/bw-agent/src/git_sign.rs @@ -22,6 +22,62 @@ struct AllowedSigner { public_key: PublicKey, } +/// Entry point when invoked via argv[0] detection (e.g. as `bw-agent-git-sign`). +/// Git calls: ` -Y -n git -f [options] ` +pub fn run_from_args(args: &[String]) -> anyhow::Result<()> { + let mut action = None; + let mut namespace = None; + let mut key_file = None; + let mut principal = None; + let mut signature_file = None; + let mut data_file = None; + + let mut i = 0; + while i < args.len() { + match args[i].as_str() { + "-Y" => { + i += 1; + action = args.get(i).cloned(); + } + "-n" => { + i += 1; + namespace = args.get(i).cloned(); + } + "-f" => { + i += 1; + key_file = args.get(i).cloned(); + } + "-I" => { + i += 1; + principal = args.get(i).cloned(); + } + "-s" => { + i += 1; + signature_file = args.get(i).cloned(); + } + "-U" => { /* use-agent flag, ignored */ } + "-O" => { + i += 1; // skip option value + } + other if !other.starts_with('-') => { + data_file = Some(other.to_string()); + } + _ => {} + } + i += 1; + } + + let action = action.ok_or_else(|| anyhow!("missing -Y action"))?; + run( + &action, + namespace.as_deref(), + key_file.as_deref(), + principal.as_deref(), + signature_file.as_deref(), + data_file.as_deref(), + ) +} + /// Entry point for the git-sign subcommand. pub fn run( action: &str, diff --git a/crates/bw-agent/src/main.rs b/crates/bw-agent/src/main.rs index c86220b..2d8d5ab 100644 --- a/crates/bw-agent/src/main.rs +++ b/crates/bw-agent/src/main.rs @@ -40,6 +40,21 @@ enum Commands { #[tokio::main] async fn main() -> anyhow::Result<()> { env_logger::init(); + + // If invoked as a binary whose name ends with "git-sign" (e.g. via a + // hardlink / symlink named bw-agent-git-sign), skip clap and go straight + // to the signing code path. Git calls gpg.ssh.program as: + // -Y -n git -f [options] + let argv0 = std::env::args().next().unwrap_or_default(); + let bin_name = std::path::Path::new(&argv0) + .file_stem() + .unwrap_or_default() + .to_string_lossy(); + + if bin_name.ends_with("git-sign") { + return bw_agent::git_sign::run_from_args(&std::env::args().skip(1).collect::>()); + } + let cli = Cli::parse(); match cli.command { diff --git a/scripts/stage-sidecar.mjs b/scripts/stage-sidecar.mjs index 73d3c31..4d8ed70 100644 --- a/scripts/stage-sidecar.mjs +++ b/scripts/stage-sidecar.mjs @@ -9,7 +9,7 @@ // If target-triple is omitted, defaults to the host triple from `rustc`. import { execSync } from "node:child_process"; -import { existsSync, mkdirSync, copyFileSync } from "node:fs"; +import { existsSync, linkSync, mkdirSync, copyFileSync } from "node:fs"; import { join, resolve } from "node:path"; const root = resolve(import.meta.dirname, ".."); @@ -47,3 +47,13 @@ mkdirSync(binariesDir, { recursive: true }); const dstPath = join(binariesDir, dstName); copyFileSync(srcPath, dstPath); console.log(`Staged sidecar: ${dstPath}`); + +// Create a hardlink named bw-agent-git-sign- for gpg.ssh.program. +// Git calls gpg.ssh.program as a single executable (no argument splitting), +// so we need a separate entry point that detects "git-sign" in argv[0]. +const signDstName = `bw-agent-git-sign-${triple}${ext}`; +const signDstPath = join(binariesDir, signDstName); +if (!existsSync(signDstPath)) { + linkSync(dstPath, signDstPath); + console.log(`Staged git-sign link: ${signDstPath}`); +} diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index bbe5e1a..807ea16 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -23,6 +23,12 @@ pub struct GitSigningStatus { pub ssh_program: Option, pub gpg_format: Option, pub commit_gpgsign: bool, + /// Whether gpg.ssh.program points to our bw-agent binary. + pub program_correct: bool, + /// Whether gpg.format == "ssh". + pub format_correct: bool, + /// Whether commit.gpgsign == true. + pub signing_enabled: bool, } /// Spawn background sync + vault unlock after successful login. @@ -245,19 +251,31 @@ pub async fn get_git_signing_status() -> Result { .map(|v| v == "true") .unwrap_or(false); + let program_correct = { + let expected = ensure_git_sign_binary(); + match (&ssh_program, expected) { + (Some(program), Ok(expected_path)) => *program == expected_path.display().to_string(), + _ => false, + } + }; + let format_correct = gpg_format.as_deref() == Some("ssh"); + let signing_enabled = commit_gpgsign; + Ok(GitSigningStatus { ssh_program, gpg_format, commit_gpgsign, + program_correct, + format_correct, + signing_enabled, }) } #[tauri::command] pub async fn configure_git_signing() -> Result<(), String> { - let cli_path = resolve_git_sign_program_path()?; - let program = format!("{} git-sign", cli_path.display()); + let signing_bin = ensure_git_sign_binary()?; - git_config_set("gpg.ssh.program", &program)?; + git_config_set("gpg.ssh.program", &signing_bin.display().to_string())?; git_config_set("gpg.format", "ssh")?; git_config_set("commit.gpgsign", "true")?; @@ -304,7 +322,10 @@ fn git_config_set(key: &str, value: &str) -> Result<(), String> { } } -fn resolve_git_sign_program_path() -> Result { +/// Find bw-agent(.exe) and return the path to a hardlink named +/// bw-agent-git-sign(.exe) sitting next to it (creating the hardlink if +/// needed). This link is what gets written to gpg.ssh.program. +fn ensure_git_sign_binary() -> Result { let current_exe = std::env::current_exe().map_err(|e| format!("Cannot determine executable path: {e}"))?; @@ -315,31 +336,54 @@ fn resolve_git_sign_program_path() -> Result { ) })?; - let cli_name = if cfg!(windows) { - "bw-agent.exe" + let (base_name, link_name) = if cfg!(windows) { + ("bw-agent.exe", "bw-agent-git-sign.exe") } else { - "bw-agent" + ("bw-agent", "bw-agent-git-sign") }; - let sibling_cli = current_dir.join(cli_name); - if sibling_cli.exists() { - return Ok(sibling_cli); + // Look for bw-agent(.exe) as a sibling (sidecar / same dir). + let src_path = current_dir.join(base_name); + let link_path = current_dir.join(link_name); + + // If the hardlink already exists, just return it. + if link_path.exists() { + return Ok(link_path); } - // Dev-workspace fallback: target//bw-agent(.exe) next to src-tauri target output. - if let Some(target_dir) = current_dir.parent() { - let target_cli = target_dir.join(cli_name); - if target_cli.exists() { - return Ok(target_cli); + // Try dev-workspace fallback: target//bw-agent(.exe) + let src_path = if src_path.exists() { + src_path + } else if let Some(target_dir) = current_dir.parent() { + let fallback = target_dir.join(base_name); + if fallback.exists() { + fallback + } else { + return Err(format!( + "Could not locate {} next to desktop executable or in parent target/ directory", + base_name + )); } - } + } else { + return Err(format!( + "Could not locate {} next to desktop executable {}", + base_name, + current_exe.display() + )); + }; + + // Create hardlink. On Windows this uses fs::hard_link (which calls + // CreateHardLink). On Unix it calls link(). + std::fs::hard_link(&src_path, &link_path).map_err(|e| { + format!( + "Failed to create hardlink {} -> {}: {e}", + link_path.display(), + src_path.display() + ) + })?; - Err(format!( - "Could not locate {} next to desktop executable {}; looked for {}", - cli_name, - current_exe.display(), - sibling_cli.display() - )) + log::info!("Created git-sign hardlink: {}", link_path.display()); + Ok(link_path) } /// Background sync + unlock. Runs after login succeeds. diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index dd87572..fac7da8 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -39,6 +39,6 @@ "icons/icon.icns", "icons/icon.ico" ], - "externalBin": ["binaries/bw-agent"] + "externalBin": ["binaries/bw-agent", "binaries/bw-agent-git-sign"] } } diff --git a/src/lib/tauri.ts b/src/lib/tauri.ts index b04fb65..bea9c9d 100644 --- a/src/lib/tauri.ts +++ b/src/lib/tauri.ts @@ -58,6 +58,12 @@ export interface GitSigningStatus { ssh_program: string | null; gpg_format: string | null; commit_gpgsign: boolean; + /** Whether gpg.ssh.program points to our bw-agent binary */ + program_correct: boolean; + /** Whether gpg.format == "ssh" */ + format_correct: boolean; + /** Whether commit.gpgsign == true */ + signing_enabled: boolean; } export const unlock = (password: string) => invoke("unlock", { password }); diff --git a/src/pages/SettingsPage.tsx b/src/pages/SettingsPage.tsx index 177a32b..ec9b22c 100644 --- a/src/pages/SettingsPage.tsx +++ b/src/pages/SettingsPage.tsx @@ -154,6 +154,34 @@ export default function SettingsPage() { } }; + const allCorrect = () => + gitSigningStatus()?.program_correct && + gitSigningStatus()?.format_correct && + gitSigningStatus()?.signing_enabled; + + const signChecks = () => ( +
    +
  • + {gitSigningStatus()?.program_correct ? "✅" : "❌"} + gpg.ssh.program + + ({gitSigningStatus()?.ssh_program}) + + + (current: {gitSigningStatus()?.ssh_program}) + +
  • +
  • + {gitSigningStatus()?.format_correct ? "✅" : "❌"} + gpg.format = ssh +
  • +
  • + {gitSigningStatus()?.signing_enabled ? "✅" : "❌"} + commit.gpgsign = true +
  • +
+ ); + const updateField = (field: keyof Config, value: string | number | null) => { setConfig((prev) => ({ ...prev, [field]: value })); }; @@ -371,7 +399,7 @@ export default function SettingsPage() {
@@ -381,9 +409,8 @@ export default function SettingsPage() {
-

- Git SSH signing is not configured. -

+

Git SSH signing is not fully configured

+ {signChecks()}
-

- Git SSH signing is configured -

-

- gpg.ssh.program: {gitSigningStatus()?.ssh_program} -

+

Git SSH signing is configured

+ {signChecks()}
From cc6d0b5797047363405238fb8d933ab7df48ec7c Mon Sep 17 00:00:00 2001 From: reamd7 Date: Mon, 20 Apr 2026 15:33:46 +0800 Subject: [PATCH 10/15] fix: read data from stdin when git verify omits data file --- crates/bw-agent/src/git_sign.rs | 49 ++++++++++++++++++++++++++------- 1 file changed, 39 insertions(+), 10 deletions(-) diff --git a/crates/bw-agent/src/git_sign.rs b/crates/bw-agent/src/git_sign.rs index bbb4519..08433c4 100644 --- a/crates/bw-agent/src/git_sign.rs +++ b/crates/bw-agent/src/git_sign.rs @@ -154,9 +154,7 @@ fn verify_action( let principal = principal.ok_or_else(|| anyhow!("missing required principal (-I/--principal)"))?; let sshsig = read_signature(required_path(signature_file, "-s/--signature-file")?)?; - let data_path = required_path(data_file, "data file")?; - let data = fs::read(&data_path) - .with_context(|| format!("failed to read data file {}", data_path.display()))?; + let data = read_data_or_stdin(data_file)?; let allowed_signers = parse_allowed_signers_file(&allowed_signers_path)?; let signer = allowed_signers @@ -195,12 +193,30 @@ fn find_principals_action( ) -> anyhow::Result<()> { let allowed_signers_path = required_path(key_file, "-f/--key-file")?; let sshsig = read_signature(required_path(signature_file, "-s/--signature-file")?)?; - let data_path = required_path(data_file, "data file")?; - let data = fs::read(&data_path) - .with_context(|| format!("failed to read data file {}", data_path.display()))?; let allowed_signers = parse_allowed_signers_file(&allowed_signers_path)?; - let matched_principals = matching_principals(namespace, &data, &sshsig, &allowed_signers); + // ssh-keygen -Y find-principals does NOT require data — it matches the + // public key embedded in the signature against allowed signers. When git + // calls us there is no data file on the command line. + let matched_principals = match data_file { + Some(data_path) => { + let data = fs::read(data_path) + .with_context(|| format!("failed to read data file {data_path}"))?; + matching_principals(namespace, &data, &sshsig, &allowed_signers) + } + None => { + // Without data we can only match by public key fingerprint. + let sig_fingerprint = sshsig.public_key().fingerprint(Default::default()); + allowed_signers + .iter() + .filter(|entry| { + entry.public_key.fingerprint(Default::default()) == sig_fingerprint + }) + .flat_map(|entry| entry.principals.iter().map(String::as_str)) + .map(String::from) + .collect() + } + }; if matched_principals.is_empty() { eprintln!("No principal matched."); process::exit(255); @@ -246,9 +262,7 @@ fn check_novalidate_action( data_file: Option<&str>, ) -> anyhow::Result<()> { let sshsig = read_signature(required_path(signature_file, "-s/--signature-file")?)?; - let data_path = required_path(data_file, "data file")?; - let data = fs::read(&data_path) - .with_context(|| format!("failed to read data file {}", data_path.display()))?; + let data = read_data_or_stdin(data_file)?; let public_key = PublicKey::from(sshsig.public_key().clone()); if let Err(error) = public_key.verify(namespace, &data, &sshsig) { @@ -296,6 +310,21 @@ fn required_path(value: Option<&str>, label: &str) -> anyhow::Result { .ok_or_else(|| anyhow!("missing required {label}")) } +/// Read data from a file path, or fall back to stdin when git pipes the +/// commit contents without a positional file argument. +fn read_data_or_stdin(data_file: Option<&str>) -> anyhow::Result> { + match data_file { + Some(path) => fs::read(path) + .with_context(|| format!("failed to read data file {path}")), + None => { + use std::io::Read; + let mut buf = Vec::new(); + std::io::stdin().read_to_end(&mut buf)?; + Ok(buf) + } + } +} + fn read_signing_public_key(path: &Path) -> anyhow::Result { let contents = fs::read_to_string(path) .with_context(|| format!("failed to read key file {}", path.display()))?; From c0322a1792710807ed465f1d54860de4b06dbc05 Mon Sep 17 00:00:00 2001 From: reamd7 Date: Mon, 20 Apr 2026 16:46:07 +0800 Subject: [PATCH 11/15] style: cargo fmt --- crates/bw-agent/src/git_sign.rs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/crates/bw-agent/src/git_sign.rs b/crates/bw-agent/src/git_sign.rs index 08433c4..b6e2bc4 100644 --- a/crates/bw-agent/src/git_sign.rs +++ b/crates/bw-agent/src/git_sign.rs @@ -209,9 +209,7 @@ fn find_principals_action( let sig_fingerprint = sshsig.public_key().fingerprint(Default::default()); allowed_signers .iter() - .filter(|entry| { - entry.public_key.fingerprint(Default::default()) == sig_fingerprint - }) + .filter(|entry| entry.public_key.fingerprint(Default::default()) == sig_fingerprint) .flat_map(|entry| entry.principals.iter().map(String::as_str)) .map(String::from) .collect() @@ -314,8 +312,7 @@ fn required_path(value: Option<&str>, label: &str) -> anyhow::Result { /// commit contents without a positional file argument. fn read_data_or_stdin(data_file: Option<&str>) -> anyhow::Result> { match data_file { - Some(path) => fs::read(path) - .with_context(|| format!("failed to read data file {path}")), + Some(path) => fs::read(path).with_context(|| format!("failed to read data file {path}")), None => { use std::io::Read; let mut buf = Vec::new(); From 3c7fedf9c12ec38e085078ab38bf9152287c73eb Mon Sep 17 00:00:00 2001 From: reamd7 Date: Mon, 20 Apr 2026 17:03:35 +0800 Subject: [PATCH 12/15] fix(ci): stage sidecar binaries before clippy and test Tauri's build script validates externalBin paths exist. Without staging the sidecar binaries first, both cargo clippy (check job) and cargo test (test job) fail because the binaries directory is empty. The stage-sidecar.mjs script now auto-builds bw-agent if the binary is not found locally. --- .github/workflows/ci.yml | 6 ++++++ scripts/stage-sidecar.mjs | 15 +++++++++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 290dc4e..878bfdc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,6 +39,9 @@ jobs: shared-key: ci-check cache-targets: 'false' + - name: Stage sidecar binaries + run: node scripts/stage-sidecar.mjs + - name: pnpm run check (cargo fmt + cargo clippy) run: pnpm run check @@ -63,6 +66,9 @@ jobs: with: shared-key: ci-test-${{ matrix.os }} + - name: Stage sidecar binaries + run: node scripts/stage-sidecar.mjs + - name: pnpm run test (cargo test --workspace) run: pnpm run test diff --git a/scripts/stage-sidecar.mjs b/scripts/stage-sidecar.mjs index 4d8ed70..a18b508 100644 --- a/scripts/stage-sidecar.mjs +++ b/scripts/stage-sidecar.mjs @@ -39,8 +39,19 @@ for (const candidate of candidates) { } if (!srcPath) { - console.error(`Error: ${srcName} not found. Run 'cargo build -p bw-agent' first.`); - process.exit(1); + console.log(`bw-agent binary not found, building...`); + execSync("cargo build -p bw-agent", { stdio: "inherit" }); + // Re-check after build + for (const candidate of candidates) { + if (existsSync(candidate)) { + srcPath = candidate; + break; + } + } + if (!srcPath) { + console.error(`Error: ${srcName} still not found after build.`); + process.exit(1); + } } mkdirSync(binariesDir, { recursive: true }); From b73ecdd358da49442da48a1260a59ba4a17b2682 Mon Sep 17 00:00:00 2001 From: reamd7 Date: Mon, 20 Apr 2026 19:39:02 +0800 Subject: [PATCH 13/15] refactor: drop standalone bw-agent.exe sidecar, keep only git-sign MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The bw-agent.exe sidecar was redundant — bw-agent-git-sign.exe is already a full copy of the CLI binary with argv[0] detection routing to the git-sign code path. Git only needs gpg.ssh.program to point to a single executable, so the extra sidecar served no purpose. Changes: - tauri.conf.json: remove binaries/bw-agent from externalBin - stage-sidecar.mjs: copy directly as bw-agent-git-sign- - commands.rs: simplify ensure_git_sign_binary() — just locate the sidecar, no runtime hardlink creation needed - release.yml: copy as git-sign name directly, no hardlink step --- .github/workflows/release.yml | 7 ++--- scripts/stage-sidecar.mjs | 20 +++--------- src-tauri/src/commands.rs | 59 ++++++++--------------------------- src-tauri/tauri.conf.json | 2 +- 4 files changed, 22 insertions(+), 66 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ad38d66..b44a1ab 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -105,10 +105,9 @@ jobs: else EXT="" fi - cp "target/${TRIPLE}/release/bw-agent${EXT}" "src-tauri/binaries/bw-agent-${TRIPLE}${EXT}" - # Hardlink for gpg.ssh.program — git calls it as a single executable, - # so we use argv[0] detection instead of passing arguments. - ln "src-tauri/binaries/bw-agent-${TRIPLE}${EXT}" "src-tauri/binaries/bw-agent-git-sign-${TRIPLE}${EXT}" + # Copy as bw-agent-git-sign — the sidecar name Tauri expects. + # argv[0] detection routes to the git-sign code path at runtime. + cp "target/${TRIPLE}/release/bw-agent${EXT}" "src-tauri/binaries/bw-agent-git-sign-${TRIPLE}${EXT}" echo "--- Sidecar binaries ---" ls -la src-tauri/binaries/ diff --git a/scripts/stage-sidecar.mjs b/scripts/stage-sidecar.mjs index a18b508..3f65156 100644 --- a/scripts/stage-sidecar.mjs +++ b/scripts/stage-sidecar.mjs @@ -1,7 +1,7 @@ #!/usr/bin/env node -// Stages the bw-agent CLI binary as a Tauri sidecar. -// Run after `cargo build` — copies the binary to src-tauri/binaries/ with -// the target-triple suffix that Tauri's externalBin expects. +// Stages the bw-agent CLI binary as a Tauri sidecar for git signing. +// The binary is copied as bw-agent-git-sign- so that argv[0] +// detection routes to the git-sign code path at runtime. // // Usage: // node scripts/stage-sidecar.mjs [target-triple] @@ -9,7 +9,7 @@ // If target-triple is omitted, defaults to the host triple from `rustc`. import { execSync } from "node:child_process"; -import { existsSync, linkSync, mkdirSync, copyFileSync } from "node:fs"; +import { existsSync, mkdirSync, copyFileSync } from "node:fs"; import { join, resolve } from "node:path"; const root = resolve(import.meta.dirname, ".."); @@ -20,7 +20,7 @@ const isWindows = triple.includes("windows"); const ext = isWindows ? ".exe" : ""; const srcName = `bw-agent${ext}`; -const dstName = `bw-agent-${triple}${ext}`; +const dstName = `bw-agent-git-sign-${triple}${ext}`; // Check debug first, then release const candidates = [ @@ -58,13 +58,3 @@ mkdirSync(binariesDir, { recursive: true }); const dstPath = join(binariesDir, dstName); copyFileSync(srcPath, dstPath); console.log(`Staged sidecar: ${dstPath}`); - -// Create a hardlink named bw-agent-git-sign- for gpg.ssh.program. -// Git calls gpg.ssh.program as a single executable (no argument splitting), -// so we need a separate entry point that detects "git-sign" in argv[0]. -const signDstName = `bw-agent-git-sign-${triple}${ext}`; -const signDstPath = join(binariesDir, signDstName); -if (!existsSync(signDstPath)) { - linkSync(dstPath, signDstPath); - console.log(`Staged git-sign link: ${signDstPath}`); -} diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 807ea16..0f73fea 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -322,9 +322,8 @@ fn git_config_set(key: &str, value: &str) -> Result<(), String> { } } -/// Find bw-agent(.exe) and return the path to a hardlink named -/// bw-agent-git-sign(.exe) sitting next to it (creating the hardlink if -/// needed). This link is what gets written to gpg.ssh.program. +/// Find the bw-agent-git-sign(.exe) sidecar sitting next to the desktop binary. +/// This is the path written to gpg.ssh.program. fn ensure_git_sign_binary() -> Result { let current_exe = std::env::current_exe().map_err(|e| format!("Cannot determine executable path: {e}"))?; @@ -336,54 +335,22 @@ fn ensure_git_sign_binary() -> Result { ) })?; - let (base_name, link_name) = if cfg!(windows) { - ("bw-agent.exe", "bw-agent-git-sign.exe") + let sidecar_name = if cfg!(windows) { + "bw-agent-git-sign.exe" } else { - ("bw-agent", "bw-agent-git-sign") + "bw-agent-git-sign" }; - // Look for bw-agent(.exe) as a sibling (sidecar / same dir). - let src_path = current_dir.join(base_name); - let link_path = current_dir.join(link_name); + let sidecar_path = current_dir.join(sidecar_name); - // If the hardlink already exists, just return it. - if link_path.exists() { - return Ok(link_path); - } - - // Try dev-workspace fallback: target//bw-agent(.exe) - let src_path = if src_path.exists() { - src_path - } else if let Some(target_dir) = current_dir.parent() { - let fallback = target_dir.join(base_name); - if fallback.exists() { - fallback - } else { - return Err(format!( - "Could not locate {} next to desktop executable or in parent target/ directory", - base_name - )); - } + if sidecar_path.exists() { + Ok(sidecar_path) } else { - return Err(format!( - "Could not locate {} next to desktop executable {}", - base_name, - current_exe.display() - )); - }; - - // Create hardlink. On Windows this uses fs::hard_link (which calls - // CreateHardLink). On Unix it calls link(). - std::fs::hard_link(&src_path, &link_path).map_err(|e| { - format!( - "Failed to create hardlink {} -> {}: {e}", - link_path.display(), - src_path.display() - ) - })?; - - log::info!("Created git-sign hardlink: {}", link_path.display()); - Ok(link_path) + Err(format!( + "Git signing sidecar not found: {}", + sidecar_path.display() + )) + } } /// Background sync + unlock. Runs after login succeeds. diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index fac7da8..a3cf4b8 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -39,6 +39,6 @@ "icons/icon.icns", "icons/icon.ico" ], - "externalBin": ["binaries/bw-agent", "binaries/bw-agent-git-sign"] + "externalBin": ["binaries/bw-agent-git-sign"] } } From ba60f4f57aa385e01f343296f95334e3cd4e1ca7 Mon Sep 17 00:00:00 2001 From: reamd7 Date: Mon, 20 Apr 2026 19:42:30 +0800 Subject: [PATCH 14/15] fix(ui): show git sign operation in logs instead of ssh When git signs a commit via bw-agent-git-sign, the process chain contains the git-sign binary, not an SSH connection. Detect this pattern and display operation as 'git sign' instead of 'ssh'. --- src/components/LogTable.tsx | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/components/LogTable.tsx b/src/components/LogTable.tsx index bb4593a..d543b34 100644 --- a/src/components/LogTable.tsx +++ b/src/components/LogTable.tsx @@ -70,6 +70,18 @@ const parseSshCmdline = (processChain: ProcessInfo[]): SshInfo => { return { operation: "unknown", target: "unknown" }; } + // Detect git-sign: bw-agent-git-sign in the process chain indicates a git + // commit signing operation, not an SSH connection. + for (const proc of processChain) { + const exeName = extractExeName(proc.exe).toLowerCase(); + if (exeName.includes("git-sign")) { + // Extract -Y action (sign, verify, find-principals, etc.) + const actionMatch = proc.cmdline.match(/-Y\s+(\S+)/); + const action = actionMatch ? actionMatch[1] : "sign"; + return { operation: `git ${action}`, target: "commit" }; + } + } + const sshNode = processChain[processChain.length - 1]; const cmdline = sshNode.cmdline; From 2ee4b536d2f0edf852a236a1e288afb1a828b917 Mon Sep 17 00:00:00 2001 From: reamd7 Date: Mon, 20 Apr 2026 19:44:13 +0800 Subject: [PATCH 15/15] fix(ui): show git subcommand and cwd for signing log entries Instead of hardcoded target 'commit', extract the actual git subcommand (commit/tag/merge) from the parent process and show the working directory as the target. --- src/components/LogTable.tsx | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/components/LogTable.tsx b/src/components/LogTable.tsx index d543b34..37f4c56 100644 --- a/src/components/LogTable.tsx +++ b/src/components/LogTable.tsx @@ -78,7 +78,24 @@ const parseSshCmdline = (processChain: ProcessInfo[]): SshInfo => { // Extract -Y action (sign, verify, find-principals, etc.) const actionMatch = proc.cmdline.match(/-Y\s+(\S+)/); const action = actionMatch ? actionMatch[1] : "sign"; - return { operation: `git ${action}`, target: "commit" }; + + // Look for the parent git process to determine what triggered signing + // (commit, tag, merge, etc.) and the working directory. + let gitCmd = ""; + let cwd = ""; + for (const parent of processChain) { + const parentExe = extractExeName(parent.exe).toLowerCase(); + if (parentExe === "git.exe" || parentExe === "git") { + const cmdMatch = parent.cmdline.match(/^git\s+(\S+)/); + if (cmdMatch) gitCmd = cmdMatch[1]; + cwd = parent.cwd || ""; + break; + } + } + + const operation = gitCmd ? `git ${gitCmd} (${action})` : `git ${action}`; + const target = cwd || "unknown"; + return { operation, target }; } }