diff --git a/crates/stdiod/README.md b/crates/stdiod/README.md index dfe700d..dcc8758 100644 --- a/crates/stdiod/README.md +++ b/crates/stdiod/README.md @@ -215,6 +215,26 @@ credential. `logout` removes authentication while retaining preferences; +## Connect to multiple backends + +Keep your existing sign-in and add a named profile for each additional backend. +One daemon opens a separate WebSocket for each signed-in profile. Each profile +has its own credentials, connection state, and MCP server processes. + +```sh +sealgate-stdiod login --profile staging --backend https://staging.example.com +sealgate-stdiod status --profile staging +sealgate-stdiod logout --profile staging +``` + +Complete browser authorization for each new backend once. A running daemon +discovers new profiles automatically. If the service is not installed, run +`sealgate-stdiod install` once after signing in. Commands without `--profile` +continue to use your existing default sign-in. Named profiles are stored under +`~/.config/sealgate-stdiod/profiles//`. Use `--profile` with `server` commands +to manage MCP servers for that backend. `uninstall --purge` removes all named +profiles. Add `--keep-profiles` to preserve their sign-ins and preferences. + ## Files on disk TLDR: the daemon keeps almost nothing durable - the backend is the source of truth. @@ -227,7 +247,12 @@ TLDR: the daemon keeps almost nothing durable - the backend is the source of tru config.toml # backend URL, account IDs, token, device ID, secret (mode 0600) server_envs.json # legacy-auth local server values (mode 0600) server_envs/.json # client-installation-isolated server values (mode 0600) - state.json # atomic writes; snapshot consumed by the desktop tray UI + state.json # default connection snapshot for the desktop tray + profiles// # named backend + config.toml # backend URL and credentials (mode 0600) + state.json # connection and child snapshot + server_envs.json # legacy-auth server values (mode 0600) + server_envs/.json # client-installation server values (mode 0600) ~/Library/Logs/sealgate-stdiod/ # macOS - platform-equivalent paths elsewhere daemon.log # rotated daily child-.log # per-child stdout/stderr capture diff --git a/crates/stdiod/crates/sealgate-stdiod/src/cli/install.rs b/crates/stdiod/crates/sealgate-stdiod/src/cli/install.rs index 1ece7d1..853089a 100644 --- a/crates/stdiod/crates/sealgate-stdiod/src/cli/install.rs +++ b/crates/stdiod/crates/sealgate-stdiod/src/cli/install.rs @@ -29,6 +29,9 @@ pub struct UninstallArgs { /// `--purge` to wipe everything stdiod-related. #[arg(long)] pub purge: bool, + /// Preserve named backend credentials and preferences during a default sign-in reset. + #[arg(long, requires = "purge")] + pub keep_profiles: bool, } pub fn install(_args: InstallArgs) -> Result<()> { @@ -55,27 +58,56 @@ pub fn uninstall(args: UninstallArgs) -> Result<()> { // uninstall, even without ``--purge``. config.toml stays because it // carries the user's credentials. if let Ok(state_path) = paths::state_file() { - match std::fs::remove_file(&state_path) { - Ok(()) => info!(path = %state_path.display(), "removed state.json"), - Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} - Err(e) => { - tracing::warn!(error = %e, "failed to remove state.json; continuing"); + remove_state(&state_path); + } + match paths::profile_names() { + Ok(names) => { + for name in names { + remove_state(&paths::profile_dir(&name)?.join("state.json")); } } + Err(error) => tracing::warn!(%error, "could not discover backend profiles"), } if args.purge { - purge_user_data().context("purge")?; + purge_user_data(args.keep_profiles).context("purge")?; } Ok(()) } -fn purge_user_data() -> Result<()> { - let config_dir = paths::config_dir()?; - if config_dir.exists() { - std::fs::remove_dir_all(&config_dir) +fn remove_state(path: &std::path::Path) { + match std::fs::remove_file(path) { + Ok(()) => info!(path = %path.display(), "removed state.json"), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => tracing::warn!(%error, path = %path.display(), "failed to remove state.json"), + } +} + +fn purge_config(config_dir: &std::path::Path, keep_profiles: bool) -> Result<()> { + if keep_profiles { + for entry in std::fs::read_dir(config_dir)? { + let entry = entry?; + if entry.file_name() == paths::PROFILES_DIRECTORY { + continue; + } + let path = entry.path(); + let remove = if entry.file_type()?.is_dir() { + std::fs::remove_dir_all(&path) + } else { + std::fs::remove_file(&path) + }; + remove.with_context(|| format!("removing {}", path.display()))?; + } + } else if config_dir.exists() { + std::fs::remove_dir_all(config_dir) .with_context(|| format!("removing {}", config_dir.display()))?; info!(path = %config_dir.display(), "purged config dir"); } + Ok(()) +} + +fn purge_user_data(keep_profiles: bool) -> Result<()> { + let config_dir = paths::config_dir()?; + purge_config(&config_dir, keep_profiles)?; let log_dir = paths::log_dir()?; if log_dir.exists() { std::fs::remove_dir_all(&log_dir) @@ -85,3 +117,27 @@ fn purge_user_data() -> Result<()> { println!("Purged config and logs."); Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn default_reset_preserves_named_profile_credentials() { + let root = + std::env::temp_dir().join(format!("stdiod-profile-purge-{}", std::process::id())); + let profile = root.join(paths::PROFILES_DIRECTORY).join("staging"); + std::fs::create_dir_all(&profile).unwrap(); + std::fs::write(root.join("config.toml"), "default-config").unwrap(); + std::fs::write(profile.join("config.toml"), "staging-config").unwrap(); + + purge_config(&root, true).unwrap(); + assert!(!root.join("config.toml").exists()); + assert_eq!( + std::fs::read_to_string(profile.join("config.toml")).unwrap(), + "staging-config" + ); + purge_config(&root, false).unwrap(); + assert!(!root.exists()); + } +} diff --git a/crates/stdiod/crates/sealgate-stdiod/src/cli/login.rs b/crates/stdiod/crates/sealgate-stdiod/src/cli/login.rs index 94efe83..2529b08 100644 --- a/crates/stdiod/crates/sealgate-stdiod/src/cli/login.rs +++ b/crates/stdiod/crates/sealgate-stdiod/src/cli/login.rs @@ -242,7 +242,11 @@ fn save_login(cfg: &PersistedConfig) -> Result<()> { crate::power::save_keeping_power(cfg, &path)?; info!(path = %path.display(), "wrote config.toml"); println!("Saved {}", path.display()); - println!("Next: `sealgate-stdiod install` to register the supervisor service."); + if paths::profile_name().is_some() { + println!("A running daemon picks up this profile automatically. To start the service, run `sealgate-stdiod install`."); + } else { + println!("Next: `sealgate-stdiod install` to register the supervisor service."); + } Ok(()) } diff --git a/crates/stdiod/crates/sealgate-stdiod/src/cli/server.rs b/crates/stdiod/crates/sealgate-stdiod/src/cli/server.rs index 76d55d4..b369025 100644 --- a/crates/stdiod/crates/sealgate-stdiod/src/cli/server.rs +++ b/crates/stdiod/crates/sealgate-stdiod/src/cli/server.rs @@ -142,8 +142,11 @@ pub(crate) async fn submit( fn format_create_result(name: &str, response: ClientCreateRequestResponse) -> String { if response.auto_approved { + let profile_option = crate::paths::profile_name() + .map(|profile| format!(" --profile {profile}")) + .unwrap_or_default(); format!( - "Request '{name}' was auto-approved (request ID {}). Run `sealgate-stdiod status` to confirm it has spawned.", + "Request '{name}' was auto-approved (request ID {}). Run `sealgate-stdiod status{profile_option}` to confirm it has spawned.", response.request_id ) } else { diff --git a/crates/stdiod/crates/sealgate-stdiod/src/cli/status.rs b/crates/stdiod/crates/sealgate-stdiod/src/cli/status.rs index cce5407..bcb72b1 100644 --- a/crates/stdiod/crates/sealgate-stdiod/src/cli/status.rs +++ b/crates/stdiod/crates/sealgate-stdiod/src/cli/status.rs @@ -68,6 +68,17 @@ pub fn run(_args: StatusArgs) -> Result<()> { } } + if paths::profile_name().is_none() { + match paths::profile_names() { + Ok(names) if !names.is_empty() => println!( + "Backend profiles: {} (use `status --profile `)", + names.join(", ") + ), + Ok(_) => {} + Err(error) => println!("Backend profiles: (unavailable: {error})"), + } + } + // Exit codes describe HEALTH; the line printed above describes the cause. // So "loaded but dead" and "never loaded" both map to EXIT_NOT_RUNNING // rather than growing a fourth code - callers branch on healthy/unhealthy, diff --git a/crates/stdiod/crates/sealgate-stdiod/src/daemon.rs b/crates/stdiod/crates/sealgate-stdiod/src/daemon.rs index c379aa8..c7664ec 100644 --- a/crates/stdiod/crates/sealgate-stdiod/src/daemon.rs +++ b/crates/stdiod/crates/sealgate-stdiod/src/daemon.rs @@ -3,7 +3,7 @@ //! //! Connection lifecycle: //! -//! 1. Outer ``run`` loop keeps a long-lived [`Supervisor`] across WS +//! 1. ``run_backend`` loop keeps a long-lived [`Supervisor`] across WS //! reconnects. Children survive transient disconnects - their //! [`OutgoingHandle`] is rewired on each new WS so MCP frames keep //! flowing without restarting subprocesses. @@ -27,17 +27,18 @@ use tokio::sync::{mpsc, watch, Mutex}; use tokio::time::sleep; use tracing::{debug, info, warn}; -use crate::config; -pub use crate::daemon_auth::RunArgs; +use crate::daemon_auth::RunArgs; use crate::daemon_auth::{ connection_error_message, is_auth_rejection, is_protocol_rejection, requires_child_reset, ResolveRunError, ResolvedRun, }; +use crate::daemon_profiles::wait_for_shutdown; use crate::env_store::EnvStore; use crate::power::controller::{KeepAwake, ReportTarget}; use crate::state::{ConnectionState, State, StateWriter}; use crate::supervisor::Supervisor; use crate::tunnel::{self, OutgoingHandle}; +use crate::{config, paths}; // The daemon pings every 15s and considers the connection dead if no pong // arrives within HEARTBEAT_STALE_AFTER. On stale, the WS is closed and @@ -56,9 +57,9 @@ const BACKOFF_MIN: Duration = Duration::from_secs(1); const BACKOFF_MAX: Duration = Duration::from_secs(30); const CONFIG_POLL_INTERVAL: Duration = Duration::from_secs(1); -pub async fn run(args: RunArgs) -> Result<()> { - #[cfg(windows)] - crate::platform::windows::kill_children_on_exit(); +pub(crate) async fn run_backend(args: RunArgs, signal: watch::Receiver) -> Result<()> { + let shutdown_signal = wait_for_shutdown(signal); + tokio::pin!(shutdown_signal); let initial = ResolvedRun::from_args(&args); // The keep-awake status from the previous run: its local choice applies // while config.toml cannot be read. Its dashboard value applies until the @@ -67,15 +68,18 @@ pub async fn run(args: RunArgs) -> Result<()> { let previous_keep_awake = State::load() .ok() .and_then(|state| previous_keep_awake(state, initial.as_ref().ok())); - let writer = StateWriter::new(State { - backend_url: initial.as_ref().ok().map(|value| value.backend.clone()), - device_id: initial.as_ref().ok().map(|value| value.device_id.clone()), - device_label: initial.as_ref().ok().map(|value| value.label.clone()), - pid: Some(std::process::id()), - ..State::default() - }); + let writer = StateWriter::new_at( + State { + backend_url: initial.as_ref().ok().map(|value| value.backend.clone()), + device_id: initial.as_ref().ok().map(|value| value.device_id.clone()), + device_label: initial.as_ref().ok().map(|value| value.label.clone()), + pid: Some(std::process::id()), + ..State::default() + }, + paths::state_file()?, + ); writer.update(|_| {}).await; - let keep_awake = KeepAwake::start(previous_keep_awake, writer.clone()); + let keep_awake = KeepAwake::start(previous_keep_awake, writer.clone(), paths::config_file()?); let mut resolved = match initial { Ok(resolved) => resolved, Err(ResolveRunError::AwaitingLogin) => { @@ -88,7 +92,10 @@ pub async fn run(args: RunArgs) -> Result<()> { }) .await; loop { - sleep(CONFIG_POLL_INTERVAL).await; + tokio::select! { + _ = &mut shutdown_signal => return Ok(()), + _ = sleep(CONFIG_POLL_INTERVAL) => {} + } if let Ok(resolved) = ResolvedRun::from_args(&args) { break resolved; } @@ -106,11 +113,6 @@ pub async fn run(args: RunArgs) -> Result<()> { }) .await; - // Resolve the interactive login-shell PATH once, up front, so child MCP - // servers can find version-manager node/npx (nvm/fnm/...) - the daemon's own - // (systemd/launchd) PATH doesn't include shell-rc additions. See proc.rs. - crate::proc::init_child_env().await; - // The supervisor - and the broker handle the children depend on - // live across reconnects. ``apply_snapshot`` on each new WS will // diff and reconcile. @@ -125,8 +127,6 @@ pub async fn run(args: RunArgs) -> Result<()> { ))); let mut backoff = BACKOFF_MIN; - let shutdown_signal = crate::process_shutdown::wait(); - tokio::pin!(shutdown_signal); loop { let result = tokio::select! { result = run_one_session(&resolved, &args, supervisor.clone(), &outgoing, &writer, &keep_awake) => result, @@ -212,7 +212,13 @@ pub async fn run(args: RunArgs) -> Result<()> { let current_env_namespace = resolved.env_namespace(); let next_env_namespace = next.env_namespace(); if current_env_namespace != next_env_namespace { - let env_store = EnvStore::open_for(next_env_namespace.as_deref())?; + let env_store = match EnvStore::open_for(next_env_namespace.as_deref()) { + Ok(store) => store, + Err(error) => { + supervisor.lock().await.shutdown_children().await; + return Err(error); + } + }; supervisor.lock().await.switch_env_store(env_store).await; } else if reset_children { supervisor.lock().await.shutdown_children().await; @@ -321,6 +327,7 @@ async fn wait_for_config( return current.clone(); } let sleep_for = deadline + .filter(|_| !saw_unusable_config) .map(|deadline| { deadline .saturating_duration_since(Instant::now()) @@ -354,6 +361,19 @@ async fn wait_for_connection_change( } } +// A shutdown can cancel run_one_session while any of its tasks are still +// running. Dropping a JoinHandle alone would leave that task detached. +#[derive(Default)] +struct SessionTasks(Vec); + +impl Drop for SessionTasks { + fn drop(&mut self) { + for task in &self.0 { + task.abort(); + } + } +} + /// One connect + drain pass. Returns Ok when the WS closed cleanly (we'll /// reconnect), Err on connect failure. async fn run_one_session( @@ -375,9 +395,11 @@ async fn run_one_session( let (incoming_tx, mut incoming_rx) = mpsc::channel::(64); // Wire the broker before any task can publish a frame. - outgoing.set(outgoing_tx.clone()); + outgoing.set(outgoing_tx); + let mut tasks = SessionTasks::default(); let mut ws_task = tokio::spawn(tunnel::run_frame_loop(ws, outgoing_rx, incoming_tx)); + tasks.0.push(ws_task.abort_handle()); // client_hello: announce which servers we already have running so the // backend can reconcile. @@ -420,6 +442,8 @@ async fn run_one_session( tokio::spawn(heartbeat(outgoing, last_pong, keep_awake.clone())) }; + tasks.0.push(hb_task.abort_handle()); + // Children that exit on their own are started again, with backoff // (Supervisor::respawn_exited). Only after server_hello: a respawn sends // frames the backend refuses before it has registered the device, and the @@ -443,6 +467,8 @@ async fn run_one_session( }) }; + tasks.0.push(respawn_task.abort_handle()); + let session = SessionContext { keep_awake, target: ReportTarget { @@ -453,7 +479,7 @@ async fn run_one_session( sent: keep_awake_sent, resume_sent, }; - let result = tokio::select! { + tokio::select! { biased; r = drain_incoming(supervisor.clone(), &mut incoming_rx, last_pong, writer, &hello_tx, &session) => match r { Ok(()) => websocket_task_result(&mut ws_task).await, @@ -471,12 +497,7 @@ async fn run_one_session( info!("configuration changed; restarting authenticated session"); Ok(()) } - }; - hb_task.abort(); - respawn_task.abort(); - ws_task.abort(); - drop(outgoing_tx); - result + } } async fn websocket_task_result(task: &mut tokio::task::JoinHandle>) -> Result<()> { diff --git a/crates/stdiod/crates/sealgate-stdiod/src/daemon_auth.rs b/crates/stdiod/crates/sealgate-stdiod/src/daemon_auth.rs index 0704bfb..f7eea8e 100644 --- a/crates/stdiod/crates/sealgate-stdiod/src/daemon_auth.rs +++ b/crates/stdiod/crates/sealgate-stdiod/src/daemon_auth.rs @@ -6,7 +6,7 @@ use thiserror::Error; use crate::{config, tunnel}; -#[derive(Debug, Args, Clone)] +#[derive(Debug, Args, Clone, Default)] pub struct RunArgs { /// Backend base URL (http://localhost:8000, https://dashboard.sealgate.ai, ...). /// Falls back to `backend_url` in `~/.config/sealgate-stdiod/config.toml`. diff --git a/crates/stdiod/crates/sealgate-stdiod/src/daemon_profiles.rs b/crates/stdiod/crates/sealgate-stdiod/src/daemon_profiles.rs new file mode 100644 index 0000000..9472753 --- /dev/null +++ b/crates/stdiod/crates/sealgate-stdiod/src/daemon_profiles.rs @@ -0,0 +1,109 @@ +//! Discovery and lifecycle of backend sessions in one daemon process. + +use std::collections::HashSet; +use std::time::Duration; + +use anyhow::Result; +use tokio::sync::watch; +use tokio::time::sleep; +use tracing::{warn, Instrument}; + +use crate::config::PersistedConfig; +use crate::daemon_auth::RunArgs; +use crate::{daemon, paths}; + +const PROFILE_POLL_INTERVAL: Duration = Duration::from_secs(1); +const PROFILE_RETRY_DELAY: Duration = Duration::from_secs(10); + +pub async fn run(args: RunArgs) -> Result<()> { + #[cfg(windows)] + crate::platform::windows::kill_children_on_exit(); + crate::proc::init_child_env().await; + + let (shutdown, signal) = watch::channel(false); + let mut sessions = tokio::task::JoinSet::new(); + let mut active_profiles = HashSet::new(); + let mut poll = tokio::time::interval(PROFILE_POLL_INTERVAL); + let stop = crate::process_shutdown::wait(); + tokio::pin!(stop); + + let outcome = loop { + tokio::select! { + _ = &mut stop => break Ok(()), + _ = poll.tick() => { + // The default may be waiting for its first login. A named + // profile joins the daemon only after its config is saved. + if active_profiles.insert(None) { + sessions.spawn(run_profile(None, args.clone(), signal.clone())); + } + match paths::profile_names() { + Ok(names) => { + for name in names { + let profile = Some(name); + if active_profiles.insert(profile.clone()) { + sessions.spawn(run_profile(profile, RunArgs::default(), signal.clone())); + } + } + } + Err(error) => warn!(%error, "could not discover backend profiles"), + } + } + Some(result) = sessions.join_next() => { + // A session exits normally only after shutdown is requested. + // A panic is a daemon failure so the service manager can restart it. + if let Err(error) = result { + break Err(error.into()); + } + }, + } + }; + + shutdown.send_replace(true); + while let Some(result) = sessions.join_next().await { + result?; + } + outcome +} + +async fn run_profile(profile: Option, args: RunArgs, signal: watch::Receiver) { + let span = tracing::info_span!( + "backend_session", + profile = profile.as_deref().unwrap_or("default") + ); + paths::with_profile(profile, async { + loop { + match daemon::run_backend(args.clone(), signal.clone()).await { + Ok(()) => return, + Err(error) => warn!(%error, "backend session stopped; will retry"), + } + tokio::select! { + _ = sleep(PROFILE_RETRY_DELAY) => {} + _ = wait_for_shutdown(signal.clone()) => return, + } + } + }) + .instrument(span) + .await; +} + +pub(crate) async fn wait_for_shutdown(mut signal: watch::Receiver) { + let _ = signal.wait_for(|shutdown| *shutdown).await; +} + +/// A single installed daemon can start with any usable backend profile. +pub fn ensure_daemon_installable() -> Result<()> { + let default = PersistedConfig::load().and_then(|config| config.ensure_installable()); + if default.is_ok() { + return default; + } + for name in paths::profile_names()? { + let path = paths::profile_dir(&name)?.join("config.toml"); + if PersistedConfig::load_from(&path) + .and_then(|config| config.ensure_installable()) + .is_ok() + { + return Ok(()); + } + } + default +} diff --git a/crates/stdiod/crates/sealgate-stdiod/src/main.rs b/crates/stdiod/crates/sealgate-stdiod/src/main.rs index 6cc7ff4..7a6873f 100644 --- a/crates/stdiod/crates/sealgate-stdiod/src/main.rs +++ b/crates/stdiod/crates/sealgate-stdiod/src/main.rs @@ -16,6 +16,7 @@ mod cli; mod config; mod daemon; mod daemon_auth; +mod daemon_profiles; mod env_store; mod http; mod machine_id; @@ -46,6 +47,9 @@ pub const DAEMON_VERSION: &str = env!("SEALGATE_DAEMON_VERSION"); struct Cli { #[command(subcommand)] command: Command, + /// Select a named backend profile for login, logout, status, keep-awake or server. + #[arg(long, global = true, value_parser = paths::validate_profile)] + profile: Option, /// For the Windows setup program, which runs a step in the background and /// follows it through files (src/setup/stepio.rs): exit (code 130) as soon /// as this file exists. @@ -62,7 +66,7 @@ struct Cli { #[derive(Debug, Subcommand)] enum Command { /// Run the daemon in the foreground. v1 MVP entry point. - Run(daemon::RunArgs), + Run(daemon_auth::RunArgs), /// Authorize this device in a browser and persist its client credential. Login(cli::login::LoginArgs), /// Revoke the current client credential and remove local account bindings. @@ -118,6 +122,23 @@ fn open_daemon_log() -> Option { #[tokio::main] async fn main() -> anyhow::Result<()> { let cli = Cli::parse(); + if let Some(profile) = &cli.profile { + match &cli.command { + Command::Login(_) => {} + Command::Logout(_) + | Command::Status(_) + | Command::KeepAwake(_) + | Command::Server(_) => { + let config = paths::profile_dir(profile)?.join("config.toml"); + if !config.try_exists()? { + anyhow::bail!("profile '{profile}' does not exist. Run `sealgate-stdiod login --profile {profile} --backend `."); + } + } + _ => anyhow::bail!( + "--profile is available for login, logout, status, keep-awake and server" + ), + } + } if let Some(path) = &cli.output_file { if let Err(e) = setup::stepio::redirect_output(path) { eprintln!("could not write output to {}: {e}", path.display()); @@ -170,20 +191,25 @@ async fn main() -> anyhow::Result<()> { .init(), } - let result = match cli.command { - Command::Run(args) => daemon::run(args).await, - Command::Login(args) => cli::login::run(args).await, - Command::Logout(args) => cli::logout::run(args).await, - Command::Install(args) => cli::install::install(args), - Command::Uninstall(args) => cli::install::uninstall(args), - Command::Restart(args) => cli::install::restart(args), - Command::Status(args) => cli::status::run(args), - Command::Logs(args) => cli::logs::run(args), - Command::Update(args) => cli::update::run(args).await, - Command::KeepAwake(args) => cli::keep_awake::run(args), - Command::Server(args) => cli::server::run(cli::server::ServerArgs { command: args }).await, - Command::Setup(command) => setup::stepio::exit(setup::run(command).await), - }; + let result = paths::with_profile(cli.profile, async { + match cli.command { + Command::Run(args) => daemon_profiles::run(args).await, + Command::Login(args) => cli::login::run(args).await, + Command::Logout(args) => cli::logout::run(args).await, + Command::Install(args) => cli::install::install(args), + Command::Uninstall(args) => cli::install::uninstall(args), + Command::Restart(args) => cli::install::restart(args), + Command::Status(args) => cli::status::run(args), + Command::Logs(args) => cli::logs::run(args), + Command::Update(args) => cli::update::run(args).await, + Command::KeepAwake(args) => cli::keep_awake::run(args), + Command::Server(args) => { + cli::server::run(cli::server::ServerArgs { command: args }).await + } + Command::Setup(command) => setup::stepio::exit(setup::run(command).await), + } + }) + .await; // With an exit-code file, every way out records its code, errors included. if setup::stepio::has_exit_code_file() { match result { diff --git a/crates/stdiod/crates/sealgate-stdiod/src/paths.rs b/crates/stdiod/crates/sealgate-stdiod/src/paths.rs index 5053825..b5bdf24 100644 --- a/crates/stdiod/crates/sealgate-stdiod/src/paths.rs +++ b/crates/stdiod/crates/sealgate-stdiod/src/paths.rs @@ -6,6 +6,7 @@ //! ~/.config/sealgate-stdiod/ //! config.toml backend URL + credentials (mode 0600) //! state.json live connection + child snapshot for the tray +//! profiles// separate config, state and server environment per backend //! ~/Library/Logs/sealgate-stdiod/ (macOS) //! ~/.local/state/sealgate-stdiod/ (Linux, XDG_STATE_HOME) //! daemon.log rotated by the supervisor unit @@ -16,21 +17,88 @@ //! platform-specific accessor isn't available, so the daemon never crashes //! on an exotic environment - it just lands files under `~/.sealgate-stdiod/`. -use std::path::PathBuf; +use std::{future::Future, path::PathBuf}; use anyhow::{anyhow, Result}; -/// Returns `~/.config/sealgate-stdiod/`, creating the directory if it -/// doesn't already exist. +// Scope synchronous CLI and session file lookups to a profile. Spawned +// workers receive resolved paths or stores because task locals do not propagate. +tokio::task_local! { + static PROFILE: String; +} + +pub fn validate_profile(name: &str) -> Result { + if (1..=48).contains(&name.len()) + && name.as_bytes()[0].is_ascii_lowercase() + && name + .bytes() + .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-') + { + Ok(name.to_owned()) + } else { + Err("use 1–48 lowercase letters, digits or hyphens, starting with a letter".into()) + } +} + +pub async fn with_profile(profile: Option, work: impl Future) -> T { + match profile { + Some(profile) => PROFILE.scope(profile, work).await, + None => work.await, + } +} + +pub fn profile_name() -> Option { + PROFILE.try_with(Clone::clone).ok() +} + +pub const PROFILES_DIRECTORY: &str = "profiles"; + +pub fn profile_dir(name: &str) -> Result { + Ok(root_config_dir()?.join(PROFILES_DIRECTORY).join(name)) +} + +pub fn profile_names() -> Result> { + let directory = root_config_dir()?.join(PROFILES_DIRECTORY); + let entries = match std::fs::read_dir(directory) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(error) => return Err(error.into()), + }; + let mut names = Vec::new(); + for entry in entries { + let entry = entry?; + if entry.file_type()?.is_dir() && entry.path().join("config.toml").is_file() { + if let Some(name) = entry + .file_name() + .to_str() + .and_then(|name| validate_profile(name).ok()) + { + names.push(name); + } + } + } + names.sort(); + Ok(names) +} + +fn root_config_dir() -> Result { + let home = + dirs::home_dir().ok_or_else(|| anyhow!("could not resolve home dir; HOME not set?"))?; + Ok(home.join(".config").join("sealgate-stdiod")) +} + +/// Returns the default config directory, or the selected named profile's +/// directory under `profiles/`. Only the default directory is created here. /// /// We pin to `~/.config/` on every platform (including macOS, where the /// OS convention is `~/Library/Application Support/`) so the docs in /// ARCHITECTURE.md can name a single canonical path /// and so admins shelling into a user's machine know where to look. pub fn config_dir() -> Result { - let home = - dirs::home_dir().ok_or_else(|| anyhow!("could not resolve home dir; HOME not set?"))?; - let dir = home.join(".config").join("sealgate-stdiod"); + if let Some(profile) = profile_name() { + return profile_dir(&profile); + } + let dir = root_config_dir()?; std::fs::create_dir_all(&dir)?; Ok(dir) } diff --git a/crates/stdiod/crates/sealgate-stdiod/src/platform/linux.rs b/crates/stdiod/crates/sealgate-stdiod/src/platform/linux.rs index 36d714a..b569068 100644 --- a/crates/stdiod/crates/sealgate-stdiod/src/platform/linux.rs +++ b/crates/stdiod/crates/sealgate-stdiod/src/platform/linux.rs @@ -133,8 +133,7 @@ pub fn install() -> Result<()> { // Refuse to install without credentials - the daemon would just spin in // a reconnect loop. Surface it now, not later in the logs. (Mirrors the // macOS path.) - let cfg = crate::config::PersistedConfig::load()?; - cfg.ensure_installable()?; + crate::daemon_profiles::ensure_daemon_installable()?; if !systemd_user_available() { return Err(anyhow!( diff --git a/crates/stdiod/crates/sealgate-stdiod/src/platform/macos.rs b/crates/stdiod/crates/sealgate-stdiod/src/platform/macos.rs index d191473..4c21415 100644 --- a/crates/stdiod/crates/sealgate-stdiod/src/platform/macos.rs +++ b/crates/stdiod/crates/sealgate-stdiod/src/platform/macos.rs @@ -351,8 +351,7 @@ pub fn install() -> Result<()> { // Refuse to install if there are no credentials on disk - the daemon // would just spin in a reconnect loop. The user sees this error // immediately rather than discovering it in the logs later. - let cfg = crate::config::PersistedConfig::load()?; - cfg.ensure_installable()?; + crate::daemon_profiles::ensure_daemon_installable()?; let binary = std::env::current_exe().context("could not resolve current exe path")?; let log = paths::daemon_log_file()?; diff --git a/crates/stdiod/crates/sealgate-stdiod/src/platform/windows.rs b/crates/stdiod/crates/sealgate-stdiod/src/platform/windows.rs index a1869af..bceedd4 100644 --- a/crates/stdiod/crates/sealgate-stdiod/src/platform/windows.rs +++ b/crates/stdiod/crates/sealgate-stdiod/src/platform/windows.rs @@ -160,8 +160,7 @@ fn schtasks(args: &[&str]) -> Result { pub fn install() -> Result<()> { // Refuse to install without credentials - the daemon would just spin in a // reconnect loop. Surface the error now, not later in the logs. - let cfg = crate::config::PersistedConfig::load()?; - cfg.ensure_installable()?; + crate::daemon_profiles::ensure_daemon_installable()?; let binary = std::env::current_exe().context("could not resolve current exe path")?; let user = current_user(); diff --git a/crates/stdiod/crates/sealgate-stdiod/src/power/controller.rs b/crates/stdiod/crates/sealgate-stdiod/src/power/controller.rs index 5bac405..d10ec5d 100644 --- a/crates/stdiod/crates/sealgate-stdiod/src/power/controller.rs +++ b/crates/stdiod/crates/sealgate-stdiod/src/power/controller.rs @@ -19,7 +19,7 @@ //! next `client_hello` can say that the last disconnect was a sleep. use std::sync::mpsc::{self, RecvTimeoutError}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, Weak}; use std::time::{Duration, Instant}; use tracing::{debug, info, warn}; @@ -82,7 +82,7 @@ enum ReportResult { /// Handle to the controller thread. Cheap to clone. #[derive(Clone)] pub struct KeepAwake { - events: mpsc::Sender, + events: Arc>, status: Arc>, resume: Arc, /// False where keep-awake is not offered (every OS except Windows). The @@ -96,10 +96,14 @@ impl KeepAwake { /// the backend sends one, and its local choice applies while /// `config.toml` cannot be read. Returns after the first decision, so the /// first `client_hello` already carries the real state. - pub fn start(previous: Option, writer: StateWriter) -> Self { + pub fn start( + previous: Option, + writer: StateWriter, + config_path: std::path::PathBuf, + ) -> Self { Self::start_with( super::platform(), - super::read_local_choice, + move || super::read_local_choice(&config_path), previous.is_some_and(|status| status.desired), previous.map(|status| status.local).unwrap_or_default(), writer, @@ -108,7 +112,7 @@ impl KeepAwake { pub(crate) fn start_with( platform: Option>, - read_local: fn() -> Result, + read_local: impl Fn() -> Result + Send + 'static, initial_desired: bool, initial_local: LocalChoice, writer: StateWriter, @@ -120,7 +124,7 @@ impl KeepAwake { effective: Effective::Inactive, })); let handle = Self { - events, + events: Arc::new(events), status: status.clone(), resume: Arc::new(Resume::new()), enabled: platform.is_some(), @@ -128,9 +132,9 @@ impl KeepAwake { let (ready_tx, ready_rx) = mpsc::channel(); let worker = Worker { platform, - read_local, + read_local: Box::new(read_local), rx, - events: handle.events.clone(), + events: Arc::downgrade(&handle.events), status, resume: handle.resume.clone(), writer, @@ -215,9 +219,9 @@ struct Session { struct Worker { platform: Option>, - read_local: fn() -> Result, + read_local: Box Result + Send>, rx: mpsc::Receiver, - events: mpsc::Sender, + events: Weak>, status: Arc>, resume: Arc, writer: StateWriter, @@ -470,6 +474,9 @@ impl Worker { ReportResult::Failed } }; + let Some(events) = events.upgrade() else { + return; + }; let _ = events.send(Event::Reported { generation, sent: (local, effective), diff --git a/crates/stdiod/crates/sealgate-stdiod/src/power/controller_tests.rs b/crates/stdiod/crates/sealgate-stdiod/src/power/controller_tests.rs index 77e4209..679f593 100644 --- a/crates/stdiod/crates/sealgate-stdiod/src/power/controller_tests.rs +++ b/crates/stdiod/crates/sealgate-stdiod/src/power/controller_tests.rs @@ -271,12 +271,12 @@ fn target() -> ReportTarget { } fn worker() -> Worker { - let (events, rx) = mpsc::channel(); + let (_, rx) = mpsc::channel(); Worker { platform: Some(Box::new(Fake::default())), - read_local: auto, + read_local: Box::new(auto), rx, - events, + events: Weak::new(), status: Arc::new(Mutex::new(KeepAwakeStatus { local: LocalChoice::Auto, desired: false, diff --git a/crates/stdiod/crates/sealgate-stdiod/src/power/mod.rs b/crates/stdiod/crates/sealgate-stdiod/src/power/mod.rs index 17044a1..6e68202 100644 --- a/crates/stdiod/crates/sealgate-stdiod/src/power/mod.rs +++ b/crates/stdiod/crates/sealgate-stdiod/src/power/mod.rs @@ -219,12 +219,11 @@ fn lock_with( /// cannot be read or parsed, is an error, so that the controller keeps its /// last choice instead of switching an explicit `on` or `off` to `auto`. /// On Windows, saving the file leaves a moment in which it is missing. -pub fn read_local_choice() -> Result { - let path = crate::paths::config_file().map_err(|error| format!("{error:#}"))?; +pub fn read_local_choice(path: &std::path::Path) -> Result { if !path.exists() { return Err(format!("{} is missing", path.display())); } - crate::config::PersistedConfig::load_from(&path) + crate::config::PersistedConfig::load_from(path) .map(|config| config.power.keep_awake()) .map_err(|error| format!("{error:#}")) } diff --git a/crates/stdiod/crates/sealgate-stdiod/src/state.rs b/crates/stdiod/crates/sealgate-stdiod/src/state.rs index b301d19..69155ff 100644 --- a/crates/stdiod/crates/sealgate-stdiod/src/state.rs +++ b/crates/stdiod/crates/sealgate-stdiod/src/state.rs @@ -145,13 +145,12 @@ impl State { #[derive(Clone)] pub struct StateWriter { inner: Arc>, - /// Where to write. `None` resolves [`paths::state_file`] at write time, - /// which is what the daemon does; tests set an explicit path so they can - /// assert on the bytes that reach disk. + /// The daemon pins the path so worker tasks and threads write to their profile. path: Option, } impl StateWriter { + #[cfg(all(test, unix))] pub fn new(initial: State) -> Self { Self { inner: Arc::new(Mutex::new(initial)), @@ -160,7 +159,6 @@ impl StateWriter { } /// A writer pinned to `path` instead of the per-user config dir. - #[cfg(test)] pub fn new_at(initial: State, path: PathBuf) -> Self { Self { inner: Arc::new(Mutex::new(initial)), @@ -186,14 +184,10 @@ impl StateWriter { let mut guard = self.inner.lock().await; f(&mut guard); guard.generation = guard.generation.saturating_add(1); - let path = match self.path.clone().map(Ok).unwrap_or_else(paths::state_file) { - Ok(p) => p, - Err(e) => { - debug!(error = %e, "state.json: cannot resolve path; skipping write"); - return; - } + let Some(path) = &self.path else { + return; }; - if let Err(e) = guard.write_atomic(&path) { + if let Err(e) = guard.write_atomic(path) { debug!(error = %e, "state.json: write failed; skipping"); } } diff --git a/crates/stdiod/crates/sealgate-stdiod/tests/multiple_backends.rs b/crates/stdiod/crates/sealgate-stdiod/tests/multiple_backends.rs new file mode 100644 index 0000000..82d2858 --- /dev/null +++ b/crates/stdiod/crates/sealgate-stdiod/tests/multiple_backends.rs @@ -0,0 +1,168 @@ +#![cfg(unix)] + +use std::{path::Path, process::Stdio, time::Duration}; + +use futures_util::{SinkExt, StreamExt}; +use sealgate_tunnel_protocol::PROTOCOL_VERSION; +use tokio::{ + net::{TcpListener, TcpStream}, + process::Command, + time::{sleep, timeout}, +}; +use tokio_tungstenite::{ + accept_hdr_async, + tungstenite::{ + handshake::server::{Request, Response}, + Message, + }, + WebSocketStream, +}; + +struct TestHome(std::path::PathBuf); + +impl Drop for TestHome { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn cli(home: &Path) -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_sealgate-stdiod")); + command + .env("HOME", home) + .env_remove("SEALGATE_BACKEND_URL") + .env_remove("SEALGATE_API_KEY") + .env_remove("SEALGATE_DEVICE_ID") + .env_remove("SEALGATE_DEVICE_LABEL") + .kill_on_drop(true); + command +} + +async fn login(home: &Path, backend: &TcpListener, key: &str, profile: &[&str]) { + let output = cli(home) + .args([ + "login", + "--backend", + &format!("http://{}", backend.local_addr().unwrap()), + "--api-key", + key, + ]) + .args(profile) + .output() + .await + .unwrap(); + assert!(output.status.success(), "{output:?}"); +} + +// The WebSocket handshake callback fixes the error type. +#[allow(clippy::result_large_err)] +async fn handshake(listener: &TcpListener, key: &str) -> WebSocketStream { + let (stream, _) = listener.accept().await.unwrap(); + let mut ws = accept_hdr_async(stream, |request: &Request, response: Response| { + assert_eq!(request.headers()["authorization"], format!("Bearer {key}")); + Ok(response) + }) + .await + .unwrap(); + let hello = ws.next().await.unwrap().unwrap(); + let hello: serde_json::Value = serde_json::from_str(hello.to_text().unwrap()).unwrap(); + assert_eq!(hello["type"], "client_hello"); + ws.send(Message::text( + serde_json::json!({ + "type": "server_hello", "protocol_version": PROTOCOL_VERSION, "servers": [], + }) + .to_string(), + )) + .await + .unwrap(); + ws +} + +async fn wait_for_state(path: &Path, expected: &str, pid: u32, backend: &TcpListener) { + loop { + if let Ok(raw) = std::fs::read_to_string(path) { + let state: serde_json::Value = serde_json::from_str(&raw).unwrap(); + if state["connection_state"] == expected { + assert_eq!(state["pid"], pid); + assert_eq!( + state["backend_url"], + format!("http://{}", backend.local_addr().unwrap()) + ); + return; + } + } + sleep(Duration::from_millis(25)).await; + } +} + +#[tokio::test] +async fn discovers_a_second_backend_without_replacing_the_first_session() { + timeout(Duration::from_secs(15), async { + let home = + TestHome(std::env::temp_dir().join(format!("stdiod-profiles-{}", std::process::id()))); + std::fs::create_dir(&home.0).unwrap(); + let default = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let staging = TcpListener::bind("127.0.0.1:0").await.unwrap(); + login(&home.0, &default, "default-test-key", &[]).await; + let mut daemon = cli(&home.0) + .arg("run") + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let pid = daemon.id().unwrap(); + let mut default_ws = handshake(&default, "default-test-key").await; + + let config = home.0.join(".config/sealgate-stdiod"); + let missing = cli(&home.0) + .args(["logout", "--profile", "missing"]) + .output() + .await + .unwrap(); + assert!(!missing.status.success()); + assert!(!config.join("profiles/missing").exists()); + + let default_state = config.join("state.json"); + let staging_state = config.join("profiles/staging/state.json"); + wait_for_state(&default_state, "connected", pid, &default).await; + + login( + &home.0, + &staging, + "staging-test-key", + &["--profile", "staging"], + ) + .await; + let mut staging_ws = handshake(&staging, "staging-test-key").await; + wait_for_state(&staging_state, "connected", pid, &staging).await; + + let logout = cli(&home.0) + .args(["logout", "--profile", "staging"]) + .output() + .await + .unwrap(); + assert!(logout.status.success(), "{logout:?}"); + wait_for_state(&staging_state, "needs_reauth", pid, &staging).await; + loop { + match staging_ws.next().await { + Some(Ok(message)) if !message.is_close() => {} + _ => break, + } + } + default_ws + .send(Message::text(r#"{"type":"ping"}"#)) + .await + .unwrap(); + loop { + let message = default_ws.next().await.unwrap().unwrap(); + let frame: serde_json::Value = + serde_json::from_str(message.to_text().unwrap()).unwrap(); + if frame["type"] == "pong" { + break; + } + } + wait_for_state(&default_state, "connected", pid, &default).await; + daemon.kill().await.unwrap(); + }) + .await + .expect("daemon did not complete the two-backend scenario"); +} diff --git a/packages/desktop/src/main/stdiod/controller.ts b/packages/desktop/src/main/stdiod/controller.ts index cd4d672..82ba3bf 100644 --- a/packages/desktop/src/main/stdiod/controller.ts +++ b/packages/desktop/src/main/stdiod/controller.ts @@ -281,13 +281,16 @@ export async function login(input: StdiodLoginInput): Promise { } } -export async function uninstall(opts: { purge?: boolean } = {}): Promise { +export async function uninstall( + opts: { purge?: boolean; keepProfiles?: boolean } = {} +): Promise { if (dryRun()) return { ok: true } const missing = await ensureBinary() if (missing) return missing invalidateInstalledCache() const args = ['uninstall'] if (opts.purge) args.push('--purge') + if (opts.purge && opts.keepProfiles) args.push('--keep-profiles') stdiodLog(`uninstall: purge=${Boolean(opts.purge)}`) try { const result = await runStdiod(args) @@ -327,10 +330,9 @@ export async function resetStdiod(input: StdiodLoginInput): Promise { title: 'Reset Local Tunnel', message: 'Reset the local stdio tunnel daemon?', detail: - 'This stops the daemon, wipes its local config, state, and logs, then ' + + 'This stops the daemon, clears the default sign-in, connection state, and logs, then ' + 're-registers and restarts it with your current credentials. Tunneled ' + 'servers reconnect automatically. Use this if the tunnel is stuck or ' + 'failed to start.'