diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 16e658f8f3..f00ed5fff4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,6 +25,7 @@ jobs: timeout-minutes: 5 outputs: rust: ${{ steps.groups.outputs.rust }} + sharing: ${{ steps.groups.outputs.sharing }} windows: ${{ steps.groups.outputs.windows }} windows_native: ${{ steps.groups.outputs.windows_native }} static: ${{ steps.groups.outputs.static }} @@ -103,7 +104,7 @@ jobs: cargo run --locked -p xtask-check windows-cli: needs: changes - if: needs.changes.outputs.windows == 'true' || needs.changes.outputs.windows_native == 'true' + if: needs.changes.outputs.windows == 'true' || needs.changes.outputs.windows_native == 'true' || needs.changes.outputs.sharing == 'true' runs-on: [self-hosted, windows, x64] timeout-minutes: 15 env: @@ -125,8 +126,11 @@ jobs: run: '& "$env:GITHUB_WORKSPACE\scripts\ci-windows-target.ps1"' - name: Verify native Windows CLI boundaries run: cargo test --locked -p dim-cli --lib + - name: Verify independent shared RPC streams on native Windows pipes + if: needs.changes.outputs.sharing == 'true' + run: cargo test --locked -p dim-terminal-transport --test windows_pipe_flow - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 - if: needs.changes.outputs.windows_native == 'true' + if: needs.changes.outputs.windows_native == 'true' || needs.changes.outputs.sharing == 'true' with: node-version-file: .node-version package-manager-cache: false @@ -134,7 +138,7 @@ jobs: # aws-lc-sys builds C sources on Windows x64 and needs NASM and CMake. # The self-hosted runner has no installer rights, so unpack pinned # portable archives under RUNNER_TEMP and expose them to this job only. - if: needs.changes.outputs.windows_native == 'true' + if: needs.changes.outputs.windows_native == 'true' || needs.changes.outputs.sharing == 'true' shell: powershell env: CMAKE_VERSION: '3.31.6' @@ -147,6 +151,27 @@ jobs: if: needs.changes.outputs.windows_native == 'true' shell: powershell run: node scripts/test-windows-native.mjs + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 + if: needs.changes.outputs.sharing == 'true' + with: + go-version-file: runtime/native-sharing/go.mod + cache: false + - name: Verify shared daemon shutdown from the Windows CLI + if: needs.changes.outputs.sharing == 'true' + shell: powershell + run: | + cargo build --locked -p dimcode -p dim-terminal-transport -p dim-app-server --bin dimcode --bin dim-terminal-transport --example sharing-shutdown-fixture + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $bin = New-Item -ItemType Directory (Join-Path $env:RUNNER_TEMP ([guid]::NewGuid())) + try { + Copy-Item "$env:CARGO_TARGET_DIR/debug/dimcode.exe", "$env:CARGO_TARGET_DIR/debug/dim-terminal-transport.exe" $bin.FullName + node scripts/build-sharing.mjs $bin.FullName + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $env:DIM_SHARING_TEST_CLI = Join-Path $bin.FullName 'dimcode.exe' + node --test scripts/native-sharing-flow.mjs + } finally { + Remove-Item -Recurse -Force $bin.FullName + } web: needs: changes if: needs.changes.outputs.web == 'true' @@ -374,6 +399,23 @@ jobs: - name: Verify downloaded Node runtime if: needs.changes.outputs.node == 'true' && github.event_name != 'pull_request' run: node scripts/run-rust-test.mjs target/test-artifacts.jsonl transport_flow runtime_manager::runtime_switches_from_system_to_downloaded_node --ignored --exact + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 + if: needs.changes.outputs.sharing == 'true' + with: + go-version-file: runtime/native-sharing/go.mod + cache: false + - name: Verify native sharing and App Server protocol parity + if: needs.changes.outputs.sharing == 'true' + shell: bash + run: | + set -euo pipefail + (cd runtime/native-sharing && go test -mod=readonly -race ./...) + bin=$(mktemp -d) + trap 'rm -rf "$bin"' EXIT + cp target/debug/{dimcode,dim-terminal-transport} "$bin/" + node scripts/build-sharing.mjs "$bin" + cargo build --locked -p dim-app-server --example sharing-shutdown-fixture + DIM_SHARING_TEST_CLI="$bin/dimcode" node --test scripts/native-sharing-flow.mjs macos-native: needs: changes if: (github.event_name == 'pull_request' && needs.changes.outputs.rust == 'true') || needs.changes.outputs.macos_scripts == 'true' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 652ce892b2..89ab86d304 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -179,6 +179,11 @@ jobs: node-version-file: .node-version architecture: ${{ runner.arch == 'ARM64' && 'arm64' || 'x64' }} package-manager-cache: false + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 + if: hashFiles('runtime/native-sharing/go.mod') != '' + with: + go-version-file: runtime/native-sharing/go.mod + cache-dependency-path: runtime/native-sharing/go.sum - name: Check native build host and disk space shell: bash run: | @@ -259,10 +264,16 @@ jobs: else cargo build --release --locked --target "$DIM_BUILD_TARGET" -p dimcode fi + if [[ -f runtime/native-sharing/go.mod ]]; then + cargo build --release --locked --target "$DIM_BUILD_TARGET" -p dim-terminal-transport + fi "$BIN_DIR/dimcode" --version ' else DIM_RELEASE_BUILD=1 cargo build --release --locked --target "$DIM_BUILD_TARGET" -p dimcode + if [[ -f runtime/native-sharing/go.mod ]]; then + cargo build --release --locked --target "$DIM_BUILD_TARGET" -p dim-terminal-transport + fi fi echo "DIM_BIN_DIR=$PWD/$bin_dir" >> "$GITHUB_ENV" - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 @@ -279,7 +290,13 @@ jobs: set -euo pipefail if [[ "$RUNNER_OS" == Windows ]]; then export PATH="$(cygpath -u "$WINDIR")/System32:$PATH"; fi node scripts/stage-plugins.mjs "staging/plugins-$DIM_BUILD_PLATFORM" - node scripts/stage-release.mjs "$DIM_BIN_DIR" "staging/$DIM_BUILD_PLATFORM" "$RELEASE_VERSION" "$SOURCE_SHA" --account --plugins "staging/plugins-$DIM_BUILD_PLATFORM" --rust-notices staging/rust-notices.txt + sharing=() + if [[ -f runtime/native-sharing/go.mod ]]; then + sharing_dir="target/$DIM_BUILD_TARGET/release" + node scripts/build-sharing.mjs "$sharing_dir" + sharing=(--sharing "$sharing_dir") + fi + node scripts/stage-release.mjs "$DIM_BIN_DIR" "staging/$DIM_BUILD_PLATFORM" "$RELEASE_VERSION" "$SOURCE_SHA" --account --plugins "staging/plugins-$DIM_BUILD_PLATFORM" --rust-notices staging/rust-notices.txt "${sharing[@]}" node scripts/pack-release.mjs "staging/$DIM_BUILD_PLATFORM" "release/$DIM_BUILD_PLATFORM" - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: diff --git a/Cargo.lock b/Cargo.lock index 8d6277c385..ce25f43136 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -358,7 +358,7 @@ dependencies = [ "serde_json", "serde_path_to_error", "serde_urlencoded", - "sha1", + "sha1 0.10.7", "sync_wrapper", "tokio", "tokio-tungstenite 0.29.0", @@ -1207,6 +1207,7 @@ dependencies = [ "dim-agent-runtime", "dim-agent-types", "dim-app-server", + "dim-client", "dim-codemode", "dim-modality", "encoding_rs", @@ -1308,6 +1309,7 @@ dependencies = [ "tempfile", "tokio", "url", + "windows-sys 0.61.2", ] [[package]] @@ -1580,6 +1582,24 @@ dependencies = [ "uuid", ] +[[package]] +name = "dim-terminal-transport" +version = "0.1.0-alpha.29" +dependencies = [ + "base64 0.22.1", + "dim-client", + "libc", + "rutis", + "rutis-bridge", + "rutis-host", + "serde", + "serde_json", + "tempfile", + "tokio", + "tokio-util", + "uuid", +] + [[package]] name = "dimcode" version = "0.1.0-alpha.29" @@ -4210,19 +4230,44 @@ version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc5b5671633d5054a4b4a1ba34d1560b98fd9e2b871383db314386824c811f0d" dependencies = [ + "futures-util", "getrandom 0.2.17", "libc", + "rustls", + "rustls-native-certs", "rutis", "serde", "serde_json", "sha2 0.10.9", "shuttle", + "socket2", "tempfile", "thiserror 2.0.20", "tokio", + "tokio-rustls", + "tokio-tungstenite 0.30.0", "windows-sys 0.61.2", ] +[[package]] +name = "rutis-host" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "574e0ab16bbe8504a6d8a9638695e58a8cbdb901f07d09b91dc05dfae003502d" +dependencies = [ + "libc", + "rustls-pki-types", + "rutis", + "rutis-bridge", + "rutis-loader", + "rutis-types", + "serde", + "serde_json", + "shuttle", + "tokio", + "url", +] + [[package]] name = "rutis-loader" version = "0.23.0" @@ -4525,6 +4570,17 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "digest 0.11.3", +] + [[package]] name = "sha2" version = "0.10.9" @@ -5193,6 +5249,18 @@ dependencies = [ "tungstenite 0.29.0", ] +[[package]] +name = "tokio-tungstenite" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17a073bfed563fa236697a068031408a93cd9522e08abf9933ead3e73411bd71" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite 0.30.0", +] + [[package]] name = "tokio-util" version = "0.7.19" @@ -5384,7 +5452,7 @@ dependencies = [ "rand 0.8.8", "rustls", "rustls-pki-types", - "sha1", + "sha1 0.10.7", "thiserror 1.0.69", "utf-8", ] @@ -5401,7 +5469,23 @@ dependencies = [ "httparse", "log", "rand 0.9.5", - "sha1", + "sha1 0.10.7", + "thiserror 2.0.20", +] + +[[package]] +name = "tungstenite" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e48ac77174b19c110a50ab2128b24215ac9cb40e0e12e093fb602d175c569d22" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.10.2", + "sha1 0.11.0", "thiserror 2.0.20", ] diff --git a/Cargo.toml b/Cargo.toml index e52145df4e..1d2dbf152b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "2" -members = ["crates/dim-agent-types", "crates/dim-agent-runtime", "crates/dim-agent-capabilities", "crates/dim-agent-aimux", "crates/dim-agent-attachments", "crates/dim-agent-questions", "crates/dim-agent-scheduler", "crates/dim-event-hub", "crates/dim-app-server", "crates/dim-client", "crates/dim-acp", "crates/dim-cli", "crates/dim-oauth", "crates/dim-session-title", "crates/dim-goal", "crates/dim-report", "crates/dim-codemode", "crates/dim-modality", "crates/dim-image-understanding", "crates/dim-ocr", "crates/dim-modality-aimux", "crates/dimcode", "crates/dim-migration", "xtask", "xtask/check", "tests/extension-a", "tests/extension-b", "tests/integration"] +members = ["crates/dim-agent-types", "crates/dim-agent-runtime", "crates/dim-agent-capabilities", "crates/dim-agent-aimux", "crates/dim-agent-attachments", "crates/dim-agent-questions", "crates/dim-agent-scheduler", "crates/dim-event-hub", "crates/dim-app-server", "crates/dim-client", "crates/dim-terminal-transport", "crates/dim-acp", "crates/dim-cli", "crates/dim-oauth", "crates/dim-session-title", "crates/dim-goal", "crates/dim-report", "crates/dim-codemode", "crates/dim-modality", "crates/dim-image-understanding", "crates/dim-ocr", "crates/dim-modality-aimux", "crates/dimcode", "crates/dim-migration", "xtask", "xtask/check", "tests/extension-a", "tests/extension-b", "tests/integration"] exclude = ["vendor/grok-build"] [workspace.package] diff --git a/crates/dim-app-server/Cargo.toml b/crates/dim-app-server/Cargo.toml index a65e520fe5..8a73044a0a 100644 --- a/crates/dim-app-server/Cargo.toml +++ b/crates/dim-app-server/Cargo.toml @@ -79,6 +79,7 @@ webpki-roots = "1" [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_System_SystemServices", "Win32_System_Threading"] } +dim-client.workspace = true [target.'cfg(unix)'.dependencies] libc = "0.2.189" @@ -111,3 +112,7 @@ flate2 = "1.1" [lints] workspace = true + +[[example]] +name = "sharing-shutdown-fixture" +path = "tests/fixtures/sharing_shutdown.rs" diff --git a/crates/dim-app-server/src/cli.rs b/crates/dim-app-server/src/cli.rs index fd9d8c7365..212d16eace 100644 --- a/crates/dim-app-server/src/cli.rs +++ b/crates/dim-app-server/src/cli.rs @@ -361,6 +361,7 @@ pub fn run_with( { config.startup_timeout = std::time::Duration::from_millis(timeout); } + let mut sharing_helper = None; let mut threads = 2usize; let mut model_config = None; let mut mock_model = false; @@ -383,6 +384,11 @@ pub fn run_with( ) } "--no-ws" => config.websocket_address = None, + "--sharing-helper" => { + sharing_helper = Some(PathBuf::from( + args.next().ok_or("--sharing-helper needs a path")?, + )) + } "--database" => { config.database_path = Some(PathBuf::from( args.next().ok_or("--database requires a path")?, @@ -637,19 +643,46 @@ pub fn run_with( defaults::tool_host(&mut builder, Arc::new(MockTools)); collaboration::install(&mut builder); } + let sharing_home = config.target_home.clone(); let server = serve(builder, config).await?; + let endpoint = server + .unix_path + .clone() + .or_else(|| server.pipe_name.as_ref().map(PathBuf::from)); + let shutdown = server.shutdown_signal(); + let sharing_stop = tokio_util::sync::CancellationToken::new(); + let helper = sharing_helper.or_else(|| { + std::env::current_exe().ok().map(|exe| { + exe.with_file_name(format!("dim-sharing{}", std::env::consts::EXE_SUFFIX)) + }) + }); + let sharing = helper + .filter(|path| path.is_file()) + .zip(sharing_home.zip(endpoint)) + .map(|(helper, (home, endpoint))| { + tokio::spawn(supervise_sharing( + helper, + home, + endpoint, + sharing_stop.clone(), + )) + }); println!( "{}", serde_json::json!({"unixPath": server.unix_path, "pipeName": server.pipe_name, "websocketAddress": server.websocket_address.map(|a| a.to_string())}) ); - let shutdown = server.shutdown_signal(); let join = server.join(); tokio::pin!(join); - tokio::select! { + let result = tokio::select! { result = &mut join => result, signal = tokio::signal::ctrl_c() => { signal?; shutdown.cancel(); join.await }, signal = terminate_signal() => { signal?; shutdown.cancel(); join.await } + }; + sharing_stop.cancel(); + if let Some(task) = sharing { + let _ = task.await; } + result }; let reason = runtime.block_on(operation)?; if reason == ShutdownReason::Forced { @@ -658,6 +691,51 @@ pub fn run_with( Ok(()) } +async fn supervise_sharing( + helper: PathBuf, + home: PathBuf, + endpoint: PathBuf, + stop: tokio_util::sync::CancellationToken, +) { + use std::{process::Stdio, time::Duration}; + let mut command = tokio::process::Command::new(helper); + command + .arg("--home") + .arg(home) + .arg("serve") + .arg(endpoint) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .kill_on_drop(true); + let mut delay = Duration::from_secs(1); + while !stop.is_cancelled() { + match command.spawn() { + Ok(mut child) => { + let lifetime = child.stdin.take(); + tokio::select! { + status = child.wait() => eprintln!("Remote sharing stopped: {status:?}"), + () = stop.cancelled() => { + drop(lifetime); + if tokio::time::timeout(Duration::from_secs(15), child.wait()) + .await + .is_err() + { + let _ = child.kill().await; + } + return; + } + } + } + Err(error) => eprintln!("Remote sharing could not start: {error}"), + } + tokio::select! { + () = stop.cancelled() => return, + () = tokio::time::sleep(delay) => {} + } + delay = (delay * 2).min(Duration::from_secs(60)); + } +} + async fn terminate_signal() -> std::io::Result<()> { #[cfg(unix)] { diff --git a/crates/dim-app-server/src/pipe_client.rs b/crates/dim-app-server/src/pipe_client.rs index b5748c473c..0020231f68 100644 --- a/crates/dim-app-server/src/pipe_client.rs +++ b/crates/dim-app-server/src/pipe_client.rs @@ -6,7 +6,7 @@ pub fn run(name: &str) -> io::Result<()> { .enable_all() .build()?; let result = runtime.block_on(async { - let pipe = match connect(name).await { + let pipe = match dim_client::pipe::connect(name).await { Ok(pipe) => pipe, Err((code, error)) => { writeln!( @@ -32,106 +32,3 @@ pub fn run(name: &str) -> io::Result<()> { runtime.shutdown_background(); result } - -async fn connect( - name: &str, -) -> Result { - use tokio::net::windows::named_pipe::ClientOptions; - use windows_sys::Win32::Foundation::{ERROR_FILE_NOT_FOUND, ERROR_PIPE_BUSY}; - if !name.starts_with(r"\\.\pipe\") || name.len() == r"\\.\pipe\".len() || name.contains('\0') { - return Err(( - "EINVAL", - io::Error::new( - io::ErrorKind::InvalidInput, - "a local named pipe is required", - ), - )); - } - let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5); - let pipe = loop { - match ClientOptions::new().open(name) { - Ok(pipe) => break pipe, - Err(error) => { - let code = match error.raw_os_error().map(|code| code as u32) { - Some(ERROR_PIPE_BUSY) if tokio::time::Instant::now() < deadline => { - tokio::time::sleep(std::time::Duration::from_millis(20)).await; - continue; - } - Some(ERROR_FILE_NOT_FOUND) => "ENOENT", - Some(ERROR_PIPE_BUSY) => "EBUSY", - _ => "EACCES", - }; - return Err((code, error)); - } - } - }; - authenticate(&pipe).map_err(|error| ("EACCES", error))?; - Ok(pipe) -} - -fn authenticate(pipe: &tokio::net::windows::named_pipe::NamedPipeClient) -> io::Result<()> { - use std::{ - mem::size_of, - os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}, - ptr::null_mut, - }; - use windows_sys::Win32::{ - Foundation::{ERROR_INSUFFICIENT_BUFFER, LocalFree}, - Security::{ - Authorization::{GetSecurityInfo, SE_KERNEL_OBJECT}, - EqualSid, GetTokenInformation, OWNER_SECURITY_INFORMATION, TOKEN_QUERY, TOKEN_USER, - TokenUser, - }, - System::Threading::{GetCurrentProcess, OpenProcessToken}, - }; - let mut token = null_mut(); - if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 { - return Err(io::Error::last_os_error()); - } - let _token = unsafe { OwnedHandle::from_raw_handle(token) }; - let mut length = 0; - unsafe { GetTokenInformation(token, TokenUser, null_mut(), 0, &mut length) }; - if io::Error::last_os_error().raw_os_error() != Some(ERROR_INSUFFICIENT_BUFFER as i32) { - return Err(io::Error::last_os_error()); - } - let mut user = vec![0usize; (length as usize).div_ceil(size_of::())]; - if unsafe { - GetTokenInformation( - token, - TokenUser, - user.as_mut_ptr().cast(), - length, - &mut length, - ) - } == 0 - { - return Err(io::Error::last_os_error()); - } - let mut owner = null_mut(); - let mut descriptor = null_mut(); - let status = unsafe { - GetSecurityInfo( - pipe.as_raw_handle(), - SE_KERNEL_OBJECT, - OWNER_SECURITY_INFORMATION, - &mut owner, - null_mut(), - null_mut(), - null_mut(), - &mut descriptor, - ) - }; - if status != 0 { - return Err(io::Error::from_raw_os_error(status as i32)); - } - let same_user = !owner.is_null() - && unsafe { EqualSid(owner, (*user.as_ptr().cast::()).User.Sid) != 0 }; - unsafe { LocalFree(descriptor) }; - if !same_user { - return Err(io::Error::new( - io::ErrorKind::PermissionDenied, - "named pipe is not owned by the current user", - )); - } - Ok(()) -} diff --git a/crates/dim-app-server/src/transport.rs b/crates/dim-app-server/src/transport.rs index 939a500733..3b4f99399a 100644 --- a/crates/dim-app-server/src/transport.rs +++ b/crates/dim-app-server/src/transport.rs @@ -33,7 +33,7 @@ use tokio::{ use tokio_util::sync::CancellationToken; #[cfg(windows)] -use tokio::net::windows::named_pipe::{NamedPipeServer as LocalStream, ServerOptions}; +use tokio::net::windows::named_pipe::NamedPipeServer as LocalStream; #[cfg(unix)] use { std::path::Path, @@ -172,105 +172,6 @@ async fn unix_bind( Ok((listener, owned)) } -#[cfg(windows)] -fn pipe_bind(name: &str, first: bool) -> io::Result { - use std::{ - ffi::c_void, - mem::size_of, - os::windows::io::{FromRawHandle, OwnedHandle}, - ptr::null_mut, - }; - use windows_sys::Win32::{ - Foundation::{ERROR_INSUFFICIENT_BUFFER, LocalFree}, - Security::{ - Authorization::{ - ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, - SDDL_REVISION_1, - }, - GetTokenInformation, SECURITY_ATTRIBUTES, TOKEN_QUERY, TOKEN_USER, TokenUser, - }, - System::Threading::{GetCurrentProcess, OpenProcessToken}, - }; - if !name.starts_with(r"\\.\pipe\") || name.len() == r"\\.\pipe\".len() || name.contains('\0') { - return Err(io::Error::new( - io::ErrorKind::InvalidInput, - "named pipe requires a local \\\\.\\pipe\\ name", - )); - } - struct LocalMemory(*mut c_void); - impl Drop for LocalMemory { - fn drop(&mut self) { - unsafe { LocalFree(self.0) }; - } - } - let mut token = null_mut(); - if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 { - return Err(io::Error::last_os_error()); - } - let _token = unsafe { OwnedHandle::from_raw_handle(token) }; - let mut length = 0; - if unsafe { GetTokenInformation(token, TokenUser, null_mut(), 0, &mut length) } == 0 - && io::Error::last_os_error().raw_os_error() != Some(ERROR_INSUFFICIENT_BUFFER as i32) - { - return Err(io::Error::last_os_error()); - } - let mut user = vec![0usize; (length as usize).div_ceil(size_of::())]; - if unsafe { - GetTokenInformation( - token, - TokenUser, - user.as_mut_ptr().cast(), - length, - &mut length, - ) - } == 0 - { - return Err(io::Error::last_os_error()); - } - let sid = unsafe { (*user.as_ptr().cast::()).User.Sid }; - let mut sid_text = null_mut(); - if unsafe { ConvertSidToStringSidW(sid, &mut sid_text) } == 0 { - return Err(io::Error::last_os_error()); - } - let _sid_text = LocalMemory(sid_text.cast()); - let mut sid_length = 0; - while unsafe { *sid_text.add(sid_length) } != 0 { - sid_length += 1; - } - let sid = String::from_utf16(unsafe { std::slice::from_raw_parts(sid_text, sid_length) }) - .map_err(io::Error::other)?; - let descriptor: Vec = format!("O:{sid}D:P(A;;GA;;;{sid})") - .encode_utf16() - .chain(Some(0)) - .collect(); - let mut security = null_mut(); - if unsafe { - ConvertStringSecurityDescriptorToSecurityDescriptorW( - descriptor.as_ptr(), - SDDL_REVISION_1, - &mut security, - null_mut(), - ) - } == 0 - { - return Err(io::Error::last_os_error()); - } - let _security = LocalMemory(security); - let mut attributes = SECURITY_ATTRIBUTES { - nLength: size_of::() as u32, - lpSecurityDescriptor: security, - bInheritHandle: 0, - }; - unsafe { - ServerOptions::new() - .first_pipe_instance(first) - .reject_remote_clients(true) - .create_with_security_attributes_raw( - name, - (&mut attributes as *mut SECURITY_ATTRIBUTES).cast(), - ) - } -} /// Addresses actually bound by the transport plugin. pub struct ListenAddresses { pub unix_path: Option, @@ -371,7 +272,7 @@ impl DynPlugin for TransportPlugin { .config .pipe_name .as_ref() - .map(|name| pipe_bind(name, true)) + .map(|name| dim_client::pipe::bind(name, true)) .transpose() .map_err(io_failure)?; let websocket = match self.config.websocket_address { @@ -458,7 +359,7 @@ impl DynPlugin for TransportPlugin { }; if let Err(error) = accepted { tracing::warn!(%error, "Named pipe accept failed; retrying"); - listener = pipe_bind(&name, false)?; + listener = dim_client::pipe::bind(&name, false)?; tokio::select! { biased; _ = closing() => return Ok(()), @@ -467,7 +368,7 @@ impl DynPlugin for TransportPlugin { continue; } let stream = listener; - listener = pipe_bind(&name, false)?; + listener = dim_client::pipe::bind(&name, false)?; let hub = hub.clone(); hub.tasks.clone().spawn(async move { run_local(hub, stream).await; diff --git a/crates/dim-app-server/tests/fixtures/sharing_shutdown.rs b/crates/dim-app-server/tests/fixtures/sharing_shutdown.rs new file mode 100644 index 0000000000..2c71a572a0 --- /dev/null +++ b/crates/dim-app-server/tests/fixtures/sharing_shutdown.rs @@ -0,0 +1,39 @@ +use dim_agent_runtime::{AgentBuilder, Feature}; +use rutis::{Ctx, Plugin}; +use std::time::Duration; + +struct DelayedCleanup(bool); + +impl Plugin for DelayedCleanup { + type Deps = (); + fn name(&self) -> &str { + "DelayedCleanup" + } + async fn apply(&self, ctx: &Ctx, (): Self::Deps) -> rutis::Result { + let fail = self.0; + ctx.effect(move || async move { + tokio::time::sleep(Duration::from_millis(400)).await; + if fail { + return Err(rutis::host::ErrorKind::PluginFailed( + std::io::Error::other("fixture cleanup failed").into(), + ) + .into()); + } + Ok(()) + })?; + Ok(()) + } +} + +fn install(builder: &mut AgentBuilder) { + let fail = std::env::var_os("DIM_TEST_FAIL_CLEANUP").is_some(); + builder.require_feature( + Feature::new("DelayedCleanup").session("DelayedCleanup", move |_| { + Ok(Box::new(DelayedCleanup(fail))) + }), + ); +} + +fn main() -> Result<(), Box> { + dim_app_server::cli::run_with(std::env::args().skip(1), None, install) +} diff --git a/crates/dim-cli/src/args.rs b/crates/dim-cli/src/args.rs index 24f8c9d644..caf7d79250 100644 --- a/crates/dim-cli/src/args.rs +++ b/crates/dim-cli/src/args.rs @@ -207,6 +207,10 @@ Commands: Read tasks or request cancellation migration retry TASK [--source OLD_HOME] Resume a task, reconciling imported objects + share status|enable|disable|rename NAME|reset|discover + Manage inbound sharing on this computer + share connect ADDRESS [--pair] [--no-remember] [-- CLI_ARGS...] + Open a native client on a shared computer web [--port N] [--no-open] Hold the Web workspace until Ctrl+C web --off Turn off the daemon-owned Web switch web install Install this version's Web workspace @@ -378,6 +382,7 @@ pub enum Action { Tui, Exec, Update, + Share(Vec), Migration(crate::migration_command::Command), Acp { agent_id: Option, @@ -573,6 +578,7 @@ pub struct Options { /// own file system work resolves against. Requests carry [`Self::workspace`] /// instead. cwd: PathBuf, + remote_workspace: Option, /// The workspace the command names in its requests, resolved once the /// options are complete; `None` for a command that names none. workspace: Option, @@ -625,6 +631,8 @@ impl Options { home_explicit: false, modality: ModalityFlags::default(), cwd: std::env::current_dir()?, + remote_workspace: crate::sharing::proxy() + .and_then(|_| std::env::var("DIMCODE_TERMINAL_WORKSPACE").ok()), workspace: None, server: None, model_config: None, @@ -906,6 +914,9 @@ impl Options { options.home = PathBuf::from(value(&mut args)?); options.home_explicit = true; } + "--cwd" if options.remote_workspace.is_some() => { + options.remote_workspace = Some(value(&mut args)?) + } "--cwd" => options.cwd = PathBuf::from(value(&mut args)?), "--server" => options.server = Some(PathBuf::from(value(&mut args)?)), "--model-config" => options.model_config = Some(PathBuf::from(value(&mut args)?)), @@ -1514,6 +1525,10 @@ impl Options { }; options.action = Action::Recording { enabled }; } + "share" if matches!(options.action, Action::Chat) => { + options.action = Action::Share(args.by_ref().collect()); + break; + } "web" if matches!(options.action, Action::Chat) => { options.action = Action::Web { port: None, @@ -2107,7 +2122,10 @@ impl Options { pub fn resolve_workspace(&mut self) -> Result<()> { self.workspace = self .names_workspace() - .then(|| Workspace::resolve(&self.cwd)) + .then(|| match &self.remote_workspace { + Some(path) => Ok(Workspace(path.clone())), + None => Workspace::resolve(&self.cwd), + }) .transpose()?; Ok(()) } @@ -2173,6 +2191,7 @@ impl Options { | Action::Update | Action::DaemonStop | Action::Web { .. } + | Action::Share(_) | Action::WebInstall | Action::DefaultTerminalMode { .. } | Action::Help diff --git a/crates/dim-cli/src/client.rs b/crates/dim-cli/src/client.rs index a0ed65895d..d7615fc615 100644 --- a/crates/dim-cli/src/client.rs +++ b/crates/dim-cli/src/client.rs @@ -1020,6 +1020,34 @@ fn protocol_refused(error: &crate::Error) -> bool { && app_error(error) == Some("protocol_version") } +fn connection_config( + options: &Options, + endpoint: PathBuf, + server: Server, + profile: Option, +) -> ConnectionConfig { + ConnectionConfig { + endpoint, + server, + profile, + client_kind: if matches!(options.action, crate::args::Action::Acp { .. }) { + "other" + } else { + "cli" + }, + client_name: if matches!(options.action, crate::args::Action::Acp { .. }) { + "AcpGateway" + } else { + "dimcode" + }, + protocol_version: if matches!(options.action, crate::args::Action::Acp { .. }) { + 3 + } else { + 4 + }, + } +} + /// The connection to the daemon of `options.home` after `hello`. Without a /// daemon, starts one when `start` and waits for it; else `None`. With /// `start`, one client at a time decides under `/daemon.start.lock` @@ -1031,6 +1059,22 @@ pub async fn connect_inner( options: &Options, start: bool, locale: crate::locale::Locale, +) -> Result> { + if let Some(endpoint) = crate::sharing::proxy() { + let config = connection_config(options, endpoint, server(options)?, None); + let client = tokio::time::timeout(DAEMON_START_TIMEOUT, Client::connect(&config)).await??; + return Ok(Some(Link { + client, + notice: None, + })); + } + connect_local(options, start, locale).await +} + +pub(crate) async fn connect_local( + options: &Options, + start: bool, + locale: crate::locale::Locale, ) -> Result> { let profile = if !start { None @@ -1080,26 +1124,7 @@ pub async fn connect_inner( }; let server = server(options)?; let binary = &server.program; - let connection = ConnectionConfig { - endpoint: endpoint.clone(), - server: server.clone(), - profile, - client_kind: if matches!(options.action, crate::args::Action::Acp { .. }) { - "other" - } else { - "cli" - }, - client_name: if matches!(options.action, crate::args::Action::Acp { .. }) { - "AcpGateway" - } else { - "dimcode" - }, - protocol_version: if matches!(options.action, crate::args::Action::Acp { .. }) { - 3 - } else { - 4 - }, - }; + let connection = connection_config(options, endpoint.clone(), server.clone(), profile); // `daemon stop` addresses the home's daemon whatever binary runs it, and a // start reuses a `--server` daemon as it is and never replaces it, so it // greets that daemon once. @@ -1180,6 +1205,12 @@ pub async fn connect_inner( }; let mut command = Command::new(&program); command.args(server.subcommand()); + if server.embedded { + let helper = binary.with_file_name(format!("dim-sharing{}", std::env::consts::EXE_SUFFIX)); + if helper.is_file() { + command.arg("--sharing-helper").arg(helper); + } + } for name in [ "DIM_MODEL", "DIM_EFFORT_LEVEL", diff --git a/crates/dim-cli/src/lib.rs b/crates/dim-cli/src/lib.rs index 2512f50696..d17917a17b 100644 --- a/crates/dim-cli/src/lib.rs +++ b/crates/dim-cli/src/lib.rs @@ -39,6 +39,7 @@ mod sanitize; mod session; mod session_command; mod session_host; +mod sharing; mod ui; mod update; mod usage; @@ -695,6 +696,22 @@ pub(crate) fn limits_undeclared( fn prepare() -> Result> { let mut options = Options::parse(std::env::args().skip(1))?; + if sharing::proxy().is_some() { + let local_command = match &options.action { + Action::DaemonVacuum { .. } => Some("daemon vacuum"), + Action::Timeline { .. } => Some("export (offline Timeline)"), + Action::Migration(_) => Some("migration"), + Action::Update => Some("update"), + Action::WebInstall => Some("web install"), + Action::Web { off: false, .. } => Some("web"), + Action::Share(_) => Some("share"), + Action::DefaultTerminalMode { .. } => Some("setting the default terminal mode"), + _ => None, + }; + if let Some(command) = local_command { + return Err(sharing::unavailable(command).into()); + } + } if matches!(options.action, Action::Help) { print!("{}", args::HELP); return Ok(None); @@ -835,6 +852,22 @@ async fn act(root: &rutis::Ctx, mut options: Options) -> Result { // same language as a value. let locale = crate::ui::i18n::interface_locale(&options.home); crate::ui::i18n::set(locale); + if let Action::Share(arguments) = &options.action { + if matches!( + arguments.first().map(String::as_str), + Some("enable" | "reset" | "rename") + ) { + let mut local = options.clone(); + local.action = Action::Chat; + if client::connect_local(&local, false, locale) + .await? + .is_none() + { + client::connect_local(&local, true, locale).await?; + } + } + return sharing::run(&options.home, arguments); + } if let Action::Migration(command) = &options.action { return migration_command::run(root, &options, command, locale).await; } @@ -1198,6 +1231,7 @@ async fn act(root: &rutis::Ctx, mut options: Options) -> Result { worktree_command::run(&mut client, command, options.json).await } Action::Acp { .. } + | Action::Share(_) | Action::Migration(_) | Action::Help | Action::Version diff --git a/crates/dim-cli/src/session_host.rs b/crates/dim-cli/src/session_host.rs index 3e1e5a0916..286427bc77 100644 --- a/crates/dim-cli/src/session_host.rs +++ b/crates/dim-cli/src/session_host.rs @@ -457,7 +457,7 @@ async fn run( if let Some(notice) = notice { let _ = updates.send(Update::Notice(notice)); } - if update::enabled() { + if update::enabled() && crate::sharing::proxy().is_none() { let offers = updates.clone(); let home = options.home.clone(); let managed = options.server.is_none() && client.offers("daemon.shutdown.ifIdle"); @@ -2000,6 +2000,11 @@ impl Worker { Command::Earlier { line, .. } => self.earlier(&line), Command::Goal { request, .. } => self.goal(request).await, Command::Loop { request, .. } => self.loop_command(request).await, + Command::CheckUpdate if crate::sharing::proxy().is_some() => { + self.send(Update::UpgradeChecked(Err(crate::sharing::unavailable( + "/update", + )))); + } Command::CheckUpdate => { let updates = self.updates.clone(); let managed = @@ -2012,6 +2017,9 @@ impl Worker { let _ = updates.send(Update::UpgradeChecked(checked)); }); } + Command::ToggleWeb if crate::sharing::proxy().is_some() => { + self.report(crate::sharing::unavailable("/web"), true); + } Command::ToggleWeb => { let result: crate::Result = self.client.typed("web.toggle", json!({})).await; @@ -3050,12 +3058,20 @@ impl Worker { } if self.ui_identity.is_none() && self.client.offers("ui.leaf.2") { let leaf = crate::leaf::Leaf::bind(&self.options)?; - let params = json!({ - "sessionId": self.session_id, - "kind": "tui", - "peer": leaf.peer, - "address": leaf.address, - }); + #[derive(serde::Serialize)] + #[serde(rename_all = "camelCase")] + struct OpenLeaf<'a> { + session_id: &'a str, + kind: &'static str, + peer: &'a str, + address: String, + } + let params = serde_json::to_value(OpenLeaf { + session_id: &self.session_id, + kind: "tui", + peer: &leaf.peer, + address: crate::sharing::leaf_address(&leaf.address).await?, + })?; let end = self .leaf_end .take() diff --git a/crates/dim-cli/src/sharing.rs b/crates/dim-cli/src/sharing.rs new file mode 100644 index 0000000000..77183298a2 --- /dev/null +++ b/crates/dim-cli/src/sharing.rs @@ -0,0 +1,95 @@ +use serde::Deserialize; +use std::{ + path::{Path, PathBuf}, + process::Command, +}; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; + +#[derive(Deserialize, Default)] +pub(crate) struct Status { + pub name: String, + pub enabled: bool, + pub token: Option, + pub addresses: Vec, + pub error: Option, +} + +pub(crate) fn installed() -> bool { + std::env::current_exe().is_ok_and(|exe| { + exe.with_file_name(format!("dim-sharing{}", std::env::consts::EXE_SUFFIX)) + .is_file() + }) +} + +fn command(home: &Path) -> crate::Result { + let path = std::env::current_exe()? + .with_file_name(format!("dim-sharing{}", std::env::consts::EXE_SUFFIX)); + let mut cmd = Command::new(path); + cmd.arg("--home").arg(home.join("rust")); + Ok(cmd) +} +pub(crate) fn run(home: &Path, args: &[String]) -> crate::Result { + if args.is_empty() + || !matches!( + args[0].as_str(), + "status" | "enable" | "disable" | "reset" | "rename" | "discover" | "connect" + ) + { + return Err( + "Use share status, enable, disable, rename NAME, reset, discover or connect ADDRESS" + .into(), + ); + } + Ok(command(home)?.args(args).status()?.code().unwrap_or(1)) +} +pub(crate) fn setting(home: &Path, args: &[String]) -> crate::Result { + let mut owner = Command::new(std::env::current_exe()?); + let result = owner + .env_remove("DIMCODE_TERMINAL_PROXY") + .arg("--home") + .arg(home) + .arg("share") + .args(args) + .output()?; + if !result.status.success() { + return Err(String::from_utf8_lossy(&result.stderr) + .trim() + .to_owned() + .into()); + } + Ok(serde_json::from_slice(&result.stdout)?) +} +pub(crate) fn unavailable(command: &str) -> String { + format!( + "{command} is unavailable through a shared connection. \ + Run it directly on the intended computer." + ) +} + +pub(crate) fn proxy() -> Option { + std::env::var_os("DIMCODE_TERMINAL_PROXY").map(PathBuf::from) +} +pub(crate) async fn leaf_address(local: &str) -> crate::Result { + let Some(proxy) = proxy() else { + return Ok(local.to_owned()); + }; + let path = proxy.with_extension("leaf"); + #[cfg(unix)] + let mut control = tokio::net::UnixStream::connect(path).await?; + #[cfg(windows)] + let mut control = dim_client::pipe::connect(path.to_str().ok_or("invalid leaf pipe")?) + .await + .map_err(|(_, err)| err)?; + control.write_all(local.as_bytes()).await?; + control.write_all(b"\n").await?; + let mut address = String::new(); + tokio::time::timeout( + std::time::Duration::from_secs(10), + BufReader::new(control.take(4097)).read_line(&mut address), + ) + .await??; + Ok(address + .strip_suffix('\n') + .ok_or("shared computer did not prepare its leaf listener")? + .to_owned()) +} diff --git a/crates/dim-cli/src/ui/i18n/de/chrome.rs b/crates/dim-cli/src/ui/i18n/de/chrome.rs index 6bbef13b35..03b3b08729 100644 --- a/crates/dim-cli/src/ui/i18n/de/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/de/chrome.rs @@ -1,5 +1,17 @@ pub fn lookup(english: &str) -> Option<&'static str> { Some(match english { + "This computer" => "Dieser Computer", + "Remote access" => "Fernzugriff", + "Allow connections to this computer" => "Verbindungen zu diesem Computer erlauben", + "Computer name" => "Computername", + "Sharing token" => "Freigabetoken", + "Reset sharing token" => "Freigabetoken zurücksetzen", + "Disconnect all shared terminals and issue a new token?" => { + "Alle verbundenen Terminals trennen und ein neues Token ausstellen?" + } + "y confirm · Esc cancel" => "y bestätigen · Esc abbrechen", + "Enter save · Esc cancel" => "Enter speichern · Esc abbrechen", + "Loading…" => "Wird geladen…", "Tab / Enter complete" => "Tab / Enter vervollständigen", "Queue" => "Warteschlange", "Export session" => "Sitzung exportieren", diff --git a/crates/dim-cli/src/ui/i18n/es/chrome.rs b/crates/dim-cli/src/ui/i18n/es/chrome.rs index dd5b657c6b..142b02a1e7 100644 --- a/crates/dim-cli/src/ui/i18n/es/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/es/chrome.rs @@ -1,5 +1,17 @@ pub fn lookup(english: &str) -> Option<&'static str> { Some(match english { + "This computer" => "Este equipo", + "Remote access" => "Acceso remoto", + "Allow connections to this computer" => "Permitir conexiones a este equipo", + "Computer name" => "Nombre del equipo", + "Sharing token" => "Token de acceso", + "Reset sharing token" => "Restablecer token de acceso", + "Disconnect all shared terminals and issue a new token?" => { + "¿Desconectar todos los terminales remotos y generar un nuevo token?" + } + "y confirm · Esc cancel" => "y confirmar · Esc cancelar", + "Enter save · Esc cancel" => "Enter guardar · Esc cancelar", + "Loading…" => "Cargando…", "Tab / Enter complete" => "Tab / Enter completar", "Queue" => "Cola", "Export session" => "Exportar sesión", diff --git a/crates/dim-cli/src/ui/i18n/fr/chrome.rs b/crates/dim-cli/src/ui/i18n/fr/chrome.rs index c833589911..b7aa4a6893 100644 --- a/crates/dim-cli/src/ui/i18n/fr/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/fr/chrome.rs @@ -1,5 +1,17 @@ pub fn lookup(english: &str) -> Option<&'static str> { Some(match english { + "This computer" => "Cet ordinateur", + "Remote access" => "Accès à distance", + "Allow connections to this computer" => "Autoriser les connexions à cet ordinateur", + "Computer name" => "Nom de l’ordinateur", + "Sharing token" => "Jeton de partage", + "Reset sharing token" => "Réinitialiser le jeton de partage", + "Disconnect all shared terminals and issue a new token?" => { + "Déconnecter tous les terminaux distants et générer un nouveau jeton ?" + } + "y confirm · Esc cancel" => "y confirmer · Échap annuler", + "Enter save · Esc cancel" => "Entrée enregistrer · Échap annuler", + "Loading…" => "Chargement…", "Tab / Enter complete" => "Tab / Enter compléter", "Queue" => "File d’attente", "Export session" => "Exporter la session", diff --git a/crates/dim-cli/src/ui/i18n/id/chrome.rs b/crates/dim-cli/src/ui/i18n/id/chrome.rs index 04037b1d0d..d5521b9193 100644 --- a/crates/dim-cli/src/ui/i18n/id/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/id/chrome.rs @@ -1,5 +1,17 @@ pub fn lookup(english: &str) -> Option<&'static str> { Some(match english { + "This computer" => "Komputer ini", + "Remote access" => "Akses jarak jauh", + "Allow connections to this computer" => "Izinkan koneksi ke komputer ini", + "Computer name" => "Nama komputer", + "Sharing token" => "Token berbagi", + "Reset sharing token" => "Atur ulang token berbagi", + "Disconnect all shared terminals and issue a new token?" => { + "Putuskan semua terminal jarak jauh dan buat token baru?" + } + "y confirm · Esc cancel" => "y konfirmasi · Esc batal", + "Enter save · Esc cancel" => "Enter simpan · Esc batal", + "Loading…" => "Memuat…", "Tab / Enter complete" => "Tab / Enter lengkapi", "Queue" => "Antrean", "Export session" => "Ekspor sesi", diff --git a/crates/dim-cli/src/ui/i18n/ja/chrome.rs b/crates/dim-cli/src/ui/i18n/ja/chrome.rs index 59eea9e470..ebad68269d 100644 --- a/crates/dim-cli/src/ui/i18n/ja/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/ja/chrome.rs @@ -1,5 +1,17 @@ pub fn lookup(english: &str) -> Option<&'static str> { Some(match english { + "This computer" => "このコンピューター", + "Remote access" => "リモートアクセス", + "Allow connections to this computer" => "このコンピューターへの接続を許可", + "Computer name" => "コンピューター名", + "Sharing token" => "共有トークン", + "Reset sharing token" => "共有トークンをリセット", + "Disconnect all shared terminals and issue a new token?" => { + "すべてのリモート端末を切断し、新しいトークンを発行しますか?" + } + "y confirm · Esc cancel" => "y 確定 · Esc キャンセル", + "Enter save · Esc cancel" => "Enter 保存 · Esc キャンセル", + "Loading…" => "読み込み中…", "Tab / Enter complete" => "Tab / Enter 補完", "Queue" => "キュー", "Export session" => "セッションをエクスポート", diff --git a/crates/dim-cli/src/ui/i18n/ko/chrome.rs b/crates/dim-cli/src/ui/i18n/ko/chrome.rs index 7861057638..299aced5ea 100644 --- a/crates/dim-cli/src/ui/i18n/ko/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/ko/chrome.rs @@ -1,5 +1,17 @@ pub fn lookup(english: &str) -> Option<&'static str> { Some(match english { + "This computer" => "이 컴퓨터", + "Remote access" => "원격 접근", + "Allow connections to this computer" => "이 컴퓨터에 연결 허용", + "Computer name" => "컴퓨터 이름", + "Sharing token" => "공유 토큰", + "Reset sharing token" => "공유 토큰 재설정", + "Disconnect all shared terminals and issue a new token?" => { + "모든 원격 터미널의 연결을 끊고 새 토큰을 발급할까요?" + } + "y confirm · Esc cancel" => "y 확인 · Esc 취소", + "Enter save · Esc cancel" => "Enter 저장 · Esc 취소", + "Loading…" => "불러오는 중…", "Tab / Enter complete" => "Tab / Enter 완성", "Queue" => "대기열", "Export session" => "세션 내보내기", diff --git a/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs b/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs index 2c504d06f8..37dd6ee289 100644 --- a/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs @@ -1,5 +1,17 @@ pub fn lookup(english: &str) -> Option<&'static str> { Some(match english { + "This computer" => "Este computador", + "Remote access" => "Acesso remoto", + "Allow connections to this computer" => "Permitir conexões com este computador", + "Computer name" => "Nome do computador", + "Sharing token" => "Token de compartilhamento", + "Reset sharing token" => "Redefinir o token de compartilhamento", + "Disconnect all shared terminals and issue a new token?" => { + "Desconectar todos os terminais remotos e gerar um novo token?" + } + "y confirm · Esc cancel" => "y confirmar · Esc cancelar", + "Enter save · Esc cancel" => "Enter salvar · Esc cancelar", + "Loading…" => "Carregando…", "Tab / Enter complete" => "Tab / Enter completar", "Queue" => "Fila", "Export session" => "Exportar sessão", diff --git a/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs b/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs index e4c61f26c5..4ba74a9a03 100644 --- a/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs @@ -1,5 +1,17 @@ pub fn lookup(english: &str) -> Option<&'static str> { Some(match english { + "This computer" => "Este computador", + "Remote access" => "Acesso remoto", + "Allow connections to this computer" => "Permitir ligações a este computador", + "Computer name" => "Nome do computador", + "Sharing token" => "Token de partilha", + "Reset sharing token" => "Repor o token de partilha", + "Disconnect all shared terminals and issue a new token?" => { + "Desligar todos os terminais remotos e gerar um novo token?" + } + "y confirm · Esc cancel" => "y confirmar · Esc cancelar", + "Enter save · Esc cancel" => "Enter guardar · Esc cancelar", + "Loading…" => "A carregar…", "Tab / Enter complete" => "Tab / Enter completar", "Queue" => "Fila", "Export session" => "Exportar sessão", diff --git a/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs b/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs index ed8795c1a5..371290f65d 100644 --- a/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs @@ -1,5 +1,17 @@ pub fn lookup(english: &str) -> Option<&'static str> { Some(match english { + "Loading…" => "正在加载…", + "This computer" => "本机", + "Remote access" => "远程访问", + "Allow connections to this computer" => "允许其他电脑连接本机", + "Computer name" => "电脑名称", + "Sharing token" => "共享 Token", + "Reset sharing token" => "重置共享 Token", + "Disconnect all shared terminals and issue a new token?" => { + "断开所有已连接的远程终端并生成新 Token?" + } + "y confirm · Esc cancel" => "y 确认 · Esc 取消", + "Enter save · Esc cancel" => "Enter 保存 · Esc 取消", "Tab / Enter complete" => "Tab / Enter 补全", "Queue" => "队列", "Export session" => "导出会话", diff --git a/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs b/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs index 05e9caf252..f8430524be 100644 --- a/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs @@ -1,5 +1,17 @@ pub fn lookup(english: &str) -> Option<&'static str> { Some(match english { + "This computer" => "本機", + "Remote access" => "遠端存取", + "Allow connections to this computer" => "允許其他電腦連線到本機", + "Computer name" => "電腦名稱", + "Sharing token" => "共享 Token", + "Reset sharing token" => "重設共享 Token", + "Disconnect all shared terminals and issue a new token?" => { + "中斷所有遠端終端的連線並產生新 Token?" + } + "y confirm · Esc cancel" => "y 確認 · Esc 取消", + "Enter save · Esc cancel" => "Enter 儲存 · Esc 取消", + "Loading…" => "載入中…", "Tab / Enter complete" => "Tab / Enter 補全", "Queue" => "佇列", "Export session" => "匯出工作階段", diff --git a/crates/dim-cli/src/ui/mod.rs b/crates/dim-cli/src/ui/mod.rs index fac2f6f8f2..2eb9878a26 100644 --- a/crates/dim-cli/src/ui/mod.rs +++ b/crates/dim-cli/src/ui/mod.rs @@ -79,6 +79,7 @@ pub mod progress; pub mod prompts; pub mod providers_panel; pub mod queue_panel; +mod remote_access; pub mod render; mod report_panel; pub mod rows; diff --git a/crates/dim-cli/src/ui/remote_access.rs b/crates/dim-cli/src/ui/remote_access.rs new file mode 100644 index 0000000000..eac5c98dc1 --- /dev/null +++ b/crates/dim-cli/src/ui/remote_access.rs @@ -0,0 +1,187 @@ +use super::{ + i18n::t, + list_panel::{Event, Item, ListPanel}, + prompts::Effect, + render::panel::{confirm_panel, wrap}, + terminal::{KeyCode, KeyEvent}, + theme::Palette, +}; +use crate::sharing::Status; +use std::{ + path::PathBuf, + sync::mpsc::{Receiver, channel}, +}; + +enum Page { + Settings, + Name(String), + Reset, + Token, +} +pub struct RemoteAccess { + home: PathBuf, + list: ListPanel, + status: Option, + error: Option, + page: Page, + loading: Option>>, +} +impl RemoteAccess { + pub fn new(home: PathBuf) -> Self { + let mut panel = Self { + home, + list: Self::list(), + status: None, + error: None, + page: Page::Settings, + loading: None, + }; + panel.request(vec!["status".into()]); + panel + } + fn list() -> ListPanel { + ListPanel::new( + "Remote access", + t("↑↓ move · Enter select · Esc close"), + "Loading…", + "", + "", + false, + ) + .without_filter() + } + fn request(&mut self, args: Vec) { + let home = self.home.clone(); + let (tx, rx) = channel(); + std::thread::spawn(move || { + let result = crate::sharing::setting(&home, &args).map_err(|error| error.to_string()); + let _ = tx.send(result); + }); + self.loading = Some(rx); + self.page = Page::Settings; + } + pub fn tick(&mut self) -> bool { + let Some(rx) = &self.loading else { + return false; + }; + let Ok(result) = rx.try_recv() else { + return false; + }; + self.loading = None; + match result { + Ok(status) => { + self.error = status.error.clone(); + self.status = Some(status) + } + Err(err) => self.error = Some(err), + } + let selected = self.list.selected_id(); + let mut items = Vec::new(); + let mut notes = Vec::new(); + if let Some(s) = &self.status { + items.push(Item::new( + "toggle", + t("Allow connections to this computer"), + if s.enabled { t("on") } else { t("off") }, + )); + items.push(Item::new("name", t("Computer name"), &s.name)); + if let Some(token) = &s.token { + items.push(Item::new("token", t("Sharing token"), "›")); + notes.push(token.clone()); + } + items.push(Item::new("reset", t("Reset sharing token"), "›")); + notes.extend(s.addresses.iter().cloned()); + } + if let Some(message) = &self.error { + notes.insert(0, message.clone()); + items.push(Item::new("reload", t("Reload"), "")); + } + self.list = Self::list().with_notes(notes); + self.list.set_items(Ok(items), selected.as_deref()); + true + } + pub fn paste(&mut self, text: &str) { + if let Page::Name(name) = &mut self.page { + name.extend(text.chars().filter(|c| !c.is_control())); + } + } + pub fn handle_key(&mut self, key: KeyEvent) -> Effect { + match &mut self.page { + Page::Name(name) => match key.code { + KeyCode::Esc => self.page = Page::Settings, + KeyCode::Enter => { + let name = name.clone(); + self.request(vec!["rename".into(), name]) + } + KeyCode::Backspace => { + name.pop(); + } + KeyCode::Char(c) if !c.is_control() => name.push(c), + _ => {} + }, + Page::Reset => match key.code { + KeyCode::Char('y') => self.request(vec!["reset".into()]), + KeyCode::Char('n') | KeyCode::Esc | KeyCode::Enter => self.page = Page::Settings, + _ => {} + }, + Page::Token => { + if matches!(key.code, KeyCode::Esc | KeyCode::Enter) { + self.page = Page::Settings + } + } + Page::Settings => match self.list.handle_key(key) { + Event::Close => return Effect::Close, + Event::Pick { id, .. } if self.loading.is_none() => match id.as_str() { + "toggle" => { + let on = self.status.as_ref().is_some_and(|s| s.enabled); + self.request(vec![if on { "disable" } else { "enable" }.into()]) + } + "name" => { + if let Some(s) = &self.status { + self.page = Page::Name(s.name.clone()) + } + } + "reset" => self.page = Page::Reset, + "token" => self.page = Page::Token, + "reload" => self.request(vec!["status".into()]), + _ => {} + }, + _ => {} + }, + } + Effect::None + } + pub fn render(&self, width: usize, rows: usize, p: &Palette) -> Vec { + let (title, body, hint) = match &self.page { + Page::Settings if self.loading.is_some() => return Self::list().render(width, rows, p), + Page::Settings => return self.list.render(width, rows, p), + Page::Name(name) => ( + t("Computer name"), + name.as_str(), + t("Enter save · Esc cancel"), + ), + Page::Reset => ( + t("Reset sharing token"), + t("Disconnect all shared terminals and issue a new token?"), + t("y confirm · Esc cancel"), + ), + Page::Token => ( + t("Sharing token"), + self.status + .as_ref() + .and_then(|s| s.token.as_deref()) + .unwrap_or(""), + t("Esc back"), + ), + }; + confirm_panel( + title, + &wrap(body, width.saturating_sub(4).max(1)), + &[], + 0, + hint, + width, + p, + ) + } +} diff --git a/crates/dim-cli/src/ui/settings_panel.rs b/crates/dim-cli/src/ui/settings_panel.rs index ad792a69c5..fc8f1afb7f 100644 --- a/crates/dim-cli/src/ui/settings_panel.rs +++ b/crates/dim-cli/src/ui/settings_panel.rs @@ -78,9 +78,10 @@ pub enum Setting { Permission, Isolation, ToolMode, + RemoteAccess, } -const ROWS: [(Setting, &str); 16] = [ +const ROWS: [(Setting, &str); 17] = [ (Setting::Theme, "theme"), (Setting::Language, "language"), (Setting::StartupForm, "startup-form"), @@ -97,6 +98,7 @@ const ROWS: [(Setting, &str); 16] = [ (Setting::Permission, "permission"), (Setting::Isolation, "isolation"), (Setting::ToolMode, "tool-mode"), + (Setting::RemoteAccess, "remote-access"), ]; impl Setting { @@ -257,6 +259,10 @@ impl SettingsPanel { ]); items.push(Item::heading(t("Tools"))); items.push(row(Setting::ToolMode, "Tool mode", link(&values.tool_mode))); + if crate::sharing::installed() { + items.push(Item::heading(t("This computer"))); + items.push(row(Setting::RemoteAccess, "Remote access", link(""))); + } let mut list = ListPanel::new("Settings", HINT, "", "", "", false).without_filter(); list.set_items(Ok(items), Some(select.id())); list.set_hint(t(hint_for(select)).to_owned()); diff --git a/crates/dim-cli/src/ui/tui.rs b/crates/dim-cli/src/ui/tui.rs index 1979834c8f..3c3f8a4eff 100644 --- a/crates/dim-cli/src/ui/tui.rs +++ b/crates/dim-cli/src/ui/tui.rs @@ -1634,6 +1634,7 @@ enum Prompt { Theme(ThemePanel), Language(LanguagePanel), Settings(SettingsPanel), + RemoteAccess(Box), Isolation(Box), Exit(ExitConfirm), Upgrade(UpgradeDialog), @@ -2276,6 +2277,7 @@ impl App { | Some(Prompt::Approvals(_)) | Some(Prompt::Theme(_)) | Some(Prompt::Language(_)) + | Some(Prompt::RemoteAccess(_)) | Some(Prompt::Settings(_)) | Some(Prompt::Isolation(_)) | Some(Prompt::Lines(_)) @@ -2343,6 +2345,9 @@ impl App { self.sync_sessions(); self.sync_task_details(); let mut changed = false; + if let Some(Prompt::RemoteAccess(panel)) = &mut self.prompt { + changed = panel.tick(); + } for excerpt in self.excerpts.values_mut() { if excerpt.next != excerpt.text && now.duration_since(excerpt.at) >= Duration::from_millis(500) @@ -3453,6 +3458,7 @@ impl App { } Some(Prompt::Theme(panel)) => panel.paste(&text), Some(Prompt::Language(panel)) => panel.paste(&text), + Some(Prompt::RemoteAccess(panel)) => panel.paste(&text), Some(Prompt::Settings(panel)) => panel.paste(&text), Some(Prompt::Isolation(panel)) => panel.paste(&text), Some(Prompt::Management(panel)) => panel.paste(&text), @@ -3582,6 +3588,7 @@ impl App { Prompt::Approvals(p) => p.handle_key(key), Prompt::Theme(p) => p.handle_key(key), Prompt::Language(p) => p.handle_key(key), + Prompt::RemoteAccess(p) => p.handle_key(key), Prompt::Settings(p) => p.handle_key(key), Prompt::Isolation(p) => p.handle_key(key), Prompt::Exit(p) => p.handle_key(key), @@ -5247,6 +5254,9 @@ impl App { fn setting(&mut self, setting: Setting) { self.settings_return = Some(setting); match setting { + Setting::RemoteAccess => self.open_prompt(Prompt::RemoteAccess(Box::new( + super::remote_access::RemoteAccess::new(self.home.clone()), + ))), Setting::Theme => { self.settings_return = None; self.run_command("theme", ""); @@ -6855,6 +6865,9 @@ impl App { Some(Prompt::Language(prompt)) => { Some(prompt.render(list_width, budget, p)) } + Some(Prompt::RemoteAccess(prompt)) => { + Some(prompt.render(list_width, budget, p)) + } Some(Prompt::Settings(prompt)) => { Some(prompt.render(list_width, budget, p)) } @@ -6899,6 +6912,7 @@ impl App { Some(Prompt::Approvals(prompt)) => Some(prompt.render(outer, panel_rows, p)), Some(Prompt::Theme(prompt)) => Some(prompt.render(outer, panel_rows, p)), Some(Prompt::Language(prompt)) => Some(prompt.render(outer, panel_rows, p)), + Some(Prompt::RemoteAccess(prompt)) => Some(prompt.render(outer, panel_rows, p)), Some(Prompt::Settings(prompt)) => Some(prompt.render(outer, panel_rows, p)), Some(Prompt::Isolation(prompt)) => Some(prompt.render(outer, panel_rows, p)), Some(Prompt::Exit(prompt)) => Some(prompt.render(outer, p)), diff --git a/crates/dim-client/Cargo.toml b/crates/dim-client/Cargo.toml index fe19df0082..434dfd7566 100644 --- a/crates/dim-client/Cargo.toml +++ b/crates/dim-client/Cargo.toml @@ -17,6 +17,9 @@ url = "2" [target.'cfg(unix)'.dependencies] libc = "0.2" +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_System_SystemServices", "Win32_System_Threading"] } + [dev-dependencies] tempfile = "3" diff --git a/crates/dim-client/src/lib.rs b/crates/dim-client/src/lib.rs index 3564fa2036..365da34326 100644 --- a/crates/dim-client/src/lib.rs +++ b/crates/dim-client/src/lib.rs @@ -8,6 +8,9 @@ pub mod wire; pub type Error = Box; pub type Result = std::result::Result; +#[cfg(windows)] +pub mod pipe; + use serde::{Deserialize, de::DeserializeOwned}; use serde_json::{Value, json}; #[cfg(windows)] diff --git a/crates/dim-client/src/pipe.rs b/crates/dim-client/src/pipe.rs new file mode 100644 index 0000000000..cfa2a2bf5d --- /dev/null +++ b/crates/dim-client/src/pipe.rs @@ -0,0 +1,204 @@ +use std::io; +use tokio::net::windows::named_pipe::{NamedPipeServer, ServerOptions}; + +pub fn bind(name: &str, first: bool) -> io::Result { + use std::{ + ffi::c_void, + mem::size_of, + os::windows::io::{FromRawHandle, OwnedHandle}, + ptr::null_mut, + }; + use windows_sys::Win32::{ + Foundation::{ERROR_INSUFFICIENT_BUFFER, LocalFree}, + Security::{ + Authorization::{ + ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, + SDDL_REVISION_1, + }, + GetTokenInformation, SECURITY_ATTRIBUTES, TOKEN_QUERY, TOKEN_USER, TokenUser, + }, + System::Threading::{GetCurrentProcess, OpenProcessToken}, + }; + if !name.starts_with(r"\\.\pipe\") || name.len() == r"\\.\pipe\".len() || name.contains('\0') { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "named pipe requires a local \\\\.\\pipe\\ name", + )); + } + struct LocalMemory(*mut c_void); + impl Drop for LocalMemory { + fn drop(&mut self) { + unsafe { LocalFree(self.0) }; + } + } + let mut token = null_mut(); + if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 { + return Err(io::Error::last_os_error()); + } + let _token = unsafe { OwnedHandle::from_raw_handle(token) }; + let mut length = 0; + if unsafe { GetTokenInformation(token, TokenUser, null_mut(), 0, &mut length) } == 0 + && io::Error::last_os_error().raw_os_error() != Some(ERROR_INSUFFICIENT_BUFFER as i32) + { + return Err(io::Error::last_os_error()); + } + let mut user = vec![0usize; (length as usize).div_ceil(size_of::())]; + if unsafe { + GetTokenInformation( + token, + TokenUser, + user.as_mut_ptr().cast(), + length, + &mut length, + ) + } == 0 + { + return Err(io::Error::last_os_error()); + } + let sid = unsafe { (*user.as_ptr().cast::()).User.Sid }; + let mut sid_text = null_mut(); + if unsafe { ConvertSidToStringSidW(sid, &mut sid_text) } == 0 { + return Err(io::Error::last_os_error()); + } + let _sid_text = LocalMemory(sid_text.cast()); + let mut sid_length = 0; + while unsafe { *sid_text.add(sid_length) } != 0 { + sid_length += 1; + } + let sid = String::from_utf16(unsafe { std::slice::from_raw_parts(sid_text, sid_length) }) + .map_err(io::Error::other)?; + let descriptor: Vec = format!("O:{sid}D:P(A;;GA;;;{sid})") + .encode_utf16() + .chain(Some(0)) + .collect(); + let mut security = null_mut(); + if unsafe { + ConvertStringSecurityDescriptorToSecurityDescriptorW( + descriptor.as_ptr(), + SDDL_REVISION_1, + &mut security, + null_mut(), + ) + } == 0 + { + return Err(io::Error::last_os_error()); + } + let _security = LocalMemory(security); + let mut attributes = SECURITY_ATTRIBUTES { + nLength: size_of::() as u32, + lpSecurityDescriptor: security, + bInheritHandle: 0, + }; + unsafe { + ServerOptions::new() + .first_pipe_instance(first) + .reject_remote_clients(true) + .create_with_security_attributes_raw( + name, + (&mut attributes as *mut SECURITY_ATTRIBUTES).cast(), + ) + } +} + +pub async fn connect( + name: &str, +) -> Result { + use tokio::net::windows::named_pipe::ClientOptions; + use windows_sys::Win32::Foundation::{ERROR_FILE_NOT_FOUND, ERROR_PIPE_BUSY}; + if !name.starts_with(r"\\.\pipe\") || name.len() == r"\\.\pipe\".len() || name.contains('\0') { + return Err(( + "EINVAL", + io::Error::new( + io::ErrorKind::InvalidInput, + "a local named pipe is required", + ), + )); + } + let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5); + let pipe = loop { + match ClientOptions::new().open(name) { + Ok(pipe) => break pipe, + Err(error) => { + let code = match error.raw_os_error().map(|code| code as u32) { + Some(ERROR_PIPE_BUSY) if tokio::time::Instant::now() < deadline => { + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + continue; + } + Some(ERROR_FILE_NOT_FOUND) => "ENOENT", + Some(ERROR_PIPE_BUSY) => "EBUSY", + _ => "EACCES", + }; + return Err((code, error)); + } + } + }; + authenticate(&pipe).map_err(|error| ("EACCES", error))?; + Ok(pipe) +} + +fn authenticate(pipe: &tokio::net::windows::named_pipe::NamedPipeClient) -> io::Result<()> { + use std::{ + mem::size_of, + os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}, + ptr::null_mut, + }; + use windows_sys::Win32::{ + Foundation::{ERROR_INSUFFICIENT_BUFFER, LocalFree}, + Security::{ + Authorization::{GetSecurityInfo, SE_KERNEL_OBJECT}, + EqualSid, GetTokenInformation, OWNER_SECURITY_INFORMATION, TOKEN_QUERY, TOKEN_USER, + TokenUser, + }, + System::Threading::{GetCurrentProcess, OpenProcessToken}, + }; + let mut token = null_mut(); + if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 { + return Err(io::Error::last_os_error()); + } + let _token = unsafe { OwnedHandle::from_raw_handle(token) }; + let mut length = 0; + unsafe { GetTokenInformation(token, TokenUser, null_mut(), 0, &mut length) }; + if io::Error::last_os_error().raw_os_error() != Some(ERROR_INSUFFICIENT_BUFFER as i32) { + return Err(io::Error::last_os_error()); + } + let mut user = vec![0usize; (length as usize).div_ceil(size_of::())]; + if unsafe { + GetTokenInformation( + token, + TokenUser, + user.as_mut_ptr().cast(), + length, + &mut length, + ) + } == 0 + { + return Err(io::Error::last_os_error()); + } + let mut owner = null_mut(); + let mut descriptor = null_mut(); + let status = unsafe { + GetSecurityInfo( + pipe.as_raw_handle(), + SE_KERNEL_OBJECT, + OWNER_SECURITY_INFORMATION, + &mut owner, + null_mut(), + null_mut(), + null_mut(), + &mut descriptor, + ) + }; + if status != 0 { + return Err(io::Error::from_raw_os_error(status as i32)); + } + let same_user = !owner.is_null() + && unsafe { EqualSid(owner, (*user.as_ptr().cast::()).User.Sid) != 0 }; + unsafe { LocalFree(descriptor) }; + if !same_user { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "named pipe is not owned by the current user", + )); + } + Ok(()) +} diff --git a/crates/dim-terminal-transport/Cargo.toml b/crates/dim-terminal-transport/Cargo.toml new file mode 100644 index 0000000000..48abe209b8 --- /dev/null +++ b/crates/dim-terminal-transport/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "dim-terminal-transport" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true + +[dependencies] +rutis.workspace = true +rutis-host = "=0.23.0" +rutis-bridge.workspace = true +serde.workspace = true +serde_json.workspace = true +tokio.workspace = true +tokio-util.workspace = true +uuid.workspace = true +base64 = "0.22" +libc = "0.2" + +[target.'cfg(windows)'.dependencies] +dim-client.workspace = true + +[dev-dependencies] +tempfile = "3" + +[lints] +workspace = true diff --git a/crates/dim-terminal-transport/src/main.rs b/crates/dim-terminal-transport/src/main.rs new file mode 100644 index 0000000000..9dc34fdfcd --- /dev/null +++ b/crates/dim-terminal-transport/src/main.rs @@ -0,0 +1,140 @@ +mod proxy; +mod streams; +use rutis::{ + Ctx, + host::{CtxHost, FiberState}, +}; +use rutis_bridge::{Close, LocalId, PeerId, Session, channel::Closer, pipe}; +use std::{io, path::PathBuf, sync::Arc}; + +struct ShareEndpoint(PathBuf); + +impl rutis::host::DynPlugin for ShareEndpoint { + fn name(&self) -> &str { + "terminal-transport" + } + fn apply<'a>( + &'a self, + ctx: &'a Ctx, + ) -> rutis::host::BoxFuture<'a, Result> { + Box::pin(async move { + ctx.provide(streams::TerminalTransport::new(self.0.clone()))?; + Ok(rutis::host::Effect::Done) + }) + } +} + +struct PipeEnd; +impl Closer for PipeEnd { + fn close(&self, _: Close) {} +} + +#[tokio::main(worker_threads = 2)] +async fn main() { + if let Err(e) = run().await { + eprintln!("{e}"); + std::process::exit(1) + } +} +type Error = Box; +async fn run() -> Result<(), Error> { + let mut args = std::env::args_os().skip(1); + let mode = args.next().ok_or("missing terminal transport role")?; + let target = PathBuf::from(args.next().ok_or("missing endpoint")?); + if mode == "discover" || mode == "announce" { + return discovery(&target, if mode == "discover" { Some(args) } else { None }).await; + } + let root = Ctx::root()?; + let serving = mode == "serve"; + if serving { + root.plugin(ShareEndpoint(target.clone())).await?; + } else if mode != "connect" { + return Err("unknown terminal role".into()); + } + root.provide(LocalId(PeerId::new(if serving { + "dim-sharing" + } else { + "dim-terminal" + })?))?; + let channel = pipe::framed(io::stdin(), io::stdout(), Arc::new(PipeEnd)); + let greeted = Session::handshake(&root, channel).await?; + if greeted.id() + != if serving { + "dim-terminal" + } else { + "dim-sharing" + } + { + return Err("unexpected terminal peer".into()); + } + let session = root.plugin(greeted); + (&session).await?; + let mut state = session.watch(); + let closed = state.wait_for(|s| matches!(s.state, FiberState::Disposed | FiberState::Failed)); + if serving { + let _ = closed.await; + } else { + let ready = args.next().ok_or("missing readiness path")?; + let connect = async { + let service = tokio::time::timeout(std::time::Duration::from_secs(10), async { + let key = rutis_bridge::session::host_key("terminalTransport"); + loop { + if let Some(service) = root.get_at(&key) { + return service; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + }) + .await?; + proxy::serve(service, &target, std::path::Path::new(&ready)).await + }; + tokio::select! { + _ = closed => {}, + result = connect => result?, + } + } + root.shutdown().await?; + Ok(()) +} + +async fn discovery( + path: &std::path::Path, + services: Option>, +) -> Result<(), Error> { + use rutis_host::{config::HostConfig, host::Host}; + let config = HostConfig::read(path)?; + let host = Host::start(&config).await?; + let run = async { + host.start_rows(config.rows()).await?; + match services { + None => std::future::pending::<()>().await, + Some(names) => { + #[derive(serde::Deserialize, serde::Serialize)] + struct Snapshot { + candidates: Vec, + } + tokio::time::sleep(std::time::Duration::from_secs(3)).await; + let mut candidates = Vec::new(); + for name in names { + let name = name.to_str().ok_or("invalid discovery service")?; + if host.service(name).is_some() { + let snapshot: Snapshot = + rutis_bridge::session::call_service(&host.root(), name, "snapshot", ()) + .await?; + candidates.extend(snapshot.candidates); + } + } + println!("{}", serde_json::to_string(&candidates)?); + } + } + Ok::<_, Error>(()) + }; + let (stop, ended) = tokio::sync::oneshot::channel(); + std::thread::spawn(move || { + let _ = std::io::Read::read(&mut std::io::stdin(), &mut [0; 1]); + let _ = stop.send(()); + }); + let result = tokio::select! { r=run=>r, _=ended=>Ok(()) }; + host.root().shutdown().await?; + result +} diff --git a/crates/dim-terminal-transport/src/proxy.rs b/crates/dim-terminal-transport/src/proxy.rs new file mode 100644 index 0000000000..4626e005c4 --- /dev/null +++ b/crates/dim-terminal-transport/src/proxy.rs @@ -0,0 +1,177 @@ +use crate::{ + Error, + streams::{CHUNK, Duplex, ReturnAddress}, +}; +use base64::{Engine, engine::general_purpose::STANDARD}; +use rutis_bridge::session::{HostDispatch, Value, settle}; +use serde::{Serialize, de::DeserializeOwned}; +use std::{ + io, + path::{Path, PathBuf}, + sync::Arc, +}; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; +use tokio::task::JoinSet; + +type Face = Arc; + +async fn call( + face: &Face, + method: &str, + args: impl Serialize, +) -> Result { + let args = Value::Data(serde_json::to_value(args)?); + let value = settle(face.invoke(method, args)?).await?; + Ok(serde_json::from_value( + if matches!(value, Value::Undefined) { + serde_json::Value::Null + } else { + value.json()? + }, + )?) +} + +async fn relay(face: &Face, id: &str, socket: impl Duplex, named_pipe: bool) -> Result<(), Error> { + let (mut input, mut output) = tokio::io::split(socket); + let send = async { + let mut buf = vec![0; CHUNK]; + loop { + let n = input.read(&mut buf).await?; + if n == 0 { + return call::<()>(face, "finishWrite", [id]).await; + } + call::<()>(face, "write", (id, STANDARD.encode(&buf[..n]))).await?; + } + }; + let receive = async { + while let Some(chunk) = call::>(face, "read", [id]).await? { + output.write_all(&STANDARD.decode(chunk)?).await?; + } + output.shutdown().await?; + Ok::<_, Error>(()) + }; + if named_pipe { + return tokio::select! { + result = send => result, + result = receive => result, + }; + } + tokio::try_join!(send, receive)?; + Ok(()) +} + +async fn serve_rpc(face: Face, stream: impl Duplex) -> Result<(), Error> { + let id: String = call(&face, "open", Vec::<()>::new()).await?; + let result = relay(&face, &id, stream, cfg!(windows)).await; + let _ = call::<()>(&face, "close", [id]).await; + result +} + +#[cfg(unix)] +async fn local_leaf(address: &str) -> Result, Error> { + let path = address + .strip_prefix("unix:") + .ok_or("invalid local leaf socket")?; + Ok(Box::new(tokio::net::UnixStream::connect(path).await?)) +} +#[cfg(windows)] +async fn local_leaf(address: &str) -> Result, Error> { + let (address, token) = address + .strip_prefix("tcp:") + .and_then(|a| a.split_once('#')) + .ok_or("invalid local leaf address")?; + let address: std::net::SocketAddr = address.parse()?; + if !address.ip().is_loopback() { + return Err("expected a loopback leaf".into()); + } + let mut s = tokio::net::TcpStream::connect(address).await?; + s.write_all(format!("{token}\n").as_bytes()).await?; + Ok(Box::new(s)) +} + +async fn serve_leaf(face: Face, mut control: impl Duplex) -> Result<(), Error> { + let mut addr = String::new(); + let n = BufReader::new((&mut control).take(4097)) + .read_line(&mut addr) + .await?; + if n > 4096 || !addr.ends_with('\n') { + return Err("invalid leaf request".into()); + } + let remote: ReturnAddress = call(&face, "prepareLeaf", Vec::<()>::new()).await?; + let result = async { + control + .write_all(format!("{}\n", remote.address).as_bytes()) + .await?; + call::<()>(&face, "acceptLeaf", [&remote.id]).await?; + relay(&face, &remote.id, local_leaf(addr.trim_end()).await?, false).await + } + .await; + let _ = call::<()>(&face, "close", [remote.id]).await; + result +} + +#[cfg(unix)] +struct Listener { + socket: tokio::net::UnixListener, + path: PathBuf, +} +#[cfg(unix)] +impl Listener { + fn bind(path: PathBuf) -> io::Result { + use std::os::unix::fs::PermissionsExt; + let socket = tokio::net::UnixListener::bind(&path)?; + let owner = Self { socket, path }; + std::fs::set_permissions(&owner.path, std::fs::Permissions::from_mode(0o600))?; + Ok(owner) + } + async fn accept(&mut self) -> io::Result { + Ok(self.socket.accept().await?.0) + } +} +#[cfg(unix)] +impl Drop for Listener { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.path); + } +} + +#[cfg(windows)] +struct Listener { + socket: tokio::net::windows::named_pipe::NamedPipeServer, + path: PathBuf, +} +#[cfg(windows)] +impl Listener { + fn bind(path: PathBuf) -> io::Result { + let socket = dim_client::pipe::bind( + path.to_str() + .ok_or_else(|| io::Error::other("invalid pipe name"))?, + true, + )?; + Ok(Self { socket, path }) + } + async fn accept(&mut self) -> io::Result { + self.socket.connect().await?; + let next = dim_client::pipe::bind( + self.path + .to_str() + .ok_or_else(|| io::Error::other("invalid pipe name"))?, + false, + )?; + Ok(std::mem::replace(&mut self.socket, next)) + } +} + +pub async fn serve(face: Face, endpoint: &Path, ready: &Path) -> Result<(), Error> { + let mut rpc = Listener::bind(endpoint.to_owned())?; + let mut leaf = Listener::bind(endpoint.with_extension("leaf"))?; + std::fs::write(ready, b"ready\n")?; + let mut tasks = JoinSet::new(); + loop { + tokio::select! { + stream=rpc.accept()=>{tasks.spawn(serve_rpc(face.clone(),stream?));} + stream=leaf.accept()=>{tasks.spawn(serve_leaf(face.clone(),stream?));} + Some(_)=tasks.join_next()=>{} + } + } +} diff --git a/crates/dim-terminal-transport/src/streams.rs b/crates/dim-terminal-transport/src/streams.rs new file mode 100644 index 0000000000..dc87efe068 --- /dev/null +++ b/crates/dim-terminal-transport/src/streams.rs @@ -0,0 +1,214 @@ +use base64::{Engine, engine::general_purpose::STANDARD}; +use serde::{Deserialize, Serialize}; +use std::{ + collections::HashMap, + io, + path::PathBuf, + sync::{Arc, Mutex}, + time::Duration, +}; +use tokio::{ + io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}, + net::TcpListener, + sync::Mutex as AsyncMutex, +}; +use tokio_util::sync::CancellationToken; +use uuid::Uuid; + +pub const CHUNK: usize = 48 * 1024; +pub trait Duplex: AsyncRead + AsyncWrite + Send + Unpin {} +impl Duplex for T {} +type Socket = Box; +struct Stream { + close_on_input_eof: bool, + read: AsyncMutex>, + write: AsyncMutex>, + closed: CancellationToken, +} + +#[derive(Serialize, Deserialize)] +pub struct ReturnAddress { + pub id: String, + pub address: String, +} + +struct PendingLeaf { + listener: Mutex>, + token: String, + closed: CancellationToken, +} + +pub struct TerminalTransport { + endpoint: PathBuf, + streams: Mutex>>, + listeners: Arc>>>, +} + +fn gone() -> io::Error { + io::Error::new(io::ErrorKind::NotConnected, "unknown terminal stream") +} +impl TerminalTransport { + pub fn new(endpoint: PathBuf) -> Self { + Self { + endpoint, + streams: Default::default(), + listeners: Default::default(), + } + } + fn insert(&self, id: String, socket: Socket, close_on_input_eof: bool) { + let (read, write) = tokio::io::split(socket); + self.streams.lock().unwrap().insert( + id, + Arc::new(Stream { + close_on_input_eof, + read: AsyncMutex::new(read), + write: AsyncMutex::new(write), + closed: CancellationToken::new(), + }), + ); + } + fn stream(&self, id: &str) -> io::Result> { + self.streams + .lock() + .unwrap() + .get(id) + .cloned() + .ok_or_else(gone) + } +} + +#[rutis::service] +impl TerminalTransport { + pub async fn open(&self) -> io::Result { + #[cfg(unix)] + let socket = { + use std::os::unix::fs::{FileTypeExt, MetadataExt}; + let meta = std::fs::symlink_metadata(&self.endpoint)?; + let uid = unsafe { libc::geteuid() }; + if !meta.file_type().is_socket() || meta.uid() != uid || meta.mode() & 0o077 != 0 { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "expected private App Server socket", + )); + } + let stream = tokio::net::UnixStream::connect(&self.endpoint).await?; + if stream.peer_cred()?.uid() != uid { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "unexpected App Server owner", + )); + } + stream + }; + #[cfg(windows)] + let socket = dim_client::pipe::connect( + self.endpoint + .to_str() + .ok_or_else(|| io::Error::other("invalid pipe name"))?, + ) + .await + .map_err(|(_, error)| error)?; + let id = Uuid::new_v4().to_string(); + self.insert(id.clone(), Box::new(socket), cfg!(windows)); + Ok(id) + } + pub async fn prepare_leaf(&self) -> io::Result { + let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)).await?; + let token = Uuid::new_v4().simple().to_string(); + let address = format!("tcp:{}#{token}", listener.local_addr()?); + let id = Uuid::new_v4().to_string(); + let pending = Arc::new(PendingLeaf { + listener: Mutex::new(Some(listener)), + token, + closed: CancellationToken::new(), + }); + let closed = pending.closed.clone(); + let listeners = self.listeners.clone(); + let expires = id.clone(); + listeners.lock().unwrap().insert(id.clone(), pending); + tokio::spawn(async move { + tokio::select! { + _=closed.cancelled()=>{}, + _=tokio::time::sleep(Duration::from_secs(15))=>{ + listeners.lock().unwrap().remove(&expires); + closed.cancel(); + } + } + }); + Ok(ReturnAddress { id, address }) + } + pub async fn accept_leaf(&self, id: String) -> io::Result<()> { + let pending = self + .listeners + .lock() + .unwrap() + .get(&id) + .cloned() + .ok_or_else(gone)?; + let listener = pending.listener.lock().unwrap().take().ok_or_else(gone)?; + let expected = format!("{}\n", pending.token); + let accept = async { + loop { + let (mut conn, _) = listener.accept().await?; + let mut supplied = vec![0; expected.len()]; + if matches!( + tokio::time::timeout(Duration::from_secs(1), conn.read_exact(&mut supplied)) + .await, + Ok(Ok(_)) + ) && supplied == expected.as_bytes() + { + return Ok::<_, io::Error>(conn); + } + } + }; + let socket = tokio::select! { + _ = pending.closed.cancelled() => return Err(gone()), + socket = accept => socket?, + }; + let mut listeners = self.listeners.lock().unwrap(); + listeners.remove(&id).ok_or_else(gone)?.closed.cancel(); + self.insert(id, Box::new(socket), false); + Ok(()) + } + pub async fn read(&self, id: String) -> io::Result> { + let stream = self.stream(&id)?; + let mut buf = vec![0; CHUNK]; + let mut reader = stream.read.lock().await; + let count = tokio::select! { + _ = stream.closed.cancelled() => return Err(gone()), + n = reader.read(&mut buf) => n?, + }; + Ok((count != 0).then(|| STANDARD.encode(&buf[..count]))) + } + pub async fn write(&self, id: String, data: String) -> io::Result<()> { + if data.len() > CHUNK.div_ceil(3) * 4 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "terminal block too large", + )); + } + let bytes = STANDARD.decode(data).map_err(io::Error::other)?; + let stream = self.stream(&id)?; + let mut writer = stream.write.lock().await; + tokio::select! { + _ = stream.closed.cancelled() => Err(gone()), + result = writer.write_all(&bytes) => result, + } + } + pub async fn finish_write(&self, id: String) -> io::Result<()> { + let stream = self.stream(&id)?; + if stream.close_on_input_eof { + self.close(id); + return Ok(()); + } + stream.write.lock().await.shutdown().await + } + pub fn close(&self, id: String) { + if let Some(pending) = self.listeners.lock().unwrap().remove(&id) { + pending.closed.cancel(); + } + if let Some(stream) = self.streams.lock().unwrap().remove(&id) { + stream.closed.cancel() + } + } +} diff --git a/crates/dim-terminal-transport/tests/windows_pipe_flow.rs b/crates/dim-terminal-transport/tests/windows_pipe_flow.rs new file mode 100644 index 0000000000..099c1a60fb --- /dev/null +++ b/crates/dim-terminal-transport/tests/windows_pipe_flow.rs @@ -0,0 +1,62 @@ +#![cfg(windows)] + +use dim_client::pipe; +use std::{io, time::Duration}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + process::Command, +}; +use uuid::Uuid; + +#[tokio::test] +async fn either_end_of_a_shared_rpc_pipe_can_finish_while_the_link_stays_open() { + let temp = tempfile::tempdir().unwrap(); + let ready = temp.path().join("ready"); + let target = format!(r"\\.\pipe\dim-test-target-{}", Uuid::new_v4()); + let proxy = format!(r"\\.\pipe\dim-test-proxy-{}", Uuid::new_v4()); + let mut first_target = pipe::bind(&target, true).unwrap(); + let (target_in, proxy_out) = io::pipe().unwrap(); + let (proxy_in, target_out) = io::pipe().unwrap(); + let binary = env!("CARGO_BIN_EXE_dim-terminal-transport"); + let mut target_host = Command::new(binary) + .args(["serve", &target]) + .stdin(target_in) + .stdout(target_out) + .kill_on_drop(true) + .spawn() + .unwrap(); + let mut proxy_host = Command::new(binary) + .args(["connect", &proxy]) + .arg(&ready) + .stdin(proxy_in) + .stdout(proxy_out) + .kill_on_drop(true) + .spawn() + .unwrap(); + tokio::time::timeout(Duration::from_secs(15), async { + while !ready.is_file() { + tokio::time::sleep(Duration::from_millis(25)).await; + } + let first = pipe::connect(&proxy).await.unwrap(); + first_target.connect().await.unwrap(); + let mut second_target = pipe::bind(&target, false).unwrap(); + let mut second = pipe::connect(&proxy).await.unwrap(); + second_target.connect().await.unwrap(); + + drop(first); + assert_eq!(first_target.read(&mut [0; 1]).await.unwrap(), 0); + second.write_all(b"request").await.unwrap(); + let mut request = [0; 7]; + second_target.read_exact(&mut request).await.unwrap(); + assert_eq!(&request, b"request"); + second_target.write_all(b"reply").await.unwrap(); + drop(second_target); + let mut reply = Vec::new(); + second.read_to_end(&mut reply).await.unwrap(); + assert_eq!(reply, b"reply"); + }) + .await + .expect("the keyboard receives the complete reply and EOF while the sharing link is open"); + proxy_host.kill().await.unwrap(); + let _ = target_host.kill().await; +} diff --git a/docs/architecture/build.md b/docs/architecture/build.md index e4ddcecf88..b7c1a64dc2 100644 --- a/docs/architecture/build.md +++ b/docs/architecture/build.md @@ -11,6 +11,8 @@ cargo build --workspace --locked A normal Cargo installation is sufficient; compiler caching is optional. Each worktree keeps its own target directory. Existing source caches can be reused without sharing build outputs. +For native sharing in a source build, run `cargo build --locked -p dimcode -p dim-terminal-transport` and `node scripts/build-sharing.mjs target/debug`. The Go module pins the toolchain and dependencies. The Alpha platform package places both helpers beside `dimcode`. The Rust helper embeds the rutis host, and its loader starts the bundled Go runtime for DNS-SD. The sharing listener authenticates TLS before passing the admitted connection to rutis-network's TCP link. Finishing a Windows RPC releases its target named pipe. POSIX sockets and the TCP UI return stream support half-close. The Go and Rust dependency notices are included in the archive. [User flow](../../npm/README.alpha.md#share-an-app-server) To run the protocol and shutdown regression, build the test server with `cargo build --locked -p dim-app-server --example sharing-shutdown-fixture`, then run `node --test scripts/native-sharing-flow.mjs`. + The release profile uses full LTO (`lto = "fat"`) with one codegen unit to reduce binary size. Hosted release builds use two Cargo jobs. The macOS ARM64 and Linux ARM64 release jobs override LTO to `thin` on their 7 GB and 16 GB runners; full LTO requires a successful release-profile build and runtime smoke test within that runner's memory budget before enabling it there. The other release targets retain full LTO. [The resource investigation](https://github.com/arcships/dim/issues/1674) tracks measurements and build costs. Code residency depends on executable layout and file-cache mapping conditions as well as code size. Normal PR tests use the dev profile, so release builds and runtime smoke tests on each supported platform must validate this setting. ## Native executable layout diff --git a/docs/architecture/tui-e2e.md b/docs/architecture/tui-e2e.md index b55f18da29..a7f0579bfa 100644 --- a/docs/architecture/tui-e2e.md +++ b/docs/architecture/tui-e2e.md @@ -112,6 +112,7 @@ daemon. `--keep` leaves the home and raw streams in place for inspection. | composer | `file_mention_inserts_a_workspace_link` | The `@` picker lists the `--cwd` workspace, inserts the chosen file, and completes a directory prefix to the file under it; the prompt carries both as absolute links | | no-session | `home_commands_without_a_session_answer_and_send_nothing` | `/export`, `/queue` and `/mcp list` run from the palette over a draft answer at home in both layouts, the draft returns to the composer after each, no command sends it, and the fixture model receives no request; `/agent` and a valued `/effort` stay with `tui_home_commands_without_a_session_answer_and_send_nothing` in CI | | hooks | `hook_context_and_stop_follow_up_stay_status_rows` | A prompt hook's context draws one closed row, named in the singular for its one line, and reaches the model after the operator's words; a stop hook's follow-up draws its own closed row and starts a turn; neither body nor the `` marker reaches the transcript; three `/tools` toggles open and close both | +| commands | `settings_manage_inbound_sharing` | With the Alpha sharing helpers alongside the CLI, enable access, read the token, rename, rotate and disable from Settings. Source-only builds omit the entry. | | commands | `slash_palette_lists_curated_commands_and_settings` | The palette's curated order and filter, the Settings panel, and `/keys` output | | commands | `palette_tab_completes_and_enter_runs_the_command` | `Tab` completes the command without running it, three `Tab`s keep completing and never exit the palette, and `Enter` still runs it, in both layouts | | runs | `streaming_status_reports_and_interrupts` | The status row says `working…`/`esc interrupt`, OSC 7501 reports `working`, `Escape` interrupts with the recorded reason, and the status settles; with `DIM_TERMINAL_PROGRESS=on`, OSC 9;4 draws the working bar and takes it down when the run settles, and the last sequence the pane receives after exit is that clear | diff --git a/docs/design/plugins/Tui.md b/docs/design/plugins/Tui.md index 2cd20a30b6..68b269e72c 100644 --- a/docs/design/plugins/Tui.md +++ b/docs/design/plugins/Tui.md @@ -284,6 +284,8 @@ The daemon does not start the leaf process: the user's shell does, and the process keeps the terminal it was started on. This leaves the daemon nothing to do with terminals, processes or their exit codes. +For a shared App Server, the terminal first binds its local leaf, then asks the authenticated target's `terminalTransport.prepareLeaf` for a one-use address on the target. The terminal passes that address and its original peer id to `ui.open`. The target daemon dials the address with its one-use token. The transport relays the resulting stream back to the waiting leaf. Both ends keep their normal rutis handshake and close semantics. Dropping the link releases its pending listeners and open streams. [Native terminal target topology](../research/native-terminal-targets.md#posix-连接怎样跨机器) + **Session.** On its first Session attachment, before `ui.open`, the running `Tui` binds a private address and mounts `LeafNode` at the client root, beside `Tui` and `DaemonLink`, accepting there. `LeafNode` provides the diff --git a/npm/README.alpha.md b/npm/README.alpha.md index ff5d9fc0ab..4d8363c6b1 100644 --- a/npm/README.alpha.md +++ b/npm/README.alpha.md @@ -30,3 +30,26 @@ See the [plugin author's guide](https://github.com/arcships/dim/blob/main/docs/t The type-only entry adds no runtime code or plugin registration. Dim's original source uses MIT. See `NOTICE` for distribution attribution. Native platform packages include `licenses/RUST-THIRD-PARTY-NOTICES.txt`, terminal library licenses under `licenses/grok-build/`, and Aimux's own MIT license under `licenses/aimux/`. The optional `dimcode-web` package includes `web/THIRD-PARTY-NOTICES.txt`, covering its JavaScript dependencies and Geist fonts under their own licenses. Bundled plugins retain the license files supplied by their npm packages. + +### Share an App Server + +On the computer you want to control, open `/settings → Remote access` and turn on **Allow connections to this computer**, or run `dima share enable` in a shell. Both show the reachable addresses and the complete token. The token is readable on a narrow screen by selecting it in Settings. Sharing starts off and stays available when you exit the TUI while the App Server is running. + +On the computer at the keyboard, run `dima share discover` to see LAN candidates, or use an address from the other computer directly. A Tailscale IP or DNS name works too. The default port is 7443. + +**Open the remote TUI from a shell.** Run the following in your terminal. At the first prompt, type the token from the computer you want to control and press Enter. Input is hidden. Successful pairing opens an interactive TUI on that computer. + +```text +$ dima share connect
+Sharing token: _ + | + +-- Enter --> remote TUI +``` + +**Run one remote CLI command.** Put the command after `--`. For example, `dima share connect
-- mcp list` prints the target's MCP configuration and returns to the shell. A previous successful pairing lets you run this without another token prompt. For a specific target directory, use `dima share connect
-- --cwd /srv/project mcp list`. To reopen a known session in the TUI, use `dima share connect
-- --resume `. + +Use `--no-remember` for a one-time pairing. After a token reset, enter the new one with `dima share connect
--pair`. Resetting the token or turning sharing off disconnects existing remote terminals. Remote access in Settings always controls the computer at the keyboard. + +Run offline database maintenance (including `daemon vacuum` and raw Timeline `export`), migration, client updates, Web installation and local sharing settings directly on the intended computer. For a remote session export, use `dima share connect
-- session export --format json`. + +For clients using the shared byte stream directly, keep a Windows RPC open until its reply has arrived. Ending input closes that target named pipe in both directions. On a Windows keyboard computer, the proxy delivers the final reply and closes its local RPC pipe when the target stream ends. POSIX sockets and the TCP UI return stream can close their write side and continue reading. diff --git a/runtime/native-sharing/client.go b/runtime/native-sharing/client.go new file mode 100644 index 0000000000..610f8ef9d8 --- /dev/null +++ b/runtime/native-sharing/client.go @@ -0,0 +1,151 @@ +package main + +import ( + "context" + "crypto/ed25519" + "crypto/tls" + "errors" + "fmt" + "io" + "net" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "time" + + "golang.org/x/term" +) + +func tokenInput() (string, error) { + fmt.Fprint(os.Stderr, "Sharing token: ") + if term.IsTerminal(int(os.Stdin.Fd())) { + bytes, err := term.ReadPassword(int(os.Stdin.Fd())) + fmt.Fprintln(os.Stderr) + return string(bytes), err + } + var token strings.Builder + var byteIn [1]byte + for token.Len() <= 128 { + _, err := io.ReadFull(os.Stdin, byteIn[:]) + if errors.Is(err, io.EOF) || byteIn[0] == '\n' { + break + } + if err != nil { + return "", err + } + token.WriteByte(byteIn[0]) + } + return token.String(), nil +} +func connect(ctx context.Context, dir, address string, saveToken, fresh bool, args []string) error { + if _, _, err := net.SplitHostPort(address); err != nil { + address = net.JoinHostPort(strings.Trim(address, "[]"), "7443") + } + known, err := readKnown(dir) + if err != nil { + return err + } + var token string + var cred credential + confirmed := known.Routes[address] + if !fresh { + token = known.Tokens[confirmed].Token + } + if token == "" && !fresh && confirmed == "" && len(known.Tokens) > 0 { + raw, err := (&net.Dialer{Timeout: 8 * time.Second}).DialContext(ctx, "tcp", address) + if err != nil { + return err + } + probe := tls.Client(raw, &tls.Config{MinVersion: tls.VersionTLS13, NextProtos: []string{protocol}, InsecureSkipVerify: true, VerifyConnection: func(state tls.ConnectionState) error { + if len(state.PeerCertificates) == 1 { + if key, ok := state.PeerCertificates[0].PublicKey.(ed25519.PublicKey); ok { + token = known.Tokens[encoding.EncodeToString(fingerprint(key))].Token + } + } + return errors.New("identity lookup complete") + }}) + probeCtx, cancel := context.WithTimeout(ctx, 8*time.Second) + _ = probe.HandshakeContext(probeCtx) + cancel() + raw.Close() + } + if token == "" { + token, err = tokenInput() + if err != nil { + return err + } + } + cred, err = parseCredential(token) + if err != nil { + return err + } + if confirmed != "" && confirmed != encoding.EncodeToString(cred.pin) && !fresh { + return errors.New("the computer at this address changed; use --pair to confirm its new token") + } + raw, err := (&net.Dialer{Timeout: 8 * time.Second}).DialContext(ctx, "tcp", address) + if err != nil { + return err + } + defer raw.Close() + cfg := &tls.Config{MinVersion: tls.VersionTLS13, NextProtos: []string{protocol}, InsecureSkipVerify: true, VerifyConnection: cred.verify} + tlsConn, err := authenticate(ctx, raw, cfg, false, cred.secret) + if err != nil { + return fmt.Errorf("sharing authentication failed (use --pair after a token reset): %w", err) + } + if err = tlsConn.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil { + return err + } + info, err := readTarget(tlsConn) + if err != nil { + return err + } + if err = tlsConn.SetReadDeadline(time.Time{}); err != nil { + return err + } + if saveToken { + if err = remember(dir, address, token, info.Name, cred); err != nil { + return err + } + } + tmp, err := os.MkdirTemp("", "dim-link-") + if err != nil { + return err + } + defer os.RemoveAll(tmp) + endpoint := filepath.Join(tmp, "rpc.sock") + if runtime.GOOS == "windows" { + suffix, err := randomBytes(24) + if err != nil { + return err + } + endpoint = `\\.\pipe\dim-link-` + encoding.EncodeToString(suffix) + } + ready := filepath.Join(tmp, "ready") + link, stop := context.WithCancel(ctx) + done := make(chan error, 1) + go func() { done <- runPeer(link, tlsConn, sibling("dim-terminal-transport"), "connect", endpoint, ready) }() + defer func() { stop(); tlsConn.Close(); <-done }() + deadline := time.NewTimer(15 * time.Second) + defer deadline.Stop() + tick := time.NewTicker(30 * time.Millisecond) + defer tick.Stop() + for { + if _, err = os.Stat(ready); err == nil { + break + } + select { + case err := <-done: + done <- err + return fmt.Errorf("terminal transport unavailable: %v", err) + case <-deadline.C: + return errors.New("terminal transport startup timed out") + case <-tick.C: + } + } + cmd := exec.CommandContext(ctx, sibling("dimcode"), args...) + cmd.Env = append(os.Environ(), "DIMCODE_TERMINAL_PROXY="+endpoint, "DIMCODE_TERMINAL_WORKSPACE="+info.WorkingDirectory) + cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr + return cmd.Run() +} diff --git a/runtime/native-sharing/discovery.go b/runtime/native-sharing/discovery.go new file mode 100644 index 0000000000..b6038d33fa --- /dev/null +++ b/runtime/native-sharing/discovery.go @@ -0,0 +1,188 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net" + "os" + "os/exec" + "path/filepath" + "slices" + "strconv" + "time" + + "github.com/arcships/rutis-network/discovery/mdns" +) + +type advertisement struct { + Type string `json:"type"` + Instance string `json:"instance"` + Port int `json:"port"` +} +type discoveryRow struct { + ID string `json:"id"` + Name string `json:"name"` + Config discoveryOptions `json:"config"` +} +type discoveryOptions struct { + Interface string `json:"interface"` + Service string `json:"service,omitempty"` + Browse string `json:"browse,omitempty"` + Publish *advertisement `json:"publish,omitempty"` +} +type goBinaries struct { + Binaries []string `json:"binaries"` +} +type manifest struct { + ID string `json:"id"` + Runtimes map[string]goBinaries `json:"runtimes"` + Rows []discoveryRow `json:"rows"` +} + +const serviceType = "_dim-alpha._tcp" + +func discovery(ctx context.Context, publish *advertisement, bound net.IP, out io.Writer) error { + tmp, err := os.MkdirTemp("", "dim-mdns-") + if err != nil { + return err + } + defer os.RemoveAll(tmp) + ifaces, err := net.Interfaces() + if err != nil { + return err + } + rows := []discoveryRow{} + for _, i := range ifaces { + if i.Flags&(net.FlagUp|net.FlagMulticast) != net.FlagUp|net.FlagMulticast || i.Flags&(net.FlagLoopback|net.FlagPointToPoint) != 0 { + continue + } + matches := false + addresses, _ := i.Addrs() + for _, a := range addresses { + ip, _, err := net.ParseCIDR(a.String()) + if err == nil && (ip.IsGlobalUnicast() || ip.IsLinkLocalUnicast()) && (bound == nil || bound.IsUnspecified() || ip.Equal(bound)) { + matches = true + break + } + } + if !matches { + continue + } + opts := discoveryOptions{Interface: i.Name, Publish: publish} + id := "lan-" + strconv.Itoa(i.Index) + if publish == nil { + opts.Browse = serviceType + opts.Service = id + } + rows = append(rows, discoveryRow{id, "go:discover-mdns", opts}) + } + if len(rows) == 0 { + if publish == nil { + return json.NewEncoder(out).Encode([]mdns.Candidate{}) + } + return nil + } + file := filepath.Join(tmp, "rutis.json") + if err = save(file, manifest{"dim-discovery", map[string]goBinaries{"go": {[]string{sibling("dim-sharing")}}}, rows}); err != nil { + return err + } + mode := "announce" + if publish == nil { + mode = "discover" + } + args := []string{mode, file} + if publish == nil { + for _, row := range rows { + args = append(args, row.Config.Service) + } + } + cmd := exec.CommandContext(ctx, sibling("dim-terminal-transport"), args...) + cmd.Stdout = out + cmd.Stderr = os.Stderr + cmd.Dir = tmp + input, err := cmd.StdinPipe() + if err != nil { + return err + } + defer input.Close() + cmd.Cancel = input.Close + cmd.WaitDelay = 3 * time.Second + return cmd.Run() +} +func advertise(ctx context.Context, name string, bound *net.TCPAddr) { + for ctx.Err() == nil { + if err := discovery(ctx, &advertisement{serviceType, name, bound.Port}, bound.IP, io.Discard); err != nil && ctx.Err() == nil { + fmt.Fprintln(os.Stderr, "LAN announcement unavailable:", err) + } + select { + case <-ctx.Done(): + return + case <-time.After(15 * time.Second): + } + } +} + +type device struct { + Name string `json:"name"` + Addresses []string `json:"addresses"` + Verified bool `json:"verified"` +} + +func browse(ctx context.Context, dir string) error { + k, err := readKnown(dir) + if err != nil { + return err + } + var observed bytes.Buffer + window, cancel := context.WithTimeout(ctx, 12*time.Second) + defer cancel() + err = discovery(window, nil, nil, &observed) + if err != nil { + fmt.Fprintln(os.Stderr, "LAN discovery unavailable:", err) + } + var candidates []mdns.Candidate + if err == nil { + if err = json.Unmarshal(observed.Bytes(), &candidates); err != nil { + return err + } + } + devices := []device{} + for id, saved := range k.Tokens { + d := device{Name: saved.Name, Verified: true} + for address, owner := range k.Routes { + if owner == id { + d.Addresses = append(d.Addresses, address) + } + } + slices.Sort(d.Addresses) + if len(d.Addresses) > 0 { + devices = append(devices, d) + } + } + for _, c := range candidates { + d := device{Name: c.Instance} + if !validName(d.Name) { + continue + } + for _, address := range c.Addresses { + ip := net.ParseIP(address) + if ip == nil { + continue + } + if ip.IsLinkLocalUnicast() && ip.To4() == nil { + address += "%" + c.Interface + } + route := net.JoinHostPort(address, strconv.Itoa(int(c.Port))) + if k.Routes[route] == "" { + d.Addresses = append(d.Addresses, route) + } + } + if len(d.Addresses) > 0 { + devices = append(devices, d) + } + } + return json.NewEncoder(os.Stdout).Encode(devices) +} diff --git a/runtime/native-sharing/go.mod b/runtime/native-sharing/go.mod new file mode 100644 index 0000000000..4f45f704b0 --- /dev/null +++ b/runtime/native-sharing/go.mod @@ -0,0 +1,19 @@ +module github.com/arcships/dim/runtime/native-sharing + +go 1.26.0 + +require ( + github.com/arcships/rutis-network/discovery/mdns v0.1.0 + github.com/arcships/rutis-network/link/tcp v0.1.0 + github.com/arcships/rutis/go/rutis v0.23.0 + github.com/fsnotify/fsnotify v1.9.0 + github.com/gofrs/flock v0.12.1 + golang.org/x/sys v0.50.0 + golang.org/x/term v0.48.0 +) + +require ( + github.com/ebitengine/purego v0.11.1 // indirect + github.com/miekg/dns v1.1.73 // indirect + golang.org/x/net v0.62.0 // indirect +) diff --git a/runtime/native-sharing/go.sum b/runtime/native-sharing/go.sum new file mode 100644 index 0000000000..c37667311d --- /dev/null +++ b/runtime/native-sharing/go.sum @@ -0,0 +1,32 @@ +github.com/arcships/rutis-network/discovery/mdns v0.1.0 h1:DRyjxr/irAkk67K0fEKptQIqv7NX4BBDjoPB4H4A1yU= +github.com/arcships/rutis-network/discovery/mdns v0.1.0/go.mod h1:OAWx7mGjCwrRf15RH0mfzkpIjz2GfLsha3y5scjTLls= +github.com/arcships/rutis-network/link/tcp v0.1.0 h1:syDwa6hBAjpdy65C8bjT6/G2efZkDS9YFDqdA4Dm40U= +github.com/arcships/rutis-network/link/tcp v0.1.0/go.mod h1:0CEOEP3y2KTdMG+gzLoZ00l9hbgZTRdmgRTy35mViow= +github.com/arcships/rutis/go/rutis v0.23.0 h1:K9m6tbHbrHowIR3GIU8s/sP7UClJf0cAviZtlqX+wxw= +github.com/arcships/rutis/go/rutis v0.23.0/go.mod h1:JLxW7fPIlGfD7O0VeBXIQd+Mdya5ZYprMhBIAUSQ258= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/ebitengine/purego v0.11.1 h1:2zpWRSQNVKN4eKsKO9eM1ILDgWfYMY9GwqRmK6XeQ/0= +github.com/ebitengine/purego v0.11.1/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ= +github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= +github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= +github.com/gofrs/flock v0.12.1 h1:MTLVXXHf8ekldpJk3AKicLij9MdwOWkZ+a/jHHZby9E= +github.com/gofrs/flock v0.12.1/go.mod h1:9zxTsyu5xtJ9DK+1tFZyibEV7y3uwDxPPfbxeeHCoD0= +github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE= +github.com/miekg/dns v1.1.73/go.mod h1:RW2Obtfd5NZHvOFe3zYG0W8koWOQtAzyHaLo8vASBuQ= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/term v0.48.0 h1:G6UU1eiSB8nl3DzeUGt7Mg+2SctI8tPS6Z5/mBt6cOk= +golang.org/x/term v0.48.0/go.mod h1:BRDLHCZr2SUjIeBHHpRyQeC9xzSAVbzY2rvKgafnHf4= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/runtime/native-sharing/identity.go b/runtime/native-sharing/identity.go new file mode 100644 index 0000000000..b08ad07557 --- /dev/null +++ b/runtime/native-sharing/identity.go @@ -0,0 +1,90 @@ +package main + +import ( + "crypto/ed25519" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "crypto/tls" + "crypto/x509" + "encoding/base32" + "errors" + "fmt" + "math/big" + "strings" + "time" +) + +const secretSize = 24 +const pinSize = 20 + +var encoding = base32.StdEncoding.WithPadding(base32.NoPadding) +var errCredential = errors.New("invalid sharing token") + +type identity struct { + Seed []byte `json:"seed"` + Secret []byte `json:"secret"` +} + +func randomBytes(n int) ([]byte, error) { + b := make([]byte, n) + _, err := rand.Read(b) + return b, err +} + +func newIdentity() (identity, error) { + seed, err := randomBytes(ed25519.SeedSize) + if err != nil { + return identity{}, err + } + secret, err := randomBytes(secretSize) + return identity{seed, secret}, err +} + +func fingerprint(key ed25519.PublicKey) []byte { + sum := sha256.Sum256(key) + return sum[:pinSize] +} + +func (i identity) token() string { + key := ed25519.NewKeyFromSeed(i.Seed) + return "DIM1-" + encoding.EncodeToString(fingerprint(key.Public().(ed25519.PublicKey))) + "-" + encoding.EncodeToString(i.Secret) +} + +type credential struct{ pin, secret []byte } + +func parseCredential(text string) (credential, error) { + parts := strings.Split(strings.ToUpper(strings.TrimSpace(text)), "-") + if len(parts) != 3 || parts[0] != "DIM1" { + return credential{}, errCredential + } + pin, e1 := encoding.DecodeString(parts[1]) + secret, e2 := encoding.DecodeString(parts[2]) + if e1 != nil || e2 != nil || len(pin) != pinSize || len(secret) != secretSize { + return credential{}, errCredential + } + return credential{pin, secret}, nil +} + +func (i identity) certificate() (tls.Certificate, error) { + if len(i.Seed) != ed25519.SeedSize || len(i.Secret) != secretSize { + return tls.Certificate{}, errCredential + } + key := ed25519.NewKeyFromSeed(i.Seed) + pub := key.Public().(ed25519.PublicKey) + now := time.Now() + cert := &x509.Certificate{SerialNumber: new(big.Int).SetBytes(fingerprint(pub)), NotBefore: now.Add(-time.Hour), NotAfter: now.AddDate(1, 0, 0), KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}} + der, err := x509.CreateCertificate(rand.Reader, cert, cert, pub, key) + return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key}, err +} + +func (c credential) verify(state tls.ConnectionState) error { + if len(state.PeerCertificates) != 1 { + return errors.New("unexpected sharing certificate chain") + } + pub, ok := state.PeerCertificates[0].PublicKey.(ed25519.PublicKey) + if !ok || subtle.ConstantTimeCompare(c.pin, fingerprint(pub)) != 1 { + return fmt.Errorf("sharing computer identity does not match the token") + } + return nil +} diff --git a/runtime/native-sharing/link.go b/runtime/native-sharing/link.go new file mode 100644 index 0000000000..134182cb26 --- /dev/null +++ b/runtime/native-sharing/link.go @@ -0,0 +1,157 @@ +package main + +import ( + "bufio" + "bytes" + "context" + "crypto/subtle" + "crypto/tls" + "encoding/binary" + "encoding/json" + "errors" + "io" + "net" + "os" + "os/exec" + "time" + + "github.com/arcships/rutis-network/link/tcp" +) + +const protocol = "dim-terminal/1" +const maxFrame = 16 << 20 + +type targetInfo struct { + Name string `json:"name"` + WorkingDirectory string `json:"workingDirectory"` +} + +func (info targetInfo) write(conn net.Conn) error { + data, err := json.Marshal(info) + if err != nil { + return err + } + if len(data) > 16384 { + return errors.New("target information is too large") + } + _, err = conn.Write(append(binary.BigEndian.AppendUint16(nil, uint16(len(data))), data...)) + return err +} +func readTarget(conn net.Conn) (targetInfo, error) { + var info targetInfo + var length uint16 + if err := binary.Read(conn, binary.BigEndian, &length); err != nil { + return info, err + } + if length == 0 || length > 16384 { + return info, errors.New("invalid target information length") + } + data := make([]byte, length) + if _, err := io.ReadFull(conn, data); err != nil { + return info, err + } + if err := json.Unmarshal(data, &info); err != nil { + return info, err + } + if !validName(info.Name) || info.WorkingDirectory == "" { + return info, errors.New("invalid target information") + } + return info, nil +} + +func authenticate(ctx context.Context, raw net.Conn, cfg *tls.Config, server bool, secret []byte) (net.Conn, error) { + if err := raw.SetDeadline(time.Now().Add(10 * time.Second)); err != nil { + return nil, err + } + var conn *tls.Conn + if server { + conn = tls.Server(raw, cfg) + } else { + conn = tls.Client(raw, cfg) + } + if err := conn.HandshakeContext(ctx); err != nil { + return nil, err + } + if conn.ConnectionState().NegotiatedProtocol != protocol { + return nil, errors.New("incompatible sharing protocol") + } + if server { + var offered [secretSize]byte + if _, err := io.ReadFull(conn, offered[:]); err != nil { + return nil, err + } + if subtle.ConstantTimeCompare(secret, offered[:]) != 1 { + _, _ = conn.Write([]byte{0}) + return nil, errCredential + } + if _, err := conn.Write([]byte{1}); err != nil { + return nil, err + } + } else { + if _, err := conn.Write(secret); err != nil { + return nil, err + } + var ack [1]byte + if _, err := io.ReadFull(conn, ack[:]); err != nil { + return nil, err + } + if ack[0] != 1 { + return nil, errCredential + } + } + return conn, conn.SetDeadline(time.Time{}) +} + +// runPeer connects an admitted TCP link to a dedicated rutis kernel. The kernel owns all +// RPC streams for this link and exits with it. +func runPeer(parent context.Context, conn net.Conn, executable string, args ...string) error { + ctx, cancel := context.WithCancel(parent) + defer cancel() + defer conn.Close() + cmd := exec.CommandContext(ctx, executable, args...) + cmd.Stderr = os.Stderr + input, err := cmd.StdinPipe() + if err != nil { + return err + } + output, err := cmd.StdoutPipe() + if err != nil { + return err + } + if err = cmd.Start(); err != nil { + return err + } + done, err := tcp.Open(ctx, conn, tcp.Sessions{Open: func(_ context.Context, far tcp.Far) (tcp.Near, error) { + go func() { + reader := bufio.NewScanner(output) + reader.Buffer(make([]byte, 8192), maxFrame+1) + for reader.Scan() { + if err := far.Send(reader.Bytes()); err != nil { + break + } + } + far.Close(tcp.CloseReason{Kind: "done"}) + }() + return tcp.Near{Receive: func(_ context.Context, frame []byte) error { + if bytes.IndexByte(frame, '\n') >= 0 { + return errors.New("invalid rutis frame") + } + _, err := input.Write(append(frame, '\n')) + return err + }, End: func(context.Context, tcp.CloseReason) error { return input.Close() }}, nil + }}) + if err == nil { + err = <-done + } + _ = input.Close() + waited := make(chan error, 1) + go func() { waited <- cmd.Wait() }() + select { + case childErr := <-waited: + return errors.Join(err, childErr) + case <-time.After(time.Second): + cancel() + <-waited + return err + } +} diff --git a/runtime/native-sharing/main.go b/runtime/native-sharing/main.go new file mode 100644 index 0000000000..9e83cd6b83 --- /dev/null +++ b/runtime/native-sharing/main.go @@ -0,0 +1,119 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" + "os/signal" + "path/filepath" + "runtime" + "syscall" + + "github.com/arcships/rutis-network/discovery/mdns" + "github.com/arcships/rutis-network/link/tcp" + "github.com/arcships/rutis/go/rutis/advanced" +) + +func sibling(name string) string { + path, err := os.Executable() + if err != nil { + panic(err) + } + if runtime.GOOS == "windows" { + name += ".exe" + } + return filepath.Join(filepath.Dir(path), name) +} +func main() { + ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer cancel() + if err := run(ctx, os.Args[1:]); err != nil { + var exit *exec.ExitError + if errors.As(err, &exit) && exit.ExitCode() > 0 { + os.Exit(exit.ExitCode()) + } + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} +func run(ctx context.Context, args []string) error { + if len(args) > 0 && args[0] != "--home" { + return advanced.ServeArgs(args, mdns.Plugin, tcp.Dial, tcp.Listen) + } + if len(args) < 3 { + return errors.New("usage: dim-sharing --home DIR status|enable|disable|rename NAME|reset|discover|connect ADDRESS [--pair] [--no-remember] [-- CLI_ARGS...]") + } + dir := filepath.Join(args[1], "sharing") + op := args[2] + rest := args[3:] + if err := os.MkdirAll(dir, 0700); err != nil { + return err + } + if err := secureDirectory(dir); err != nil { + return err + } + switch op { + case "serve": + if len(rest) != 1 { + return errors.New("missing App Server endpoint") + } + ctx, stop := context.WithCancel(ctx) + defer stop() + go func() { _, _ = io.Copy(io.Discard, os.Stdin); stop() }() + return sharing(ctx, dir, rest[0]) + case "discover": + return browse(ctx, dir) + case "connect": + if len(rest) == 0 { + return errors.New("connect needs an address") + } + address := rest[0] + args := rest[1:] + remember, fresh := true, false + flags: + for len(args) > 0 { + switch args[0] { + case "--pair": + fresh = true + case "--no-remember": + remember = false + case "--": + args = args[1:] + break flags + default: + return errors.New("put native CLI arguments after --") + } + args = args[1:] + } + return connect(ctx, dir, address, remember, fresh, append([]string{"--home", filepath.Dir(filepath.Dir(dir))}, args...)) + case "status", "enable", "disable", "rename", "reset": + var s settings + var err error + if op == "status" { + s, err = readSettings(dir) + } else { + name := "" + if op == "rename" { + if len(rest) != 1 { + return errors.New("rename needs a computer name") + } + name = rest[0] + } + s, err = mutate(dir, op, name) + } + if err != nil { + return err + } + st, err := localStatus(dir, s, op != "status") + if err != nil { + return err + } + return json.NewEncoder(os.Stdout).Encode(st) + default: + return fmt.Errorf("unknown sharing operation %q", op) + } +} diff --git a/runtime/native-sharing/private_unix.go b/runtime/native-sharing/private_unix.go new file mode 100644 index 0000000000..89ecab1ca6 --- /dev/null +++ b/runtime/native-sharing/private_unix.go @@ -0,0 +1,21 @@ +//go:build !windows + +package main + +import ( + "errors" + "os" + "syscall" +) + +func secureDirectory(path string) error { + info, err := os.Lstat(path) + if err != nil { + return err + } + owner, ok := info.Sys().(*syscall.Stat_t) + if !ok || !info.IsDir() || info.Mode().Perm()&0077 != 0 || int(owner.Uid) != os.Geteuid() { + return errors.New("sharing directory must be private and owned by the current user") + } + return nil +} diff --git a/runtime/native-sharing/private_windows.go b/runtime/native-sharing/private_windows.go new file mode 100644 index 0000000000..512d485085 --- /dev/null +++ b/runtime/native-sharing/private_windows.go @@ -0,0 +1,42 @@ +package main + +import ( + "errors" + "os" + + "golang.org/x/sys/windows" +) + +func secureDirectory(path string) error { + info, err := os.Lstat(path) + if err != nil { + return err + } + if !info.IsDir() { + return errors.New("expected a private sharing directory") + } + user, err := windows.GetCurrentProcessToken().GetTokenUser() + if err != nil { + return err + } + existing, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION) + if err != nil { + return err + } + owner, _, err := existing.Owner() + if err != nil { + return err + } + if !owner.Equals(user.User.Sid) { + return errors.New("sharing directory has a different owner") + } + security, err := windows.SecurityDescriptorFromString("D:P(A;OICI;FA;;;" + user.User.Sid.String() + ")") + if err != nil { + return err + } + acl, _, err := security.DACL() + if err != nil { + return err + } + return windows.SetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, nil, nil, acl, nil) +} diff --git a/runtime/native-sharing/server.go b/runtime/native-sharing/server.go new file mode 100644 index 0000000000..5579d56dc6 --- /dev/null +++ b/runtime/native-sharing/server.go @@ -0,0 +1,256 @@ +package main + +import ( + "bytes" + "context" + "crypto/tls" + "errors" + "fmt" + "github.com/fsnotify/fsnotify" + "net" + "os" + "path/filepath" + "slices" + "strconv" + "sync" + "time" + + "github.com/gofrs/flock" +) + +type status struct { + Name string `json:"name"` + Enabled bool `json:"enabled"` + Token string `json:"token,omitempty"` + Addresses []string `json:"addresses"` + Revision uint64 `json:"revision"` + Error string `json:"error,omitempty"` +} + +func addresses(l net.Listener) []string { + bound := l.Addr().(*net.TCPAddr) + if !bound.IP.IsUnspecified() { + return []string{bound.String()} + } + result := []string{} + ifaces, _ := net.Interfaces() + for _, i := range ifaces { + if i.Flags&net.FlagUp == 0 || i.Flags&net.FlagLoopback != 0 { + continue + } + addrs, _ := i.Addrs() + for _, a := range addrs { + ip, _, err := net.ParseCIDR(a.String()) + if err == nil && ip.IsGlobalUnicast() { + result = append(result, net.JoinHostPort(ip.String(), strconv.Itoa(bound.Port))) + } + } + } + return result +} +func sharing(ctx context.Context, dir, endpoint string) error { + owner := flock.New(filepath.Join(dir, "serving.lock")) + ok, err := owner.TryLock() + if err != nil { + return err + } + if !ok { + return errors.New("sharing supervisor already running") + } + defer owner.Unlock() + statusFile := filepath.Join(dir, "listener.json") + defer os.Remove(statusFile) + watcher, err := fsnotify.NewWatcher() + if err != nil { + return err + } + defer watcher.Close() + if err = watcher.Add(dir); err != nil { + return err + } + var active, announce context.CancelFunc + var peersDone <-chan struct{} + var announcements sync.WaitGroup + var listener net.Listener + stopAnnouncement := func() { + if announce != nil { + announce() + announcements.Wait() + announce = nil + } + } + stop := func() { + if active != nil { + active() + <-peersDone + active = nil + listener = nil + } + stopAnnouncement() + } + defer stop() + var applied settings + var previous status + refresh := time.NewTicker(15 * time.Second) + defer refresh.Stop() + for { + s, err := readSettings(dir) + if err != nil { + return err + } + st := status{Name: s.Name, Enabled: s.Enabled, Revision: s.Revision, Addresses: []string{}} + listen := os.Getenv("DIMCODE_SHARING_LISTEN") + if listen == "" { + listen = ":7443" + } + if listener != nil { + listen = listener.Addr().String() + } + if !s.Enabled || !bytes.Equal(applied.Identity.Secret, s.Identity.Secret) { + stop() + } + if s.Enabled && listener == nil { + cert, err := s.Identity.certificate() + if err != nil { + return err + } + l, err := net.Listen("tcp", listen) + if err != nil { + st.Error = err.Error() + } else { + var generation context.Context + generation, active = context.WithCancel(context.WithoutCancel(ctx)) + listener = l + done := make(chan struct{}) + peersDone = done + go func() { + defer close(done) + acceptLinks(generation, l, &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS13, NextProtos: []string{protocol}}, s.Identity.Secret, endpoint, dir) + }() + } + } + if listener != nil { + st.Addresses = addresses(listener) + if announce == nil || applied.Name != s.Name || !slices.Equal(st.Addresses, previous.Addresses) { + stopAnnouncement() + var generation context.Context + generation, announce = context.WithCancel(ctx) + bound := listener.Addr().(*net.TCPAddr) + announcements.Go(func() { advertise(generation, s.Name, bound) }) + } + } + if previous.Name == "" || previous.Revision != st.Revision || !slices.Equal(st.Addresses, previous.Addresses) || previous.Error != st.Error { + if err = save(statusFile, st); err != nil { + return err + } + } + applied = s + previous = st + waiting: + for { + select { + case <-ctx.Done(): + if listener != nil { + listener.Close() + select { + case <-peersDone: + case <-time.After(10 * time.Second): + } + } + return nil + case err := <-watcher.Errors: + return err + case event := <-watcher.Events: + if filepath.Base(event.Name) == "sharing.json" { + break waiting + } + case <-refresh.C: + if s.Enabled { + break waiting + } + } + } + } + +} +func acceptLinks(ctx context.Context, l net.Listener, cfg *tls.Config, secret []byte, endpoint, dir string) { + defer l.Close() + finished := context.AfterFunc(ctx, func() { l.Close() }) + defer finished() + var links sync.WaitGroup + defer links.Wait() + slots := make(chan struct{}, 32) + for { + conn, err := l.Accept() + if err != nil { + return + } + select { + case slots <- struct{}{}: + default: + conn.Close() + continue + } + links.Go(func() { + defer func() { <-slots }() + defer conn.Close() + stop := context.AfterFunc(ctx, func() { conn.Close() }) + defer stop() + admitted, err := authenticate(ctx, conn, cfg, true, secret) + if err != nil { + return + } + current, err := readSettings(dir) + if err != nil || !validName(current.Name) { + return + } + cwd, err := os.Getwd() + if err != nil { + return + } + if err = (targetInfo{current.Name, cwd}).write(admitted); err != nil { + return + } + _ = runPeer(ctx, admitted, sibling("dim-terminal-transport"), "serve", endpoint) + }) + } +} +func localStatus(dir string, s settings, wait bool) (status, error) { + st := status{Name: s.Name, Enabled: s.Enabled, Revision: s.Revision, Addresses: []string{}} + deadline := time.Now().Add(4 * time.Second) + for { + var live status + err := load(filepath.Join(dir, "listener.json"), &live) + applied := err == nil && live.Revision == s.Revision + if applied || wait && !s.Enabled { + lock := flock.New(filepath.Join(dir, "serving.lock")) + free, err := lock.TryLock() + if err != nil { + return st, err + } + if free { + lock.Unlock() + if !s.Enabled { + break + } + } else if applied { + st = live + break + } + } + if !wait || time.Now().After(deadline) { + if s.Enabled || wait { + st.Error = "sharing supervisor is unavailable" + } + break + } + time.Sleep(40 * time.Millisecond) + } + if s.Enabled && len(s.Identity.Secret) > 0 { + st.Token = s.Identity.token() + } + if st.Error != "" && wait { + return st, fmt.Errorf("%s", st.Error) + } + return st, nil +} diff --git a/runtime/native-sharing/sharing_test.go b/runtime/native-sharing/sharing_test.go new file mode 100644 index 0000000000..079650cabb --- /dev/null +++ b/runtime/native-sharing/sharing_test.go @@ -0,0 +1,146 @@ +package main + +import ( + "bufio" + "context" + "crypto/tls" + "errors" + "net" + "path/filepath" + "testing" +) + +func TestPairingSurvivesRouteAndNameChangesButNotTokenReset(t *testing.T) { + server, client := t.TempDir(), t.TempDir() + initial, err := readSettings(server) + if err != nil || initial.Enabled { + t.Fatal("a new installation must be off", err) + } + before, err := mutate(server, "enable", "") + if err != nil { + t.Fatal(err) + } + original := before.Identity.token() + proof, err := parseCredential(original) + if err != nil { + t.Fatal(err) + } + dial := func(server identity, offered credential) error { + cert, err := server.certificate() + if err != nil { + t.Fatal(err) + } + a, b := net.Pipe() + ctx := t.Context() + go func() { + defer b.Close() + admitted, err := authenticate(ctx, b, &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS13, NextProtos: []string{protocol}}, true, server.Secret) + if err == nil { + var end [1]byte + _, _ = admitted.Read(end[:]) + } + }() + defer a.Close() + _, err = authenticate(ctx, a, &tls.Config{MinVersion: tls.VersionTLS13, NextProtos: []string{protocol}, InsecureSkipVerify: true, VerifyConnection: offered.verify}, false, offered.secret) + return err + } + if err = dial(before.Identity, proof); err != nil { + t.Fatal(err) + } + for _, route := range []string{"office.local:7443", "office.test:7443"} { + if err = remember(client, route, original, "Office", proof); err != nil { + t.Fatal(err) + } + } + saved, err := readKnown(client) + if err != nil || len(saved.Tokens) != 1 || len(saved.Routes) != 2 { + t.Fatal("two verified routes must share one credential", err) + } + renamed, err := mutate(server, "rename", "Desk") + if err != nil { + t.Fatal(err) + } + if renamed.Identity.token() != original { + t.Fatal("renaming changed the credential") + } + replacement, err := newIdentity() + if err != nil { + t.Fatal(err) + } + if err = dial(replacement, proof); err == nil || errors.Is(err, errCredential) { + t.Fatal("replacement at the same address must fail certificate verification") + } + reset, err := mutate(server, "reset", "") + if err != nil { + t.Fatal(err) + } + if err = dial(reset.Identity, proof); !errors.Is(err, errCredential) { + t.Fatal("old secret must fail after reset", err) + } + current, err := parseCredential(reset.Identity.token()) + if err != nil { + t.Fatal(err) + } + if err = dial(reset.Identity, current); err != nil { + t.Fatal(err) + } +} + +func TestSupervisorRevokesALiveLinkAndWithdrawsTheListener(t *testing.T) { + dir := t.TempDir() + t.Setenv("DIMCODE_SHARING_LISTEN", "127.0.0.1:0") + ctx, stop := context.WithCancel(t.Context()) + owner := make(chan error, 1) + go func() { owner <- sharing(ctx, dir, filepath.Join(dir, "daemon.sock")) }() + defer func() { + stop() + if err := <-owner; err != nil { + t.Error(err) + } + }() + s, err := mutate(dir, "enable", "") + if err != nil { + t.Fatal(err) + } + st, err := localStatus(dir, s, true) + if err != nil { + t.Fatal(err) + } + endpoint := st.Addresses[0] + raw, err := net.Dial("tcp", endpoint) + if err != nil { + t.Fatal(err) + } + defer raw.Close() + if _, err = raw.Write([]byte{22, 3}); err != nil { + t.Fatal(err) + } + s, err = mutate(dir, "reset", "") + if err != nil { + t.Fatal(err) + } + if _, err = localStatus(dir, s, true); err != nil { + t.Fatal(err) + } + if _, err = bufio.NewReader(raw).ReadByte(); err == nil { + t.Fatal("old connection stayed open") + } + s, err = mutate(dir, "disable", "") + if err != nil { + t.Fatal(err) + } + st, err = localStatus(dir, s, true) + if err != nil || len(st.Addresses) != 0 || st.Token != "" { + t.Fatal("disabled listener still visible", err) + } + if conn, err := net.Dial("tcp", endpoint); err == nil { + conn.Close() + t.Fatal("withdrawn listener accepted a connection") + } + if err = load(filepath.Join(dir, "sharing.json"), &s); err != nil { + t.Fatal(err) + } + if s.Enabled { + t.Fatal("disabled state must survive a restart") + } +} diff --git a/runtime/native-sharing/state.go b/runtime/native-sharing/state.go new file mode 100644 index 0000000000..b317cf033c --- /dev/null +++ b/runtime/native-sharing/state.go @@ -0,0 +1,150 @@ +package main + +import ( + "crypto/ed25519" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "runtime" + "strings" + "unicode" + "unicode/utf8" + + "github.com/gofrs/flock" +) + +type settings struct { + Name string `json:"name"` + Enabled bool `json:"enabled"` + Identity identity `json:"identity"` + Revision uint64 `json:"revision"` +} +type savedComputer struct { + Name string `json:"name"` + Token string `json:"token"` +} +type known struct { + Tokens map[string]savedComputer `json:"tokens"` + Routes map[string]string `json:"routes"` +} + +func load(path string, dst any) error { + info, err := os.Lstat(path) + if err != nil { + return err + } + if !info.Mode().IsRegular() || (runtime.GOOS != "windows" && info.Mode().Perm()&0077 != 0) { + return errors.New("sharing data must be a private regular file") + } + data, err := os.ReadFile(path) + if err != nil { + return err + } + return json.Unmarshal(data, dst) +} +func save(path string, data any) error { + f, err := os.CreateTemp(filepath.Dir(path), ".sharing-*") + if err != nil { + return err + } + defer os.Remove(f.Name()) + err = json.NewEncoder(f).Encode(data) + if err == nil { + err = f.Sync() + } + ce := f.Close() + if err != nil { + return err + } + if ce != nil { + return ce + } + return os.Rename(f.Name(), path) +} +func readSettings(dir string) (settings, error) { + var s settings + err := load(filepath.Join(dir, "sharing.json"), &s) + if errors.Is(err, os.ErrNotExist) { + s.Name, err = os.Hostname() + if err == nil && !validName(s.Name) { + s.Name = strings.SplitN(s.Name, ".", 2)[0] + if !validName(s.Name) { + s.Name = "Dim" + } + } + return s, err + } + if err == nil && (len(s.Identity.Seed) != ed25519.SeedSize || len(s.Identity.Secret) != secretSize) { + err = errCredential + } + return s, err +} +func validName(name string) bool { + return name != "" && len(name) <= 63 && utf8.ValidString(name) && strings.IndexFunc(name, unicode.IsControl) < 0 +} +func mutate(dir, op, name string) (settings, error) { + lock := flock.New(filepath.Join(dir, "settings.lock")) + if err := lock.Lock(); err != nil { + return settings{}, err + } + defer lock.Unlock() + s, err := readSettings(dir) + if err != nil { + return s, err + } + if s.Identity.Seed == nil { + s.Identity, err = newIdentity() + if err != nil { + return s, err + } + } + switch op { + case "enable": + s.Enabled = true + case "disable": + s.Enabled = false + case "rename": + name = strings.TrimSpace(name) + if !validName(name) { + return s, errors.New("name must be 1 to 63 UTF-8 bytes without control characters") + } + s.Name = name + case "reset": + s.Identity.Secret, err = randomBytes(secretSize) + if err != nil { + return s, err + } + default: + return s, fmt.Errorf("unknown sharing setting %q", op) + } + s.Revision++ + return s, save(filepath.Join(dir, "sharing.json"), s) +} +func readKnown(dir string) (known, error) { + k := known{Tokens: map[string]savedComputer{}, Routes: map[string]string{}} + err := load(filepath.Join(dir, "known.json"), &k) + if errors.Is(err, os.ErrNotExist) { + err = nil + } + if err == nil && (k.Tokens == nil || k.Routes == nil) { + err = errors.New("invalid remembered computers") + } + return k, err +} +func remember(dir, address, token, name string, c credential) error { + lock := flock.New(filepath.Join(dir, "known.lock")) + if err := lock.Lock(); err != nil { + return err + } + defer lock.Unlock() + k, err := readKnown(dir) + if err != nil { + return err + } + id := encoding.EncodeToString(c.pin) + k.Tokens[id] = savedComputer{name, token} + k.Routes[address] = id + return save(filepath.Join(dir, "known.json"), k) +} diff --git a/scripts/build-sharing.mjs b/scripts/build-sharing.mjs new file mode 100644 index 0000000000..080c381f5a --- /dev/null +++ b/scripts/build-sharing.mjs @@ -0,0 +1,25 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { buildPlatform } from './native-binary.mjs'; + +const [destination] = process.argv.slice(2); +assert(destination, 'Usage: node scripts/build-sharing.mjs BIN_DIR'); +const { osName, cpu } = buildPlatform(); +const dir = path.resolve(destination); +mkdirSync(dir, { recursive: true }); +const cwd = path.resolve(import.meta.dirname, '../runtime/native-sharing'); +const options = { cwd, encoding: 'utf8', env: { ...process.env, CGO_ENABLED: '0', + GOOS: osName === 'windows' ? 'windows' : osName, GOARCH: cpu === 'arm64' ? 'arm64' : 'amd64' } }; +const suffix = osName === 'windows' ? '.exe' : ''; +execFileSync('go', ['build', '-mod=readonly', '-trimpath', '-ldflags=-s -w', '-o', path.join(dir, 'dim-sharing' + suffix), '.'], options); +const goroot = execFileSync('go', ['env', 'GOROOT'], options).trim(); +const modules = execFileSync('go', ['list', '-mod=readonly', '-deps', '-f', + '{{if and .Module (not .Module.Main)}}{{.Module.Path}} {{.Module.Version}} {{.Module.Dir}}{{end}}', '.'], options); +const notices = [readFileSync(path.join(goroot, 'LICENSE'), 'utf8')]; +for (const line of [...new Set(modules.trim().split(/\r?\n/).filter(Boolean))].sort()) { + const [, name, version, directory] = /^(\S+) (\S+) (.+)$/.exec(line); + notices.push(`${name} ${version}\n\n${readFileSync(path.join(directory, 'LICENSE'), 'utf8')}`); +} +writeFileSync(path.join(dir, 'GO-THIRD-PARTY-NOTICES.txt'), notices.join('\n\n')); diff --git a/scripts/ci-changes.mjs b/scripts/ci-changes.mjs index c426d1ad15..b0e9867717 100644 --- a/scripts/ci-changes.mjs +++ b/scripts/ci-changes.mjs @@ -1,7 +1,7 @@ import {execFileSync,spawnSync} from 'node:child_process'; import {appendFileSync} from 'node:fs'; -export const groups=['rust','windows','windows_native','static','xtask','node','eval','execution','debug','web','scripts','macos_scripts','dependencies']; +export const groups=['rust','windows','windows_native','static','xtask','node','eval','execution','debug','web','scripts','macos_scripts','dependencies','sharing']; const everything=Object.fromEntries(groups.map(group=>[group,true])); const documentation=/^docs\/|^[^/]+\.md$/; const cargoManifest=/(?:^|\/)Cargo\.toml$/; @@ -43,6 +43,9 @@ const rules=[ [/^web\/src\/features\/chat\/quote-cases\.json$/,['web','rust','windows']], [/^web\/src\/.*\.(ts|vue|mjs|js)$/,['web','static']], [/^web\//,['web']], + [/^runtime\/native-sharing\/|^crates\/dim-terminal-transport\//,['rust','sharing']], + [/^crates\/dim-cli\/src\/(?:sharing|ui\/remote_access)\.rs$/,['rust','windows','sharing']], + [/^scripts\/(?:build-sharing|native-sharing-flow)\.mjs$/,['rust','scripts','sharing']], [/^scripts\/run-rust-test\.mjs$/,groups], [/^scripts\/test-macos-native(?:\.test)?\.mjs$/,['rust','scripts']], [/^scripts\/stage-web\.mjs$/,['scripts','web']], diff --git a/scripts/native-sharing-flow.mjs b/scripts/native-sharing-flow.mjs new file mode 100644 index 0000000000..2222ce11b8 --- /dev/null +++ b/scripts/native-sharing-flow.mjs @@ -0,0 +1,228 @@ +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { randomUUID } from 'node:crypto'; +import { once } from 'node:events'; +import { chmod, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'; +import { connect } from 'node:net'; +import os from 'node:os'; +import path from 'node:path'; +import { createInterface } from 'node:readline'; +import test from 'node:test'; +import { setTimeout as delay } from 'node:timers/promises'; + +const windows = process.platform === 'win32'; +const suffix = windows ? '.exe' : ''; +const debug = path.resolve(process.env.CARGO_TARGET_DIR || 'target', 'debug'); +const cli = path.resolve(process.env.DIM_SHARING_TEST_CLI || path.join(debug, 'dimcode' + suffix)); +const helper = path.join(path.dirname(cli), 'dim-sharing' + suffix); +const fixture = path.join(debug, 'examples', 'sharing-shutdown-fixture' + suffix); +const model = path.resolve(import.meta.dirname, '../crates/dim-agent-aimux/examples/offline.json'); + +async function rpc(socket) { + const stream = connect(socket); + await once(stream, 'connect'); + const lines = createInterface({ input: stream, crlfDelay: Infinity })[Symbol.asyncIterator](); + let id = 0; + async function receive(matches) { + for (;;) { + const { value, done } = await lines.next(); + if (done) throw Error('App Server stream ended'); + const reply = JSON.parse(value); + if (matches(reply)) return reply; + } + } + function call(method, params) { + const request = ++id; + stream.write(JSON.stringify({ jsonrpc: '2.0', id: request, method, params }) + '\n'); + return receive(reply => reply.id === request); + } + const { result: hello } = await call('hello', { protocolVersion: 4, clientKind: 'cli', clientName: 'sharing-test' }); + return { stream, call, hello, receive }; +} + +async function environment(t) { + const temp = await mkdtemp(path.join(os.tmpdir(), 'dim-net-')); + const a = path.join(temp, 'a'), b = path.join(temp, 'b'), tmp = path.join(temp, 'tmp'); + const env = { ...process.env, HOME: temp, TMPDIR: tmp, DIMCODE_HOME: b, DIMCODE_UPDATE_CHECK: '0', DIMCODE_SHARING_LISTEN: '127.0.0.1:0' }; + const children = new Set(); + function start(args, program = cli, extraEnv) { + const child = spawn(program, args, { env: { ...env, ...extraEnv }, cwd: temp, stdio: 'pipe' }); + children.add(child); + child.on('close', () => children.delete(child)); + return child; + } + async function run(args, input = '', program = cli, extraEnv) { + const child = start(args, program, extraEnv), out = [], err = []; + child.stdout.on('data', chunk => out.push(chunk)); + child.stderr.on('data', chunk => err.push(chunk)); + child.stdin.end(input); + const [code] = await once(child, 'close'); + return { code, out: Buffer.concat(out).toString(), err: Buffer.concat(err).toString() }; + } + t.after(async () => { + for (const child of children) child.kill(); + await Promise.allSettled([...children].map(child => once(child, 'close'))); + await rm(temp, { recursive: true, force: true }); + }); + await mkdir(tmp, { mode: 0o700 }); + return { temp, a, b, tmp, env, start, run }; +} + +test('a remembered shared link carries independent native streams, large frames and revocation', { skip: windows, timeout: 50_000 }, async (t) => { + const { temp, a, b, tmp, env, start, run } = await environment(t); + const target = path.join(b, 'rust', 'daemon.sock'); + async function share(...args) { + const result = await run(['--home', b, '--model-config', model, 'share', ...args]); + assert.equal(result.code, 0, result.err); + return JSON.parse(result.out); + } + await mkdir(path.dirname(target), { recursive: true, mode: 0o700 }); + await chmod(path.dirname(target), 0o700); + const disabled = await run(['--home', a, 'share', 'disable']); + assert.equal(disabled.code, 0, disabled.err); + assert.equal(JSON.parse(disabled.out).enabled, false); + await assert.rejects(readFile(path.join(a, 'rust', 'daemon.sock')), { code: 'ENOENT' }); + const replacement = path.join(temp, 'sharing-helper'); + await writeFile(replacement, '', { mode: 0o600 }); + env.DIM_TEST_SHARING_HELPER = helper; + const server = start(['app-server', '--sharing-helper', replacement, '--home', path.dirname(target), '--model-config', model, '--no-ws', '--unix', target]); + const diagnostics = createInterface({ input: server.stderr })[Symbol.asyncIterator](); + async function waitForDiagnostic(message) { + for (;;) { + const { value, done } = await diagnostics.next(); + assert.ok(!done, 'the sharing supervisor stopped before ' + message); + if (value.includes(message)) return; + } + } + await Promise.all([once(server.stdout, 'data'), waitForDiagnostic('Remote sharing could not start')]); + const direct = await rpc(target); + t.after(() => direct.stream.destroy()); + await writeFile(replacement, [ + '#!/bin/sh', 'if [ ! -e "$2/restart-check" ]; then', + ' touch "$2/restart-check"', ' exit 1', 'fi', + 'echo "starting repaired helper" >&2', 'exec "$DIM_TEST_SHARING_HELPER" "$@"', '', + ].join('\n')); + await chmod(replacement, 0o700); + await waitForDiagnostic('starting repaired helper'); + assert.equal((await share('status')).enabled, false); + const { token, addresses: [address] } = await share('enable'); + const clientArgs = ['--home', a, 'share', 'connect', address]; + assert.notEqual((await run([...clientArgs, '--', 'mcp', 'list'], 'incorrect\n')).code, 0); + + const hold = start([...clientArgs, '--', '--no-tui']); + hold.stdin.write(token + '\n'); + let proxy; + for (let i = 0; i < 200 && !proxy; i++) { + for (const entry of await readdir(tmp, { withFileTypes: true })) { + if (entry.isDirectory() && entry.name.startsWith('dim-link-')) { + const dir = path.join(tmp, entry.name); + if ((await readdir(dir)).includes('ready')) proxy = path.join(dir, 'rpc.sock'); + } + } + if (!proxy) await delay(50); + } + assert.ok(proxy, 'the authenticated client must publish its private socket'); + const first = await rpc(proxy), second = await rpc(proxy); + t.after(() => { first.stream.destroy(); second.stream.destroy(); }); + const database = path.join(temp, 'keyboard.sqlite'); + const localOutput = path.join(temp, 'timeline.json'); + await writeFile(database, 'local fixture'); + for (const args of [ + ['daemon', 'vacuum', '--database', database], ['export', 'fixture-session', '--database', database, '--output', localOutput], + ['migration', 'list'], ['update'], ['web', 'install'], ['share', 'enable'], ['--fullscreen', 'default'], + ]) { + const refused = await run([...clientArgs, '--', ...args]); + assert.notEqual(refused.code, 0); + assert.match(refused.err, /unavailable through a shared connection/, args.join(' ')); + } + assert.equal(await readFile(database, 'utf8'), 'local fixture'); + for (const file of [localOutput, path.join(a, 'config.json'), path.join(a, 'rust', 'daemon.sock')]) { + await assert.rejects(readFile(file), { code: 'ENOENT' }); + } + assert.equal(first.hello.instanceId, direct.hello.instanceId); + assert.deepEqual(first.hello.features, direct.hello.features); + for (let attempt = 0; attempt < 50; attempt++) { + const { result } = await direct.call('mcp.catalog', {}); + if (result.userApplication.appliedRevision === result.userRevision && result.pluginApplication.appliedRevision) break; + await delay(50); + } + for (const [method, params] of [['mcp.catalog', {}], ['plugin.list', {}], ['sharing.absent', {}]]) { + const { id: _local, ...local } = await direct.call(method, params); + const { id: _remote, ...remote } = await first.call(method, params); + assert.deepEqual(remote, local); + } + const { result: session } = await direct.call('session.create', { cwd: temp }); + assert.equal((await first.call('session.attach', { sessionId: session.sessionId })).result.sessionId, session.sessionId); + const notice = first.receive(message => message.method === 'session.event' && message.params.sessionId === session.sessionId); + assert.ok((await direct.call('session.submit', { sessionId: session.sessionId, text: 'Hello' })).result); + await notice; + first.stream.destroy(); + const large = { key: 'x'.repeat(1024 * 1024) }; + const expected = await direct.call('sharing.absent', large); + const actual = await second.call('sharing.absent', large); + assert.deepEqual(actual.error, expected.error); + const pendingClose = once(second.stream, 'close'); + await share('reset'); + await pendingClose; + hold.stdin.end(); + const stale = await run([...clientArgs, '--', 'mcp', 'list']); + assert.notEqual(stale.code, 0); + assert.doesNotMatch(stale.err, /Sharing token: /, 'reconnect must try its saved credential'); + const current = await share('status'); + assert.notEqual(current.token, token); + const repaired = await run([...clientArgs, '--pair', '--', 'mcp', 'list'], current.token + '\n'); + assert.equal(repaired.code, 0, repaired.err); + const reconnected = await run([...clientArgs, '--', 'mcp', 'list']); + assert.equal(reconnected.code, 0, reconnected.err); + assert.doesNotMatch(reconnected.err, /Sharing token: /); + const alternateAddress = address.replace('127.0.0.1', 'localhost'); + const alternate = await run(['--home', a, 'share', 'connect', alternateAddress, '--', 'mcp', 'list']); + assert.equal(alternate.code, 0, alternate.err); + assert.doesNotMatch(alternate.err, /Sharing token: /, 'a different route to the same authenticated instance can reconnect'); + assert.deepEqual((await share('disable')).addresses, []); +}); + +test('daemon stop reports the same cleanup result through direct and shared connections', { timeout: 90_000 }, async (t) => { + const { temp, a, start, run } = await environment(t); + for (const fail of [false, true]) { + await t.test(fail ? 'remote stop preserves a delayed cleanup error' : 'remote stop waits for successful cleanup', async () => { + const results = []; + for (const shared of [false, true]) { + const home = path.join(temp, 'stop-' + Number(fail) + Number(shared)); + const native = path.join(home, 'rust'); + const endpoint = windows ? String.raw`\\.\pipe\dim-test-${randomUUID()}` : path.join(native, 'daemon.sock'); + await mkdir(native, { recursive: true, mode: 0o700 }); + const owner = start(['--home', native, '--model-config', model, windows ? '--pipe' : '--unix', endpoint, + '--no-ws', '--sharing-helper', helper], fixture, fail ? { DIM_TEST_FAIL_CLEANUP: '1' } : {}); + const ended = once(owner, 'close'); + let diagnostics = ''; + owner.stderr.on('data', chunk => { diagnostics += chunk; }); + const ready = createInterface({ input: owner.stdout })[Symbol.asyncIterator](); + assert.equal((await ready.next()).done, false, diagnostics); + const setup = await rpc(endpoint); + assert.ok((await setup.call('session.create', { cwd: temp })).result); + setup.stream.destroy(); + let args = ['--home', home], input = ''; + if (shared) { + const enabled = await run(['--home', native, 'enable'], '', helper); + assert.equal(enabled.code, 0, enabled.err); + const { addresses, token } = JSON.parse(enabled.out); + args = ['--home', a, 'share', 'connect', addresses[0], '--pair', '--']; + input = token + '\n'; + } + const directPipe = !shared && windows ? { DIMCODE_TERMINAL_PROXY: endpoint } : {}; + const result = await run([...args, 'daemon', 'stop'], input, cli, directPipe); + assert.equal(result.code === 0, !fail, result.err); + if (fail) assert.match(result.err, /shutdown_failed/); + else assert.match(result.out, /Daemon stopped/); + results.push(result); + const [code] = await ended; + assert.equal(code === 0, !fail); + } + const [direct, shared] = results; + assert.equal(shared.code, direct.code); + assert.equal(shared.out, direct.out); + assert.equal(shared.err.replace('Sharing token: ', ''), direct.err); + }); + } +}); diff --git a/scripts/release.test.mjs b/scripts/release.test.mjs index 87d9cc6874..67cbd81941 100644 --- a/scripts/release.test.mjs +++ b/scripts/release.test.mjs @@ -1106,3 +1106,26 @@ test('collects exact platform packages, installs wrapper offline and rejects inc assert.notEqual(run('collect-release.mjs',[temporary,path.join(temporary,'inconsistent')]).status,0); assert.equal(existsSync(path.join(temporary,'inconsistent')),false); }); + +test('the Alpha platform archive includes both sharing processes and their notices', { skip: process.platform === 'win32' }, (t) => { + const temporary = fixture(t); + const bin = path.join(temporary, 'bin'); + const stage = path.join(temporary, 'stage'); + mkdirSync(bin); + writeFileSync(path.join(bin, 'dimcode'), `#!/bin/sh\nprintf "dimcode ${version}\\n"\n`, { mode: 0o755 }); + const sharing = path.join(temporary, 'sharing'); + mkdirSync(sharing); + for (const name of ['dim-terminal-transport', 'dim-sharing']) { + const bytes = readFileSync(process.execPath).subarray(0, 4096); + writeFileSync(path.join(sharing, name), bytes); + } + writeFileSync(path.join(sharing, 'GO-THIRD-PARTY-NOTICES.txt'), 'Go license fixture'); + const args = [bin, stage, version, commit, '--plugins', stubPlugins(temporary), + '--rust-notices', stubRustNotices(temporary), '--sharing', sharing]; + const result = run('stage-release.mjs', args); + assert.equal(result.status, 0, result.stderr); + const files = JSON.parse(readFileSync(path.join(stage, 'release-manifest.json'))).files; + for (const file of ['bin/dim-terminal-transport', 'bin/dim-sharing', 'licenses/GO-THIRD-PARTY-NOTICES.txt']) { + assert.equal(files[file], createHash('sha256').update(readFileSync(path.join(stage, file))).digest('hex')); + } +}); diff --git a/scripts/stage-release.mjs b/scripts/stage-release.mjs index 759a260580..7abd224908 100644 --- a/scripts/stage-release.mjs +++ b/scripts/stage-release.mjs @@ -8,14 +8,16 @@ import { buildPlatform, checkArchitecture } from './native-binary.mjs'; import { readStoreFormats } from './store-formats.mjs'; const [binaryDirectory, destination, version, sourceCommit, ...rest] = process.argv.slice(2); -const usage = 'Usage: node scripts/stage-release.mjs BIN_DIR DESTINATION VERSION SOURCE_COMMIT --plugins DIR --rust-notices FILE [--account]'; +const usage = 'Usage: node scripts/stage-release.mjs BIN_DIR DESTINATION VERSION SOURCE_COMMIT --plugins DIR --rust-notices FILE [--account] [--sharing DIR]'; assert(binaryDirectory && destination && version && sourceCommit, usage); let account = false; let plugins; let rustNotices; +let sharing; for (let index = 0; index < rest.length; index += 1) { if (rest[index] === '--account' && !account) account = true; else if (rest[index] === '--plugins' && plugins === undefined && rest[index + 1]) plugins = path.resolve(rest[++index]); + else if (rest[index] === '--sharing' && !sharing && rest[index + 1]) sharing = path.resolve(rest[++index]); else if (rest[index] === '--rust-notices' && rustNotices === undefined && rest[index + 1]) rustNotices = path.resolve(rest[++index]); else assert.fail(usage); } @@ -52,6 +54,17 @@ try { chmodSync(path.join(output, 'bin', `dimcode${suffix}`), 0o755); copyFileSync(path.join(repo, 'LICENSE'), path.join(output, 'LICENSE')); cpSync(plugins, output, { recursive: true }); + if (sharing) { + for (const name of ['dim-terminal-transport', 'dim-sharing']) { + const file = name + suffix; + const source = path.join(sharing, file); + checkArchitecture(source, osName, cpu); + copyFileSync(source, path.join(output, 'bin', file)); + chmodSync(path.join(output, 'bin', file), 0o755); + } + mkdirSync(path.join(output, 'licenses'), { recursive: true }); + copyFileSync(path.join(sharing, 'GO-THIRD-PARTY-NOTICES.txt'), path.join(output, 'licenses/GO-THIRD-PARTY-NOTICES.txt')); + } const notices = ['LICENSE', 'NOTICE', 'xai-ratatui-inline/NOTICE', 'xai-ratatui-textarea/NOTICE']; for (const file of notices) { const destination = path.join(output, 'licenses/grok-build', file); diff --git a/scripts/tui-tmux/scenarios.mjs b/scripts/tui-tmux/scenarios.mjs index b5adfc12f7..b3728c8b14 100644 --- a/scripts/tui-tmux/scenarios.mjs +++ b/scripts/tui-tmux/scenarios.mjs @@ -1,4 +1,5 @@ import assert from 'node:assert/strict'; +import {execFileSync} from 'node:child_process'; import fs from 'node:fs'; import path from 'node:path'; @@ -868,6 +869,61 @@ const scenarios = [ await exitWith(terminal); }, }, + { + name: 'settings_manage_inbound_sharing', + area: 'commands', + title: 'Settings controls inbound access, displays the complete token and revokes it on reset', + async run(tui) { + await tui.setup({respond: () => ({text: ANSWER})}); + const terminal = await tui.launch(['--fullscreen'], { + env: {DIMCODE_SHARING_LISTEN: '127.0.0.1:0'}, waitForComposer: true, cols: 90, rows: 36, + }); + terminal.send('/settings'); + terminal.key('Enter'); + await terminal.waitFor('Language'); + terminal.key('End'); + if (!fs.existsSync(path.join(path.dirname(tui.binary), 'dim-sharing'))) { + assert(!terminal.capture().includes('Remote access')); + return; + } + const status = () => JSON.parse(execFileSync(tui.binary, ['--home', tui.home, 'share', 'status'], { + env: tui.environment({}), encoding: 'utf8', + })); + assert.equal(status().enabled, false); + await terminal.waitFor('Remote access'); + terminal.key('Enter'); + await terminal.waitFor('Allow connections to this computer'); + terminal.key('Enter'); + await terminal.waitFor('DIM1-'); + const token = status().token; + terminal.key('Down', 'Enter'); + await terminal.waitFor('Enter save'); + terminal.send('-fixture'); + terminal.key('Enter'); + await terminal.waitFor('-fixture'); + terminal.key('Down', 'Enter'); + await terminal.waitFor('Esc back'); + assert(terminal.capture().includes(token), 'the complete sharing token is readable'); + terminal.key('Escape', 'Down', 'Enter'); + await terminal.waitFor('Disconnect all shared terminals'); + terminal.key('y'); + await terminal.waitFor('Allow connections to this computer'); + for (let i = 0; i < 30 && status().token === token; i++) await sleep(100); + assert(status().token !== token, 'confirming reset must rotate the token'); + const previousToken = status().token; + terminal.key('Home', 'Enter'); + await terminal.waitFor('off'); + assert.equal(status().enabled, false); + terminal.key('End', 'Enter'); + await terminal.waitFor('Disconnect all shared terminals'); + terminal.key('y'); + await terminal.waitFor('Allow connections to this computer'); + assert.equal(status().enabled, false); + terminal.key('Home', 'Enter'); + await terminal.waitFor('DIM1-'); + assert(status().token && status().token !== previousToken, 'rotation while off replaces the token on next enable'); + }, + }, { name: 'slash_palette_lists_curated_commands_and_settings', area: 'commands',