diff --git a/.github/RELEASE.md b/.github/RELEASE.md index acec236cc..808989252 100644 --- a/.github/RELEASE.md +++ b/.github/RELEASE.md @@ -113,6 +113,7 @@ Every run of `upload-r2.yml` also copies the channel manifests onto the GitHub R - **稳定发布同时刷新 beta 清单**:a stable run also publishes the exact same stable manifests as `feed--beta.json` and overwrites the R2 beta keys (`updates/beta/latest.json`, `updates/navop-shell/shell/beta/latest.json`, `updates/navop-data/data/beta/latest.json`) with that same stable manifest. Beta clients only read the beta feed/assets; without this refresh they would stay pinned to the last beta forever and never receive a new stable release. A beta run still writes only the beta keys and beta asset names, so the stable feed and the un-suffixed asset names are never touched. - **CNB 同步由 `upload-r2.yml` 最后派发**:`sync-cnb-release-assets.yml` must run after the `feed-*.json` assets exist. The dispatch used to live at the end of `release.yml`, which raced the concurrent `upload-r2.yml` run and could complete before the feed assets were uploaded. `release.yml` now dispatches only `upload-r2.yml` (with `-f channel`), and the CNB sync is dispatched by the last step of `upload-r2.yml`. - **`feed-*.json` 不会被误当成安装包**:the installer download/upload globs are `navop-*` / `navop_*`, and the manifest's `packages` list keeps only names matching `/^navop[-_]/`, so feed assets never appear in `downloads`, `fallback_downloads` or `packages`, and never land under the R2 `releases//` prefix. +- **CNB 只保留最新 5 个版本**:CNB 对象存储免费额度 100 GiB,统计「制品、LFS 对象、图片及附件」,而单版镜像(三个产品 × 多平台 × 多种包格式)已涨到约 3 GiB,历史 Release 会持续吃额度直到按 ¥1/GiB/月 计费。因此 `sync-cnb-release-assets.yml` 在每同步完一个 tag 后会调用 `.github/scripts/prune-cnb-releases.sh`,只保留版本号最大的 5 个 Release,并额外保底保留最新稳定版与最新 beta 各一个(两条通道的客户端都按「最新 tag」取 `feed-*.json`,保底保证任何情况下都拿得到清单)。清理**只删 CNB Release,不动 git tag** —— 更新器靠 git refs 广告发现新版本,tag 没了就永远收不到更新。脚本拒绝在「本次同步的 tag 不在 CNB 上」时清理,避免镜像没传成功反而把旧版本删光;令牌缺 `repo-release:rw` 时任务报错并提示更新 `CNB_TOKEN`。 ## Changelog format diff --git a/.github/scripts/prune-cnb-releases.sh b/.github/scripts/prune-cnb-releases.sh new file mode 100644 index 000000000..34ec6af95 --- /dev/null +++ b/.github/scripts/prune-cnb-releases.sh @@ -0,0 +1,176 @@ +#!/usr/bin/env bash +# 清理 navop 在 CNB 上的 Release,只保留最新若干个版本。 +# +# 背景:CNB 对象存储免费额度 100 GiB,统计「制品、LFS 对象、图片及附件」, +# 而 navop 每个版本在 CNB Release 上约有 27 个安装包(约 1.75 GiB)。发版节奏 +# 一快就会顶满 100 GiB 并开始按 ¥1/GiB/月 计费。GitHub Release 才是分发主线, +# CNB 只是国内镜像,旧版本没有保留价值。 +# +# 安全约束(见 crates/app_kit/src/update/mirror.rs): +# * 更新器先用 git refs 广告发现 tag,再取「最新 tag」Release 里的 feed-*.json, +# 所以最新版本必须留着,且只删 Release —— 不碰 git tag。 +# * 保留集合固定包含:本次同步的 tag、版本号最大的稳定版、版本号最大的 beta, +# 再叠加版本号最大的 N 个版本。稳定版/beat 保底是为了让两个通道的客户端 +# 永远拿得到最新清单,即使 N 个最新版本恰好全是 beta。 +# +# 环境变量: +# CNB_REPOSITORY navop-dev/navop +# CNB_TOKEN 具备 repo-release:rw 的 CNB 访问令牌 +# SYNCED_TAG 本次刚同步完的 tag(必须存在于 CNB,否则拒绝清理) +# CNB_RELEASE_RETENTION 保留的版本数,默认 5 +# CNB_PRUNE_DRY_RUN true 时只打印计划,不实际删除 +set -uo pipefail + +: "${CNB_REPOSITORY:?CNB_REPOSITORY is required}" +: "${CNB_TOKEN:?CNB_TOKEN is required}" +: "${SYNCED_TAG:?SYNCED_TAG is required}" + +RETENTION="${CNB_RELEASE_RETENTION:-5}" +DRY_RUN="${CNB_PRUNE_DRY_RUN:-false}" +API="https://api.cnb.cool/${CNB_REPOSITORY}" + +work="$(mktemp -d)" +trap 'rm -rf "${work}"' EXIT + +fail() { echo "::error::$*"; exit 1; } +warn() { echo "::warning::$*"; } + +human_size() { + awk -v b="$1" 'BEGIN { + split("B KiB MiB GiB TiB", u, " "); i = 1 + while (b >= 1024 && i < 5) { b /= 1024; i++ } + printf "%.2f %s", b, u[i] + }' +} + +# ---------------------------------------------------------------- 拉取 Release +# page_size 默认只有 10,必须显式传;逐页拉到取空为止。 +fetch_releases() { + local page=1 count status + : >"${work}/releases.ndjson" + while [ "${page}" -le 20 ]; do + status="$(curl -sS -o "${work}/page.json" -w '%{http_code}' \ + -H "Authorization: Bearer ${CNB_TOKEN}" \ + -H "Accept: application/json" \ + "${API}/-/releases?page=${page}&page_size=100")" || { + warn "Cannot list CNB releases (network error on page ${page})" + return 1 + } + case "${status}" in + 200) ;; + 401 | 403) + echo "::error::CNB token cannot list releases (HTTP ${status}): $(head -c 300 "${work}/page.json")" + return 2 + ;; + *) + warn "Cannot list CNB releases (HTTP ${status} on page ${page}): $(head -c 300 "${work}/page.json")" + return 1 + ;; + esac + count="$(jq 'length' "${work}/page.json" 2>/dev/null || echo 0)" + if [ "${count}" -eq 0 ]; then + break + fi + jq -c '.[] | {id: .id, tag: .tag_name, size: ([.assets[]?.size] | add // 0)}' \ + "${work}/page.json" >>"${work}/releases.ndjson" + if [ "${count}" -lt 100 ]; then + break + fi + page=$((page + 1)) + done + [ -s "${work}/releases.ndjson" ] || { + warn "CNB returned no releases; nothing to prune." + return 1 + } +} + +fetch_releases +case $? in + 0) ;; + 2) exit 1 ;; + *) exit 0 ;; # 瞬时故障不该让发版流程变红,下次构建会再清一次 +esac + +total="$(jq -r '.tag' "${work}/releases.ndjson" | wc -l | tr -d ' ')" +echo "CNB has ${total} release(s); retention policy keeps the newest ${RETENTION} plus the newest stable/beta entry point." + +# 本次同步的 tag 不在 CNB 上就什么都不删:宁可留下旧版本,也不能在「新版本 +# 其实没同步成功」时把镜像清空。 +if ! jq -r '.tag' "${work}/releases.ndjson" | grep -Fxq "${SYNCED_TAG}"; then + fail "Refusing to prune: ${SYNCED_TAG} is not present on CNB" +fi + +# ---------------------------------------------------------------- 计算保留集合 +tags_sorted="$(jq -r '.tag' "${work}/releases.ndjson" | sort -V)" + +keep=" ${SYNCED_TAG} " + +newest="$(printf '%s\n' "${tags_sorted}" | tail -n "${RETENTION}")" +for t in ${newest}; do + keep="${keep}${t} " +done + +# 稳定版与 beta 各保底一个:两条通道的客户端都按「最新 tag」取 feed-*.json。 +stable_tag="$(printf '%s\n' "${tags_sorted}" | grep -v -- '-' | tail -n 1 || true)" +beta_tag="$(printf '%s\n' "${tags_sorted}" | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+-' | tail -n 1 || true)" +[ -n "${stable_tag}" ] && keep="${keep}${stable_tag} " +[ -n "${beta_tag}" ] && keep="${keep}${beta_tag} " + +# 去重并排序,便于阅读日志。 +keep_list="$(printf '%s\n' ${keep} | sort -uV | tr '\n' ' ')" +echo "Keeping releases: ${keep_list}" +echo " ${SYNCED_TAG} = just synced; ${stable_tag:-none} = newest stable; ${beta_tag:-none} = newest beta; newest ${RETENTION} by version" + +if [ "$(printf '%s\n' ${keep} | sort -u | wc -l | tr -d ' ')" -ge "${total}" ]; then + echo "Nothing to prune." + exit 0 +fi + +# ---------------------------------------------------------------- 删除旧 Release +deleted=0 +freed=0 +failed=0 +while IFS=$'\t' read -r id tag size; do + case " ${keep} " in + *" ${tag} "*) + echo "keep ${tag} ($(human_size "${size}"))" + continue + ;; + esac + if [ "${DRY_RUN}" = "true" ]; then + echo "delete ${tag} ($(human_size "${size}"), id=${id}) [dry-run]" + deleted=$((deleted + 1)) + freed=$((freed + size)) + continue + fi + status="$(curl -sS -o "${work}/del.json" -w '%{http_code}' -X DELETE \ + -H "Authorization: Bearer ${CNB_TOKEN}" \ + -H "Accept: application/json" \ + "${API}/-/releases/${id}")" || status="000" + case "${status}" in + 200 | 202 | 204) + echo "delete ${tag} ($(human_size "${size}"), id=${id})" + deleted=$((deleted + 1)) + freed=$((freed + size)) + ;; + 404) + echo "delete ${tag} (already gone)" + deleted=$((deleted + 1)) + freed=$((freed + size)) + ;; + 401 | 403) + echo "::error::CNB token lacks release write scope (HTTP ${status}) when deleting ${tag}: $(head -c 300 "${work}/del.json")" + echo "::error::Create a CNB access token with repo-release:rw at https://cnb.cool/profile/token and update the CNB_TOKEN secret." + exit 1 + ;; + *) + warn "Failed to delete ${tag} (HTTP ${status}): $(head -c 200 "${work}/del.json")" + failed=$((failed + 1)) + ;; + esac +done < <(jq -r '[.id, .tag, .size] | @tsv' "${work}/releases.ndjson") + +echo "Pruned ${deleted} release(s), freed $(human_size "${freed}") of CNB object storage (kept ${keep_list})." +if [ "${failed}" -gt 0 ]; then + warn "${failed} release(s) could not be deleted; the next build will retry." +fi diff --git a/.github/workflows/sync-cnb-release-assets.yml b/.github/workflows/sync-cnb-release-assets.yml index b6ef0c894..a01ca2b14 100644 --- a/.github/workflows/sync-cnb-release-assets.yml +++ b/.github/workflows/sync-cnb-release-assets.yml @@ -14,6 +14,8 @@ permissions: env: CNB_REPOSITORY: "navop-dev/navop" + # CNB 只当国内镜像,旧版本没有保留价值:每次同步新版本后清掉更旧的 Release。 + CNB_RELEASE_RETENTION: "5" concurrency: group: navop-cnb-release @@ -111,3 +113,24 @@ jobs: echo "::error::mpgrm release sync failed after 3 attempts for ${TAG_NAME}" exit 1 fi + + # 对象存储免费额度只有 100 GiB(统计制品、LFS、图片与附件),而单版镜像 + # 已涨到约 3 GiB,历史 Release 会持续吃额度直到开始计费。这里只删 Release, + # 不动 git tag —— 更新器靠 refs 广告发现 tag,tag 必须留着(已实测:删 + # Release 不会连带删 tag)。 + # 脚本从「本次 workflow 的 ref」取,而不是上面按 tag 检出的工作区:手工 + # 重跑旧 tag 时,那个 tag 的树里还没有这个脚本。 + # 清理失败不让整个同步 job 变红(镜像本身已经同步成功),但令牌缺 + # repo-release:rw 时报错,因为那是必须人工修一次的问题。 + - name: Checkout maintenance scripts + uses: actions/checkout@v4 + with: + ref: ${{ github.ref }} + sparse-checkout: .github/scripts + path: .maintenance + + - name: Prune old CNB releases + env: + CNB_TOKEN: ${{ secrets.CNB_TOKEN }} + SYNCED_TAG: ${{ inputs.tag }} + run: bash .maintenance/.github/scripts/prune-cnb-releases.sh diff --git a/Cargo.lock b/Cargo.lock index d848ed2d8..063df3409 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10458,6 +10458,7 @@ version = "0.15.2" dependencies = [ "anyhow", "one-core", + "sftp_transfer", "ssh", "tokio", ] @@ -11570,6 +11571,7 @@ dependencies = [ "anyhow", "async-trait", "chrono", + "connection_tunnel", "futures", "one-core", "redis", @@ -11811,6 +11813,7 @@ dependencies = [ "anyhow", "gpui-component", "gpui-fast", + "image", "one-core", "rust-i18n", "sftp", @@ -12084,6 +12087,7 @@ dependencies = [ "rusqlite", "serde_json", "sftp", + "sftp_transfer", "ssh", "tempfile", "tokio", @@ -13032,6 +13036,7 @@ dependencies = [ "async-trait", "base64 0.22.1", "futures", + "rand 0.10.3", "russh", "russh-sftp", "rust-i18n", @@ -13661,6 +13666,7 @@ dependencies = [ "qrcode", "rqrr", "rust-i18n", + "sftp_transfer", "ssh", "tempfile", "terminal", @@ -14191,6 +14197,7 @@ dependencies = [ "serde", "serde_json", "serialport", + "sftp_transfer", "shell-words", "ssh", "tempfile", diff --git a/crates/app_kit/resources/linux/navop.desktop b/crates/app_kit/resources/linux/navop.desktop index 3e8aa2dbc..1fffc9f1d 100644 --- a/crates/app_kit/resources/linux/navop.desktop +++ b/crates/app_kit/resources/linux/navop.desktop @@ -1,11 +1,11 @@ [Desktop Entry] Name=Navop Comment=Navop - Database, SSH, Terminal, AI Tools -Exec=navop %F +Exec=navop %U Icon=navop Type=Application Categories=Development;Utility;Database; Terminal=false StartupWMClass=navop -MimeType=application/vnd.sqlite3;application/x-sqlite3;application/x-duckdb;application/vnd.duckdb;text/markdown;application/x-asciicast; +MimeType=application/vnd.sqlite3;application/x-sqlite3;application/x-duckdb;application/vnd.duckdb;text/markdown;application/x-asciicast;x-scheme-handler/jms; Keywords=database;ssh;sftp;terminal;redis;mongodb;postgresql;mysql; diff --git a/crates/app_kit/src/file_association.rs b/crates/app_kit/src/file_association.rs index 0d1b8acd5..da7ad609e 100644 --- a/crates/app_kit/src/file_association.rs +++ b/crates/app_kit/src/file_association.rs @@ -13,8 +13,10 @@ use std::fs; use std::path::{Path, PathBuf}; use std::process::Command; -const ASSOCIATION_SCHEMA_VERSION: u32 = 2; -const REGISTRATION_STAMP_FILE: &str = "file-association-registration-v2"; +const ASSOCIATION_SCHEMA_VERSION: u32 = 3; +const REGISTRATION_STAMP_FILE: &str = "file-association-registration-v3"; +/// 上次写入系统的 URL scheme 清单,用于关闭开关时精确摘除注册。 +const REGISTERED_URL_SCHEMES_FILE: &str = "file-association-schemes-v1"; /// 反向域名 `app_id` 里不参与 ProgID 的根段:`com.navop.shell` → `NavopShell`。 const REVERSE_DNS_ROOT: &str = "com"; /// Linux 注册文件名里追加的扩展名。 @@ -140,24 +142,40 @@ pub fn associations_for(identity: &AppIdentity) -> Vec { specs } -/// 注册当前产品的文件关联;没有扩展名的产品直接跳过。 -pub fn schedule_registration(cx: &mut App) { +/// 注册当前产品的文件关联与 URL 协议;两者都没声明的产品直接跳过。 +pub fn schedule_registration_with_schemes(cx: &mut App, enabled_schemes: Vec) { let Some(identity) = crate::identity() else { tracing::debug!("application identity is not configured; skipping file associations"); return; }; - if associations_for(identity).is_empty() { - tracing::debug!("product declares no file associations; skipping registration"); + if !claims_any_registration(identity) { + tracing::debug!( + "product declares no file associations or URL schemes; skipping registration" + ); return; } cx.background_spawn(async move { - if let Err(error) = ensure_registered(identity) { + if let Err(error) = ensure_registered(identity, &enabled_schemes) { tracing::warn!(error = %error, "file association migration failed"); } }) .detach(); } +/// 声明的 scheme 里用户启用的部分(大小写不敏感,保持声明顺序)。 +fn enabled_url_schemes<'a>(identity: &AppIdentity, enabled: &[String]) -> Vec<&'a str> { + identity + .url_schemes + .iter() + .copied() + .filter(|scheme| { + enabled + .iter() + .any(|candidate| candidate.trim().eq_ignore_ascii_case(scheme)) + }) + .collect() +} + fn association_kind(declared: &str) -> Option<&'static AssociationKind> { let name = declared.trim().trim_start_matches('.'); ASSOCIATION_CATALOG @@ -182,26 +200,69 @@ fn prog_id_prefix(identity: &AppIdentity) -> String { prefix } -fn ensure_registered(identity: &'static AppIdentity) -> Result<()> { - if associations_for(identity).is_empty() { +/// 产品是否声明了任何需要写进系统的关联(扩展名或 URL scheme)。 +fn claims_any_registration(identity: &AppIdentity) -> bool { + !associations_for(identity).is_empty() || !identity.url_schemes.is_empty() +} + +fn ensure_registered(identity: &'static AppIdentity, enabled_schemes: &[String]) -> Result<()> { + if !claims_any_registration(identity) { return Ok(()); } let executable = std::env::current_exe().context("resolve current executable")?; + let schemes = enabled_url_schemes(identity, enabled_schemes); + remove_stale_url_schemes(identity, &schemes)?; #[cfg(target_os = "windows")] - return ensure_windows_registered(&executable, identity); + let result = ensure_windows_registered(&executable, identity, &schemes); #[cfg(target_os = "linux")] - return ensure_linux_registered(&executable, identity); + let result = ensure_linux_registered(&executable, identity, &schemes); #[cfg(target_os = "macos")] - return ensure_macos_registered(&executable, identity); + let result = ensure_macos_registered(&executable, identity, &schemes); + + #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))] + let result: Result<()> = Ok(()); + + result?; + save_registered_url_schemes(&schemes) +} + +/// 之前注册过、现在被用户关掉的 scheme 需要从系统里摘掉,否则关掉开关后 +/// 链接仍然会被系统交给 Navop。只删自己写过的键,不碰第三方应用的注册。 +fn remove_stale_url_schemes(identity: &AppIdentity, current: &[&str]) -> Result<()> { + let Some(previous) = read_registered_url_schemes()? else { + return Ok(()); + }; + let stale = previous + .iter() + .filter(|scheme| !current.iter().any(|kept| kept.eq_ignore_ascii_case(scheme))) + .filter(|scheme| { + identity + .url_schemes + .iter() + .any(|declared| declared.eq_ignore_ascii_case(scheme)) + }) + .cloned() + .collect::>(); + + #[cfg(target_os = "windows")] + for scheme in &stale { + remove_windows_url_protocol(scheme)?; + } + + #[cfg(target_os = "linux")] + { + // 桌面文件的 MimeType 会随重渲染去掉;Linux 没有「删除默认关联」的 + // 标准做法,未启用的 scheme 由应用层拒绝,不再回写默认值即可。 + } - #[allow(unreachable_code)] + let _ = stale; Ok(()) } -fn registration_stamp(executable: &Path, identity: &AppIdentity) -> String { +fn registration_stamp(executable: &Path, identity: &AppIdentity, schemes: &[&str]) -> String { let mut hasher = Sha256::new(); hasher.update(ASSOCIATION_SCHEMA_VERSION.to_le_bytes()); hasher.update(std::env::consts::OS.as_bytes()); @@ -209,30 +270,73 @@ fn registration_stamp(executable: &Path, identity: &AppIdentity) -> String { hasher.update(identity.app_id.as_bytes()); hasher.update([0]); hasher.update(executable.to_string_lossy().as_bytes()); + hasher.update([0]); + // 启用集合也是注册结果的一部分:开关变化必须重跑一次。 + hasher.update(schemes.join(",").as_bytes()); let digest = hasher.finalize(); digest.iter().map(|byte| format!("{byte:02x}")).collect() } +/// 记录「上次真正写进系统的 scheme」。关闭某个 scheme 时据此精确摘除自己 +/// 写过的注册表键,而不是把同名键都删掉。 +fn registered_url_schemes_path() -> Result { + Ok(get_config_dir()?.join(REGISTERED_URL_SCHEMES_FILE)) +} + +fn read_registered_url_schemes() -> Result>> { + match fs::read_to_string(registered_url_schemes_path()?) { + Ok(contents) => Ok(Some( + contents + .lines() + .map(str::trim) + .filter(|line| !line.is_empty()) + .map(str::to_string) + .collect(), + )), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(error.into()), + } +} + +fn save_registered_url_schemes(schemes: &[&str]) -> Result<()> { + let contents = if schemes.is_empty() { + String::new() + } else { + format!("{}\n", schemes.join("\n")) + }; + write_if_changed(®istered_url_schemes_path()?, &contents)?; + Ok(()) +} + fn registration_stamp_path() -> Result { Ok(get_config_dir()?.join(REGISTRATION_STAMP_FILE)) } -fn stamp_matches(executable: &Path, identity: &AppIdentity) -> Result { - stamp_matches_at(®istration_stamp_path()?, executable, identity) +fn stamp_matches(executable: &Path, identity: &AppIdentity, schemes: &[&str]) -> Result { + stamp_matches_at(®istration_stamp_path()?, executable, identity, schemes) } -fn stamp_matches_at(path: &Path, executable: &Path, identity: &AppIdentity) -> Result { +fn stamp_matches_at( + path: &Path, + executable: &Path, + identity: &AppIdentity, + schemes: &[&str], +) -> Result { match fs::read_to_string(path) { - Ok(current) => Ok(current.trim() == registration_stamp(executable, identity)), + Ok(current) => Ok(current.trim() == registration_stamp(executable, identity, schemes)), Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false), Err(error) => Err(error.into()), } } -fn save_registration_stamp(executable: &Path, identity: &AppIdentity) -> Result<()> { +fn save_registration_stamp( + executable: &Path, + identity: &AppIdentity, + schemes: &[&str], +) -> Result<()> { write_if_changed( ®istration_stamp_path()?, - &format!("{}\n", registration_stamp(executable, identity)), + &format!("{}\n", registration_stamp(executable, identity, schemes)), )?; Ok(()) } @@ -242,6 +346,7 @@ struct WindowsPlanContext { open_command: String, default_icon: String, application_key: String, + url_protocol_description: String, } #[cfg(any(target_os = "windows", test))] @@ -254,6 +359,7 @@ fn windows_plan_context(executable: &Path, identity: &AppIdentity) -> WindowsPla r"HKCU\Software\Classes\Applications\{}{}", identity.binary_name, WINDOWS_EXECUTABLE_SUFFIX ), + url_protocol_description: format!("URL:{} protocol", identity.display_name), } } @@ -261,12 +367,16 @@ fn windows_plan_context(executable: &Path, identity: &AppIdentity) -> WindowsPla const WINDOWS_EXECUTABLE_SUFFIX: &str = ".exe"; #[cfg(any(target_os = "windows", test))] -fn windows_registry_plan(executable: &Path, identity: &AppIdentity) -> Vec { +fn windows_registry_plan( + executable: &Path, + identity: &AppIdentity, + schemes: &[&str], +) -> Vec { let context = windows_plan_context(executable, identity); let specs = associations_for(identity); - // 没有声明扩展名的产品不注册任何东西:只写 `Applications` 键既没人用, - // 又会在注册表里留下一个永远无法打开文件的项。 - if specs.is_empty() { + // 既没有扩展名也没有 URL scheme 的产品不注册任何东西:只写 `Applications` + // 键既没人用,又会在注册表里留下一个永远无法打开文件的项。 + if specs.is_empty() && schemes.is_empty() { return Vec::new(); } let mut commands = Vec::new(); @@ -274,10 +384,52 @@ fn windows_registry_plan(executable: &Path, identity: &AppIdentity) -> Vec` +/// 下的默认值、空的 `URL Protocol`、`DefaultIcon` 与 `shell\open\command`。 +#[cfg(any(target_os = "windows", test))] +fn append_windows_url_protocol_commands( + commands: &mut Vec, + context: &WindowsPlanContext, + scheme: &str, +) { + let base = format!(r"HKCU\Software\Classes\{scheme}"); + for (key, value_name, data) in [ + (base.clone(), None, context.url_protocol_description.clone()), + ( + base.clone(), + Some("URL Protocol".to_string()), + String::new(), + ), + ( + format!(r"{base}\DefaultIcon"), + None, + context.default_icon.clone(), + ), + ( + format!(r"{base}\shell\open\command"), + None, + context.open_command.clone(), + ), + ] { + commands.push(RegistryCommand { + key, + value_name, + value_type: "REG_SZ", + data, + policy: RegistryWritePolicy::Always, + }); + } +} + #[cfg(any(target_os = "windows", test))] fn append_windows_association_commands( commands: &mut Vec, @@ -350,11 +502,15 @@ fn append_windows_application_commands( } #[cfg(target_os = "windows")] -fn ensure_windows_registered(executable: &Path, identity: &AppIdentity) -> Result<()> { - if stamp_matches(executable, identity)? { +fn ensure_windows_registered( + executable: &Path, + identity: &AppIdentity, + schemes: &[&str], +) -> Result<()> { + if stamp_matches(executable, identity, schemes)? { return Ok(()); } - for registry_command in windows_registry_plan(executable, identity) { + for registry_command in windows_registry_plan(executable, identity, schemes) { if let RegistryWritePolicy::IfNoDefaultAssociation { extension } = registry_command.policy && windows_default_association_exists(extension)? { @@ -363,7 +519,28 @@ fn ensure_windows_registered(executable: &Path, identity: &AppIdentity) -> Resul run_registry_command(®istry_command)?; } notify_windows_association_changed(); - save_registration_stamp(executable, identity) + save_registration_stamp(executable, identity, schemes) +} + +/// 把一个之前由 Navop 写过的 scheme 键从用户注册表里删掉(含子键)。 +#[cfg(target_os = "windows")] +fn remove_windows_url_protocol(scheme: &str) -> Result<()> { + use std::os::windows::process::CommandExt; + + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + let key = format!(r"HKCU\Software\Classes\{scheme}"); + let status = Command::new("reg.exe") + .arg("delete") + .arg(&key) + .arg("/f") + .creation_flags(CREATE_NO_WINDOW) + .status() + .context("delete registered URL protocol")?; + if !status.success() { + // 键可能本来就不存在(例如从未真正写入过),删除失败不算致命错误。 + tracing::debug!(%scheme, "reg.exe delete did not remove the URL protocol key"); + } + Ok(()) } #[cfg(target_os = "windows")] @@ -441,13 +618,14 @@ fn linux_registration_files( executable: &Path, data_dir: &Path, identity: &AppIdentity, + schemes: &[&str], ) -> LinuxRegistrationFiles { let applications = data_dir.join("applications"); let desktop_name = format!("{}{LINUX_DESKTOP_SUFFIX}", identity.binary_name); let mime_name = format!("{}{LINUX_MIME_SUFFIX}", identity.binary_name); LinuxRegistrationFiles { desktop_path: applications.join(&desktop_name), - desktop_contents: render_linux_desktop(executable, identity), + desktop_contents: render_linux_desktop(executable, identity, schemes), mime_path: data_dir.join("mime").join("packages").join(mime_name), mime_contents: LINUX_MIME_TEMPLATE.to_string(), } @@ -455,23 +633,31 @@ fn linux_registration_files( /// 把模板里的产品名、图标与启动命令换成本产品的值。 #[cfg(any(target_os = "linux", test))] -fn render_linux_desktop(executable: &Path, identity: &AppIdentity) -> String { +fn render_linux_desktop(executable: &Path, identity: &AppIdentity, schemes: &[&str]) -> String { let quoted = desktop_exec_quote(executable); let name = identity.display_name; let binary = identity.binary_name; + let mime_types = linux_default_mime_types(identity, schemes); LINUX_DESKTOP_TEMPLATE .lines() - .map(|line| { + .filter_map(|line| { if line.starts_with("Exec=") { - format!("Exec={quoted} %F") + // `%U` 才能把 `jms://` 与 `file://` 这类 URL 传给应用;`%F` 只给路径。 + Some(format!("Exec={quoted} %U")) } else if line.starts_with("Name=") { - format!("Name={name}") + Some(format!("Name={name}")) } else if line.starts_with("Icon=") { - format!("Icon={binary}") + Some(format!("Icon={binary}")) } else if line.starts_with("StartupWMClass=") { - format!("StartupWMClass={binary}") + Some(format!("StartupWMClass={binary}")) + } else if line.starts_with("MimeType=") { + if mime_types.is_empty() { + None + } else { + Some(format!("MimeType={};", mime_types.join(";"))) + } } else { - line.to_string() + Some(line.to_string()) } }) .collect::>() @@ -495,23 +681,34 @@ fn desktop_exec_quote(executable: &Path) -> String { format!("\"{escaped}\"") } +/// 产品需要设为默认的 MIME 类型:文件关联的 MIME 加上每个 URL scheme 对应的 +/// `x-scheme-handler/`。 #[cfg(any(target_os = "linux", test))] -fn linux_default_mime_types(identity: &AppIdentity) -> Vec<&'static str> { - identity +fn linux_default_mime_types(identity: &AppIdentity, schemes: &[&str]) -> Vec { + let mut mime_types = identity .file_associations .iter() .filter_map(|declared| association_kind(declared)) .flat_map(|kind| kind.mime_types.iter().copied()) - .collect() + .map(str::to_string) + .collect::>(); + for scheme in schemes { + mime_types.push(format!("x-scheme-handler/{scheme}")); + } + mime_types } #[cfg(target_os = "linux")] -fn ensure_linux_registered(executable: &Path, identity: &AppIdentity) -> Result<()> { +fn ensure_linux_registered( + executable: &Path, + identity: &AppIdentity, + schemes: &[&str], +) -> Result<()> { let data_dir = dirs::data_local_dir().context("resolve user data directory")?; - let files = linux_registration_files(executable, &data_dir, identity); + let files = linux_registration_files(executable, &data_dir, identity, schemes); let desktop_changed = write_if_changed(&files.desktop_path, &files.desktop_contents)?; let mime_changed = write_if_changed(&files.mime_path, &files.mime_contents)?; - let stamp_current = stamp_matches(executable, identity)?; + let stamp_current = stamp_matches(executable, identity, schemes)?; if mime_changed || !stamp_current { run_optional_refresh("update-mime-database", &data_dir.join("mime"))?; @@ -521,11 +718,11 @@ fn ensure_linux_registered(executable: &Path, identity: &AppIdentity) -> Result< } if !stamp_current { let desktop_name = format!("{}{LINUX_DESKTOP_SUFFIX}", identity.binary_name); - for mime_type in linux_default_mime_types(identity) { - ensure_linux_default_if_missing(mime_type, &desktop_name)?; + for mime_type in linux_default_mime_types(identity, schemes) { + ensure_linux_default_if_missing(&mime_type, &desktop_name)?; } } - save_registration_stamp(executable, identity) + save_registration_stamp(executable, identity, schemes) } #[cfg(target_os = "linux")] @@ -601,8 +798,12 @@ fn macos_app_bundle_from_executable(executable: &Path) -> Result { } #[cfg(target_os = "macos")] -fn ensure_macos_registered(executable: &Path, identity: &AppIdentity) -> Result<()> { - if stamp_matches(executable, identity)? { +fn ensure_macos_registered( + executable: &Path, + identity: &AppIdentity, + schemes: &[&str], +) -> Result<()> { + if stamp_matches(executable, identity, schemes)? { return Ok(()); } let app_bundle = match macos_app_bundle_from_executable(executable) { @@ -621,7 +822,7 @@ fn ensure_macos_registered(executable: &Path, identity: &AppIdentity) -> Result< if !status.success() { bail!("lsregister failed with status {status}"); } - save_registration_stamp(executable, identity) + save_registration_stamp(executable, identity, schemes) } fn write_if_changed(path: &Path, contents: &str) -> Result { @@ -678,7 +879,10 @@ mod tests { fn standalone_products_claim_no_extensions() { assert!(associations_for(&AppIdentity::SHELL).is_empty()); assert!(associations_for(&AppIdentity::DATA).is_empty()); - assert!(linux_default_mime_types(&AppIdentity::SHELL).is_empty()); + assert!(linux_default_mime_types(&AppIdentity::SHELL, &[]).is_empty()); + assert_eq!(["jms", "ssh", "sftp"], AppIdentity::FULL.url_schemes); + assert!(AppIdentity::SHELL.url_schemes.is_empty()); + assert!(AppIdentity::DATA.url_schemes.is_empty()); } #[test] @@ -695,7 +899,7 @@ mod tests { #[test] fn windows_registry_plan_registers_handlers_without_overwriting_user_choice() { let executable = Path::new(r"C:\Program Files\Navop\navop.exe"); - let commands = windows_registry_plan(executable, &AppIdentity::FULL); + let commands = windows_registry_plan(executable, &AppIdentity::FULL, &["jms", "ssh"]); let rendered = commands .iter() .map(|command| format!("{} {:?} {}", command.key, command.value_name, command.data)) @@ -713,6 +917,8 @@ mod tests { } assert!(rendered.contains(r#""C:\Program Files\Navop\navop.exe" "%1""#)); assert!(rendered.contains(r"Applications\navop.exe")); + assert!(rendered.contains(r"Software\Classes\jms")); + assert!(rendered.contains("URL Protocol")); assert!(!rendered.contains("UserChoice")); assert!(!rendered.contains(".partial")); for (extension, prog_id) in [ @@ -739,7 +945,8 @@ mod tests { assert!( windows_registry_plan( Path::new(r"C:\Navop Shell\navop-shell.exe"), - &AppIdentity::SHELL + &AppIdentity::SHELL, + &[] ) .is_empty() ); @@ -751,6 +958,7 @@ mod tests { Path::new("/opt/Navop 100%/navop"), Path::new("/home/alice/.local/share"), &AppIdentity::FULL, + &["jms", "ssh", "sftp"], ); assert_eq!( @@ -764,7 +972,7 @@ mod tests { assert!( files .desktop_contents - .contains(r#"Exec="/opt/Navop 100%%/navop" %F"#) + .contains(r#"Exec="/opt/Navop 100%%/navop" %U"#) ); assert!(files.desktop_contents.contains("Name=Navop")); assert!( @@ -773,6 +981,7 @@ mod tests { .contains("MimeType=application/vnd.sqlite3") ); assert!(files.desktop_contents.contains("application/x-asciicast")); + assert!(files.desktop_contents.contains("x-scheme-handler/jms;")); assert!(files.mime_contents.contains("")); assert!(files.mime_contents.contains("")); assert!(files.mime_contents.contains("")); @@ -794,8 +1003,9 @@ mod tests { "application/vnd.duckdb", "text/markdown", "application/x-asciicast", + "x-scheme-handler/jms", ], - linux_default_mime_types(&AppIdentity::FULL) + linux_default_mime_types(&AppIdentity::FULL, &["jms"]) ); } @@ -810,6 +1020,7 @@ mod tests { Path::new("/opt/Navop Data/navop-data"), Path::new("/home/alice/.local/share"), &custom, + &[], ); assert_eq!( @@ -824,14 +1035,15 @@ mod tests { assert!(files.desktop_contents.contains("Icon=navop-data")); assert_eq!( vec!["application/x-asciicast"], - linux_default_mime_types(&custom) + linux_default_mime_types(&custom, &[]) ); + assert!(!files.desktop_contents.contains("x-scheme-handler/")); } #[test] - fn terminal_recording_associations_bump_the_registration_schema() { - assert_eq!(2, ASSOCIATION_SCHEMA_VERSION); - assert_eq!("file-association-registration-v2", REGISTRATION_STAMP_FILE); + fn registration_schema_covers_url_schemes() { + assert_eq!(3, ASSOCIATION_SCHEMA_VERSION); + assert_eq!("file-association-registration-v3", REGISTRATION_STAMP_FILE); } #[test] @@ -852,21 +1064,38 @@ mod tests { assert_eq!( registration_stamp( Path::new("/Applications/Navop.app/Contents/MacOS/navop"), - identity + identity, + &["jms"] ), registration_stamp( Path::new("/Applications/Navop.app/Contents/MacOS/navop"), - identity + identity, + &["jms"] ) ); assert_ne!( registration_stamp( Path::new("/Applications/Navop.app/Contents/MacOS/navop"), - identity + identity, + &["jms"] ), registration_stamp( Path::new("/Users/alice/Applications/Navop.app/Contents/MacOS/navop"), - identity + identity, + &["jms"] + ) + ); + // 启用集合变化也必须触发一次重新注册。 + assert_ne!( + registration_stamp( + Path::new("/Applications/Navop.app/Contents/MacOS/navop"), + identity, + &["jms"] + ), + registration_stamp( + Path::new("/Applications/Navop.app/Contents/MacOS/navop"), + identity, + &["jms", "ssh"] ) ); } @@ -878,16 +1107,33 @@ mod tests { let executable = Path::new("/Applications/Navop.app/Contents/MacOS/navop"); let identity = &AppIdentity::FULL; - assert!(!stamp_matches_at(&stamp_path, executable, identity)?); + assert!(!stamp_matches_at( + &stamp_path, + executable, + identity, + &["jms"] + )?); std::fs::write( &stamp_path, - format!("{}\n", registration_stamp(executable, identity)), + format!("{}\n", registration_stamp(executable, identity, &["jms"])), )?; - assert!(stamp_matches_at(&stamp_path, executable, identity)?); + assert!(stamp_matches_at( + &stamp_path, + executable, + identity, + &["jms"] + )?); assert!(!stamp_matches_at( &stamp_path, Path::new("/Applications/Navop 2.app/Contents/MacOS/navop"), - identity + identity, + &["jms"] + )?); + assert!(!stamp_matches_at( + &stamp_path, + executable, + identity, + &["jms", "ssh"] )?); Ok(()) } diff --git a/crates/app_kit/src/host.rs b/crates/app_kit/src/host.rs index 205424e0d..0f2025117 100644 --- a/crates/app_kit/src/host.rs +++ b/crates/app_kit/src/host.rs @@ -4,7 +4,8 @@ //! 领域把事件交给这里注册的应用壳实现,由具体产品决定怎么打开 SFTP、 //! 保存临时连接等。没有注册宿主时(例如领域单元测试)调用会被忽略。 -use gpui::{AnyWindowHandle, App, Window}; +use domain_api::{ConnectionFormRequest, ConnectionKindDescriptor}; +use gpui::{AnyView, AnyWindowHandle, App, Window}; use one_core::storage::StoredConnection; use std::path::PathBuf; use std::sync::{Arc, OnceLock}; @@ -54,6 +55,25 @@ pub fn shell_host() -> Option> { pub trait ExtensionsHost: Send + Sync { /// `parent` 是向导弹窗的父窗口(应用主窗口);返回 `false` 表示无法打开。 fn open_extensions(&self, parent: AnyWindowHandle, window: &mut Window, cx: &mut App) -> bool; + + /// 已安装扩展贡献的连接种类。 + /// + /// 新建连接向导把它们归入「中间件」类目;没有任何扩展贡献时返回空。 + fn connection_kinds(&self, _cx: &App) -> Vec { + Vec::new() + } + + /// 构造扩展连接的新建 / 编辑表单。 + /// + /// `request.kind_id` 不属于扩展种类时返回 `None`,由领域注册表继续兜底。 + fn build_connection_form( + &self, + _request: ConnectionFormRequest, + _window: &mut Window, + _cx: &mut App, + ) -> Option { + None + } } static EXTENSIONS_HOST: OnceLock> = OnceLock::new(); diff --git a/crates/app_kit/src/new_connection.rs b/crates/app_kit/src/new_connection.rs index 1a2ece3a7..cfbf8e2fe 100644 --- a/crates/app_kit/src/new_connection.rs +++ b/crates/app_kit/src/new_connection.rs @@ -316,7 +316,11 @@ impl ConnectionFormDialog { window: &mut Window, cx: &mut Context, ) -> Self { - let kinds = crate::registry().kinds(cx); + let mut kinds = crate::registry().kinds(cx); + // 扩展贡献的连接(中间件)不在领域注册表里:由应用壳的扩展宿主补进来。 + if let Some(host) = crate::host::extensions_host() { + kinds.extend(host.connection_kinds(cx)); + } let mut dialog = Self { focus_handle: cx.focus_handle(), kinds, @@ -428,18 +432,20 @@ impl ConnectionFormDialog { } /// 打开一个条目:真实种类进表单,伪条目跳扩展管理页。 + /// + /// 条目可能只在自己类目下出现(例如「安装扩展」入口不在「全部」里), + /// 因此按 key 在全部类目里查找,而不是只查「全部」。 fn open_entry(&mut self, key: SharedString, window: &mut Window, cx: &mut Context) { - let Some(entry) = self - .entries_in(WizardCategory::All) - .into_iter() - .find(|entry| entry.key() == key) - else { + let Some(entry) = find_entry( + &self.kinds, + key.as_ref(), + crate::host::extensions_available(), + ) else { return; }; - if entry.opens_extensions() { - self.open_extensions(window, cx); - } else if let WizardEntry::Kind(kind) = entry { - self.open_kind(kind.id, window, cx); + match entry { + WizardEntry::Kind(kind) => self.open_kind(kind.id, window, cx), + WizardEntry::Install(_) | WizardEntry::More => self.open_extensions(window, cx), } } @@ -789,7 +795,7 @@ pub fn open_form(request: ConnectionFormRequest, window: &mut Window, cx: &mut A return false; } let kind_id = request.kind_id.clone(); - let Some(form) = crate::registry().build_connection_form(request.clone(), window, cx) else { + let Some(form) = build_form_for_request(request.clone(), window, cx) else { window.push_notification( Notification::error(format!("当前产品不支持该连接类型:{kind_id}")), cx, @@ -819,7 +825,18 @@ fn build_form( let request = mode .request(kind_id, connection) .with_workspace(workspace_id); - crate::registry().build_connection_form(request, window, cx) + build_form_for_request(request, window, cx) +} + +/// 按通用请求构造表单:领域注册表优先,扩展种类(中间件)交给应用壳宿主。 +fn build_form_for_request( + request: ConnectionFormRequest, + window: &mut Window, + cx: &mut App, +) -> Option { + crate::registry() + .build_connection_form(request.clone(), window, cx) + .or_else(|| crate::host::extensions_host()?.build_connection_form(request, window, cx)) } fn category_title(category: WizardCategory) -> SharedString { @@ -903,6 +920,22 @@ fn visible_categories(kinds: &[ConnectionKindDescriptor]) -> Vec categories } +/// 按 key 在全部可见类目里定位条目。 +/// +/// 伪条目只在自己的类目下生成:「安装扩展」不在「全部」里,只查「全部」会漏掉它, +/// 点击「+」或按「下一步」就静默无反应。没有扩展管理器时这类入口不渲染, +/// 也不应该能被定位到。 +fn find_entry( + kinds: &[ConnectionKindDescriptor], + key: &str, + extensions_available: bool, +) -> Option { + visible_categories(kinds) + .into_iter() + .flat_map(|category| category_entries(kinds, category)) + .find(|entry| entry.key() == key && (extensions_available || !entry.opens_extensions())) +} + /// 当前产品是否装配了数据库侧类型(决定数据库类目与「安装时序驱动」入口)。 fn has_database_kinds(kinds: &[ConnectionKindDescriptor]) -> bool { kinds @@ -1140,6 +1173,38 @@ mod tests { assert_eq!(WizardCategory::Middleware, kind_category(&declared)); } + #[test] + fn install_entry_is_found_outside_all_category() { + let kinds = data_kinds(); + // 「中间件」为空时补安装入口,而它不属于「全部」:点击「+」/回车必须能找到。 + assert!(matches!( + find_entry(&kinds, "@install-middleware", true), + Some(WizardEntry::Install(WizardCategory::Middleware)) + )); + // 没有扩展管理器时该入口不渲染,也不应该被定位到。 + assert!(find_entry(&kinds, "@install-middleware", false).is_none()); + // 「更多连接」仍在「全部」里。 + assert!(matches!( + find_entry(&kinds, "@more-connections", true), + Some(WizardEntry::More) + )); + } + + #[test] + fn extension_kind_is_found_in_middleware_category() { + let mut kinds = data_kinds(); + kinds.push( + descriptor( + "ext:com.navop.middleware.demo", + ConnectionKindGroup::Extension, + ) + .with_label("Demo"), + ); + let entry = find_entry(&kinds, "ext:com.navop.middleware.demo", true) + .expect("extension kind is reachable"); + assert_eq!(WizardCategory::Middleware, entry.category()); + } + fn shell_kinds() -> Vec { [KIND_SSH, KIND_RDP, KIND_VNC, KIND_SERIAL] .into_iter() diff --git a/crates/connection_tunnel/src/lib.rs b/crates/connection_tunnel/src/lib.rs index 89042e2ae..d3416df9a 100644 --- a/crates/connection_tunnel/src/lib.rs +++ b/crates/connection_tunnel/src/lib.rs @@ -2,7 +2,8 @@ use std::time::Duration; use serde::{Deserialize, Serialize}; use ssh::{ - HostKeyVerifier, LocalPortForwardTunnel, SshAuth, SshConnectConfig, start_local_port_forward, + BastionUserFormat, HostKeyVerifier, JumpMode, JumpServerConnectConfig, LocalPortForwardTunnel, + SshAuth, SshConnectConfig, start_local_port_forward, }; use thiserror::Error; use tokio::time::timeout; @@ -171,6 +172,65 @@ pub struct SshTunnelConfig { pub target_port: Option, #[serde(default)] pub timeout: Option, + /// 引用 SSH 连接继承的跳板机配置(隧道也走跳板,语义不丢失)。 + /// + /// 存储层(one-core)定义的 `JumpServerConfig` 不能直接出现在这里 + /// (connection_tunnel 是 one-core 的依赖,反向引用会成环),因此 + /// 用一个隧道本地的可序列化子集,由 + /// `one_core::storage::models::inherit_tunnel_jump_and_proxy` 回填。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub jump: Option, + /// 引用 SSH 连接继承的代理配置(SOCKS5/HTTP)。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub proxy: Option, +} + +/// 隧道继承的跳板机配置(`one_core::storage::models::JumpServerConfig` +/// 的可序列化子集;凭据引用不进隧道,隧道始终用已解析的具体凭据)。 +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct TunnelJumpConfig { + pub host: String, + pub port: u16, + pub username: String, + pub auth_type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub password: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub private_key_path: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub private_key_content: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub private_key_passphrase: Option, + /// 工作模式:proxy_jump / bastion_direct。缺省 proxy_jump(旧数据)。 + #[serde(default)] + pub mode: TunnelJumpMode, + /// 堡垒机直连目标资产 ID。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub bastion_asset: Option, + /// 堡垒机直连资产登录账号。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub bastion_account: Option, +} + +/// 隧道跳板工作模式,与存储层 `JumpMode` 一一对应。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TunnelJumpMode { + #[default] + ProxyJump, + BastionDirect, +} + +/// 隧道继承的代理配置(`one_core::storage::models::ProxyConfig` 的子集)。 +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct TunnelProxyConfig { + pub proxy_type: String, + pub host: String, + pub port: u16, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub username: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub password: Option, } impl Default for SshTunnelConfig { @@ -189,6 +249,8 @@ impl Default for SshTunnelConfig { target_host: None, target_port: None, timeout: None, + jump: None, + proxy: None, } } } @@ -280,7 +342,7 @@ async fn resolve_ssh_target( timeout: Some(Duration::from_secs(timeout_secs)), keepalive_interval: None, keepalive_max: None, - jump_server: None, + jump_server: tunnel_jump_connect_config(tunnel), proxy: proxy.map(ProxyTunnelConfig::to_ssh_proxy).transpose()?, keyboard_interactive_responder: None, host_key_verifier: HostKeyVerifier::default(), @@ -309,6 +371,41 @@ async fn resolve_ssh_target( }) } +/// 隧道继承的跳板配置 → 连接层跳板配置。 +/// +/// 凭据字段由 `tunnel_auth_fields` 同款规则从 auth_type + 密钥材料还原; +/// 未配置跳板时返回 `None`,行为与历史版本一致。 +fn tunnel_jump_connect_config(tunnel: &SshTunnelConfig) -> Option { + let jump = tunnel.jump.as_ref()?; + let auth = match jump.auth_type.trim().to_ascii_lowercase().as_str() { + "agent" => SshAuth::Agent, + "private_key" => SshAuth::PrivateKey { + key_path: jump.private_key_path.clone().unwrap_or_default(), + passphrase: jump.private_key_passphrase.clone(), + certificate_path: None, + }, + "private_key_content" => SshAuth::PrivateKeyContent { + private_key: jump.private_key_content.clone().unwrap_or_default(), + passphrase: jump.private_key_passphrase.clone(), + certificate_path: None, + }, + _ => SshAuth::Password(jump.password.clone().unwrap_or_default()), + }; + Some(JumpServerConnectConfig { + host: jump.host.clone(), + port: jump.port, + username: jump.username.clone(), + auth, + mode: match jump.mode { + TunnelJumpMode::ProxyJump => JumpMode::ProxyJump, + TunnelJumpMode::BastionDirect => JumpMode::BastionDirect, + }, + bastion_asset: jump.bastion_asset.clone().unwrap_or_default(), + bastion_account: jump.bastion_account.clone().unwrap_or_default(), + bastion_user_format: BastionUserFormat::JumpServer, + }) +} + fn required_value(key: &'static str, value: &str) -> Result { let value = value.trim(); if value.is_empty() { diff --git a/crates/core/src/settings.rs b/crates/core/src/settings.rs index e69ea6473..04c61b02e 100644 --- a/crates/core/src/settings.rs +++ b/crates/core/src/settings.rs @@ -1520,6 +1520,12 @@ pub struct AppSettings { pub large_text_cell_editor_open_mode: LargeTextCellEditorOpenMode, #[serde(default)] pub startup_default_page: StartupDefaultPage, + /// 除私有 `jms://` 外允许 Navop 接管的通用 URL scheme。 + /// + /// 空集合(默认)表示只接管 `jms://`。启用的 scheme 才会注册到系统, + /// 避免默认抢走终端、文件管理器的既有 `ssh://`、`sftp://` 关联。 + #[serde(default)] + pub deeplink_schemes: Vec, /// 是否要求每次启动时输入主密钥后才能访问已保存的连接 #[serde(default)] pub require_master_key_on_startup: bool, @@ -1928,6 +1934,7 @@ impl Default for AppSettings { database_open_mode: DatabaseOpenMode::default(), large_text_cell_editor_open_mode: LargeTextCellEditorOpenMode::default(), startup_default_page: StartupDefaultPage::default(), + deeplink_schemes: Vec::new(), require_master_key_on_startup: false, portable_remember_master_key: false, master_key_storage: MasterKeyStorage::SystemCredentialStore, @@ -2019,6 +2026,48 @@ impl AppSettings { ) } + /// Navop 私有、始终启用的深链接 scheme(JumpServer)。 + pub const PRIVATE_DEEPLINK_SCHEME: &'static str = "jms"; + + /// 该 scheme 是否允许打开深链接;`jms://` 始终允许。 + pub fn deeplink_scheme_enabled(&self, scheme: &str) -> bool { + scheme.eq_ignore_ascii_case(Self::PRIVATE_DEEPLINK_SCHEME) + || self + .deeplink_schemes + .iter() + .any(|enabled| enabled.eq_ignore_ascii_case(scheme)) + } + + /// 需要注册到系统的全部 scheme:私有 scheme 始终在最前,其余按用户启用。 + pub fn enabled_deeplink_schemes(&self) -> Vec { + let mut schemes = vec![Self::PRIVATE_DEEPLINK_SCHEME.to_string()]; + for scheme in &self.deeplink_schemes { + let scheme = scheme.trim(); + if scheme.is_empty() + || schemes + .iter() + .any(|known| known.eq_ignore_ascii_case(scheme)) + { + continue; + } + schemes.push(scheme.to_string()); + } + schemes + } + + /// 启用/停用某个通用 scheme;私有 `jms://` 不受设置影响。 + pub fn set_deeplink_scheme_enabled(&mut self, scheme: &str, enabled: bool) { + let scheme = scheme.trim(); + if scheme.is_empty() || scheme.eq_ignore_ascii_case(Self::PRIVATE_DEEPLINK_SCHEME) { + return; + } + self.deeplink_schemes + .retain(|known| !known.eq_ignore_ascii_case(scheme)); + if enabled { + self.deeplink_schemes.push(scheme.to_string()); + } + } + fn migrate_legacy_mcp_toolsets(&mut self) { let Some(toolsets) = self.mcp.legacy_toolsets.take() else { return; @@ -2491,6 +2540,57 @@ mod tests { assert!(!AppSettings::default().sync_enabled); } + #[test] + fn deeplink_schemes_default_to_the_private_scheme_only() { + let settings = AppSettings::default(); + assert!(settings.deeplink_schemes.is_empty()); + assert!(settings.deeplink_scheme_enabled("jms")); + assert!(!settings.deeplink_scheme_enabled("ssh")); + assert!(!settings.deeplink_scheme_enabled("sftp")); + assert_eq!(vec!["jms".to_string()], settings.enabled_deeplink_schemes()); + } + + #[test] + fn deeplink_scheme_toggles_are_case_insensitive_and_deduplicated() { + let mut settings = AppSettings::default(); + settings.set_deeplink_scheme_enabled("SSH", true); + settings.set_deeplink_scheme_enabled("sftp", true); + settings.set_deeplink_scheme_enabled("ssh", true); + assert!(settings.deeplink_scheme_enabled("ssh")); + assert!(settings.deeplink_scheme_enabled("SFTP")); + // 重新启用只是刷新位置,不会重复;私有 scheme 永远在最前。 + assert_eq!( + vec!["jms".to_string(), "sftp".to_string(), "ssh".to_string()], + settings.enabled_deeplink_schemes() + ); + + settings.set_deeplink_scheme_enabled("ssh", false); + assert!(!settings.deeplink_scheme_enabled("ssh")); + assert_eq!( + vec!["jms".to_string(), "sftp".to_string()], + settings.enabled_deeplink_schemes() + ); + + // 私有 scheme 不能被设置关掉。 + settings.set_deeplink_scheme_enabled("jms", false); + assert!(settings.deeplink_scheme_enabled("jms")); + } + + #[test] + fn deeplink_schemes_round_trip_through_json() { + let mut settings = AppSettings::default(); + settings.set_deeplink_scheme_enabled("sftp", true); + let json = serde_json::to_string(&settings).expect("serialize"); + let restored: AppSettings = serde_json::from_str(&json).expect("deserialize"); + assert!(restored.deeplink_scheme_enabled("sftp")); + assert!(!restored.deeplink_scheme_enabled("ssh")); + + let legacy: AppSettings = + serde_json::from_str("{}").expect("missing field falls back to the default"); + assert!(legacy.deeplink_schemes.is_empty()); + assert!(legacy.deeplink_scheme_enabled("jms")); + } + #[test] fn corrupt_settings_file_is_quarantined_instead_of_silently_reset() { // 回归保护:解析失败若直接回落 Default、再被启动期任意一次 save() 全量覆盖, diff --git a/crates/core/src/storage/credential_vault/tests/reference_scan_tests.rs b/crates/core/src/storage/credential_vault/tests/reference_scan_tests.rs index 68e2f45b3..01e0c2c90 100644 --- a/crates/core/src/storage/credential_vault/tests/reference_scan_tests.rs +++ b/crates/core/src/storage/credential_vault/tests/reference_scan_tests.rs @@ -70,6 +70,8 @@ pub(super) fn ssh_connection(id: i64) -> StoredConnection { password: String::new(), }, credential_reference: Some(reference(id)), + mode: Default::default(), + bastion: None, }), proxy: Some(proxy(id)), os_id: None, @@ -353,6 +355,8 @@ fn reference_scanner_finds_disabled_jump_server_reference() { password: String::new(), }, credential_reference: Some(reference(credential_id)), + mode: Default::default(), + bastion: None, }); connection.params = serde_json::to_string(¶ms).expect("serialize SSH params"); } diff --git a/crates/core/src/storage/credential_vault/tests/resolver_tests.rs b/crates/core/src/storage/credential_vault/tests/resolver_tests.rs index 59387d013..e84c2ba4c 100644 --- a/crates/core/src/storage/credential_vault/tests/resolver_tests.rs +++ b/crates/core/src/storage/credential_vault/tests/resolver_tests.rs @@ -387,6 +387,8 @@ fn resolver_supports_proxy_jump_server_sentinel_and_private_key_content() { password: "manual".to_string(), }, credential_reference: login_reference, + mode: Default::default(), + bastion: None, }); let ssh = repository .resolve_ssh(ssh) @@ -641,6 +643,8 @@ fn resolver_applies_the_same_rules_to_the_jump_server() { private_key: false, passphrase: false, }), + mode: Default::default(), + bastion: None, }); let resolved = repository.resolve_ssh(ssh).expect("resolve ssh"); let jump = resolved.jump_server.expect("jump server"); diff --git a/crates/core/src/storage/models.rs b/crates/core/src/storage/models.rs index eb5fa95bc..a471a3cfa 100644 --- a/crates/core/src/storage/models.rs +++ b/crates/core/src/storage/models.rs @@ -807,6 +807,36 @@ impl RemoteDesktopParams { } } +/// 跳板机工作模式 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum JumpMode { + /// 现有语义:在跳板机上开 direct-tcpip 通道连目标(ProxyJump 式)。 + #[default] + ProxyJump, + /// 直连型堡垒机:目标会话就是堡垒机会话,用户名按预设格式渲染 + /// (JumpServer 的 `{user}#{account}#{asset}`),不开端口转发通道。 + BastionDirect, +} + +/// 堡垒机用户名格式预设 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum BastionUserFormat { + /// JumpServer:`{user}#{account}#{asset}` + #[default] + JumpServer, +} + +/// 堡垒机直连目标(`JumpMode::BastionDirect` 时生效) +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct BastionTarget { + /// 资产 IP / 名称 / UUID(JumpServer 支持资产 UUID) + pub asset: String, + /// 资产账号(如 root) + pub account: String, + /// 用户名格式预设 + pub user_format: BastionUserFormat, +} + /// 跳板机配置 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct JumpServerConfig { @@ -816,6 +846,33 @@ pub struct JumpServerConfig { pub auth_method: SshAuthMethod, #[serde(default, skip_serializing_if = "Option::is_none")] pub credential_reference: Option, + /// 工作模式。存量数据无此字段,反序列化缺省为 ProxyJump。 + #[serde(default, skip_serializing_if = "is_default_jump_mode")] + pub mode: JumpMode, + /// 堡垒机直连目标。仅 `JumpMode::BastionDirect` 时有意义。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub bastion: Option, +} + +/// `mode` 为缺省值(ProxyJump)时序列化省略,保证旧数据可读、diff 干净。 +fn is_default_jump_mode(mode: &JumpMode) -> bool { + matches!(mode, JumpMode::ProxyJump) +} + +impl JumpServerConfig { + /// 渲染堡垒机直连登录用户名。 + /// + /// 仅 `JumpMode::BastionDirect` 且已配置 `bastion` 时返回 `Some`; + /// ProxyJump 或漏配目标时返回 `None`,由调用方沿用普通用户名。 + pub fn bastion_login_username(&self) -> Option { + let bastion = self.bastion.as_ref()?; + match bastion.user_format { + BastionUserFormat::JumpServer => Some(format!( + "{}#{}#{}", + self.username, bastion.account, bastion.asset + )), + } + } } /// 代理类型 @@ -973,6 +1030,58 @@ fn tunnel_auth_fields(auth: &SshAuthMethod) -> TunnelAuthFields { } } +/// 把引用 SSH 连接的 jump/proxy 继承进隧道配置(T1 隧道继承)。 +/// +/// 历史 bug:`apply_referenced_ssh_tunnel` 只回填 host/port/username/auth/timeout, +/// 引用带跳板机的 SSH 连接时跳板被静默丢弃,隧道直连内网地址导致连接失败。 +/// 统一在各 `apply_referenced_ssh_tunnel` 末尾调用本函数,隧道随引用连接走跳板。 +pub fn inherit_tunnel_jump_and_proxy( + tunnel: &mut SshTunnelConfig, + ssh_params: &SshParams, +) { + if tunnel.jump.is_none() { + tunnel.jump = ssh_params.jump_server.as_ref().map(tunnel_jump_from_storage); + } + if tunnel.proxy.is_none() { + tunnel.proxy = ssh_params.proxy.as_ref().map(tunnel_proxy_from_storage); + } +} + +/// 存储 `JumpServerConfig` → 隧道 `TunnelJumpConfig`(已解析凭据子集)。 +fn tunnel_jump_from_storage(jump: &JumpServerConfig) -> connection_tunnel::TunnelJumpConfig { + let fields = tunnel_auth_fields(&jump.auth_method); + connection_tunnel::TunnelJumpConfig { + host: jump.host.clone(), + port: jump.port, + username: jump.username.clone(), + auth_type: fields.auth_type.to_string(), + password: fields.password, + private_key_path: fields.private_key_path, + private_key_content: fields.private_key_content, + private_key_passphrase: fields.passphrase, + mode: match jump.mode { + JumpMode::ProxyJump => connection_tunnel::TunnelJumpMode::ProxyJump, + JumpMode::BastionDirect => connection_tunnel::TunnelJumpMode::BastionDirect, + }, + bastion_asset: jump.bastion.as_ref().map(|target| target.asset.clone()), + bastion_account: jump.bastion.as_ref().map(|target| target.account.clone()), + } +} + +/// 存储 `ProxyConfig` → 隧道 `TunnelProxyConfig`。 +fn tunnel_proxy_from_storage(proxy: &ProxyConfig) -> connection_tunnel::TunnelProxyConfig { + connection_tunnel::TunnelProxyConfig { + proxy_type: match proxy.proxy_type { + ProxyType::Socks5 => "socks5".to_string(), + ProxyType::Http => "http".to_string(), + }, + host: proxy.host.clone(), + port: proxy.port, + username: proxy.username.clone(), + password: proxy.password.clone(), + } +} + /// 需要加入本地 ssh-agent 并通过 ForwardAgent 转发的私钥。 /// /// 独立于 [`SshAuthMethod`]:这把密钥不用于本连接自身的认证,只是被加入 @@ -1071,6 +1180,7 @@ impl RedisParams { } let ssh_params = ssh_connection.to_ssh_params()?; + inherit_tunnel_jump_and_proxy(tunnel, &ssh_params); tunnel.host = ssh_params.host; tunnel.port = ssh_params.port; tunnel.username = ssh_params.username; @@ -1085,6 +1195,7 @@ impl RedisParams { tunnel.private_key_content = auth_fields.private_key_content; tunnel.private_key_passphrase = auth_fields.passphrase; + Ok(()) } } @@ -1170,6 +1281,7 @@ impl MongoDBParams { } let ssh_params = ssh_connection.to_ssh_params()?; + inherit_tunnel_jump_and_proxy(tunnel, &ssh_params); tunnel.host = ssh_params.host; tunnel.port = ssh_params.port; tunnel.username = ssh_params.username; @@ -1184,6 +1296,7 @@ impl MongoDBParams { tunnel.private_key_content = auth_fields.private_key_content; tunnel.private_key_passphrase = auth_fields.passphrase; + Ok(()) } } @@ -1295,6 +1408,7 @@ impl MqttParams { } let ssh_params = ssh_connection.to_ssh_params()?; + inherit_tunnel_jump_and_proxy(tunnel, &ssh_params); tunnel.host = ssh_params.host; tunnel.port = ssh_params.port; tunnel.username = ssh_params.username; @@ -1309,6 +1423,7 @@ impl MqttParams { tunnel.private_key_content = auth_fields.private_key_content; tunnel.private_key_passphrase = auth_fields.passphrase; + Ok(()) } } @@ -1974,6 +2089,16 @@ impl DbConnectionConfig { .insert("ssh_private_key_passphrase".to_string(), passphrase); } + // T1 隧道继承:引用连接的 jump/proxy 经 extra_params 传递 + // (DbConnectionConfig 不持有 SshTunnelConfig 结构体,序列化进去)。 + if self.extra_params.get("ssh_jump_config").is_none() { + if let Some(jump) = &ssh_params.jump_server { + if let Ok(encoded) = serde_json::to_string(&tunnel_jump_from_storage(jump)) { + self.extra_params.insert("ssh_jump_config".to_string(), encoded); + } + } + } + Ok(()) } } diff --git a/crates/core/tests/jump_mode_model_test.rs b/crates/core/tests/jump_mode_model_test.rs new file mode 100644 index 000000000..e698bad83 --- /dev/null +++ b/crates/core/tests/jump_mode_model_test.rs @@ -0,0 +1,90 @@ +//! P1 堡垒机直连模式(BastionDirect)—— Red 测试先行。 +//! +//! 目标:`JumpServerConfig` 增加 `mode`(缺省 `ProxyJump`,旧数据无感)与 +//! `bastion`(BastionDirect 时生效),并能按 JumpServer 预设渲染用户名 +//! `{user}#{account}#{asset}`。先写测试(Red),再补模型实现(Green)。 + +use one_core::storage::models::{ + BastionTarget, BastionUserFormat, JumpMode, JumpServerConfig, SshAuthMethod, +}; +use serde_json::json; + +fn base_jump() -> JumpServerConfig { + JumpServerConfig { + host: "10.2.5.220".to_owned(), + port: 2222, + username: "hufei".to_owned(), + auth_method: SshAuthMethod::Password { + password: "secret".to_owned(), + }, + credential_reference: None, + mode: JumpMode::ProxyJump, + bastion: None, + } +} + +#[test] +fn legacy_jump_json_defaults_to_proxy_jump_mode() { + // 存量数据没有 mode/bastion 字段:反序列化必须得到 ProxyJump 且无堡垒目标。 + let legacy = json!({ + "host": "10.2.5.220", + "port": 2222, + "username": "hufei", + "auth_method": {"Password": {"password": "secret"}}, + }); + let parsed: JumpServerConfig = serde_json::from_value(legacy).expect("legacy json must parse"); + assert_eq!(parsed.mode, JumpMode::ProxyJump); + assert!(parsed.bastion.is_none()); +} + +#[test] +fn proxy_jump_mode_omits_new_fields_when_serializing() { + // 缺省模式序列化不携带新字段,保证旧版本可读、diff 干净。 + let serialized = serde_json::to_value(base_jump()).expect("serialize"); + assert!(serialized.get("mode").is_none()); + assert!(serialized.get("bastion").is_none()); +} + +#[test] +fn bastion_direct_round_trips_with_target_and_format() { + let mut config = base_jump(); + config.mode = JumpMode::BastionDirect; + config.bastion = Some(BastionTarget { + asset: "0e85eca7-422a-4cdb-8e4c-8e3ff68eee39".to_owned(), + account: "root".to_owned(), + user_format: BastionUserFormat::JumpServer, + }); + + let serialized = serde_json::to_value(&config).expect("serialize"); + assert_eq!(serialized["mode"], "BastionDirect"); + assert_eq!(serialized["bastion"]["account"], "root"); + + let parsed: JumpServerConfig = + serde_json::from_value(serialized).expect("round trip must parse"); + assert_eq!(parsed.mode, JumpMode::BastionDirect); + let bastion = parsed.bastion.expect("bastion target must survive"); + assert_eq!(bastion.user_format, BastionUserFormat::JumpServer); + assert_eq!(bastion.asset, "0e85eca7-422a-4cdb-8e4c-8e3ff68eee39"); +} + +#[test] +fn jump_server_user_format_renders_jumpserver_username() { + // JumpServer 直连用户名:{user}#{account}#{asset}。 + let mut config = base_jump(); + config.mode = JumpMode::BastionDirect; + config.bastion = Some(BastionTarget { + asset: "0e85eca7-422a-4cdb-8e4c-8e3ff68eee39".to_owned(), + account: "root".to_owned(), + user_format: BastionUserFormat::JumpServer, + }); + assert_eq!( + config.bastion_login_username().as_deref(), + Some("hufei#root#0e85eca7-422a-4cdb-8e4c-8e3ff68eee39") + ); +} + +#[test] +fn jump_server_user_format_returns_none_without_bastion_target() { + // ProxyJump 或漏配 bastion 时不得臆造用户名。 + assert_eq!(base_jump().bastion_login_username(), None); +} diff --git a/crates/core/tests/tunnel_jump_inherit_test.rs b/crates/core/tests/tunnel_jump_inherit_test.rs new file mode 100644 index 000000000..25b198773 --- /dev/null +++ b/crates/core/tests/tunnel_jump_inherit_test.rs @@ -0,0 +1,184 @@ +//! 隧道继承 jump/proxy 的单测。 +//! +//! 历史 bug:引用 SSH 连接建隧道(DB/Redis/Mongo/MQTT)时, +//! `apply_referenced_ssh_tunnel` 只回填 host/port/username/auth/timeout, +//! 跳板机与代理配置被静默丢弃——引用一个带跳板机的 SSH 连接,实际却不走跳板, +//! 直连内网地址导致连接失败。本模块锁定「引用连接的 jump/proxy 必须继承进 +//! 隧道配置」这一语义。 + +use connection_tunnel::{SshTunnelConfig, TunnelJumpMode}; +use one_core::storage::models::{ + JumpServerConfig as StorageJumpServerConfig, RedisParams, SshAuthMethod, SshParams, + StoredConnection, +}; + +fn referenced_ssh_with_jump() -> StoredConnection { + let mut connection = StoredConnection::new_ssh( + "prod-bastion".to_string(), + SshParams { + otp: None, + remote_file: None, + disabled_jump_server: None, + sftp_default_directory: None, + sftp_account: None, + host: "target.internal".to_string(), + port: 22, + username: "deploy".to_string(), + auth_method: SshAuthMethod::Password { + password: "ssh-secret".to_string(), + }, + credential_reference: None, + prompt_username: None, + prompt_password: None, + keyboard_interactive: None, + terminal_encoding: Default::default(), + terminal_type: Default::default(), + connect_timeout: Some(15), + keepalive_interval: Some(30), + keepalive_max: Some(3), + default_directory: None, + init_script: None, + disable_shell_integration: None, + x11_forwarding: None, + allow_legacy_algorithms: None, + forward_agent: None, + agent_forward_key: None, + jump_server: Some(StorageJumpServerConfig { + host: "jump.example.com".to_string(), + port: 2222, + username: "hufei".to_string(), + auth_method: SshAuthMethod::Password { + password: "jump-secret".to_string(), + }, + credential_reference: None, + mode: one_core::storage::models::JumpMode::ProxyJump, + bastion: None, + }), + proxy: None, + os_id: None, + icon: None, + icon_file_path: None, + account_expect: Default::default(), + }, + Some(7), + ); + connection.id = Some(42); + connection +} + +#[test] +fn referenced_jump_is_inherited_into_tunnel_config() { + let ssh = referenced_ssh_with_jump(); + let params = ssh.to_ssh_params().expect("ssh params should parse"); + + // 统一回填入口:把引用连接的 jump/proxy 带进隧道配置。 + let mut tunnel = SshTunnelConfig { + enabled: true, + connection_id: Some(42), + ..Default::default() + }; + one_core::storage::models::inherit_tunnel_jump_and_proxy(&mut tunnel, ¶ms); + + let jump = tunnel + .jump + .as_ref() + .expect("referenced jump server should be inherited"); + assert_eq!("jump.example.com", jump.host); + assert_eq!(2222, jump.port); + assert_eq!("hufei", jump.username); + // 认证按隧道凭据子集展开(auth_type + password/密钥材料)。 + assert_eq!("password", jump.auth_type); + assert_eq!(Some("jump-secret".to_string()), jump.password); + assert_eq!(TunnelJumpMode::ProxyJump, jump.mode); + assert_eq!(None, jump.bastion_asset); + assert_eq!(None, jump.bastion_account); +} + +#[test] +fn explicit_tunnel_jump_is_not_overridden() { + let ssh = referenced_ssh_with_jump(); + let params = ssh.to_ssh_params().expect("ssh params should parse"); + let mut tunnel = SshTunnelConfig::default(); + tunnel.jump = Some(connection_tunnel::TunnelJumpConfig { + host: "explicit-jump.internal".to_string(), + port: 2222, + username: "ops".to_string(), + auth_type: "password".to_string(), + password: Some("explicit-secret".to_string()), + private_key_path: None, + private_key_content: None, + private_key_passphrase: None, + mode: TunnelJumpMode::ProxyJump, + bastion_asset: None, + bastion_account: None, + }); + + // 显式配置优先:隧道自己配了 jump 时不被引用连接覆盖。 + one_core::storage::models::inherit_tunnel_jump_and_proxy(&mut tunnel, ¶ms); + let jump = tunnel.jump.as_ref().expect("explicit jump should remain"); + assert_eq!("explicit-jump.internal", jump.host); + assert_eq!("ops", jump.username); +} + +#[test] +fn redis_apply_referenced_tunnel_inherits_jump() { + let ssh = referenced_ssh_with_jump(); + let mut redis = RedisParams { + host: "redis.internal".to_string(), + port: 6379, + password: None, + username: None, + db_index: 0, + mode: Default::default(), + use_tls: false, + connect_timeout: Some(10), + sentinel: None, + cluster: None, + ssh_tunnel: Some(SshTunnelConfig { + enabled: true, + connection_id: Some(42), + ..Default::default() + }), + credential_reference: None, + }; + + redis + .apply_referenced_ssh_tunnel(&ssh) + .expect("referenced ssh connection should be applied"); + + let tunnel = redis.ssh_tunnel.as_ref().expect("tunnel should remain"); + assert_eq!( + "jump.example.com", + tunnel + .jump + .as_ref() + .expect("jump should be inherited into redis tunnel") + .host + ); +} + +#[test] +fn tunnel_jump_serializes_backward_compatibly() { + // 旧数据没有 jump 字段,必须能无损解析。 + let legacy_json = serde_json::json!({ + "enabled": true, + "host": "bastion.internal", + "port": 22, + "username": "deploy", + "auth_type": "password", + }); + let tunnel: SshTunnelConfig = + serde_json::from_value(legacy_json).expect("legacy tunnel json should parse"); + assert!(tunnel.jump.is_none()); + + // 新数据带上 jump 后 round-trip 保持。 + let ssh = referenced_ssh_with_jump(); + let params = ssh.to_ssh_params().unwrap(); + let mut tunnel = SshTunnelConfig::default(); + one_core::storage::models::inherit_tunnel_jump_and_proxy(&mut tunnel, ¶ms); + let json = serde_json::to_value(&tunnel).expect("tunnel should serialize"); + let parsed: SshTunnelConfig = + serde_json::from_value(json).expect("tunnel should round-trip"); + assert!(parsed.jump.is_some()); +} + diff --git a/crates/db/src/ssh_tunnel.rs b/crates/db/src/ssh_tunnel.rs index 3ce76f228..e4465b997 100644 --- a/crates/db/src/ssh_tunnel.rs +++ b/crates/db/src/ssh_tunnel.rs @@ -103,9 +103,18 @@ fn tunnel_config_from_db_config(config: &DbConnectionConfig) -> Option(SSH_TIMEOUT), + jump: optional_jump_param(config), + proxy: None, }) } +/// extra_params 里的 `ssh_jump_config`(JSON 序列化的 TunnelJumpConfig)。 +/// 由 `apply_referenced_ssh_tunnel` 在引用 SSH 连接时写入。 +fn optional_jump_param(config: &DbConnectionConfig) -> Option { + let encoded = optional_string_param(config, "ssh_jump_config")?; + serde_json::from_str(&encoded).ok() +} + fn string_param(config: &DbConnectionConfig, key: &str) -> String { config .get_param(key) diff --git a/crates/domain_api/src/identity.rs b/crates/domain_api/src/identity.rs index 2888096f2..e7b78d361 100644 --- a/crates/domain_api/src/identity.rs +++ b/crates/domain_api/src/identity.rs @@ -19,6 +19,8 @@ pub struct AppIdentity { pub mcp_legacy_app_name: Option<&'static str>, pub mcp_update_channel: &'static str, pub file_associations: &'static [&'static str], + /// 由本产品接管的 URL scheme(`jms://` 之类),只有声明了才会注册。 + pub url_schemes: &'static [&'static str], } impl AppIdentity { @@ -39,6 +41,9 @@ impl AppIdentity { mcp_legacy_app_name: Some("onetcli"), mcp_update_channel: "stable", file_associations: &["db", "duckdb", "md", "cast"], + // `jms://` 是产品私有 scheme;`ssh://`/`sftp://` 需要用户在设置里启用后 + // 才会真正写入系统关联(见 AppSettings::enabled_deeplink_schemes)。 + url_schemes: &["jms", "ssh", "sftp"], }; pub const SHELL: Self = Self { @@ -57,6 +62,7 @@ impl AppIdentity { mcp_legacy_app_name: None, mcp_update_channel: "shell", file_associations: &[], + url_schemes: &[], }; pub const DATA: Self = Self { @@ -75,6 +81,7 @@ impl AppIdentity { mcp_legacy_app_name: None, mcp_update_channel: "data", file_associations: &[], + url_schemes: &[], }; } diff --git a/crates/extension-runtime/src/catalog.rs b/crates/extension-runtime/src/catalog.rs index aff9ea07d..4e29aa027 100644 --- a/crates/extension-runtime/src/catalog.rs +++ b/crates/extension-runtime/src/catalog.rs @@ -182,19 +182,28 @@ impl ExtensionRuntimeCatalog { /// 工具箱聚合的独立 app,按 title 排序。 /// - /// 有非终端连接的扩展从工具箱排除:它是从连接打开的,工具箱打开只会 - /// 停在「请先打开一条连接」的空态。没有连接的 app(如 dev-tools)才 - /// 作为独立工具出现。 + /// 依赖连接的 app 从工具箱排除,它们应由连接或侧栏打开: + /// - 有非终端连接:从连接打开,工具箱打开只会停在「请先打开一条连接」的空态; + /// - 贡献了 panels:面板挂在终端 / 数据库侧栏里,页面依赖当前连接上下文 + /// (活动会话、选中的库表),同样只有连接内才有意义。 + /// + /// 没有连接、也没有面板的 app(如 dev-tools)才作为独立工具出现。 pub fn toolbox_apps(&self) -> Vec<&RegisteredShellAppContribution> { let connection_extensions: HashSet<&str> = self .resource_connections() .filter(|conn| conn.terminal.is_none()) .map(|conn| conn.extension_id.as_str()) .collect(); + let panel_extensions: HashSet<&str> = self + .panels + .iter() + .map(|panel| panel.extension_id.as_str()) + .collect(); let mut tools: Vec<_> = self .shell_apps .values() .filter(|app| !connection_extensions.contains(app.extension_id.as_str())) + .filter(|app| !panel_extensions.contains(app.extension_id.as_str())) .collect(); tools.sort_by(|a, b| a.title.cmp(&b.title)); tools diff --git a/crates/extension-runtime/src/extension/manifest/contributes/shell.rs b/crates/extension-runtime/src/extension/manifest/contributes/shell.rs index 7fdc46760..2497abf3e 100644 --- a/crates/extension-runtime/src/extension/manifest/contributes/shell.rs +++ b/crates/extension-runtime/src/extension/manifest/contributes/shell.rs @@ -148,7 +148,7 @@ pub struct ShellAppContrib { pub backends: BTreeMap, #[serde(default)] pub modules: Vec, - /// 工具箱卡片分组(没有连接的 app 才进工具箱)。 + /// 工具箱卡片分组(无连接、无面板的 app 才进工具箱)。 #[serde(default, skip_serializing_if = "Option::is_none")] pub category: Option, #[serde(default, skip_serializing_if = "Option::is_none")] diff --git a/crates/extension-runtime/src/extension_runtime_contract_tests.rs b/crates/extension-runtime/src/extension_runtime_contract_tests.rs index 96ce703af..f23b23277 100644 --- a/crates/extension-runtime/src/extension_runtime_contract_tests.rs +++ b/crates/extension-runtime/src/extension_runtime_contract_tests.rs @@ -1195,3 +1195,41 @@ fn catalog_toolbox_lists_apps_without_connections() { "有连接的 app 不应重复进工具箱: {ids:?}" ); } + +#[test] +fn catalog_toolbox_excludes_apps_with_sidebar_panels() { + // 侧栏面板只存在于终端 / 数据库连接里,页面依赖当前连接上下文(活动终端 + // 会话、选中的库表)。工具箱是无连接入口,打开只会停在空态,因此带面板的 + // app 不进工具箱;没有面板的独立 app 照旧列出。 + use crate::extension::manifest::PanelContrib; + + let mut panel_app = shell_manifest(); + panel_app.contributes.shell_app = Some(shell_app("ui/panel.js")); + panel_app.contributes.panels.push(PanelContrib { + id: "desk".to_string(), + title: None, + icon: None, + anchor: "terminal-sidebar".to_string(), + order: 0, + when: None, + }); + + let mut standalone = shell_manifest(); + standalone.id = "com.example.standalone".to_string(); + standalone.contributes.shell_app = Some(shell_app("ui/standalone.js")); + + let catalog = ExtensionRuntimeCatalog::from_manifests(vec![panel_app, standalone]).unwrap(); + let ids: Vec<&str> = catalog + .toolbox_apps() + .iter() + .map(|app| app.extension_id.as_str()) + .collect(); + assert!( + !ids.contains(&"com.example.tools"), + "带侧栏面板的 app 依赖终端 / 数据库连接,不应进工具箱: {ids:?}" + ); + assert!( + ids.contains(&"com.example.standalone"), + "无面板的独立 app 仍应进工具箱: {ids:?}" + ); +} diff --git a/crates/extension-runtime/src/types/shell.rs b/crates/extension-runtime/src/types/shell.rs index 5bc1ffc54..5aebb8330 100644 --- a/crates/extension-runtime/src/types/shell.rs +++ b/crates/extension-runtime/src/types/shell.rs @@ -18,7 +18,7 @@ pub struct RegisteredShellAppContribution { pub icon_path: Option, pub extension_root: PathBuf, pub entry_path: PathBuf, - /// 工具箱卡片分类(只有没有连接的 app 才进工具箱)。 + /// 工具箱卡片分类(只有无连接、无面板的 app 才进工具箱)。 pub category: Option, pub keywords: Vec, pub backends: BTreeMap, diff --git a/crates/ftp/src/listing.rs b/crates/ftp/src/listing.rs index 10bbed251..db2b82226 100644 --- a/crates/ftp/src/listing.rs +++ b/crates/ftp/src/listing.rs @@ -27,7 +27,8 @@ pub(super) enum ListLine { /// LIST 返回的名称只接受单层名称。 /// -/// 拒绝:空名、`.`、`..`、包含 `/`、`\`、NUL,以及平台路径前缀。 +/// 拒绝:空名、`.`、`..`、包含 `/`、`\`、NUL。判断与客户端平台无关: +/// Linux 上的 `c:` 是合法文件名,列举阶段照常显示。 pub(super) fn is_valid_remote_name(name: &str) -> bool { sftp::is_valid_remote_entry_name(name) } @@ -289,6 +290,9 @@ mod tests { assert!(is_valid_remote_name("...")); assert!(is_valid_remote_name("a..b.txt")); assert!(is_valid_remote_name("中文.txt")); + // Linux 服务器上的盘符形态名字是合法文件名,Windows 客户端也要能列出来。 + assert!(is_valid_remote_name("c:")); + assert!(is_valid_remote_name("c:file.txt")); } #[test] diff --git a/crates/ftp/src/transfer.rs b/crates/ftp/src/transfer.rs index 4787dc569..b955a6b8e 100644 --- a/crates/ftp/src/transfer.rs +++ b/crates/ftp/src/transfer.rs @@ -23,8 +23,6 @@ use std::time::{Duration, SystemTime}; use suppaftp::FtpError; use tokio::io::{AsyncReadExt, AsyncWriteExt}; -use crate::listing::is_valid_remote_name; - /// 数据连接读取分块大小。 const CHUNK_SIZE: usize = 256 * 1024; @@ -87,17 +85,18 @@ pub(super) fn temp_path(path: &str) -> String { ) } -/// 校验远端相对路径:每个分量都必须是"单层名称"。 +/// 校验远端相对路径:每个分量都必须能安全拼成本地路径。 /// /// LIST 名称来自可能被攻陷的服务端;拒绝 `..`、`.`、空分量、 -/// 包含 `\` 或 NUL 的分量,防止拼接出逃逸目标目录的路径。 +/// 包含 `\` 或 NUL 的分量,以及 Windows 上会被当成盘符前缀的分量 +/// (`c:` 会让 `join` 丢掉基路径),防止拼接出逃逸目标目录的路径。 pub(super) fn validate_relative_path(relative: &str) -> Result> { let components: Vec<&str> = relative.split('/').collect(); if components.is_empty() { return Err(anyhow!("Refusing empty remote entry path")); } for component in &components { - if !is_valid_remote_name(component) { + if !sftp::is_valid_local_file_name(component) { return Err(anyhow!("Refusing unsafe remote entry name: {relative:?}")); } } @@ -1121,6 +1120,15 @@ mod tests { assert!(validate_relative_path(".").is_err()); } + #[test] + fn validate_relative_path_follows_local_platform_rules() { + // `c:` 是 Linux 上的合法文件名;只有 Windows 会把 `join` 解析成盘符路径。 + #[cfg(not(windows))] + assert!(validate_relative_path("c:").is_ok()); + #[cfg(windows)] + assert!(validate_relative_path("c:").is_err()); + } + #[test] fn ftp_status_code_parses_server_replies_only() { let reply = FtpError::UnexpectedResponse(suppaftp::types::Response::new( diff --git a/crates/mongodb_view/src/mongo_form_window.rs b/crates/mongodb_view/src/mongo_form_window.rs index dd19f4767..30b437f6c 100644 --- a/crates/mongodb_view/src/mongo_form_window.rs +++ b/crates/mongodb_view/src/mongo_form_window.rs @@ -549,6 +549,8 @@ impl MongoFormWindow { target_host: value.target_host, target_port: value.target_port, timeout: value.timeout, + jump: None, + proxy: None, }) } diff --git a/crates/navop_app/locales/main.yml b/crates/navop_app/locales/main.yml index 6d44914fb..4477f32cd 100644 --- a/crates/navop_app/locales/main.yml +++ b/crates/navop_app/locales/main.yml @@ -62,6 +62,18 @@ Common: en: "Unable to open file: %{error}" zh-CN: "无法打开文件:%{error}" zh-HK: "無法開啟檔案:%{error}" + jump_deeplink_failed: + en: "Unable to open the JumpServer link: %{error}" + zh-CN: "无法打开 JumpServer 链接:%{error}" + zh-HK: "無法開啟 JumpServer 連結:%{error}" + connection_deeplink_failed: + en: "Unable to open the connection link: %{error}" + zh-CN: "无法打开连接链接:%{error}" + zh-HK: "無法開啟連線連結:%{error}" + deeplink_scheme_disabled: + en: "%{scheme}:// links are disabled. Enable them in Settings → General → Link protocols." + zh-CN: "%{scheme}:// 链接未启用,可在「设置 → 通用 → 链接协议」中开启。" + zh-HK: "%{scheme}:// 連結未啟用,可在「設定 → 一般 → 連結協定」中開啟。" storage_unavailable: en: Application storage is unavailable zh-CN: 应用存储不可用 @@ -168,6 +180,42 @@ Home: en: "Recent Connections" zh-CN: "最近连接" zh-HK: "最近連線" + host_metrics_cpu: + en: "CPU %{percent}%" + zh-CN: "CPU %{percent}%" + zh-HK: "CPU %{percent}%" + host_metrics_memory: + en: "Memory %{percent}%" + zh-CN: "内存 %{percent}%" + zh-HK: "記憶體 %{percent}%" + host_metrics_disk: + en: "Disk %{percent}%" + zh-CN: "磁盘 %{percent}%" + zh-HK: "磁碟 %{percent}%" + host_metrics_cpu_label: + en: CPU + zh-CN: CPU + zh-HK: CPU + host_metrics_memory_label: + en: Memory + zh-CN: 内存 + zh-HK: 記憶體 + host_metrics_disk_label: + en: Disk + zh-CN: 磁盘 + zh-HK: 磁碟 + host_metrics_cores: + en: "%{count} cores" + zh-CN: "%{count} 核" + zh-HK: "%{count} 核" + host_metrics_collecting: + en: "Collecting resource info…" + zh-CN: "正在采集资源信息…" + zh-HK: "正在採集資源資訊…" + host_metrics_unavailable: + en: "Resource info unavailable" + zh-CN: "资源信息不可用" + zh-HK: "資源資訊不可用" unassigned_connections: en: "Unassigned" zh-CN: "未分组" @@ -2750,6 +2798,33 @@ Settings: zh-CN: 通用 zh-HK: 通用 + # 链接协议:是否接管 ssh:// / sftp://(默认关闭) + Deeplinks: + group_title: + en: Link protocols + zh-CN: 链接协议 + zh-HK: 連結協定 + group_description: + en: Let Navop handle ssh:// and sftp:// links from browsers and documents. These schemes usually belong to the terminal or file manager, so they stay off until enabled here. + zh-CN: 允许 Navop 处理来自浏览器和文档的 ssh:// 与 sftp:// 链接。这些协议通常由终端或文件管理器接管,因此在勾选前保持关闭。 + zh-HK: 允許 Navop 處理來自瀏覽器與文件的 ssh:// 與 sftp:// 連結。這些協定通常由終端機或檔案管理器接管,因此在勾選前保持關閉。 + ssh: + en: Handle ssh:// links + zh-CN: 接管 ssh:// 链接 + zh-HK: 接管 ssh:// 連結 + ssh_desc: + en: Open an SSH terminal for the host in the link. Credentials are used for this session only and never saved. + zh-CN: 为链接中的主机打开 SSH 终端。凭据只用于本次会话,不会保存。 + zh-HK: 為連結中的主機開啟 SSH 終端機。憑證只用於本次工作階段,不會儲存。 + sftp: + en: Handle sftp:// links + zh-CN: 接管 sftp:// 链接 + zh-HK: 接管 sftp:// 連結 + sftp_desc: + en: Open the SFTP pane at the directory in the link. Credentials are used for this session only and never saved. + zh-CN: 在链接指定的目录打开 SFTP 面板。凭据只用于本次会话,不会保存。 + zh-HK: 在連結指定的目錄開啟 SFTP 面板。憑證只用於本次工作階段,不會儲存。 + # 语言设置 Language: group_title: @@ -2871,9 +2946,9 @@ Settings: zh-CN: 显示远端资源占用 zh-HK: 顯示遠端資源佔用 show_host_metrics_desc: - en: Collect CPU, memory and disk usage of SSH servers with a background session and show it on connection cards without opening a terminal. - zh-CN: 用后台 SSH 会话采集服务器的 CPU、内存与磁盘占用,无需打开终端即可在连接卡片上看到 - zh-HK: 用後台 SSH 會話採集伺服器的 CPU、記憶體與磁碟佔用,無需開啟終端即可在連線卡片上看到 + en: Collect the operating system, CPU cores, memory and disk capacity and usage of SSH servers with a background session, then show them across connection cards, lists and trees without opening a terminal. + zh-CN: 用后台 SSH 会话采集服务器的系统、CPU 核数、内存与磁盘容量及占用,无需打开终端即可在连接卡片、列表和树中看到 + zh-HK: 用後台 SSH 會話採集伺服器的系統、CPU 核心數、記憶體與磁碟容量及佔用,無需開啟終端即可在連線卡片、列表和樹狀檢視中看到 home_layout: en: Home Connection Layout zh-CN: 主页连接布局 diff --git a/crates/navop_app/src/connection_deeplink.rs b/crates/navop_app/src/connection_deeplink.rs new file mode 100644 index 000000000..c34c6c952 --- /dev/null +++ b/crates/navop_app/src/connection_deeplink.rs @@ -0,0 +1,425 @@ +//! 通用连接深链接:`ssh://` 与 `sftp://`。 +//! +//! 链接来自浏览器、文档或其它应用,例如: +//! +//! ```text +//! ssh://alice@example.com:2222 +//! sftp://alice@example.com/var/log +//! ``` +//! +//! 解析结果只会变成一条**临时连接**:不写入连接仓库、不参与云同步、不保存 +//! 密码;URL 里的密码直接用于本次认证,但不会出现在日志、通知或错误提示里。 +//! +//! 这类 scheme 会与系统里既有的终端、文件管理器争抢默认关联,所以默认关闭, +//! 只有用户在设置里显式启用后才会注册(见 `AppSettings::enabled_deeplink_schemes`)。 + +use anyhow::{Context as _, Result, bail}; +use gpui::{App, Window}; +use gpui_component::{WindowExt as _, notification::Notification}; +use one_core::settings::AppSettings; +use one_core::storage::{ + PreferredOpenMode, SshAuthMethod, SshParams, StoredConnection, StoredTerminalEncoding, + StoredTerminalType, +}; +use one_core::tab_container::TabOpenMode; +use percent_encoding::percent_decode_str; +use rust_i18n::t; +use url::{Host, Url}; + +use crate::navop_app::GlobalHomePage; + +/// 除 `jms://` 外,Navop 能直接接管的连接类 scheme。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ConnectionScheme { + Ssh, + Sftp, +} + +impl ConnectionScheme { + pub(crate) fn parse(scheme: &str) -> Option { + match scheme.to_ascii_lowercase().as_str() { + "ssh" => Some(Self::Ssh), + "sftp" => Some(Self::Sftp), + _ => None, + } + } + + pub(crate) fn as_str(self) -> &'static str { + match self { + Self::Ssh => "ssh", + Self::Sftp => "sftp", + } + } + + fn default_port(self) -> u16 { + 22 + } +} + +/// 识别 `ssh://` / `sftp://` 链接;其它内容返回 `None`。 +pub(crate) fn scheme_of(raw: &str) -> Option { + let trimmed = raw.trim(); + let (scheme, rest) = trimmed.split_once("://")?; + if rest.is_empty() { + return None; + } + ConnectionScheme::parse(scheme) +} + +/// 解析后的连接意图(不含需要落库的状态)。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct ConnectionLink { + pub scheme: ConnectionScheme, + pub host: String, + pub port: u16, + pub username: String, + pub password: Option, + /// 仅 `sftp://` 使用;已规范化,拒绝 `..` 之类的越界路径。 + pub directory: Option, +} + +/// 把深链接转成一条不落库的临时连接。 +pub(crate) fn connection_from_link(link: &ConnectionLink) -> StoredConnection { + let params = SshParams { + host: link.host.clone(), + port: link.port, + username: link.username.clone(), + auth_method: SshAuthMethod::Password { + password: link.password.clone().unwrap_or_default(), + }, + sftp_account: None, + sftp_default_directory: link.directory.clone(), + credential_reference: None, + prompt_username: Some(link.username.is_empty()), + prompt_password: Some(link.password.is_none()), + // 链接里带密码时认证方式固定为 password,避免密码错误后再弹键盘交互; + // 不带密码时交给宿主按需提示。 + keyboard_interactive: link.password.as_ref().map(|_| false), + otp: None, + terminal_encoding: StoredTerminalEncoding::default(), + terminal_type: StoredTerminalType::default(), + account_expect: Default::default(), + connect_timeout: None, + keepalive_interval: None, + keepalive_max: None, + default_directory: None, + init_script: None, + disable_shell_integration: None, + x11_forwarding: None, + allow_legacy_algorithms: None, + forward_agent: None, + agent_forward_key: None, + jump_server: None, + disabled_jump_server: None, + proxy: None, + os_id: None, + icon: None, + icon_file_path: None, + remote_file: None, + }; + let mut connection = StoredConnection::new_ssh(String::new(), params, None); + // 临时会话不参与云同步;id 为 None,打开后自动成为一次性标签页。 + connection.sync_enabled = false; + if link.scheme == ConnectionScheme::Sftp { + connection.preferred_open_mode = Some(PreferredOpenMode::DualPane); + } + connection +} + +/// 解析 `ssh://user[:password]@host[:port]` 与 +/// `sftp://user[:password]@host[:port][/path]`。 +/// +/// 错误信息只描述问题,不回显原始 URL(链接里可能带密码)。 +pub(crate) fn parse_connection_deeplink( + raw: &str, + scheme: ConnectionScheme, +) -> Result { + let url = Url::parse(raw.trim()).context("链接格式不合法")?; + if url.scheme() != scheme.as_str() { + bail!("链接协议与预期不一致"); + } + let host = match url.host() { + Some(Host::Ipv4(address)) => address.to_string(), + Some(Host::Ipv6(address)) => address.to_string(), + Some(Host::Domain(domain)) => domain.to_string(), + None => bail!("链接缺少主机名"), + }; + if host.trim().is_empty() { + bail!("链接缺少主机名"); + } + let port = match url.port() { + Some(0) => bail!("端口不合法"), + Some(port) => port, + None => scheme.default_port(), + }; + + let username = decode(url.username()).trim().to_string(); + let password = url + .password() + .map(decode) + .map(|password| password.to_string()) + .filter(|password| !password.is_empty()); + + let directory = match scheme { + ConnectionScheme::Sftp => sanitize_directory(url.path())?, + ConnectionScheme::Ssh => None, + }; + + Ok(ConnectionLink { + scheme, + host, + port, + username, + password, + directory, + }) +} + +fn decode(raw: &str) -> String { + percent_decode_str(raw).decode_utf8_lossy().to_string() +} + +/// `sftp://host/var/log` 的 path 只能作为初始目录;拒绝任何 `..` 越界。 +fn sanitize_directory(path: &str) -> Result> { + if path.is_empty() || path == "/" { + return Ok(None); + } + let decoded = decode(path); + let mut segments = Vec::new(); + for segment in decoded.split('/') { + match segment { + "" | "." => continue, + ".." => bail!("路径不合法"), + other => segments.push(other), + } + } + if segments.is_empty() { + return Ok(None); + } + Ok(Some(format!("/{}", segments.join("/")))) +} + +struct ConnectionDeepLinkNotification; + +/// 打开 `ssh://` / `sftp://` 深链接;失败只提示「无法打开」,不回显链接内容。 +pub(crate) fn open_connection_deeplink(raw: &str, window: &mut Window, cx: &mut App) { + let Some(scheme) = scheme_of(raw) else { + return; + }; + if !AppSettings::global(cx).deeplink_scheme_enabled(scheme.as_str()) { + window.push_notification( + Notification::warning( + t!("Common.deeplink_scheme_disabled", scheme = scheme.as_str()).to_string(), + ) + .id::() + .autohide(true), + cx, + ); + return; + } + if let Err(error) = try_open_connection_deeplink(raw, scheme, window, cx) { + tracing::warn!(error = %error, scheme = scheme.as_str(), "failed to open deep link"); + window.push_notification( + Notification::error( + t!( + "Common.connection_deeplink_failed", + error = format!("{error:#}") + ) + .to_string(), + ) + .id::() + .autohide(true), + cx, + ); + } +} + +fn try_open_connection_deeplink( + raw: &str, + scheme: ConnectionScheme, + window: &mut Window, + cx: &mut App, +) -> Result<()> { + let link = parse_connection_deeplink(raw, scheme)?; + let connection = connection_from_link(&link); + tracing::info!( + host = %link.host, + port = link.port, + scheme = scheme.as_str(), + "opening connection deep link" + ); + let home = cx + .try_global::() + .map(|global| global.home_page.clone()) + .context("home page is not ready")?; + window.activate_window(); + window.defer(cx, move |window, cx| { + home.update(cx, |home, cx| { + if !app_kit::registry().open_connection( + &connection, + TabOpenMode::Activate, + home, + window, + cx, + ) { + window.push_notification( + Notification::warning( + t!( + "Common.connection_type_unsupported", + name = connection.name.clone() + ) + .to_string(), + ) + .autohide(true), + cx, + ); + } + }); + }); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(raw: &str) -> Result { + let scheme = scheme_of(raw).expect("应识别 scheme"); + parse_connection_deeplink(raw, scheme) + } + + #[test] + fn recognizes_ssh_and_sftp_links_case_insensitively() { + assert_eq!(Some(ConnectionScheme::Ssh), scheme_of("ssh://host")); + assert_eq!(Some(ConnectionScheme::Sftp), scheme_of("SFTP://host")); + assert_eq!(Some(ConnectionScheme::Ssh), scheme_of(" Ssh://host ")); + assert_eq!(None, scheme_of("jms://abc")); + assert_eq!(None, scheme_of("http://host")); + assert_eq!(None, scheme_of("ssh://")); + assert_eq!(None, scheme_of("")); + } + + #[test] + fn parses_ssh_userinfo_and_default_port() { + let link = parse("ssh://alice@example.com").expect("应解析成功"); + assert_eq!(link.scheme, ConnectionScheme::Ssh); + assert_eq!(link.host, "example.com"); + assert_eq!(link.port, 22); + assert_eq!(link.username, "alice"); + assert_eq!(link.password, None); + assert_eq!(link.directory, None); + } + + #[test] + fn parses_explicit_port_and_percent_decoded_password() { + let link = parse("ssh://alice:p%40ss%20word@example.com:2222").expect("应解析成功"); + assert_eq!(link.port, 2222); + assert_eq!(link.password.as_deref(), Some("p@ss word")); + } + + #[test] + fn sftp_uses_path_as_initial_directory() { + let link = parse("sftp://alice@example.com:22/var/log").expect("应解析成功"); + assert_eq!(link.directory.as_deref(), Some("/var/log")); + + let root = parse("sftp://example.com/").expect("应解析成功"); + assert_eq!(root.directory, None); + } + + #[test] + fn sftp_directory_traversal_is_normalized_before_use() { + // url crate 在解析阶段就把 `..` 与 `%2e%2e` 规范化掉,不会把越界路径交给 + // 会话;解析结果至少不会含 `..` 段。 + for raw in [ + "sftp://example.com/var/../etc", + "sftp://example.com/var/%2e%2e/etc", + ] { + let directory = parse(raw) + .expect("规范化后的路径仍可解析") + .directory + .expect("应得到初始目录"); + assert!(!directory.split('/').any(|segment| segment == "..")); + assert_eq!(directory, "/etc"); + } + } + + #[test] + fn rejects_missing_host_and_mismatched_scheme() { + assert!(parse_connection_deeplink("ssh:///var/log", ConnectionScheme::Ssh).is_err()); + assert!(parse_connection_deeplink("sftp://example.com", ConnectionScheme::Ssh).is_err()); + } + + #[test] + fn error_messages_do_not_echo_credentials() { + let error = parse("ssh://alice:secret@").expect_err("应拒绝"); + let rendered = format!("{error:#}"); + assert!(!rendered.contains("secret")); + } + + #[test] + fn builds_ephemeral_connection_with_prompt_for_missing_credentials() { + let link = parse("ssh://alice@example.com:2222").expect("应解析成功"); + let connection = connection_from_link(&link); + assert_eq!(connection.id, None); + assert!(!connection.sync_enabled); + assert_eq!( + connection.connection_type, + one_core::storage::ConnectionType::SshSftp + ); + assert_eq!(connection.name, "alice@example.com:2222"); + + let params: SshParams = + serde_json::from_str(&connection.params).expect("params 应是合法 SshParams"); + assert_eq!(params.host, "example.com"); + assert_eq!(params.port, 2222); + assert_eq!(params.username, "alice"); + assert_eq!(params.prompt_password, Some(true)); + assert!(params.prompts_for_password()); + assert!(!params.prompts_for_username()); + assert_eq!(params.keyboard_interactive, None); + } + + #[test] + fn password_links_disable_interactive_fallback() { + let link = parse("ssh://alice:secret@example.com").expect("应解析成功"); + let connection = connection_from_link(&link); + let params: SshParams = + serde_json::from_str(&connection.params).expect("params 应是合法 SshParams"); + assert_eq!(params.prompt_password, Some(false)); + assert_eq!(params.keyboard_interactive, Some(false)); + match ¶ms.auth_method { + SshAuthMethod::Password { password } => assert_eq!(password, "secret"), + other => panic!("应使用密码认证: {other:?}"), + } + } + + #[test] + fn anonymous_links_prompt_for_username() { + let link = parse("ssh://example.com").expect("应解析成功"); + let connection = connection_from_link(&link); + let params: SshParams = + serde_json::from_str(&connection.params).expect("params 应是合法 SshParams"); + assert!(params.prompts_for_username()); + assert!(connection.name.starts_with("example.com")); + } + + #[test] + fn sftp_links_open_dual_pane_with_directory() { + let link = parse("sftp://alice@example.com/var/log").expect("应解析成功"); + let connection = connection_from_link(&link); + assert_eq!( + connection.preferred_open_mode, + Some(PreferredOpenMode::DualPane) + ); + let params: SshParams = + serde_json::from_str(&connection.params).expect("params 应是合法 SshParams"); + assert_eq!(params.sftp_default_directory.as_deref(), Some("/var/log")); + } + + #[test] + fn parses_ipv6_hosts() { + let link = parse("ssh://alice@[::1]:2222").expect("应解析成功"); + assert_eq!(link.host, "::1"); + assert_eq!(link.port, 2222); + } +} diff --git a/crates/navop_app/src/file_association.rs b/crates/navop_app/src/file_association.rs index 93d8632d0..0232c6c3a 100644 --- a/crates/navop_app/src/file_association.rs +++ b/crates/navop_app/src/file_association.rs @@ -1,6 +1,16 @@ -//! 文件关联注册。 +//! 文件关联与 URL scheme 注册。 //! //! 实现已迁入 [`app_kit::file_association`]:接管哪些扩展名由各产品的 -//! `AppIdentity::file_associations` 决定。这里只做转发,调用点保持原样。 +//! `AppIdentity::file_associations` 决定。URL scheme 还要叠加用户开关: +//! `jms://` 始终注册,`ssh://`/`sftp://` 等通用 scheme 只有用户启用后才写进系统。 -pub use app_kit::file_association::*; +/// 按当前设置重新注册关联(设置里切换协议开关后调用)。 +pub(crate) fn schedule_registration(cx: &mut gpui::App) { + if !one_core::app_paths::is_installed() { + // 开发态/便携版不写系统关联,避免改掉本机正常的链接处理程序。 + tracing::debug!("application is not installed; skipping URL scheme registration"); + return; + } + let schemes = one_core::settings::AppSettings::global(cx).enabled_deeplink_schemes(); + app_kit::file_association::schedule_registration_with_schemes(cx, schemes); +} diff --git a/crates/navop_app/src/file_open.rs b/crates/navop_app/src/file_open.rs index d01cf2117..2cc9aef3b 100644 --- a/crates/navop_app/src/file_open.rs +++ b/crates/navop_app/src/file_open.rs @@ -19,6 +19,29 @@ pub(crate) enum FileOpenInput { Url(String), } +/// 把启动参数(ARGV 里的路径或 URL)转成 `FileOpenInput`。 +/// +/// Windows/macOS 传本地路径;Linux 桌面文件的 `%U` 会把 URL 传进来,既可能是 +/// `file://` 本地文件,也可能是 `jms://`、`ssh://`、`sftp://` 深链接。 +pub(crate) fn input_from_startup_argument(argument: PathBuf) -> FileOpenInput { + let Some(raw) = argument.to_str() else { + return FileOpenInput::Path(argument); + }; + if crate::jump_deeplink::is_jump_deeplink(raw) + || crate::connection_deeplink::scheme_of(raw).is_some() + { + return FileOpenInput::Url(raw.to_string()); + } + if raw.len() > "file://".len() + && raw.is_char_boundary("file://".len()) + && raw[.."file://".len()].eq_ignore_ascii_case("file://") + && let Ok(path) = local_path_from_file_url(raw) + { + return FileOpenInput::Path(path); + } + FileOpenInput::Path(argument) +} + #[derive(Debug, Clone, PartialEq, Eq)] enum OpenFileKind { Database(DatabaseType), @@ -71,6 +94,18 @@ fn show_file_open_error(error: &anyhow::Error, window: &mut Window, cx: &mut App } fn try_open_input(input: FileOpenInput, window: &mut Window, cx: &mut App) -> Result<()> { + if let FileOpenInput::Url(url) = &input { + if crate::jump_deeplink::is_jump_deeplink(url) { + // JumpServer 深链接不指向本地文件,直接建立临时 SSH 会话。 + crate::jump_deeplink::open_jump_deeplink(url, window, cx); + return Ok(()); + } + if crate::connection_deeplink::scheme_of(url).is_some() { + // ssh:// / sftp:// 同理会话化,是否允许由设置决定。 + crate::connection_deeplink::open_connection_deeplink(url, window, cx); + return Ok(()); + } + } let path = match &input { FileOpenInput::Path(path) => Some(path.clone()), FileOpenInput::Url(url) => local_path_from_file_url(url).ok(), @@ -358,6 +393,46 @@ mod tests { assert_eq!(None, classify_supported_path(Path::new("script.sql"))); } + #[test] + fn startup_arguments_route_jms_urls_and_file_urls() { + let link = "jms://eyJwcm90b2NvbCI6InNzaCJ9"; + match input_from_startup_argument(PathBuf::from(link)) { + FileOpenInput::Url(url) => assert_eq!(url, link), + other => panic!("jms:// 应识别为 URL: {other:?}"), + } + // 大小写不敏感 + match input_from_startup_argument(PathBuf::from("JMS://abc")) { + FileOpenInput::Url(url) => assert_eq!(url, "JMS://abc"), + other => panic!("JMS:// 应识别为 URL: {other:?}"), + } + + // 通用连接链接同样走 URL 分支(是否放行由设置决定)。 + for link in ["ssh://alice@example.com:2222", "sftp://example.com/var/log"] { + match input_from_startup_argument(PathBuf::from(link)) { + FileOpenInput::Url(url) => assert_eq!(url, link), + other => panic!("{link} 应识别为 URL: {other:?}"), + } + } + // 其它 scheme 仍按路径处理,不误触发连接。 + match input_from_startup_argument(PathBuf::from("https://example.com")) { + FileOpenInput::Path(path) => assert_eq!(path, PathBuf::from("https://example.com")), + other => panic!("https:// 不应识别为连接链接: {other:?}"), + } + + let path = std::env::temp_dir().join("Navop notes").join("README.md"); + let url = url::Url::from_file_path(&path).unwrap().to_string(); + match input_from_startup_argument(PathBuf::from(url)) { + FileOpenInput::Path(decoded) => assert_eq!(decoded, path), + other => panic!("file:// 应解码成本地路径: {other:?}"), + } + + let plain = std::env::temp_dir().join("orders.db"); + match input_from_startup_argument(plain.clone()) { + FileOpenInput::Path(decoded) => assert_eq!(decoded, plain), + other => panic!("普通路径应原样保留: {other:?}"), + } + } + #[test] fn file_urls_are_decoded_to_local_paths() { let path = std::env::temp_dir().join("Navop notes").join("README.md"); diff --git a/crates/navop_app/src/home/connection_import_draft_conversion.rs b/crates/navop_app/src/home/connection_import_draft_conversion.rs index 8e4e66576..18022dee5 100644 --- a/crates/navop_app/src/home/connection_import_draft_conversion.rs +++ b/crates/navop_app/src/home/connection_import_draft_conversion.rs @@ -224,6 +224,8 @@ fn to_ssh_connection( username: jump.username.clone(), auth_method: imported_ssh_auth_method(&jump.auth_method)?, credential_reference: None, + mode: Default::default(), + bastion: None, }) }) .transpose()?, diff --git a/crates/navop_app/src/home_tab.rs b/crates/navop_app/src/home_tab.rs index 7eb045d39..319420d53 100644 --- a/crates/navop_app/src/home_tab.rs +++ b/crates/navop_app/src/home_tab.rs @@ -332,8 +332,41 @@ mod tests; #[cfg(not(feature = "shell"))] impl HomePage { - /// 没有 shell 能力时不采集远端资源,卡片上不显示这一行。 - pub(crate) fn host_metrics_summary(&self, _connection_id: Option) -> Option { + /// 没有 shell 能力时不采集远端资源,卡片和列表上不显示这一行。 + pub(crate) fn render_host_metrics_detail( + &self, + _connection: &StoredConnection, + _id_prefix: &str, + _cx: &App, + ) -> Option { + None + } + + /// 没有 shell 能力时卡片底部不显示资源状态带。 + pub(crate) fn render_host_metrics_card( + &self, + _connection: &StoredConnection, + _id_prefix: &str, + _cx: &App, + ) -> Option { + None + } + + /// 没有 shell 能力时树行也不显示资源进度条。 + pub(crate) fn render_host_metrics_compact( + &self, + _connection: &StoredConnection, + _id_prefix: &str, + _cx: &App, + ) -> Option { None } + + pub(crate) fn shows_host_metrics_strip( + &self, + _connection: &StoredConnection, + _cx: &App, + ) -> bool { + false + } } diff --git a/crates/navop_app/src/home_tab/connection_card.rs b/crates/navop_app/src/home_tab/connection_card.rs index e379f98e3..e0e45e5f1 100644 --- a/crates/navop_app/src/home_tab/connection_card.rs +++ b/crates/navop_app/src/home_tab/connection_card.rs @@ -33,6 +33,14 @@ impl HomePage { } else { connection_team_badge(conn.team_id.as_deref(), self.team_permissions.teams()) }; + let shows_host_metrics = self.shows_host_metrics_strip(&conn, cx); + let card_height = if shows_host_metrics { + 5.5 + } else if recent { + 3.625 + } else { + 4.5 + }; // 同一连接会同时出现在最近区与普通分组,元素 ID 按展示区命名空间区分(redesign §6.2)。 let card_id = if recent { "conn-card-recent" @@ -47,8 +55,8 @@ impl HomePage { .justify_center() .id(card_id.clone()) .w_full() - // 最近区更紧凑,靠留白与去重信息实现(redesign §6.1)。 - .h(gpui::rems(if recent { 3.625 } else { 4.5 })) + // 需要资源状态带时预留第二行;其他连接保持原紧凑高度。 + .h(gpui::rems(card_height)) .rounded(px(12.0)) .bg(cx.theme().background) .px_3() diff --git a/crates/navop_app/src/home_tab/connection_card_content.rs b/crates/navop_app/src/home_tab/connection_card_content.rs index 423070220..a73e12a3d 100644 --- a/crates/navop_app/src/home_tab/connection_card_content.rs +++ b/crates/navop_app/src/home_tab/connection_card_content.rs @@ -11,9 +11,10 @@ impl HomePage { let display_name = connection_display_name(conn); let name_tooltip: SharedString = display_name.clone().into(); let connection_info = card_connection_info(conn); - let host_metrics = self.host_metrics_summary(conn.id); + let host_metrics = + self.render_host_metrics_card(conn, &format!("{card_id}-host-metrics"), cx); - h_flex() + let header = h_flex() .items_center() .gap_2p5() .w_full() @@ -78,21 +79,15 @@ impl HomePage { }) .child(info), ) - }) - .when_some(host_metrics, |this, summary| { - this.child( - div() - .id(SharedString::from(format!("{card_id}-host-metrics"))) - .text_xs() - .text_color(cx.theme().muted_foreground) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .max_w_full() - .child(summary), - ) }), ) + .into_any_element(); + + v_flex() + .w_full() + .gap_2() + .child(header) + .when_some(host_metrics, |this, metrics| this.child(metrics)) .into_any_element() } } diff --git a/crates/navop_app/src/home_tab/connection_list.rs b/crates/navop_app/src/home_tab/connection_list.rs index e9dafc93d..caa181945 100644 --- a/crates/navop_app/src/home_tab/connection_list.rs +++ b/crates/navop_app/src/home_tab/connection_list.rs @@ -45,12 +45,14 @@ impl HomePage { "conn-list-item" }; let row_id = SharedString::from(format!("{row_id}-{}", conn_id.unwrap_or(0))); + let host_metrics = + self.render_host_metrics_detail(&conn, &format!("{row_id}-host-metrics"), cx); let row = h_flex() .id(row_id.clone()) .w_full() .px_3p5() - .py_2p5() + .py_2() .rounded(px(10.0)) .border_1() .border_color(cx.theme().border) @@ -202,15 +204,24 @@ impl HomePage { .child(actions), ) .child( - div() - .text_xs() - .text_color(cx.theme().muted_foreground) - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() + h_flex() .w_full() .min_w_0() - .child(self.connection_info_text(&conn)), + .flex_wrap() + .items_center() + .gap_2() + .child( + div() + .flex_shrink(1.0) + .min_w_0() + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child(self.connection_info_text(&conn)), + ) + .when_some(host_metrics, |this, metrics| this.child(metrics)), ), ); match conn_id { diff --git a/crates/navop_app/src/home_tab/host_metrics.rs b/crates/navop_app/src/home_tab/host_metrics.rs index 0d12b49cc..7a9fd3fc1 100644 --- a/crates/navop_app/src/home_tab/host_metrics.rs +++ b/crates/navop_app/src/home_tab/host_metrics.rs @@ -3,16 +3,30 @@ //! 用一次性的后台 SSH 会话采集 CPU、内存与磁盘占用,不打开终端页签; //! 结果按连接缓存,过期后再采集。任何失败都只记 debug 日志,不影响首页交互。 +use std::collections::{HashMap, HashSet}; use std::time::{Duration, Instant}; -use gpui::{AppContext, Context}; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + AnyElement, App, Context, Hsla, InteractiveElement, IntoElement, ParentElement, SharedString, + StatefulInteractiveElement, Styled, div, +}; +use gpui_component::{ + ActiveTheme, Sizable, Size, h_flex, progress::Progress, tooltip::Tooltip, v_flex, +}; +use one_core::gpui_tokio::Tokio; use one_core::settings::AppSettings; -use one_core::storage::models::ConnectionType; +use one_core::storage::{ + ConnectionRepository, ConnectionType, GlobalStorageState, StoredConnection, +}; +use rust_i18n::t; use super::HomePage; /// 同一连接资源快照的缓存时间。 const HOST_METRICS_TTL: Duration = Duration::from_secs(300); +/// 定时检查过期快照的间隔;实际采集仍受 [`HOST_METRICS_TTL`] 控制。 +const HOST_METRICS_REFRESH_INTERVAL: Duration = Duration::from_secs(60); /// 同时进行的后台采集上限:首页一次可能渲染几十个连接,不能同时拉起几十个 SSH 会话。 const HOST_METRICS_MAX_IN_FLIGHT: usize = 2; @@ -21,49 +35,91 @@ pub(crate) struct HostMetricsEntry { sampled_at: Instant, } +enum HostMetricsState { + Ready(terminal_view::HostResourceUsage), + Pending, + Unavailable, +} + #[derive(Default)] pub(crate) struct HostMetricsCache { - entries: std::collections::HashMap, - in_flight: std::collections::HashSet, + entries: HashMap, + in_flight: HashSet, + /// 最后一次尝试时间,包含凭据解析或连接失败,避免失败连接每分钟重试。 + last_attempt: HashMap, } impl HomePage { + /// 在首页生命周期内周期检查过期快照;关闭设置时也会在这里恢复采集。 + pub(crate) fn start_host_metrics_refresh(&self, cx: &mut Context) { + cx.spawn(async move |this, cx| { + loop { + cx.background_executor() + .timer(HOST_METRICS_REFRESH_INTERVAL) + .await; + if this + .update(cx, |this, cx| this.refresh_host_metrics(cx)) + .is_err() + { + break; + } + } + }) + .detach(); + } + /// 为首页的 SSH 连接排队后台采集(设置关闭或主密钥未解锁时直接跳过)。 pub(super) fn refresh_host_metrics(&mut self, cx: &mut Context) { - if !AppSettings::global(cx).home_show_host_metrics || self.saved_connections_locked() { + if !host_metrics_enabled(cx) || self.saved_connections_locked() { return; } - let pending = self - .connections - .iter() - .filter(|connection| connection.connection_type == ConnectionType::SshSftp) - .filter_map(|connection| { - let connection_id = connection.id?; - if self.host_metrics.in_flight.contains(&connection_id) { - return None; - } - if self - .host_metrics - .entries - .get(&connection_id) - .is_some_and(|entry| entry.sampled_at.elapsed() < HOST_METRICS_TTL) - { - return None; - } - Some((connection_id, connection.clone())) - }) - .collect::>(); - for (connection_id, connection) in pending { - if self.host_metrics.in_flight.len() >= HOST_METRICS_MAX_IN_FLIGHT { + // 每个任务完成后都会再次调用本方法,把超出并发上限的连接继续排空。 + while self.host_metrics.in_flight.len() < HOST_METRICS_MAX_IN_FLIGHT { + let Some((connection_id, connection)) = self.next_host_metrics_candidate() else { break; - } - let Ok(config) = terminal::terminal::ssh_terminal_config_from_connection(&connection) + }; + self.host_metrics + .last_attempt + .insert(connection_id, Instant::now()); + + let Some(repository) = cx + .global::() + .storage + .get::() else { - continue; + tracing::debug!("采集远端资源占用失败:ConnectionRepository 不可用"); + break; + }; + let connection = match repository.resolve_runtime_connection(&connection) { + Ok(connection) => connection, + Err(error) => { + tracing::debug!( + connection_id, + %error, + "采集远端资源占用失败:无法解析连接凭据" + ); + continue; + } + }; + let config = match terminal::terminal::ssh_terminal_config_from_connection(&connection) + { + Ok(config) => config, + Err(error) => { + tracing::debug!( + connection_id, + %error, + "采集远端资源占用失败:无法构造 SSH 配置" + ); + continue; + } }; + self.host_metrics.in_flight.insert(connection_id); - let task = cx.background_spawn(async move { + // SSH 建连依赖 Tokio 运行时(crates/ssh/src/ssh.rs 里的 tokio::time::timeout 等), + // 必须走应用 Tokio runtime;cx.background_spawn 跑在 GPUI 自己的线程池上, + // 没有 reactor,一旦开始建连就会 panic:there is no reactor running。 + let task = Tokio::spawn_result(cx, async move { terminal_view::probe_host_resource_usage(config.ssh_config).await }); cx.spawn(async move |this, cx| { @@ -71,7 +127,7 @@ impl HomePage { _ = this.update(cx, |this, cx| { this.host_metrics.in_flight.remove(&connection_id); match usage { - Ok(usage) => { + Ok(usage) if host_metrics_enabled(cx) => { this.host_metrics.entries.insert( connection_id, HostMetricsEntry { @@ -79,11 +135,14 @@ impl HomePage { sampled_at: Instant::now(), }, ); + this.host_metrics.last_attempt.remove(&connection_id); } + Ok(_) => {} Err(error) => { tracing::debug!(connection_id, %error, "采集远端资源占用失败"); } } + this.refresh_host_metrics(cx); cx.notify(); }); }) @@ -91,13 +150,524 @@ impl HomePage { } } - /// 卡片上显示的一行资源摘要(没有缓存快照时返回 None)。 - pub(crate) fn host_metrics_summary(&self, connection_id: Option) -> Option { - let connection_id = connection_id?; - self.host_metrics - .entries - .get(&connection_id)? - .usage - .summary() + fn next_host_metrics_candidate(&self) -> Option<(i64, one_core::storage::StoredConnection)> { + self.connections + .iter() + .filter(|connection| connection.connection_type == ConnectionType::SshSftp) + .find_map(|connection| { + let connection_id = connection.id?; + if self.host_metrics.in_flight.contains(&connection_id) { + return None; + } + if self + .host_metrics + .entries + .get(&connection_id) + .is_some_and(|entry| entry.sampled_at.elapsed() < HOST_METRICS_TTL) + { + return None; + } + if self + .host_metrics + .last_attempt + .get(&connection_id) + .is_some_and(|attempted_at| attempted_at.elapsed() < HOST_METRICS_TTL) + { + return None; + } + Some((connection_id, connection.clone())) + }) + } + + /// 卡片、列表共用的资源标签(没有缓存快照或设置关闭时返回 None)。 + pub(crate) fn render_host_metrics_detail( + &self, + connection: &StoredConnection, + id_prefix: &str, + cx: &App, + ) -> Option { + match self.host_metrics_state(connection, cx)? { + HostMetricsState::Ready(usage) => { + Some(render_host_metrics_detail(&usage, id_prefix, cx)) + } + HostMetricsState::Pending => Some(render_host_metrics_status( + id_prefix, + t!("Home.host_metrics_collecting").to_string(), + cx, + )), + HostMetricsState::Unavailable => Some(render_host_metrics_status( + id_prefix, + t!("Home.host_metrics_unavailable").to_string(), + cx, + )), + } + } + + /// 卡片宽度有限,只显示一行三项占用;系统和容量信息通过 tooltip 展开。 + pub(crate) fn render_host_metrics_card( + &self, + connection: &StoredConnection, + id_prefix: &str, + cx: &App, + ) -> Option { + match self.host_metrics_state(connection, cx)? { + HostMetricsState::Ready(usage) => Some(render_host_metrics_card(&usage, id_prefix, cx)), + HostMetricsState::Pending => Some(render_host_metrics_card_status( + id_prefix, + t!("Home.host_metrics_collecting").to_string(), + cx, + )), + HostMetricsState::Unavailable => Some(render_host_metrics_card_status( + id_prefix, + t!("Home.host_metrics_unavailable").to_string(), + cx, + )), + } + } + + /// 树行空间有限,用三条迷你进度条表示 CPU / 内存 / 磁盘,完整数值放 tooltip。 + pub(crate) fn render_host_metrics_compact( + &self, + connection: &StoredConnection, + id_prefix: &str, + cx: &App, + ) -> Option { + match self.host_metrics_state(connection, cx)? { + HostMetricsState::Ready(usage) => { + Some(render_host_metrics_compact(&usage, id_prefix, cx)) + } + HostMetricsState::Pending | HostMetricsState::Unavailable => None, + } + } + + pub(crate) fn shows_host_metrics_strip(&self, connection: &StoredConnection, cx: &App) -> bool { + host_metrics_enabled(cx) && connection.connection_type == ConnectionType::SshSftp + } + + fn host_metrics_state( + &self, + connection: &StoredConnection, + cx: &App, + ) -> Option { + if !self.shows_host_metrics_strip(connection, cx) { + return None; + } + let connection_id = connection.id?; + if let Some(entry) = self.host_metrics.entries.get(&connection_id) { + return Some(HostMetricsState::Ready(entry.usage.clone())); + } + if self.host_metrics.in_flight.contains(&connection_id) { + return Some(HostMetricsState::Pending); + } + if self.host_metrics.last_attempt.contains_key(&connection_id) { + return Some(HostMetricsState::Unavailable); + } + Some(HostMetricsState::Pending) + } +} + +fn host_metrics_enabled(cx: &App) -> bool { + AppSettings::global(cx).home_show_host_metrics +} + +fn format_host_metrics_summary(usage: &terminal_view::HostResourceUsage) -> Option { + let mut parts = Vec::new(); + if let Some(cpu) = usage.cpu_percent { + let mut text = t!("Home.host_metrics_cpu", percent = format!("{cpu:.0}")).to_string(); + if let Some(cores) = usage.cpu_cores { + text.push_str(" · "); + text.push_str(&t!("Home.host_metrics_cores", count = cores.to_string()).to_string()); + } + parts.push(text); + } + if let Some(memory) = usage.memory_percent { + let mut text = t!("Home.host_metrics_memory", percent = format!("{memory:.0}")).to_string(); + if let Some(total) = usage.memory_total_kib { + text.push_str(" · "); + text.push_str(&format_kib_compact(total)); + } + parts.push(text); + } + if let Some(disk) = usage.disk_percent { + let mut text = t!("Home.host_metrics_disk", percent = format!("{disk:.0}")).to_string(); + if let Some(total) = usage.disk_total_kib { + text.push_str(" · "); + text.push_str(&format_kib_compact(total)); + } + parts.push(text); + } + (!parts.is_empty()).then(|| parts.join(" · ")) +} + +fn render_host_metrics_detail( + usage: &terminal_view::HostResourceUsage, + id_prefix: &str, + cx: &App, +) -> AnyElement { + let metrics = host_metric_values(usage); + h_flex() + .min_w_0() + .flex_wrap() + .gap_1p5() + .when_some(usage.os_name.as_ref(), |row, os_name| { + row.child(render_host_info_chip( + SharedString::from(format!("{id_prefix}-os")), + os_name.clone(), + cx, + )) + }) + .children(metrics.into_iter().map(|(kind, value)| { + render_host_metric_chip( + SharedString::from(format!("{id_prefix}-{}", kind.id_suffix())), + kind.label(), + value, + host_metric_detail(usage, kind), + cx, + ) + })) + .into_any_element() +} + +fn render_host_metrics_status(id_prefix: &str, text: String, cx: &App) -> AnyElement { + h_flex() + .id(SharedString::from(format!("{id_prefix}-status"))) + .flex_shrink_0() + .items_center() + .gap_1p5() + .px_2() + .py_0p5() + .rounded(cx.theme().radius) + .border_1() + .border_color(cx.theme().border) + .bg(cx.theme().muted) + .child( + div() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child(text), + ) + .into_any_element() +} + +fn render_host_metrics_card_status(id_prefix: &str, text: String, cx: &App) -> AnyElement { + h_flex() + .id(SharedString::from(format!("{id_prefix}-card-status"))) + .w_full() + .items_center() + .gap_2() + .px_2() + .py_1() + .rounded(cx.theme().radius) + .border_1() + .border_color(cx.theme().border) + .bg(cx.theme().muted) + .child( + div() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child(text), + ) + .into_any_element() +} + +fn render_host_metrics_card( + usage: &terminal_view::HostResourceUsage, + id_prefix: &str, + cx: &App, +) -> AnyElement { + let metrics = host_metric_values(usage); + let tooltip: SharedString = format_host_metrics_summary(usage) + .unwrap_or_default() + .into(); + h_flex() + .id(SharedString::from(format!("{id_prefix}-card"))) + .w_full() + .min_w_0() + .items_center() + .gap_2() + .px_2() + .py_1() + .rounded(cx.theme().radius) + .border_1() + .border_color(cx.theme().border) + .bg(cx.theme().muted) + .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx)) + .children(metrics.into_iter().map(|(kind, value)| { + h_flex() + .flex_1() + .min_w_0() + .items_center() + .gap_1() + .child( + div() + .size_1p5() + .flex_shrink_0() + .rounded_full() + .bg(metric_color(value, cx)), + ) + .child( + div() + .min_w_0() + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child(kind.label()), + ) + .child( + div() + .flex_shrink_0() + .text_xs() + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(if value >= 75.0 { + metric_color(value, cx) + } else { + cx.theme().foreground + }) + .child(format!("{value:.0}%")), + ) + })) + .into_any_element() +} + +fn render_host_info_chip(id: SharedString, text: String, cx: &App) -> AnyElement { + let tooltip: SharedString = text.clone().into(); + h_flex() + .id(id) + .flex_shrink_0() + .max_w(gpui::rems(12.0)) + .px_2() + .py_0p5() + .rounded(cx.theme().radius) + .border_1() + .border_color(cx.theme().border) + .bg(cx.theme().muted) + .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx)) + .child( + div() + .min_w_0() + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child(text), + ) + .into_any_element() +} + +fn render_host_metric_chip( + id: SharedString, + label: String, + value: f64, + detail: Option, + cx: &App, +) -> AnyElement { + let tone = metric_color(value, cx); + h_flex() + .id(id) + .flex_shrink_0() + .items_center() + .gap_1() + .px_2() + .py_0p5() + .rounded(cx.theme().radius) + .border_1() + .border_color(cx.theme().border) + .bg(cx.theme().muted) + .child(div().size_1p5().flex_shrink_0().rounded_full().bg(tone)) + .child( + div() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child(label), + ) + .child( + div() + .text_xs() + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(if value >= 75.0 { + tone + } else { + cx.theme().foreground + }) + .child(format!("{value:.0}%")), + ) + .when_some(detail, |chip, detail| { + chip.child( + div() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child(format!("· {detail}")), + ) + }) + .into_any_element() +} + +fn host_metric_detail( + usage: &terminal_view::HostResourceUsage, + kind: HostMetricKind, +) -> Option { + match kind { + HostMetricKind::Cpu => usage + .cpu_cores + .map(|cores| t!("Home.host_metrics_cores", count = cores.to_string()).to_string()), + HostMetricKind::Memory => usage.memory_total_kib.map(format_kib_compact), + HostMetricKind::Disk => usage.disk_total_kib.map(format_kib_compact), + } +} + +fn format_kib_compact(kib: u64) -> String { + let gib = kib as f64 / 1024.0 / 1024.0; + if gib >= 1024.0 { + format!("{:.1}T", gib / 1024.0) + } else if gib >= 100.0 || (gib >= 10.0 && nearly_whole(gib)) { + format!("{gib:.0}G") + } else if gib >= 10.0 { + format!("{gib:.1}G") + } else if gib >= 1.0 { + format!("{gib:.2}G") + } else { + let mib = kib as f64 / 1024.0; + if mib >= 1.0 { + format!("{mib:.0}M") + } else { + format!("{kib}K") + } + } +} + +fn nearly_whole(value: f64) -> bool { + (value - value.round()).abs() < 0.05 +} + +fn render_host_metrics_compact( + usage: &terminal_view::HostResourceUsage, + id_prefix: &str, + cx: &App, +) -> AnyElement { + let metrics = host_metric_values(usage); + let tooltip: SharedString = format_host_metrics_summary(usage) + .unwrap_or_default() + .into(); + h_flex() + .id(SharedString::from(format!("{id_prefix}-compact"))) + .flex_shrink_0() + .items_center() + .justify_center() + .px_1p5() + .py_1() + .rounded_full() + .border_1() + .border_color(cx.theme().border) + .bg(cx.theme().muted) + .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx)) + .child( + v_flex() + .w_5() + .gap_0p5() + .children(metrics.into_iter().map(|(kind, value)| { + Progress::new(SharedString::from(format!( + "{id_prefix}-compact-{}", + kind.id_suffix() + ))) + .with_size(Size::XSmall) + .color(metric_color(value, cx)) + .value(value.clamp(0.0, 100.0) as f32) + .accessibility_label(format!("{} {value:.0}%", kind.label())) + })), + ) + .into_any_element() +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum HostMetricKind { + Cpu, + Memory, + Disk, +} + +impl HostMetricKind { + fn id_suffix(self) -> &'static str { + match self { + Self::Cpu => "cpu", + Self::Memory => "memory", + Self::Disk => "disk", + } + } + + fn label(self) -> String { + match self { + Self::Cpu => t!("Home.host_metrics_cpu_label").to_string(), + Self::Memory => t!("Home.host_metrics_memory_label").to_string(), + Self::Disk => t!("Home.host_metrics_disk_label").to_string(), + } + } +} + +fn host_metric_values(usage: &terminal_view::HostResourceUsage) -> Vec<(HostMetricKind, f64)> { + let parts = [usage.cpu_percent, usage.memory_percent, usage.disk_percent].into_iter(); + [ + HostMetricKind::Cpu, + HostMetricKind::Memory, + HostMetricKind::Disk, + ] + .into_iter() + .zip(parts) + .filter_map(|(kind, value)| value.map(|value| (kind, value))) + .collect() +} + +fn metric_color(value: f64, cx: &App) -> Hsla { + if value >= 90.0 { + cx.theme().danger + } else if value >= 75.0 { + cx.theme().warning + } else { + cx.theme().primary + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn metric_values_skip_missing_metrics_and_keep_column_order() { + assert_eq!( + host_metric_values(&terminal_view::HostResourceUsage { + os_name: None, + cpu_cores: None, + cpu_percent: Some(12.4), + memory_total_kib: None, + memory_percent: None, + disk_total_kib: None, + disk_percent: Some(51.6), + }) + .iter() + .map(|(kind, value)| (kind.id_suffix(), *value)) + .collect::>(), + vec![("cpu", 12.4), ("disk", 51.6)] + ); + assert_eq!( + host_metric_values(&terminal_view::HostResourceUsage { + os_name: None, + cpu_cores: None, + cpu_percent: None, + memory_total_kib: None, + memory_percent: None, + disk_total_kib: None, + disk_percent: None, + }), + Vec::new() + ); + } + + #[test] + fn compact_capacity_uses_reference_style_units() { + assert_eq!(format_kib_compact(27 * 1024 * 1024), "27G"); + assert_eq!(format_kib_compact(247 * 1024 * 1024), "247G"); + assert_eq!(format_kib_compact(512 * 1024), "512M"); } } diff --git a/crates/navop_app/src/home_tab/lifecycle.rs b/crates/navop_app/src/home_tab/lifecycle.rs index 32fb54f07..600e26775 100644 --- a/crates/navop_app/src/home_tab/lifecycle.rs +++ b/crates/navop_app/src/home_tab/lifecycle.rs @@ -261,6 +261,9 @@ impl HomePage { .detach(); } + #[cfg(feature = "shell")] + page.start_host_metrics_refresh(cx); + page } diff --git a/crates/navop_app/src/home_tab/tests/rendering.rs b/crates/navop_app/src/home_tab/tests/rendering.rs index 06652e5e7..8cf2ecd06 100644 --- a/crates/navop_app/src/home_tab/tests/rendering.rs +++ b/crates/navop_app/src/home_tab/tests/rendering.rs @@ -632,3 +632,57 @@ fn connection_card_and_row_require_the_first_click_for_double_click_open() { ); } } + +#[test] +fn host_metrics_are_wired_to_card_list_and_tree_views() { + let host_metrics = include_str!("../host_metrics.rs"); + let card = include_str!("../connection_card_content.rs"); + let list = include_str!("../connection_list.rs"); + let tree_rows = include_str!("../../persistent_connection_sidebar/rows.rs"); + + assert!( + card.contains("render_host_metrics_card"), + "卡片必须使用适配窄宽度的紧凑资源状态带" + ); + let card_layout = include_str!("../connection_card.rs"); + assert!( + card_layout.contains("shows_host_metrics") && card_layout.contains("5.5"), + "卡片必须仅在需要资源状态带时预留第二行高度" + ); + assert!( + list.contains("render_host_metrics_detail"), + "列表布局必须显示同一份资源信息" + ); + assert!( + list.contains(".flex_wrap()"), + "列表中的地址与资源标签应共用一行并在窄宽度下自然换行" + ); + assert!( + tree_rows.contains("render_host_metrics_compact"), + "树形布局和默认导航布局左侧树必须显示紧凑资源仪表" + ); + assert!( + host_metrics.contains("home_show_host_metrics"), + "所有布局共用的摘要必须尊重显示开关" + ); + assert!( + host_metrics.contains("Progress::new"), + "资源占用应使用进度条表达,不能退回纯文字摘要" + ); + assert!( + host_metrics.contains("Tooltip::new"), + "树形紧凑仪表必须能通过 tooltip 展开具体数值" + ); + assert!( + host_metrics.contains("resolve_runtime_connection"), + "后台探测前必须解析钥匙串凭据,否则引用凭据的 SSH 连接永远采不到数据" + ); + assert!( + host_metrics.contains("Tokio::spawn_result"), + "SSH 探测必须进入应用 Tokio runtime,不能直接放在 GPUI background executor" + ); + assert!( + host_metrics.contains("refresh_host_metrics(cx)"), + "一个探测槽释放后必须继续排队剩余连接" + ); +} diff --git a/crates/navop_app/src/jump_deeplink.rs b/crates/navop_app/src/jump_deeplink.rs new file mode 100644 index 000000000..9bf858ffa --- /dev/null +++ b/crates/navop_app/src/jump_deeplink.rs @@ -0,0 +1,422 @@ +//! JumpServer `jms://` 深链接:把网页端签发的一次性 connection token 变成 +//! 一条临时 SSH 会话。 +//! +//! 链接形如 `jms://`,payload 由 JumpServer 前端生成: +//! +//! ```json +//! { +//! "protocol": "ssh", +//! "name": "account@asset", +//! "token": { "id": "token-id", "value": "token-secret" }, +//! "asset": { "name": "Production Server" }, +//! "endpoint": { "host": "gateway.example.com", "port": 2222 } +//! } +//! ``` +//! +//! 打开方式与官方客户端一致:直接以 `JMS-` / `` SSH 到 +//! `endpoint`,由网关上的 Koko 用 token 桥接到目标资产;不写入连接仓库,也不 +//! 保存密码,链接本身也不会出现在日志或错误提示里。 + +use anyhow::{Context as _, Result, bail}; +use base64::Engine as _; +use gpui::{App, Window}; +use gpui_component::{WindowExt as _, notification::Notification}; +use one_core::storage::{ + PreferredOpenMode, SshAuthMethod, SshParams, StoredConnection, StoredTerminalEncoding, + StoredTerminalType, +}; +use one_core::tab_container::TabOpenMode; +use rust_i18n::t; +use serde_json::Value; + +use crate::navop_app::GlobalHomePage; + +/// JumpServer 深链接协议前缀(大小写不敏感)。 +pub(crate) const JUMP_DEEPLINK_PREFIX: &str = "jms://"; + +/// 深链接里声明的协议。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum JumpProtocol { + Ssh, + Sftp, + Telnet, +} + +impl JumpProtocol { + fn from_payload(raw: &str) -> Result { + match raw.trim().to_ascii_lowercase().as_str() { + "ssh" => Ok(Self::Ssh), + "sftp" => Ok(Self::Sftp), + "telnet" => Ok(Self::Telnet), + other => bail!("不支持的 JumpServer 协议: {other}"), + } + } +} + +/// 解析后的深链接内容(不含任何需要落库的状态)。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct JumpLink { + pub protocol: JumpProtocol, + pub label: String, + pub host: String, + pub port: u16, + pub token_id: String, + pub token_value: String, +} + +/// 判断字符串是否是 JumpServer 深链接。 +pub(crate) fn is_jump_deeplink(raw: &str) -> bool { + let trimmed = raw.trim(); + trimmed + .get(..JUMP_DEEPLINK_PREFIX.len()) + .is_some_and(|prefix| prefix.eq_ignore_ascii_case(JUMP_DEEPLINK_PREFIX)) +} + +/// 解析 `jms://` 深链接。 +pub(crate) fn parse_jump_deeplink(raw: &str) -> Result { + let trimmed = raw.trim(); + if !is_jump_deeplink(trimmed) { + bail!("不是 jms:// 深链接"); + } + // 去掉协议前缀与 JumpServer 偶尔追加的尾部 `/`。 + let encoded = trimmed[JUMP_DEEPLINK_PREFIX.len()..].trim_end_matches('/'); + if encoded.is_empty() { + bail!("jms:// 链接缺少 payload"); + } + let payload = decode_payload(encoded)?; + + let protocol = payload + .get("protocol") + .and_then(string_value) + .context("jms:// payload 缺少 protocol")?; + let protocol = JumpProtocol::from_payload(&protocol)?; + + // 新版 payload 把凭据放在 token 里,旧版(v1)直接放在顶层。 + let token = payload.get("token"); + let token_id = token + .and_then(|token| token.get("id")) + .and_then(string_value) + .or_else(|| payload.get("id").and_then(string_value)) + .context("jms:// payload 缺少 token id")?; + let token_value = token + .and_then(|token| token.get("value")) + .and_then(string_value) + .or_else(|| payload.get("value").and_then(string_value)) + .context("jms:// payload 缺少 token value")?; + + let host = payload + .pointer("/endpoint/host") + .and_then(string_value) + .context("jms:// payload 缺少 endpoint host")?; + let port = payload + .pointer("/endpoint/port") + .and_then(parse_port) + .context("jms:// payload 的 endpoint port 无效")?; + + let asset_name = payload + .pointer("/asset/name") + .and_then(string_value) + .filter(|name| !name.is_empty()); + let name = payload + .get("name") + .and_then(string_value) + .filter(|name| !name.is_empty()); + let label = asset_name.or(name).unwrap_or_else(|| host.clone()); + + Ok(JumpLink { + protocol, + label, + host, + port, + token_id, + token_value, + }) +} + +fn decode_payload(encoded: &str) -> Result { + // JumpServer 有时发 URL-safe 字符集、省略 padding,统一归一化后再解码。 + let mut normalized = encoded.replace('-', "+").replace('_', "/"); + while normalized.len() % 4 != 0 { + normalized.push('='); + } + let bytes = base64::engine::general_purpose::STANDARD + .decode(normalized.as_bytes()) + .context("jms:// payload 不是合法的 base64url")?; + let text = String::from_utf8(bytes).context("jms:// payload 不是 UTF-8 文本")?; + serde_json::from_str(&text).context("jms:// payload 不是合法的 JSON") +} + +fn string_value(value: &Value) -> Option { + let raw = value.as_str()?.trim(); + if raw.is_empty() { + None + } else { + Some(raw.to_string()) + } +} + +fn parse_port(value: &Value) -> Option { + let port = match value { + Value::Number(number) => number.as_u64()?, + Value::String(text) => text.trim().parse::().ok()?, + _ => return None, + }; + u16::try_from(port).ok().filter(|port| *port != 0) +} + +/// 把深链接转成一条不落库的 SSH 连接:用户名 `JMS-`、密码为 +/// token 值,认证由网关上的 Koko 完成。 +pub(crate) fn connection_from_link(link: &JumpLink) -> StoredConnection { + let params = SshParams { + host: link.host.clone(), + port: link.port, + username: format!("JMS-{}", link.token_id), + auth_method: SshAuthMethod::Password { + password: link.token_value.clone(), + }, + sftp_account: None, + sftp_default_directory: None, + credential_reference: None, + prompt_username: Some(false), + prompt_password: Some(false), + // token 就是密码,认证方式固定为 password,避免网关拒绝后再弹键盘交互。 + keyboard_interactive: Some(false), + otp: None, + terminal_encoding: StoredTerminalEncoding::default(), + terminal_type: StoredTerminalType::default(), + account_expect: Default::default(), + connect_timeout: None, + keepalive_interval: None, + keepalive_max: None, + default_directory: None, + init_script: None, + disable_shell_integration: None, + x11_forwarding: None, + allow_legacy_algorithms: None, + forward_agent: None, + agent_forward_key: None, + jump_server: None, + disabled_jump_server: None, + proxy: None, + os_id: None, + icon: None, + icon_file_path: None, + remote_file: None, + }; + let mut connection = StoredConnection::new_ssh(link.label.clone(), params, None); + // 临时会话不参与云同步;id 为 None,打开后自动成为一次性标签页。 + connection.sync_enabled = false; + if link.protocol == JumpProtocol::Sftp { + connection.preferred_open_mode = Some(PreferredOpenMode::DualPane); + } + connection +} + +struct JumpDeepLinkNotification; + +/// 打开 `jms://` 深链接;任何失败都只提示「无法打开」,不回显链接内容。 +pub(crate) fn open_jump_deeplink(raw: &str, window: &mut Window, cx: &mut App) { + if let Err(error) = try_open_jump_deeplink(raw, window, cx) { + tracing::warn!(error = %error, "failed to open JumpServer deep link"); + window.push_notification( + Notification::error( + t!("Common.jump_deeplink_failed", error = format!("{error:#}")).to_string(), + ) + .id::() + .autohide(true), + cx, + ); + } +} + +fn try_open_jump_deeplink(raw: &str, window: &mut Window, cx: &mut App) -> Result<()> { + let link = parse_jump_deeplink(raw)?; + let connection = connection_from_link(&link); + tracing::info!( + host = %link.host, + port = link.port, + protocol = ?link.protocol, + "opening JumpServer deep link" + ); + let home = cx + .try_global::() + .map(|global| global.home_page.clone()) + .context("home page is not ready")?; + window.activate_window(); + window.defer(cx, move |window, cx| { + home.update(cx, |home, cx| { + if !app_kit::registry().open_connection( + &connection, + TabOpenMode::Activate, + home, + window, + cx, + ) { + window.push_notification( + Notification::warning( + t!( + "Common.connection_type_unsupported", + name = connection.name.clone() + ) + .to_string(), + ) + .autohide(true), + cx, + ); + } + }); + }); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use base64::engine::general_purpose::URL_SAFE_NO_PAD; + use one_core::storage::ConnectionType; + + fn encode(payload: &str) -> String { + URL_SAFE_NO_PAD.encode(payload) + } + + const SAMPLE: &str = r#"{ + "version": 2, + "protocol": "ssh", + "name": "Account@Production Server", + "token": { "id": "token-id", "value": "token-secret" }, + "asset": { "id": "asset-id", "name": "Production Server", "address": "10.0.0.1" }, + "endpoint": { "host": "gw.example.com", "port": 2222 } + }"#; + + #[test] + fn recognizes_jms_prefix_case_insensitively() { + assert!(is_jump_deeplink("jms://abc")); + assert!(is_jump_deeplink("JMS://abc")); + assert!(is_jump_deeplink(" Jms://abc ")); + assert!(!is_jump_deeplink("jms:abc")); + assert!(!is_jump_deeplink("ssh://host")); + assert!(!is_jump_deeplink("")); + // 多字节前缀不能 panic + assert!(!is_jump_deeplink("跳板机://abc")); + } + + #[test] + fn parses_jump_server_payload() { + let link = parse_jump_deeplink(&format!("jms://{}", encode(SAMPLE))).expect("应解析成功"); + assert_eq!(link.protocol, JumpProtocol::Ssh); + assert_eq!(link.label, "Production Server"); + assert_eq!(link.host, "gw.example.com"); + assert_eq!(link.port, 2222); + assert_eq!(link.token_id, "token-id"); + assert_eq!(link.token_value, "token-secret"); + } + + #[test] + fn tolerates_url_safe_alphabet_missing_padding_and_trailing_slash() { + let encoded = encode(SAMPLE); + assert!(!encoded.contains('=')); + let link = parse_jump_deeplink(&format!("jms://{encoded}//")).expect("应解析成功"); + assert_eq!(link.host, "gw.example.com"); + } + + #[test] + fn falls_back_to_legacy_token_fields() { + let payload = r#"{ + "protocol": "sftp", + "name": "legacy", + "id": "legacy-id", + "value": "legacy-secret", + "endpoint": { "host": "gw.example.com", "port": "2222" } + }"#; + let link = parse_jump_deeplink(&format!("jms://{}", encode(payload))).expect("应解析成功"); + assert_eq!(link.protocol, JumpProtocol::Sftp); + assert_eq!(link.label, "legacy"); + assert_eq!(link.port, 2222); + assert_eq!(link.token_id, "legacy-id"); + assert_eq!(link.token_value, "legacy-secret"); + } + + #[test] + fn rejects_payload_without_credentials() { + let payload = r#"{ + "protocol": "ssh", + "endpoint": { "host": "gw.example.com", "port": 2222 } + }"#; + let error = parse_jump_deeplink(&format!("jms://{}", encode(payload))).expect_err("应拒绝"); + assert!(format!("{error:#}").contains("token")); + } + + #[test] + fn rejects_invalid_endpoint() { + let missing_host = r#"{ + "protocol": "ssh", + "token": { "id": "id", "value": "value" }, + "endpoint": { "port": 2222 } + }"#; + assert!(parse_jump_deeplink(&format!("jms://{}", encode(missing_host))).is_err()); + + let bad_port = r#"{ + "protocol": "ssh", + "token": { "id": "id", "value": "value" }, + "endpoint": { "host": "gw.example.com", "port": 70000 } + }"#; + assert!(parse_jump_deeplink(&format!("jms://{}", encode(bad_port))).is_err()); + } + + #[test] + fn rejects_unsupported_protocol() { + let payload = r#"{ + "protocol": "rdp", + "token": { "id": "id", "value": "value" }, + "endpoint": { "host": "gw.example.com", "port": 2222 } + }"#; + let error = parse_jump_deeplink(&format!("jms://{}", encode(payload))).expect_err("应拒绝"); + assert!(format!("{error:#}").contains("rdp")); + } + + #[test] + fn rejects_malformed_payload_without_echoing_it() { + let error = parse_jump_deeplink("jms://not-base64-$$$").expect_err("应拒绝"); + assert!(!format!("{error:#}").contains("not-base64")); + } + + #[test] + fn builds_ephemeral_ssh_connection() { + let link = parse_jump_deeplink(&format!("jms://{}", encode(SAMPLE))).expect("应解析成功"); + let connection = connection_from_link(&link); + assert_eq!(connection.id, None); + assert!(!connection.sync_enabled); + assert_eq!(connection.name, "Production Server"); + assert_eq!(connection.connection_type, ConnectionType::SshSftp); + + let params: SshParams = + serde_json::from_str(&connection.params).expect("params 应是合法 SshParams"); + assert_eq!(params.host, "gw.example.com"); + assert_eq!(params.port, 2222); + assert_eq!(params.username, "JMS-token-id"); + match ¶ms.auth_method { + SshAuthMethod::Password { password } => assert_eq!(password, "token-secret"), + other => panic!("应使用 token 作为密码认证: {other:?}"), + } + // 认证方式固定为密码:不要在 token 失效时退化成交互式键盘认证。 + assert_eq!(params.keyboard_interactive, Some(false)); + assert_eq!(params.prompt_password, Some(false)); + assert!(!params.prompts_for_password()); + assert!(!params.prompts_for_username()); + } + + #[test] + fn sftp_link_opens_dual_pane() { + let payload = r#"{ + "protocol": "sftp", + "token": { "id": "id", "value": "value" }, + "endpoint": { "host": "gw.example.com", "port": 2222 } + }"#; + let link = parse_jump_deeplink(&format!("jms://{}", encode(payload))).expect("应解析成功"); + let connection = connection_from_link(&link); + assert_eq!( + connection.preferred_open_mode, + Some(PreferredOpenMode::DualPane) + ); + } +} diff --git a/crates/navop_app/src/lib.rs b/crates/navop_app/src/lib.rs index 928c964c2..f101a525e 100644 --- a/crates/navop_app/src/lib.rs +++ b/crates/navop_app/src/lib.rs @@ -16,6 +16,7 @@ mod auth; mod ai_chat_acp; mod app_init; +mod connection_deeplink; mod connection_sort; mod connection_type_menu; mod connection_visuals; @@ -33,6 +34,7 @@ mod file_association; mod file_open; mod home; mod home_tab; +mod jump_deeplink; mod license; #[cfg(feature = "shell")] mod local_terminal_profiles; @@ -575,7 +577,10 @@ where } // 只有正式安装态才注册宿主文件关联;便携版与 debug 开发构建不应改写系统关联。 // 独立产品不接管任何扩展名(`file_associations` 为空),文件关联始终归全量产品。 - if one_core::app_paths::is_installed() && !product.identity().file_associations.is_empty() { + let identity = product.identity(); + if one_core::app_paths::is_installed() + && (!identity.file_associations.is_empty() || !identity.url_schemes.is_empty()) + { file_association::schedule_registration(cx); } notes::init(cx); @@ -732,7 +737,7 @@ where match request { AppOpenRequest::ActivateAndOpenPaths(paths) => { for path in paths { - let input = file_open::FileOpenInput::Path(path); + let input = file_open::input_from_startup_argument(path); file_open::open_input(input, window, cx); } } diff --git a/crates/navop_app/src/navop_app.rs b/crates/navop_app/src/navop_app.rs index c34f0dc47..46cfc038b 100644 --- a/crates/navop_app/src/navop_app.rs +++ b/crates/navop_app/src/navop_app.rs @@ -70,6 +70,34 @@ impl gpui::Global for GlobalHomePage {} #[cfg(feature = "nsh-host")] struct NavopExtensionsHost; +/// 扩展连接种类的 id 前缀与分隔符:`ext:{extension_id}::{contribution_id}`。 +/// +/// 向导只把 kind id 当不透明字符串(选中 key、表单复用键),扩展侧需要在 +/// 构造表单时拆回 (extension_id, contribution_id)。 +#[cfg(feature = "nsh-host")] +const EXTENSION_KIND_PREFIX: &str = "ext:"; +#[cfg(feature = "nsh-host")] +const EXTENSION_KIND_SEPARATOR: &str = "::"; + +#[cfg(feature = "nsh-host")] +fn extension_kind_id(extension_id: &str, contribution_id: &str) -> gpui::SharedString { + format!("{EXTENSION_KIND_PREFIX}{extension_id}{EXTENSION_KIND_SEPARATOR}{contribution_id}") + .into() +} + +#[cfg(feature = "nsh-host")] +fn split_extension_kind_id(kind_id: &str) -> Option<(&str, &str)> { + kind_id + .strip_prefix(EXTENSION_KIND_PREFIX)? + .split_once(EXTENSION_KIND_SEPARATOR) +} + +/// 扩展种类的标签占位:真实名字来自运行时清单,恒走 `label_override`。 +#[cfg(feature = "nsh-host")] +fn extension_kind_label(_cx: &App) -> gpui::SharedString { + gpui::SharedString::default() +} + #[cfg(feature = "nsh-host")] impl app_kit::ExtensionsHost for NavopExtensionsHost { fn open_extensions( @@ -88,6 +116,72 @@ impl app_kit::ExtensionsHost for NavopExtensionsHost { }) .is_ok() } + + /// 已安装扩展贡献的连接:向导把它们归入「中间件」类目。 + fn connection_kinds(&self, cx: &App) -> Vec { + let Some(catalog) = crate::connection_visuals::extension_catalog_from_cx(cx) else { + return Vec::new(); + }; + let mut kinds: Vec<_> = catalog + .resource_connections() + .map(|contribution| { + let mut kind = domain_api::ConnectionKindDescriptor::new( + extension_kind_id(&contribution.extension_id, &contribution.id), + extension_kind_label, + domain_api::ConnectionKindGroup::Extension, + 0, + ) + .with_label(contribution.label.clone()); + if let Some(description) = contribution.description.clone() { + kind = kind.with_description(description); + } + if let Some(icon) = contribution.icon_path.clone() { + kind = kind.with_icon(domain_api::ConnectionKindIcon::File(icon)); + } + kind + }) + .collect(); + // 目录底层是 HashMap,按显示名排序保证卡片顺序稳定。 + kinds.sort_by_key(|kind| kind.display_label(cx).to_lowercase()); + kinds + } + + fn build_connection_form( + &self, + request: domain_api::ConnectionFormRequest, + window: &mut Window, + cx: &mut App, + ) -> Option { + // 编辑 / 复制走主页的连接动作(`HomePage::show_extension_form`),向导只新建。 + if request.editing_connection.is_some() || request.initial_connection.is_some() { + return None; + } + let (extension_id, contribution_id) = split_extension_kind_id(request.kind_id.as_ref())?; + let contribution = crate::connection_visuals::extension_catalog_from_cx(cx)? + .resource_connection(extension_id, contribution_id)? + .clone(); + let (workspaces, teams) = match cx.try_global::() { + Some(global) => { + let workspaces = global.home_page.read(cx).workspaces.clone(); + ( + workspaces, + one_core::cloud_sync::get_cached_team_options(cx), + ) + } + None => (Vec::new(), Vec::new()), + }; + let config = universal_plugins::ExtensionConnectionFormConfig { + contribution, + editing_connection: None, + initial_workspace_id: request.initial_workspace_id, + workspaces, + teams, + }; + Some( + cx.new(|cx| universal_plugins::ExtensionConnectionForm::new(config, window, cx)) + .into(), + ) + } } #[derive(Clone)] diff --git a/crates/navop_app/src/persistent_connection_sidebar/connection_command.rs b/crates/navop_app/src/persistent_connection_sidebar/connection_command.rs index 765370a1a..f931a10d0 100644 --- a/crates/navop_app/src/persistent_connection_sidebar/connection_command.rs +++ b/crates/navop_app/src/persistent_connection_sidebar/connection_command.rs @@ -464,6 +464,8 @@ mod tests { password: "jump-secret".to_string(), }, credential_reference: None, + mode: Default::default(), + bastion: None, }), proxy: None, os_id: None, diff --git a/crates/navop_app/src/persistent_connection_sidebar/connection_share_tests.rs b/crates/navop_app/src/persistent_connection_sidebar/connection_share_tests.rs index ac4ca0a2c..339ff8804 100644 --- a/crates/navop_app/src/persistent_connection_sidebar/connection_share_tests.rs +++ b/crates/navop_app/src/persistent_connection_sidebar/connection_share_tests.rs @@ -134,6 +134,8 @@ fn basic_info_omits_nested_credentials_and_embedded_private_keys() { password: "jump-password".to_string(), }, credential_reference: None, + mode: Default::default(), + bastion: None, }), proxy: Some(ProxyConfig { proxy_type: ProxyType::Socks5, @@ -202,6 +204,8 @@ fn full_info_keeps_credentials_but_always_redacts_embedded_private_key_contents( password: "jump-password".to_string(), }, credential_reference: None, + mode: Default::default(), + bastion: None, }), proxy: Some(ProxyConfig { proxy_type: ProxyType::Http, diff --git a/crates/navop_app/src/persistent_connection_sidebar/rows.rs b/crates/navop_app/src/persistent_connection_sidebar/rows.rs index 91182dbfd..2ea61404c 100644 --- a/crates/navop_app/src/persistent_connection_sidebar/rows.rs +++ b/crates/navop_app/src/persistent_connection_sidebar/rows.rs @@ -332,9 +332,21 @@ impl PersistentConnectionSidebar { .and_then(|connection| connection.id) .map(|id| self.ai_access_levels.get(&id).copied().unwrap_or_default()) .and_then(|level| connection_ai_access_badge(level, cx)); - let type_tag = connection - .as_ref() - .map(|connection| connection_type_tag(connection, cx)); + let host_metrics_compact = connection.as_ref().and_then(|connection| { + home.read(cx).render_host_metrics_compact( + connection, + &format!("persistent-connection-metrics-{id}"), + cx, + ) + }); + // 树只有一行可用;有资源快照时让更有决策价值的数据占用类型标签位置。 + let type_tag = (host_metrics_compact.is_none()) + .then(|| { + connection + .as_ref() + .map(|connection| connection_type_tag(connection, cx)) + }) + .flatten(); let icon = connection .as_ref() .map(|connection| { @@ -476,6 +488,7 @@ impl PersistentConnectionSidebar { }) .child(tree_connection_icon_slot(icon, palette)) .child(tree_connection_name_with_type_tag(name, type_tag)) + .when_some(host_metrics_compact, |row, metrics| row.child(metrics)) .when_some(team_indicator, |row, indicator| row.child(indicator)) .when_some(ai_access_badge, |row, badge| row.child(badge)) .into_any_element() diff --git a/crates/navop_app/src/setting_tab.rs b/crates/navop_app/src/setting_tab.rs index ab72ec52c..22c25e8b2 100644 --- a/crates/navop_app/src/setting_tab.rs +++ b/crates/navop_app/src/setting_tab.rs @@ -9,6 +9,7 @@ use crate::settings::acp_agents_settings::AcpAgentsView; use crate::settings::agent_settings::agent_setting_group; use crate::settings::appearance::render as render_appearance_settings; use crate::settings::connection_display_settings::connection_display_setting_group; +use crate::settings::deeplink_settings::deeplink_setting_group; use crate::settings::llm_providers_view::LlmProvidersView; use crate::settings::mcp_settings::mcp_setting_group; use crate::settings::notes_settings::notes_setting_group; @@ -990,6 +991,7 @@ impl SettingsPanel { ), ), close_behavior_setting_group(default_settings.close_button_behavior), + deeplink_setting_group(), notes_setting_group(font_options.clone()), SettingGroup::new() .title(t!("Settings.General.Appearance.group_title")) diff --git a/crates/navop_app/src/settings/deeplink_settings.rs b/crates/navop_app/src/settings/deeplink_settings.rs new file mode 100644 index 000000000..8f25a3298 --- /dev/null +++ b/crates/navop_app/src/settings/deeplink_settings.rs @@ -0,0 +1,48 @@ +//! 「设置 → 通用 → 链接协议」:控制 Navop 是否接管 `ssh://` / `sftp://`。 +//! +//! 这些是系统级的公共 scheme,终端与文件管理器通常已经注册了默认处理程序。 +//! 注册会改变双击/点击链接时的默认行为,所以默认全部关闭,只在用户显式勾选后 +//! 才写入系统关联(macOS 的 scheme 声明是静态的,由应用层再按此设置放行)。 + +use gpui::App; +use gpui_component::setting::{SettingField, SettingGroup, SettingItem}; +use one_core::settings::AppSettings; +use rust_i18n::t; + +pub fn deeplink_setting_group() -> SettingGroup { + SettingGroup::new() + .title(t!("Settings.General.Deeplinks.group_title")) + .description(t!("Settings.General.Deeplinks.group_description")) + .items(vec![ + scheme_item( + "ssh", + t!("Settings.General.Deeplinks.ssh").to_string(), + t!("Settings.General.Deeplinks.ssh_desc").to_string(), + ), + scheme_item( + "sftp", + t!("Settings.General.Deeplinks.sftp").to_string(), + t!("Settings.General.Deeplinks.sftp_desc").to_string(), + ), + ]) +} + +fn scheme_item(scheme: &'static str, title: String, description: String) -> SettingItem { + SettingItem::new( + title, + SettingField::switch( + move |cx: &App| AppSettings::global(cx).deeplink_scheme_enabled(scheme), + move |enabled: bool, cx: &mut App| { + AppSettings::update_and_save(cx, |settings| { + settings.set_deeplink_scheme_enabled(scheme, enabled); + }); + // 开关变化后立即重写系统关联:启用会注册 scheme,停用会摘掉 + // 之前由 Navop 写过的键。 + crate::file_association::schedule_registration(cx); + cx.refresh_windows(); + }, + ) + .default_value(AppSettings::default().deeplink_scheme_enabled(scheme)), + ) + .description(description) +} diff --git a/crates/navop_app/src/settings/mod.rs b/crates/navop_app/src/settings/mod.rs index 63fee4d9f..11cac63f2 100644 --- a/crates/navop_app/src/settings/mod.rs +++ b/crates/navop_app/src/settings/mod.rs @@ -4,6 +4,7 @@ pub mod appearance; mod appearance_import; mod appearance_state; pub mod connection_display_settings; +pub mod deeplink_settings; pub mod llm_providers_view; mod mcp_agent_config_copy; pub mod mcp_client_config; diff --git a/crates/navop_app/src/toolbox_tab.rs b/crates/navop_app/src/toolbox_tab.rs index fb48885ca..b41e2635d 100644 --- a/crates/navop_app/src/toolbox_tab.rs +++ b/crates/navop_app/src/toolbox_tab.rs @@ -62,7 +62,7 @@ impl ExtensionTool { } } -/// 从全局 runtime catalog 读取工具箱里的扩展 app(没有连接的才有卡片)。 +/// 从全局 runtime catalog 读取工具箱里的扩展 app(无连接、无面板的才有卡片)。 pub(crate) fn extension_tools(cx: &App) -> Vec { // 没有 nsh 宿主时扩展 app 打不开,不展示只会弹警告的卡片。 if !crate::nsh_ui_available() { diff --git a/crates/port_forwarding/Cargo.toml b/crates/port_forwarding/Cargo.toml index c0cf15c11..86f9c4214 100644 --- a/crates/port_forwarding/Cargo.toml +++ b/crates/port_forwarding/Cargo.toml @@ -7,6 +7,7 @@ edition.workspace = true [dependencies] anyhow.workspace = true one-core.workspace = true +sftp_transfer.workspace = true ssh.workspace = true tokio.workspace = true diff --git a/crates/port_forwarding/src/runtime.rs b/crates/port_forwarding/src/runtime.rs index 5e7055c9d..f07a20793 100644 --- a/crates/port_forwarding/src/runtime.rs +++ b/crates/port_forwarding/src/runtime.rs @@ -4,15 +4,15 @@ use std::time::Duration; use anyhow::{Context, Result, bail}; use one_core::storage::{ - ConnectionType, PortForwardingKind, ProxyType as StorageProxyType, SshAuthMethod, SshParams, - StoredConnection, + ConnectionType, PortForwardingKind, SshAuthMethod, SshParams, StoredConnection, }; +use sftp_transfer::{jump_connect_config, proxy_connect_config, ssh_auth}; use ssh::{ AgentIdentity, DynamicSocksConfig, DynamicSocksTunnel, HostKeyVerifier, - JumpServerConnectConfig, LocalPortForwardActivity, LocalPortForwardConfig, - LocalPortForwardTunnel, ProxyConnectConfig, ProxyType, RemotePortForwardConfig, - RemotePortForwardTunnel, SshAuth, SshConnectConfig, start_dynamic_socks_forward, - start_local_port_forward_with_config, start_remote_port_forward_with_config, + LocalPortForwardActivity, LocalPortForwardConfig, LocalPortForwardTunnel, + RemotePortForwardConfig, RemotePortForwardTunnel, SshConnectConfig, + start_dynamic_socks_forward, start_local_port_forward_with_config, + start_remote_port_forward_with_config, }; pub struct LocalForwardingRequest { @@ -240,29 +240,12 @@ fn build_ssh_connect_config(params: &SshParams) -> SshConnectConfig { host: params.host.clone(), port: params.port, username: params.username.clone(), - auth: build_ssh_auth(¶ms.auth_method), + auth: ssh_auth(params.auth_method.clone()), timeout: params.connect_timeout.map(Duration::from_secs), keepalive_interval: params.keepalive_interval.map(Duration::from_secs), keepalive_max: params.keepalive_max, - jump_server: params - .jump_server - .as_ref() - .map(|jump| JumpServerConnectConfig { - host: jump.host.clone(), - port: jump.port, - username: jump.username.clone(), - auth: build_ssh_auth(&jump.auth_method), - }), - proxy: params.proxy.as_ref().map(|proxy| ProxyConnectConfig { - proxy_type: match proxy.proxy_type { - StorageProxyType::Socks5 => ProxyType::Socks5, - StorageProxyType::Http => ProxyType::Http, - }, - host: proxy.host.clone(), - port: proxy.port, - username: proxy.username.clone(), - password: proxy.password.clone(), - }), + jump_server: params.jump_server.as_ref().map(jump_connect_config), + proxy: params.proxy.as_ref().map(proxy_connect_config), keyboard_interactive_responder: None, host_key_verifier: HostKeyVerifier::default(), x11_forwarding: false, @@ -297,29 +280,3 @@ fn agent_identities_from_auth(auth: &SshAuthMethod) -> Vec { } } -fn build_ssh_auth(auth_method: &SshAuthMethod) -> SshAuth { - match auth_method { - SshAuthMethod::Password { password } => SshAuth::Password(password.clone()), - SshAuthMethod::PrivateKey { - key_path, - passphrase, - } => SshAuth::PrivateKey { - key_path: key_path.clone(), - passphrase: passphrase.clone(), - certificate_path: None, - }, - SshAuthMethod::PrivateKeyContent { - private_key, - passphrase, - } => SshAuth::PrivateKeyContent { - private_key: private_key.clone(), - passphrase: passphrase.clone(), - certificate_path: None, - }, - SshAuthMethod::Agent => SshAuth::Agent, - SshAuthMethod::Pageant => SshAuth::Pageant, - SshAuthMethod::AutoPublicKey => SshAuth::AutoPublicKey, - SshAuthMethod::None => SshAuth::None, - SshAuthMethod::Chain(steps) => SshAuth::Chain(steps.iter().map(build_ssh_auth).collect()), - } -} diff --git a/crates/redis-runtime/Cargo.toml b/crates/redis-runtime/Cargo.toml index d1b9e8564..652a0eb06 100644 --- a/crates/redis-runtime/Cargo.toml +++ b/crates/redis-runtime/Cargo.toml @@ -9,6 +9,7 @@ async-trait.workspace = true anyhow.workspace = true chrono.workspace = true futures.workspace = true +connection_tunnel.workspace = true one-core.workspace = true rust-i18n.workspace = true serde.workspace = true diff --git a/crates/redis-runtime/src/builtin.rs b/crates/redis-runtime/src/builtin.rs index 01f86073d..3577afc3a 100644 --- a/crates/redis-runtime/src/builtin.rs +++ b/crates/redis-runtime/src/builtin.rs @@ -9,7 +9,8 @@ use redis_client::aio::{ConnectionManager, ConnectionManagerConfig}; use redis_client::{AsyncCommands, Client, RedisResult}; use rust_i18n::t; use ssh::{ - HostKeyVerifier, LocalPortForwardTunnel, SshAuth, SshConnectConfig, start_local_port_forward, + BastionUserFormat, HostKeyVerifier, JumpMode, JumpServerConnectConfig, + LocalPortForwardTunnel, SshAuth, SshConnectConfig, start_local_port_forward, }; use std::collections::HashMap; use std::sync::Arc; @@ -80,6 +81,40 @@ fn required_ssh_value(value: &str, key: &str) -> Result { Ok(value.to_string()) } +/// 隧道继承的跳板配置 → 连接层配置(引用 SSH 连接带跳板时隧道也走跳板)。 +fn tunnel_jump_connect_config( + tunnel_config: &one_core::storage::RedisSshTunnelConfig, +) -> Option { + let jump = tunnel_config.jump.as_ref()?; + let auth = match jump.auth_type.trim().to_ascii_lowercase().as_str() { + "agent" => SshAuth::Agent, + "private_key" => SshAuth::PrivateKey { + key_path: jump.private_key_path.clone().unwrap_or_default(), + passphrase: jump.private_key_passphrase.clone(), + certificate_path: None, + }, + "private_key_content" => SshAuth::PrivateKeyContent { + private_key: jump.private_key_content.clone().unwrap_or_default(), + passphrase: jump.private_key_passphrase.clone(), + certificate_path: None, + }, + _ => SshAuth::Password(jump.password.clone().unwrap_or_default()), + }; + Some(JumpServerConnectConfig { + host: jump.host.clone(), + port: jump.port, + username: jump.username.clone(), + auth, + mode: match jump.mode { + connection_tunnel::TunnelJumpMode::ProxyJump => JumpMode::ProxyJump, + connection_tunnel::TunnelJumpMode::BastionDirect => JumpMode::BastionDirect, + }, + bastion_asset: jump.bastion_asset.clone().unwrap_or_default(), + bastion_account: jump.bastion_account.clone().unwrap_or_default(), + bastion_user_format: BastionUserFormat::JumpServer, + }) +} + fn build_ssh_auth( tunnel_config: &one_core::storage::RedisSshTunnelConfig, ) -> Result { @@ -454,7 +489,7 @@ impl RedisConnectionImpl { timeout: Some(Duration::from_secs(timeout_secs)), keepalive_interval: None, keepalive_max: None, - jump_server: None, + jump_server: tunnel_jump_connect_config(tunnel_config), proxy: None, keyboard_interactive_responder: None, host_key_verifier: HostKeyVerifier::default(), diff --git a/crates/redis_view/src/redis_form_window.rs b/crates/redis_view/src/redis_form_window.rs index 3a2c9e0d4..ff56648e6 100644 --- a/crates/redis_view/src/redis_form_window.rs +++ b/crates/redis_view/src/redis_form_window.rs @@ -536,6 +536,8 @@ impl RedisFormWindow { target_host: value.target_host, target_port: value.target_port, timeout: value.timeout, + jump: None, + proxy: None, }) } diff --git a/crates/remote_desktop_view/src/native_cursor.rs b/crates/remote_desktop_view/src/native_cursor.rs index 58656dcd5..4686887f3 100644 --- a/crates/remote_desktop_view/src/native_cursor.rs +++ b/crates/remote_desktop_view/src/native_cursor.rs @@ -32,11 +32,52 @@ mod windows { } pub(crate) fn hide() { + #[cfg(test)] + probe::record(probe::Call::Hide); #[cfg(target_os = "windows")] windows::hide(); } pub(crate) fn restore() { + #[cfg(test)] + probe::record(probe::Call::Restore); #[cfg(target_os = "windows")] windows::restore(); } + +/// Counts the `SetCursor` calls the remote desktop view makes, so tests can +/// assert who owns the OS cursor without a window server. +#[cfg(test)] +pub(crate) mod probe { + use std::cell::Cell; + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) enum Call { + Hide, + Restore, + } + + thread_local! { + static HIDES: Cell = const { Cell::new(0) }; + static RESTORES: Cell = const { Cell::new(0) }; + } + + pub(crate) fn record(call: Call) { + match call { + Call::Hide => HIDES.with(|count| count.set(count.get() + 1)), + Call::Restore => RESTORES.with(|count| count.set(count.get() + 1)), + } + } + + pub(crate) fn count(call: Call) -> usize { + match call { + Call::Hide => HIDES.with(Cell::get), + Call::Restore => RESTORES.with(Cell::get), + } + } + + pub(crate) fn reset() { + HIDES.with(|count| count.set(0)); + RESTORES.with(|count| count.set(0)); + } +} diff --git a/crates/remote_desktop_view/src/view/cursor.rs b/crates/remote_desktop_view/src/view/cursor.rs index 6ae6caee0..d41c52e00 100644 --- a/crates/remote_desktop_view/src/view/cursor.rs +++ b/crates/remote_desktop_view/src/view/cursor.rs @@ -60,6 +60,15 @@ pub(super) struct RemoteCursorState { mode: RemoteCursorMode, pointer_hovered: bool, manage_native_cursor: bool, + /// Whether navop currently drives the OS cursor at all. + /// + /// Only the canvas presentation paints the remote cursor on the GPUI + /// canvas, so only that path may call `SetCursor`. A Windows native + /// (mstscax) session draws its own session pointer and sets the cursor + /// itself; re-applying the GPUI arrow from this process fights the control + /// and makes the visible cursor flip between the local arrow and the + /// remote one, which also makes remote window borders impossible to aim at. + native_cursor_owned: bool, } impl RemoteCursorState { @@ -70,6 +79,29 @@ impl RemoteCursorState { } } + /// Transfers OS cursor ownership to or from the session presentation. + /// + /// The view calls this once per frame with `!uses_windows_native()`. Giving + /// the cursor up only undoes a hide this state actually applied; the + /// receiving presentation owns the cursor from then on. + pub(super) fn set_native_cursor_owned(&mut self, owned: bool) { + if self.native_cursor_owned == owned { + return; + } + self.native_cursor_owned = owned; + if owned { + self.sync_native_cursor(); + } else if self.manage_native_cursor + && should_hide_native_cursor( + self.mode, + self.pointer_hovered, + self.has_paintable_bitmap(), + ) + { + native_cursor::restore(); + } + } + pub(super) fn install(&mut self, cursor: RemoteDesktopCursor) -> anyhow::Result<()> { self.latest = Some(RemoteCursorImage::new(cursor)?); self.mode = RemoteCursorMode::Bitmap; @@ -116,6 +148,7 @@ impl RemoteCursorState { pub(super) fn rehide_native_cursor_after_pointer_move(&self) { if self.manage_native_cursor + && self.native_cursor_owned && should_hide_native_cursor( self.mode, self.pointer_hovered, @@ -179,7 +212,7 @@ impl RemoteCursorState { self.position = None; self.mode = RemoteCursorMode::Default; self.pointer_hovered = false; - if self.manage_native_cursor { + if self.manage_native_cursor && self.native_cursor_owned { native_cursor::restore(); } cursors.into_iter().map(|cursor| cursor.image).collect() @@ -194,6 +227,11 @@ impl RemoteCursorState { if !self.manage_native_cursor { return; } + if !self.native_cursor_owned { + // A Windows native (mstscax) session sets and draws its own session + // pointer. Touching the OS cursor here would undo it on every frame. + return; + } if should_hide_native_cursor(self.mode, self.pointer_hovered, self.has_paintable_bitmap()) { native_cursor::hide(); } else { diff --git a/crates/remote_desktop_view/src/view/cursor_tests.rs b/crates/remote_desktop_view/src/view/cursor_tests.rs index f6e7fac3c..0da298237 100644 --- a/crates/remote_desktop_view/src/view/cursor_tests.rs +++ b/crates/remote_desktop_view/src/view/cursor_tests.rs @@ -141,3 +141,66 @@ fn native_cursor_management_is_opt_in_for_rdp_only() { assert!(!RemoteCursorState::default().manage_native_cursor); assert!(RemoteCursorState::new(true).manage_native_cursor); } + +/// Regression: a Windows native (mstscax) session draws and sets its own +/// session pointer. The view must not touch the OS cursor there — doing so on +/// every frame made the visible cursor flip between the local arrow and the +/// remote cursor (e.g. the resize arrow on a remote window border). +#[test] +fn native_presentation_does_not_touch_the_os_cursor() { + use crate::native_cursor::probe::{Call, count, reset}; + + reset(); + let mut state = RemoteCursorState::new(true); + state.set_native_cursor_owned(true); + state.install(cursor(1)).unwrap(); + state.set_pointer_hovered(true); + state.set_position(25, 40); + state.promote_latest(); + let painted_while_owned = count(Call::Hide); + + // Hand the cursor over to the native presentation, then keep driving the + // state exactly like an active session does. + state.set_native_cursor_owned(false); + reset(); + state.promote_latest(); + state.show_default(); + state.hide(); + state.set_position(26, 41); + state.set_pointer_hovered(false); + state.reset_session(); + + assert!( + painted_while_owned > 0, + "the canvas presentation must hide the OS cursor it replaces" + ); + assert_eq!( + 0, + count(Call::Hide) + count(Call::Restore), + "a Windows native session owns the OS cursor; navop must not call SetCursor" + ); +} + +#[test] +fn handing_the_os_cursor_back_only_undoes_a_hide_navop_applied() { + use crate::native_cursor::probe::{Call, count, reset}; + + // Nothing was hidden, so giving the cursor up must not touch it. Taking + // ownership first adopts the current state for the canvas presentation, + // so reset after that to isolate the hand-back. + let mut state = RemoteCursorState::new(true); + state.set_native_cursor_owned(true); + reset(); + state.set_native_cursor_owned(false); + assert_eq!(0, count(Call::Restore)); + + // A hidden cursor must be restored before the native presentation takes over. + state.set_native_cursor_owned(true); + state.install(cursor(1)).unwrap(); + state.set_pointer_hovered(true); + state.set_position(25, 40); + state.promote_latest(); + reset(); + state.set_native_cursor_owned(false); + assert_eq!(1, count(Call::Restore)); +} diff --git a/crates/remote_desktop_view/src/view/render.rs b/crates/remote_desktop_view/src/view/render.rs index 383ed2653..bf39ad2c7 100644 --- a/crates/remote_desktop_view/src/view/render.rs +++ b/crates/remote_desktop_view/src/view/render.rs @@ -402,6 +402,14 @@ impl Render for RemoteDesktopView { ); } } + // Re-evaluated every frame because the presentation path can still fall + // back: only the canvas presentation paints the remote cursor, so only + // it may own the OS cursor. A Windows native (mstscax) session draws + // and sets its own session pointer, and re-applying the GPUI arrow from + // here makes the visible cursor flip between the local arrow and the + // remote one. + let uses_windows_native = self.uses_windows_native_presentation(); + self.cursor.set_native_cursor_owned(!uses_windows_native); if let Some(retired) = self.cursor.promote_latest() && let Err(error) = window.drop_image(retired) { @@ -413,7 +421,6 @@ impl Render for RemoteDesktopView { frame: rendered_frame, cursor: self.cursor.paint_state(self.remote_size), }; - let uses_windows_native = self.uses_windows_native_presentation(); let failure_detail = self.failure_detail.clone(); let show_failure_detail = failure_detail.is_some(); let presentation_initialization = self.presentation_initialization; diff --git a/crates/remote_image_preview/Cargo.toml b/crates/remote_image_preview/Cargo.toml index caf3f65fa..37f811c83 100644 --- a/crates/remote_image_preview/Cargo.toml +++ b/crates/remote_image_preview/Cargo.toml @@ -8,6 +8,7 @@ edition.workspace = true anyhow = { workspace = true } gpui = { workspace = true } gpui-component = { workspace = true } +image.workspace = true one-core = { workspace = true } rust-i18n = { workspace = true } sftp = { workspace = true } diff --git a/crates/remote_image_preview/src/lib.rs b/crates/remote_image_preview/src/lib.rs index 1d29a1425..de573e63e 100644 --- a/crates/remote_image_preview/src/lib.rs +++ b/crates/remote_image_preview/src/lib.rs @@ -16,7 +16,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::time::{SystemTime, UNIX_EPOCH}; const MAX_REMOTE_IMAGE_PREVIEW_BYTES: usize = 25 * 1024 * 1024; -const CLIPBOARD_UPLOAD_IMAGE_PREFIX: &str = "onetcli-clipboard-upload"; +const CLIPBOARD_UPLOAD_IMAGE_PREFIX: &str = "navop-clipboard-upload"; static CLIPBOARD_UPLOAD_IMAGE_SEQUENCE: AtomicU64 = AtomicU64::new(0); @@ -170,7 +170,38 @@ fn image_format_extension(format: ImageFormat) -> &'static str { } } +/// 把剪贴板图片统一成远端普遍能读的标准格式。 +/// +/// macOS 截图写进剪贴板的是 TIFF,Windows 的位图常见 BMP;这些格式落到远端后 +/// CLI(Claude Code、图片查看器等)往往直接拒收。这里把 png/jpeg/webp/gif +/// 之外的位图重编码为 PNG,解码失败时原样返回,保证上传不会因转换而失败。 +pub fn normalize_clipboard_image(image: Image) -> Image { + if matches!( + image.format, + ImageFormat::Png | ImageFormat::Jpeg | ImageFormat::Webp | ImageFormat::Gif + ) { + return image; + } + + let Ok(decoded) = image::load_from_memory(&image.bytes) else { + return image; + }; + + let mut bytes = Vec::new(); + { + let mut cursor = std::io::Cursor::new(&mut bytes); + if decoded + .write_to(&mut cursor, image::ImageFormat::Png) + .is_err() + { + return image; + } + } + Image::from_bytes(ImageFormat::Png, bytes) +} + fn write_clipboard_image_to_temp_file(image: &Image) -> anyhow::Result { + let image = normalize_clipboard_image(image.clone()); let path = temp_clipboard_image_path(image.format); std::fs::write(&path, &image.bytes).with_context(|| { t!( @@ -314,6 +345,64 @@ mod tests { assert_eq!(vec![first, second], upload_paths.paths); } + #[test] + fn clipboard_upload_paths_reencodes_tiff_to_png() { + let pixels = image::ImageBuffer::from_fn(8, 6, |x, y| { + image::Rgba([(x * 9) as u8, (y * 11) as u8, 200, 255]) + }); + let mut encoded = std::io::Cursor::new(Vec::new()); + image::DynamicImage::ImageRgba8(pixels) + .write_to(&mut encoded, image::ImageFormat::Tiff) + .expect("fixture TIFF should encode"); + let tiff_bytes = encoded.into_inner(); + assert_eq!( + image::guess_format(&tiff_bytes).expect("fixture format should be detectable"), + image::ImageFormat::Tiff + ); + + let item = ClipboardItem::new_image(&Image::from_bytes(ImageFormat::Tiff, tiff_bytes)); + + let upload_paths = + super::clipboard_upload_paths(&item).expect("clipboard image should be written"); + + assert_eq!(1, upload_paths.paths.len()); + let path = &upload_paths.paths[0]; + assert_eq!(Some("png"), path.extension().and_then(|ext| ext.to_str())); + assert!( + path.file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.starts_with("navop-clipboard-upload-")), + "临时文件应使用产品前缀: {}", + path.display() + ); + let written = std::fs::read(path).expect("read temp image"); + assert_eq!( + image::guess_format(&written).expect("temp image should be a real image"), + image::ImageFormat::Png + ); + let _ = std::fs::remove_file(path); + } + + #[test] + fn normalize_clipboard_image_keeps_standard_formats_untouched() { + let bytes = vec![1, 2, 3]; + let image = + super::normalize_clipboard_image(Image::from_bytes(ImageFormat::Png, bytes.clone())); + + assert_eq!(ImageFormat::Png, image.format); + assert_eq!(bytes, image.bytes); + } + + #[test] + fn normalize_clipboard_image_falls_back_when_bytes_do_not_decode() { + let bytes = vec![0x49, 0x49, 0x2a, 0x00, 0x01]; + let image = + super::normalize_clipboard_image(Image::from_bytes(ImageFormat::Tiff, bytes.clone())); + + assert_eq!(ImageFormat::Tiff, image.format); + assert_eq!(bytes, image.bytes); + } + #[test] fn clipboard_upload_paths_writes_image_to_temp_file() { let item = ClipboardItem::new_image(&Image::from_bytes(ImageFormat::Png, vec![1, 2, 3])); diff --git a/crates/runtime_sftp/Cargo.toml b/crates/runtime_sftp/Cargo.toml index ff0351dc8..179b2658b 100644 --- a/crates/runtime_sftp/Cargo.toml +++ b/crates/runtime_sftp/Cargo.toml @@ -7,6 +7,7 @@ publish = false [dependencies] base64.workspace = true one-core.workspace = true +sftp_transfer.workspace = true serde_json.workspace = true sftp.workspace = true ssh.workspace = true diff --git a/crates/runtime_sftp/src/sftp_tools.rs b/crates/runtime_sftp/src/sftp_tools.rs index 48d0eae37..2604df487 100644 --- a/crates/runtime_sftp/src/sftp_tools.rs +++ b/crates/runtime_sftp/src/sftp_tools.rs @@ -4,15 +4,12 @@ mod tests; use base64::{Engine as _, engine::general_purpose}; use one_core::storage::traits::Repository; use one_core::storage::{ - ConnectionRepository, ConnectionType, JumpServerConfig, ProxyConfig, - ProxyType as StorageProxyType, SshAuthMethod, SshParams, StoredConnection, + ConnectionRepository, ConnectionType, SshAuthMethod, SshParams, StoredConnection, }; use serde_json::{Value, json}; use sftp::{DirectoryConflictPolicy, RemoteFileClient, RusshSftpClient, SftpClient}; -use ssh::{ - AgentIdentity, HostKeyVerifier, JumpServerConnectConfig, ProxyConnectConfig, ProxyType, - SshAuth, SshConnectConfig, -}; +use sftp_transfer::{jump_connect_config, proxy_connect_config, ssh_auth}; +use ssh::{AgentIdentity, HostKeyVerifier, SshAuth, SshConnectConfig}; use std::path::Path; use std::sync::Arc; use std::sync::atomic::AtomicBool; @@ -253,7 +250,7 @@ fn ssh_config_from_params(params: &SshParams) -> SshConnectConfig { ), _ => ( params.username.clone(), - auth_from_method(¶ms.auth_method), + ssh_auth(params.auth_method.clone()), ), }; SshConnectConfig { @@ -264,8 +261,8 @@ fn ssh_config_from_params(params: &SshParams) -> SshConnectConfig { timeout: params.connect_timeout.map(Duration::from_secs), keepalive_interval: params.keepalive_interval.map(Duration::from_secs), keepalive_max: params.keepalive_max, - jump_server: params.jump_server.as_ref().map(jump_config), - proxy: params.proxy.as_ref().map(proxy_config), + jump_server: params.jump_server.as_ref().map(jump_connect_config), + proxy: params.proxy.as_ref().map(proxy_connect_config), keyboard_interactive_responder: None, host_key_verifier: HostKeyVerifier::default(), x11_forwarding: false, @@ -300,55 +297,8 @@ fn agent_identities_from_auth(auth: &SshAuthMethod) -> Vec { } } -fn auth_from_method(auth: &SshAuthMethod) -> SshAuth { - match auth { - SshAuthMethod::Password { password } => SshAuth::Password(password.clone()), - SshAuthMethod::PrivateKey { - key_path, - passphrase, - } => SshAuth::PrivateKey { - key_path: key_path.clone(), - passphrase: passphrase.clone(), - certificate_path: None, - }, - SshAuthMethod::PrivateKeyContent { - private_key, - passphrase, - } => SshAuth::PrivateKeyContent { - private_key: private_key.clone(), - passphrase: passphrase.clone(), - certificate_path: None, - }, - SshAuthMethod::Agent => SshAuth::Agent, - SshAuthMethod::Pageant => SshAuth::Pageant, - SshAuthMethod::AutoPublicKey => SshAuth::AutoPublicKey, - SshAuthMethod::None => SshAuth::None, - SshAuthMethod::Chain(steps) => SshAuth::Chain(steps.iter().map(auth_from_method).collect()), - } -} -fn jump_config(jump: &JumpServerConfig) -> JumpServerConnectConfig { - JumpServerConnectConfig { - host: jump.host.clone(), - port: jump.port, - username: jump.username.clone(), - auth: auth_from_method(&jump.auth_method), - } -} -fn proxy_config(proxy: &ProxyConfig) -> ProxyConnectConfig { - let proxy_type = match proxy.proxy_type { - StorageProxyType::Socks5 => ProxyType::Socks5, - StorageProxyType::Http => ProxyType::Http, - }; - ProxyConnectConfig { - proxy_type, - host: proxy.host.clone(), - port: proxy.port, - username: proxy.username.clone(), - password: proxy.password.clone(), - } -} fn file_entry_json(entry: sftp::FileEntry) -> Value { let modified_unix_secs = entry diff --git a/crates/sftp/Cargo.toml b/crates/sftp/Cargo.toml index 1756f7eb0..2caa76edb 100644 --- a/crates/sftp/Cargo.toml +++ b/crates/sftp/Cargo.toml @@ -24,4 +24,6 @@ zeroize = { workspace = true } workspace = true [dev-dependencies] +tokio = { workspace = true, features = ["test-util"] } tempfile = "3" +rand = "0.10" diff --git a/crates/sftp/src/lib.rs b/crates/sftp/src/lib.rs index 421a2e2f8..3af51b013 100644 --- a/crates/sftp/src/lib.rs +++ b/crates/sftp/src/lib.rs @@ -103,23 +103,31 @@ impl std::error::Error for TransferCancelled {} pub type ProgressCallback = Box; -/// Whether a server-provided directory entry can be used as one local path -/// component without escaping its parent directory. +/// 服务端返回的单个目录项名是否可以当作「一层远程路径」使用。 /// -/// SFTP servers control the raw `filename` bytes in `SSH_FXP_NAME`. Even -/// though a normal POSIX server cannot put `/` in a filename, a malicious -/// server can return values such as `../outside.txt`. Validate every entry -/// before path construction; components are deliberately rejected on every -/// platform so a listing cannot become traversal after transferring between -/// Unix and Windows. +/// SFTP 服务端完全控制 `SSH_FXP_NAME` 里的 filename 字节,恶意服务端可以返回 +/// `../outside.txt` 这类值,所以这里只接受单层名称:非空、不是 `.` / `..`、 +/// 不含 `/`、`\`、NUL。 +/// +/// 这个判断必须与客户端操作系统无关:`c:`、`a:b` 在 Linux 服务器上是合法 +/// 文件名,用 Windows 的路径语义去判会把整个目录判成不可读。 +/// 需要拼成本地路径时改用 [`is_valid_local_file_name`]。 pub fn is_valid_remote_entry_name(name: &str) -> bool { - if name.is_empty() + !(name.is_empty() || name == "." || name == ".." || name.contains('/') || name.contains('\\') - || name.contains('\0') - { + || name.contains('\0')) +} + +/// 远程名字拼接到本地目录后,是否仍然只解析出「父目录下的一个普通文件名」。 +/// +/// Windows 上 `base.join("c:")` 会变成盘符相对路径、`base.join("c:foo")` +/// 会丢掉整段基路径,所以真正落盘前必须额外拒绝盘符前缀形态; +/// 其他平台上这个判断与 [`is_valid_remote_entry_name`] 等价。 +pub fn is_valid_local_file_name(name: &str) -> bool { + if !is_valid_remote_entry_name(name) { return false; } @@ -344,7 +352,9 @@ impl RemoteFileClient for Box { #[cfg(test)] mod tests { - use super::{FileEntry, is_valid_remote_entry_name, validate_read_size}; + use super::{ + FileEntry, is_valid_local_file_name, is_valid_remote_entry_name, validate_read_size, + }; use std::time::SystemTime; fn file_entry(user: Option<&str>, uid: Option) -> FileEntry { @@ -404,12 +414,64 @@ mod tests { } } + #[test] + fn remote_entry_name_validation_accepts_posix_names_with_colons() { + // Linux 服务器上的 `c:`、`c:foo` 是合法文件名:远程列举绝不能 + // 因为客户端跑在 Windows 上就把它们判成非法。 + for name in ["c:", "c:foo", "a:b"] { + assert!( + is_valid_remote_entry_name(name), + "{name:?} is a legal POSIX file name and must stay listable" + ); + } + } + + #[test] + fn local_file_name_validation_accepts_ordinary_names() { + for name in ["notes.txt", "folder", "archive.tar.gz", "文件名.txt"] { + assert!( + is_valid_local_file_name(name), + "{name:?} must be safe to join onto a local directory" + ); + } + } + + #[test] + fn local_file_name_validation_rejects_traversal() { + for name in ["", ".", "..", "../outside.txt", "a/b", "..\\outside.txt"] { + assert!( + !is_valid_local_file_name(name), + "{name:?} must not be joined onto a local directory" + ); + } + } + #[cfg(windows)] #[test] - fn remote_entry_name_validation_rejects_windows_prefixes() { - assert!(!is_valid_remote_entry_name("C:outside.txt")); - assert!(!is_valid_remote_entry_name(r"C:\outside.txt")); - assert!(!is_valid_remote_entry_name(r"\\server\share\outside.txt")); + fn local_file_name_validation_rejects_windows_drive_prefixes() { + // Windows 上 `join("c:")` 会解析成盘符相对路径,落盘前必须拒绝。 + for name in ["c:", "C:", "c:outside.txt", "C:outside.txt"] { + assert!( + is_valid_remote_entry_name(name), + "{name:?} can still be listed as a remote entry" + ); + assert!( + !is_valid_local_file_name(name), + "{name:?} must not be used as a local file name on Windows" + ); + } + assert!(!is_valid_local_file_name(r"\\server\share\outside.txt")); + } + + #[cfg(not(windows))] + #[test] + fn local_file_name_validation_accepts_colons_outside_windows() { + for name in ["c:", "c:foo", "a:b"] { + assert!( + is_valid_local_file_name(name), + "{name:?} cannot escape the parent directory on this platform" + ); + } } #[test] diff --git a/crates/sftp/src/russh_impl.rs b/crates/sftp/src/russh_impl.rs index 5f0efb671..e93782efc 100644 --- a/crates/sftp/src/russh_impl.rs +++ b/crates/sftp/src/russh_impl.rs @@ -4,8 +4,8 @@ use crate::upload_batch::{ }; use crate::{ DirectoryConflictPolicy, FileEntry, PathMetadata, ProgressCallback, RemoteFileClient, - SftpClient, TransferCancelled, TransferProgress, is_valid_remote_entry_name, - validate_read_size, + SftpClient, TransferCancelled, TransferProgress, is_valid_local_file_name, + is_valid_remote_entry_name, validate_read_size, }; use anyhow::{Result, anyhow}; use async_trait::async_trait; @@ -22,8 +22,9 @@ use russh_sftp::protocol::{FileAttributes, OpenFlags, StatusCode}; use rust_i18n::t; use ssh::{ AuthFailureMessages, HostKeyAcceptance, HostKeyDetails, HostKeyIdentity, HostKeyVerifier, - ProxyConnectConfig, ProxyType, RusshClient, SshConnectConfig, add_legacy_algorithm_hint, - authenticate_with_strategy, build_client_preferred_algorithms_with_legacy, defaults, + KeyboardInteractiveTarget, ProxyConnectConfig, ProxyType, RusshClient, SshConnectConfig, + add_jump_channel_rejected_hint, add_legacy_algorithm_hint, authenticate_with_strategy, + authenticate_with_strategy_for_target, build_client_preferred_algorithms_with_legacy, defaults, }; use std::collections::{BTreeMap, BTreeSet}; use std::future::Future; @@ -78,6 +79,48 @@ const SHARED_MAX_CONCURRENT_READS: usize = 8; const OWNER_LOOKUP_BATCH_SIZE: usize = 128; const OWNER_LOOKUP_TIMEOUT: Duration = Duration::from_secs(3); +/// 目录枚举的超时上限。 +/// +/// 堡垒机和限流网络下 `read_dir` 可能长时间不返回:没有上限时文件面板会一直转圈, +/// MCP 那条连接还会因为被拖住而整条关掉(表现为「Navop MCP connection closed」)。 +const DIRECTORY_LIST_TIMEOUT: Duration = Duration::from_secs(30); + +/// 给目录枚举套一层超时,超时后给出可读的提示而不是静默挂死。 +async fn with_directory_list_timeout(path: &str, future: F) -> Result +where + F: Future>, +{ + match tokio::time::timeout(DIRECTORY_LIST_TIMEOUT, future).await { + Ok(result) => result, + Err(_) => Err(anyhow!("{}", directory_list_timeout_message(path))), + } +} + +fn directory_list_timeout_message(path: &str) -> String { + format!( + "列出目录 {path} 超时:{} 秒内没有收到服务器响应(堡垒机限流或目录过大),请稍后重试", + DIRECTORY_LIST_TIMEOUT.as_secs() + ) +} + +/// 把 SFTP 列目录失败翻译成用户能采取动作的话。 +/// +/// 堡垒机直连时 JumpServer 会把 SFTP 会话的根目录限制在资产的「文件管理根目录」, +/// 根目录之外的路径会被服务端回 `No such file`(不是 permission denied),直接 +/// 透传会让用户以为文件真的不存在。 +fn describe_list_dir_error(path: &str, bastion_direct: bool, error: &str) -> String { + if !error.contains("No such file") { + return format!("Failed to read directory {path}: {error}"); + } + if bastion_direct { + format!( + "堡垒机只开放了受限的 SFTP 根目录,{path} 不在其中:JumpServer 把会话限制在资产的「文件管理根目录」(常见为 /tmp),会话里能列出的根目录 / 就是它。请在根目录 / 内操作,或请管理员把「文件管理根目录」改成你要浏览的路径" + ) + } else { + format!("Failed to read directory {path}: 目录不存在或没有访问权限") + } +} + /// SFTP 会话独占这条 SSH 连接,还是与交互终端共用。 #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum SftpTransport { @@ -193,9 +236,11 @@ fn remote_download_root(remote_path: &str) -> &str { } } -/// Convert an SFTP entry path into a relative local path made only from -/// validated single-component names. `strip_prefix` is deliberately followed -/// by a component check because it is lexical and does not resolve `..`. +/// 把 SFTP 条目路径转换成「只由合法单层名字组成」的本机相对路径。 +/// +/// `strip_prefix` 是纯词法操作、不解析 `..`,所以切割后还要逐分量复核; +/// 这里用 [`is_valid_local_file_name`] 而不是远程名字校验,因为 Windows 上 +/// `join("c:")` 会解析成盘符相对路径,落盘前必须拒绝这种形态。 fn remote_download_relative_path(base_remote: &str, entry_path: &str) -> Result { let relative = strip_remote_download_root(base_remote, entry_path)?; if relative.is_empty() { @@ -204,7 +249,7 @@ fn remote_download_relative_path(base_remote: &str, entry_path: &str) -> Result< let mut safe_path = PathBuf::new(); for component in relative.split('/') { - if component.is_empty() || !is_valid_remote_entry_name(component) { + if !is_valid_local_file_name(component) { return Err(anyhow!( "Refusing unsafe remote entry path: {:?}", entry_path @@ -1282,6 +1327,8 @@ struct SftpHandler { identity: HostKeyIdentity, host_key_verifier: HostKeyVerifier, accepted_server_public_key: Option>>>, + /// 最近一次 CHANNEL_OPEN_FAILURE 的服务器侧描述(russh 错误链只保留原因码枚举)。 + last_open_failure: Option>>>, } impl SftpHandler { @@ -1290,6 +1337,7 @@ impl SftpHandler { identity, host_key_verifier, accepted_server_public_key: None, + last_open_failure: None, } } @@ -1302,8 +1350,18 @@ impl SftpHandler { identity, host_key_verifier, accepted_server_public_key: Some(accepted_server_public_key), + last_open_failure: None, } } + + /// 附带共享槽位,捕获服务器拒绝通道时回传的描述文本。 + fn with_open_failure_capture( + mut self, + slot: Arc>>, + ) -> Self { + self.last_open_failure = Some(slot); + self + } } impl client::Handler for SftpHandler { @@ -1367,6 +1425,31 @@ impl client::Handler for SftpHandler { } Ok(true) } + + /// 服务器拒绝通道打开请求时的回调:把被 russh 丢弃的描述文本记录到共享槽位。 + async fn channel_open_failure( + &mut self, + channel: russh::ChannelId, + reason: russh::ChannelOpenFailure, + description: &str, + _language: &str, + _session: &mut client::Session, + ) -> Result<(), Self::Error> { + tracing::warn!( + target: "ssh.channel", + identity = %self.identity, + channel = ?channel, + reason = ?reason, + description = %description, + "SFTP: SSH 服务器拒绝打开通道" + ); + if let Some(slot) = &self.last_open_failure { + if let Ok(mut guard) = slot.lock() { + *guard = Some((reason, description.to_string())); + } + } + Ok(()) + } } fn sftp_auth_failure_messages() -> AuthFailureMessages { @@ -1562,6 +1645,9 @@ pub struct RusshSftpClient { raw_sftp: Option>, owner_names: BTreeMap>, owner_lookup_disabled: bool, + /// 会话是否走「堡垒机直连」(会话即堡垒机,SFTP 根目录由 JumpServer 的 + /// 「文件管理根目录」决定)。用于把「路径不存在」翻译成用户能行动的话。 + bastion_direct: bool, } impl RusshSftpClient { @@ -1574,13 +1660,15 @@ impl RusshSftpClient { raw_sftp, owner_names: BTreeMap::new(), owner_lookup_disabled: false, + bastion_direct: false, } } pub async fn connect_with_client(client: Arc>) -> Result { - let channel = { + let (channel, bastion_direct) = { let mut guard = client.lock().await; - guard.open_raw_channel().await? + let bastion_direct = guard.is_bastion_direct(); + (guard.open_raw_channel().await?, bastion_direct) }; channel.request_subsystem(true, "sftp").await?; let sftp = SftpSession::new_with_config( @@ -1596,6 +1684,7 @@ impl RusshSftpClient { raw_sftp: None, owner_names: BTreeMap::new(), owner_lookup_disabled: false, + bastion_direct, }) } @@ -2350,6 +2439,83 @@ fn build_sftp_russh_config( })) } +impl RusshSftpClient { + async fn list_dir_untimed( + &mut self, + path: &str, + bastion_direct: bool, + ) -> Result> { + let dir_entries = self.sftp.read_dir(path).await.map_err(|e| { + anyhow!( + "{}", + describe_list_dir_error(path, bastion_direct, &e.to_string()) + ) + })?; + + let mut entries = Vec::new(); + + for entry in dir_entries { + let file_name = entry.file_name(); + + if file_name == "." || file_name == ".." { + continue; + } + if !is_valid_remote_entry_name(&file_name) { + // 服务端可以返回 `../outside.txt`、`a/b` 这类非单层名字。 + // 跳过该条目即可,不能让一个坏条目毁掉整个目录浏览 + // (真正落盘前 `remote_download_relative_path` 会再校验)。 + tracing::warn!( + directory = path, + entry = %file_name, + "跳过无法作为单层远程路径的 SFTP 目录项" + ); + continue; + } + + let metadata = entry.metadata(); + let size = metadata.size.unwrap_or(0); + let is_dir = metadata.is_dir(); + let permissions = metadata.permissions.unwrap_or(0); + let uid = metadata.uid; + let gid = metadata.gid; + let user = metadata.user.clone(); + let group = metadata.group.clone(); + + let modified = metadata + .mtime + .and_then(|mtime| UNIX_EPOCH.checked_add(Duration::from_secs(mtime as u64))) + .unwrap_or_else(SystemTime::now); + + entries.push(FileEntry { + name: file_name.clone(), + path: file_name, + size, + modified, + is_dir, + permissions, + uid, + gid, + user, + group, + }); + } + + self.resolve_entry_owners(&mut entries).await; + + entries.sort_by(|a, b| { + if a.is_dir == b.is_dir { + a.name.to_lowercase().cmp(&b.name.to_lowercase()) + } else if a.is_dir { + std::cmp::Ordering::Less + } else { + std::cmp::Ordering::Greater + } + }); + + Ok(entries) + } +} + #[async_trait] impl SftpClient for RusshSftpClient { async fn connect(ssh_config: SshConnectConfig) -> Result { @@ -2371,56 +2537,121 @@ impl SftpClient for RusshSftpClient { let jump_russh_config = jump_russh_config .clone() .expect("jump config must exist when jump server is configured"); + // 捕获跳板机在 CHANNEL_OPEN_FAILURE 里回传的描述文本。 + let open_failure_slot = Arc::new(StdMutex::new(None)); + + // 堡垒机直连(BastionDirect):目标会话就是堡垒机会话本身, + // 用户名按预设格式渲染(如 JumpServer 的 user#account#asset), + // 不开 direct-tcpip——直连型堡垒机按策略禁用端口转发, + // SFTP 子系统由堡垒机代理到资产(Koko DirectConnectSftpMode)。 + if let Some(bastion_username) = jump.bastion_login_username() { + tracing::info!( + "SFTP: 堡垒机直连模式,以渲染用户名登录 {}:{}", + jump.host, + jump.port + ); + let handler = SftpHandler::with_server_public_key_capture( + jump_identity, + host_key_verifier.clone(), + accepted_server_public_key.clone(), + ); + let mut session = if let Some(ref proxy) = ssh_config.proxy { + let stream = sftp_connect_via_proxy(proxy, &jump.host, jump.port).await?; + client::connect_stream(jump_russh_config, stream, handler) + .await + .map_err(|error| { + add_legacy_algorithm_hint(error, ssh_config.allow_legacy_algorithms) + })? + } else { + client::connect(jump_russh_config, (jump.host.as_str(), jump.port), handler) + .await + .map_err(|error| { + add_legacy_algorithm_hint(error, ssh_config.allow_legacy_algorithms) + })? + }; - // 连接跳板机 - let mut jump_session = if let Some(ref proxy) = ssh_config.proxy { - tracing::info!("SFTP: 通过代理 {}:{} 连接跳板机", proxy.host, proxy.port); - let stream = sftp_connect_via_proxy(proxy, &jump.host, jump.port).await?; - let handler = SftpHandler::new(jump_identity, host_key_verifier.clone()); - client::connect_stream(jump_russh_config, stream, handler) - .await - .map_err(|error| { - add_legacy_algorithm_hint(error, ssh_config.allow_legacy_algorithms) - })? - } else { - let handler = SftpHandler::new(jump_identity, host_key_verifier.clone()); - client::connect(jump_russh_config, (jump.host.as_str(), jump.port), handler) - .await - .map_err(|error| { - add_legacy_algorithm_hint(error, ssh_config.allow_legacy_algorithms) - })? - }; + // 认证堡垒机(会话即目标:SFTP 子系统跑在这条会话上) + authenticate_with_strategy_for_target( + &mut session, + &bastion_username, + &jump.auth, + sftp_auth_failure_messages(), + KeyboardInteractiveTarget::JumpServer, + ssh_config.keyboard_interactive_responder.clone(), + ) + .await?; - // 认证跳板机 - authenticate_with_strategy( - &mut jump_session, - &jump.username, - &jump.auth, - sftp_auth_failure_messages(), - ) - .await?; + (session, None) + } else { + // 连接跳板机 + let mut jump_session = if let Some(ref proxy) = ssh_config.proxy { + tracing::info!("SFTP: 通过代理 {}:{} 连接跳板机", proxy.host, proxy.port); + let stream = sftp_connect_via_proxy(proxy, &jump.host, jump.port).await?; + let handler = SftpHandler::new(jump_identity, host_key_verifier.clone()) + .with_open_failure_capture(Arc::clone(&open_failure_slot)); + client::connect_stream(jump_russh_config, stream, handler) + .await + .map_err(|error| { + add_legacy_algorithm_hint(error, ssh_config.allow_legacy_algorithms) + })? + } else { + let handler = SftpHandler::new(jump_identity, host_key_verifier.clone()) + .with_open_failure_capture(Arc::clone(&open_failure_slot)); + client::connect(jump_russh_config, (jump.host.as_str(), jump.port), handler) + .await + .map_err(|error| { + add_legacy_algorithm_hint(error, ssh_config.allow_legacy_algorithms) + })? + }; - // 通过跳板机转发到目标服务器 - let forwarded_channel = jump_session - .channel_open_direct_tcpip(&ssh_config.host, ssh_config.port as u32, "127.0.0.1", 0) + // 认证跳板机(与 ssh.rs 终端路径一致:携带 keyboard-interactive 响应器, + // 支持跳板机 MFA/OTP,并按跳板机目标归类认证失败提示) + authenticate_with_strategy_for_target( + &mut jump_session, + &jump.username, + &jump.auth, + sftp_auth_failure_messages(), + KeyboardInteractiveTarget::JumpServer, + ssh_config.keyboard_interactive_responder.clone(), + ) .await?; - let handler = SftpHandler::with_server_public_key_capture( - target_host_key_identity.clone(), - host_key_verifier.clone(), - accepted_server_public_key.clone(), - ); - let session = client::connect_stream( - target_russh_config, - forwarded_channel.into_stream(), - handler, - ) - .await - .map_err(|error| { - add_legacy_algorithm_hint(error, ssh_config.allow_legacy_algorithms) - })?; + // 通过跳板机转发到目标服务器 + let forwarded_channel = jump_session + .channel_open_direct_tcpip( + &ssh_config.host, + ssh_config.port as u32, + "127.0.0.1", + 0, + ) + .await + .map_err(|error| { + let description = open_failure_slot + .lock() + .ok() + .and_then(|guard| guard.clone()) + .map(|(_, description)| description) + .unwrap_or_default(); + add_jump_channel_rejected_hint(anyhow::Error::new(error), &description) + })?; + + let handler = SftpHandler::with_server_public_key_capture( + target_host_key_identity.clone(), + host_key_verifier.clone(), + accepted_server_public_key.clone(), + ); + let session = client::connect_stream( + target_russh_config, + forwarded_channel.into_stream(), + handler, + ) + .await + .map_err(|error| { + add_legacy_algorithm_hint(error, ssh_config.allow_legacy_algorithms) + })?; - (session, Some(jump_session)) + (session, Some(jump_session)) + } } else if let Some(ref proxy) = ssh_config.proxy { tracing::info!("SFTP: 通过代理 {}:{} 连接", proxy.host, proxy.port); let stream = sftp_connect_via_proxy(proxy, &ssh_config.host, ssh_config.port).await?; @@ -2453,14 +2684,20 @@ impl SftpClient for RusshSftpClient { (session, None) }; - // 认证目标服务器 - authenticate_with_strategy( - &mut session, - &ssh_config.username, - &ssh_config.auth, - sftp_auth_failure_messages(), - ) - .await?; + // 认证目标服务器(堡垒机直连模式下会话已在上面认证过,跳过) + let bastion_direct = ssh_config + .jump_server + .as_ref() + .is_some_and(|jump| jump.bastion_login_username().is_some()); + if !bastion_direct { + authenticate_with_strategy( + &mut session, + &ssh_config.username, + &ssh_config.auth, + sftp_auth_failure_messages(), + ) + .await?; + } let channel = session.channel_open_session().await?; channel.request_subsystem(true, "sftp").await?; @@ -2488,6 +2725,7 @@ impl SftpClient for RusshSftpClient { raw_sftp: None, owner_names: BTreeMap::new(), owner_lookup_disabled: false, + bastion_direct, }) } } @@ -2495,69 +2733,8 @@ impl SftpClient for RusshSftpClient { #[async_trait] impl RemoteFileClient for RusshSftpClient { async fn list_dir(&mut self, path: &str) -> Result> { - let dir_entries = self - .sftp - .read_dir(path) - .await - .map_err(|e| anyhow!("Failed to read directory {}: {}", path, e))?; - - let mut entries = Vec::new(); - - for entry in dir_entries { - let file_name = entry.file_name(); - - if file_name == "." || file_name == ".." { - continue; - } - if !is_valid_remote_entry_name(&file_name) { - return Err(anyhow!( - "Refusing unsafe SFTP directory entry name in {}: {:?}", - path, - file_name - )); - } - - let metadata = entry.metadata(); - let size = metadata.size.unwrap_or(0); - let is_dir = metadata.is_dir(); - let permissions = metadata.permissions.unwrap_or(0); - let uid = metadata.uid; - let gid = metadata.gid; - let user = metadata.user.clone(); - let group = metadata.group.clone(); - - let modified = metadata - .mtime - .and_then(|mtime| UNIX_EPOCH.checked_add(Duration::from_secs(mtime as u64))) - .unwrap_or_else(SystemTime::now); - - entries.push(FileEntry { - name: file_name.clone(), - path: file_name, - size, - modified, - is_dir, - permissions, - uid, - gid, - user, - group, - }); - } - - self.resolve_entry_owners(&mut entries).await; - - entries.sort_by(|a, b| { - if a.is_dir == b.is_dir { - a.name.to_lowercase().cmp(&b.name.to_lowercase()) - } else if a.is_dir { - std::cmp::Ordering::Less - } else { - std::cmp::Ordering::Greater - } - }); - - Ok(entries) + let bastion_direct = self.bastion_direct; + with_directory_list_timeout(path, self.list_dir_untimed(path, bastion_direct)).await } async fn stat(&mut self, path: &str) -> Result> { @@ -2978,11 +3155,14 @@ impl RemoteFileClient for RusshSftpClient { for entry in entries { ensure_not_cancelled(&cancelled)?; if !is_valid_remote_entry_name(&entry.name) { - return Err(anyhow!( - "Refusing unsafe SFTP directory entry name in {}: {:?}", - current_dir, - entry.name - )); + // `list_dir` 已经过滤过一遍,这里只是防御性复核: + // 同样跳过而不是让整棵目录树的下载失败。 + tracing::warn!( + directory = current_dir, + entry = %entry.name, + "跳过无法作为单层远程路径的 SFTP 目录项" + ); + continue; } let full_path = if current_dir == "/" { format!("/{}", entry.name) @@ -4649,6 +4829,23 @@ mod tests { remote_download_relative_path("/root", "/other/file.txt").is_err(), "paths outside the selected remote root must be rejected" ); + #[cfg(not(windows))] + assert!( + remote_download_relative_path("/root", "/root/c:").is_ok(), + "盘符形态的名字在 Linux 上是合法文件名,落盘相对路径仍可安全构造" + ); + } + + #[cfg(windows)] + #[test] + fn remote_download_relative_path_rejects_windows_drive_prefixes() { + // Windows 上 `join("c:")` 会解析成盘符相对路径,必须挡在落盘之前。 + for entry in ["/root/c:", "/root/c:notes.txt", "/root/C:notes.txt"] { + assert!( + remote_download_relative_path("/root", entry).is_err(), + "{entry:?} must be rejected before landing on a local path" + ); + } } #[cfg(unix)] @@ -4850,3 +5047,57 @@ mod short_read_tests; #[cfg(test)] #[path = "russh_impl_directory_concurrency_tests.rs"] mod directory_concurrency_tests; + +#[cfg(test)] +#[path = "russh_impl_listing_tests.rs"] +mod listing_tests; + +/// 堡垒机直连下目录浏览的用户可读性保障:超时与「根目录受限」的解释。 +#[cfg(test)] +mod jump_listing_guard_tests { + use super::*; + + #[test] + fn bastion_direct_missing_path_explains_restricted_sftp_root() { + let message = describe_list_dir_error("/root", true, "No such file: file does not exist"); + + assert!(message.contains("/root"), "{message}"); + assert!(message.contains("文件管理根目录"), "{message}"); + assert!( + !message.contains("Failed to read directory"), + "堡垒机直连不该把原始英文错误直接透给用户: {message}" + ); + } + + #[test] + fn normal_server_missing_path_keeps_failed_prefix() { + let message = describe_list_dir_error("/root", false, "No such file: file does not exist"); + + assert!( + message.starts_with("Failed to read directory /root"), + "{message}" + ); + assert!(!message.contains("文件管理根目录"), "{message}"); + } + + #[test] + fn other_failures_are_passed_through_verbatim() { + let message = describe_list_dir_error("/data", true, "Permission denied"); + + assert_eq!(message, "Failed to read directory /data: Permission denied"); + } + + #[tokio::test(start_paused = true)] + async fn directory_listing_times_out_with_path_and_limit() { + let result: Result<()> = + with_directory_list_timeout("/tmp", std::future::pending::>()).await; + + let message = result.expect_err("永不完结的目录枚举必须超时").to_string(); + assert!(message.contains("/tmp"), "{message}"); + assert!(message.contains("超时"), "{message}"); + assert!( + message.contains(&DIRECTORY_LIST_TIMEOUT.as_secs().to_string()), + "{message}" + ); + } +} diff --git a/crates/sftp/src/russh_impl_directory_concurrency_tests.rs b/crates/sftp/src/russh_impl_directory_concurrency_tests.rs index db717a5be..5b31e8dad 100644 --- a/crates/sftp/src/russh_impl_directory_concurrency_tests.rs +++ b/crates/sftp/src/russh_impl_directory_concurrency_tests.rs @@ -217,11 +217,15 @@ async fn directory_download_overlaps_small_files_and_keeps_progress_monotonic() } #[tokio::test] -async fn directory_download_rejects_server_names_that_escape_the_local_root() { - let files = vec![( - "../outside.txt".to_string(), - b"malicious remote content".to_vec(), - )]; +async fn directory_download_skips_server_names_that_escape_the_local_root() { + // 坏条目只跳过:整目录下载不能因为它失败,也不能把它落到本地。 + let files = vec![ + ( + "../outside.txt".to_string(), + b"malicious remote content".to_vec(), + ), + ("ok.txt".to_string(), b"legitimate remote content".to_vec()), + ]; let (metadata_server, _) = FakeDirectoryServer::new(files.clone()); let (metadata_client, metadata_server_stream) = tokio::io::duplex(1024 * 1024); russh_sftp::server::run(metadata_server_stream, metadata_server).await; @@ -255,13 +259,25 @@ async fn directory_download_rejects_server_names_that_escape_the_local_root() { ) .await; - assert!( - result.is_err(), - "a server-controlled parent component must abort the download" - ); + result.expect("坏条目必须被跳过,而不是让整个目录下载失败"); assert_eq!( b"original local content".as_slice(), std::fs::read(&outside).expect("outside sentinel must still exist"), "the download must never write outside the selected local directory" ); + assert_eq!( + b"legitimate remote content".as_slice(), + std::fs::read(chosen.join("ok.txt")).expect("legitimate entries must still download"), + "跳过坏条目不能影响其它文件" + ); + let landed: Vec = std::fs::read_dir(&chosen) + .expect("read chosen directory") + .filter_map(|entry| entry.ok()) + .map(|entry| entry.file_name().to_string_lossy().to_string()) + .collect(); + assert_eq!( + vec!["ok.txt".to_string()], + landed, + "malicious entries must never be materialized" + ); } diff --git a/crates/sftp/src/russh_impl_listing_tests.rs b/crates/sftp/src/russh_impl_listing_tests.rs new file mode 100644 index 000000000..ad1cf4213 --- /dev/null +++ b/crates/sftp/src/russh_impl_listing_tests.rs @@ -0,0 +1,124 @@ +//! 目录列举必须对「恶意/异常条目名」保持可用。 +//! +//! 历史上 `list_dir` 遇到非单层名字会直接返回错误,于是服务端目录里 +//! 只要存在一个 `..` 或者 Linux 上完全合法的 `c:`,Windows 客户端 +//! 就会整个目录读不出来、并被导航逻辑回退到工作目录。正确行为是 +//! 跳过这些条目:坏条目不该毁掉整个目录浏览。 + +use super::*; +use russh_sftp::protocol::{File, Handle, Name, Status, Version}; +use std::collections::HashMap; + +struct FakeListingServer { + names: Vec, + listed: bool, +} + +impl FakeListingServer { + fn new(names: &[&str]) -> Self { + Self { + names: names.iter().map(|name| (*name).to_string()).collect(), + listed: false, + } + } +} + +impl russh_sftp::server::Handler for FakeListingServer { + type Error = StatusCode; + + fn unimplemented(&self) -> Self::Error { + StatusCode::OpUnsupported + } + + fn init( + &mut self, + _version: u32, + _extensions: HashMap, + ) -> impl Future> + Send { + async { Ok(Version::new()) } + } + + fn opendir( + &mut self, + id: u32, + path: String, + ) -> impl Future> + Send { + self.listed = false; + async move { Ok(Handle { id, handle: path }) } + } + + fn readdir( + &mut self, + id: u32, + _handle: String, + ) -> impl Future> + Send { + let result = if self.listed { + Err(StatusCode::Eof) + } else { + self.listed = true; + let files = self + .names + .iter() + .map(|name| File::new(name.clone(), FileAttributes::empty())) + .collect(); + Ok(Name { id, files }) + }; + async move { result } + } + + fn close( + &mut self, + id: u32, + _handle: String, + ) -> impl Future> + Send { + async move { + Ok(Status { + id, + status_code: StatusCode::Ok, + error_message: "Ok".to_string(), + language_tag: "en-US".to_string(), + }) + } + } +} + +async fn list_fake_directory(names: &[&str]) -> Result> { + let (client_stream, server_stream) = tokio::io::duplex(1024 * 1024); + russh_sftp::server::run(server_stream, FakeListingServer::new(names)).await; + let sftp = + SftpSession::new_with_config(client_stream, sftp_session_config(SftpTransport::Owned)) + .await + .expect("fake SFTP session must initialize"); + let mut client = RusshSftpClient::for_test(sftp, None); + client.list_dir("/root").await +} + +#[tokio::test] +async fn list_dir_skips_unsafe_names_instead_of_failing_the_directory() { + let entries = list_fake_directory(&[ + ".", + "..", + "notes.txt", + "../outside.txt", + "sub/file.txt", + "c:", + "报名表.xlsx", + ]) + .await + .expect("一个坏条目不能让整个目录读取失败"); + + let names: Vec<&str> = entries.iter().map(|entry| entry.name.as_str()).collect(); + assert_eq!( + names, + vec!["c:", "notes.txt", "报名表.xlsx"], + "只保留单层名字:`.`/`..`、`../x`、`a/b` 必须被跳过" + ); +} + +#[tokio::test] +async fn list_dir_reports_an_empty_directory_instead_of_failing() { + let entries = list_fake_directory(&[".", ".."]) + .await + .expect("只含 `.`/`..` 的空目录必须正常返回"); + assert!(entries.is_empty()); +} diff --git a/crates/sftp/tests/jump_rejection_test.rs b/crates/sftp/tests/jump_rejection_test.rs new file mode 100644 index 000000000..76b8c2439 --- /dev/null +++ b/crates/sftp/tests/jump_rejection_test.rs @@ -0,0 +1,125 @@ +//! 跳板机拒绝 direct-tcpip 时的 SFTP 连接错误链测试。 +//! +//! JumpServer 这类堡垒机会默认拒绝 `direct-tcpip` 通道。这里用一个 +//! 本地 russh 测试服务器仿真该行为,验证 `RusshSftpClient::connect` 的 +//! 错误里带有 JumpChannelRejected 提示与服务器回传的描述文本。 + +use std::sync::Arc; +use std::time::Duration; + +use russh::keys::{Algorithm, PrivateKey}; +use russh::server::{Auth, Server as _}; +use sftp::{RusshSftpClient, SftpClient}; +use tokio::net::TcpListener; + +use ssh::{ + BastionUserFormat, HostKeyVerifier, JumpChannelRejected, JumpMode, JumpServerConnectConfig, + SshAuth, SshConnectConfig, +}; + +/// 接受登录但像 JumpServer 一样拒绝所有 direct-tcpip 通道的测试服务器。 +#[derive(Clone)] +struct ForwardingDenyingJumpServer; + +impl russh::server::Server for ForwardingDenyingJumpServer { + type Handler = Self; + + fn new_client(&mut self, _: Option) -> Self::Handler { + self.clone() + } +} + +impl russh::server::Handler for ForwardingDenyingJumpServer { + type Error = anyhow::Error; + + async fn auth_password(&mut self, _: &str, _: &str) -> Result { + Ok(Auth::Accept) + } + + async fn channel_open_direct_tcpip( + &mut self, + _channel: russh::Channel, + _host_to_connect: &str, + _port_to_connect: u32, + _originator_address: &str, + _originator_port: u32, + reply: russh::server::ChannelOpenHandle, + _session: &mut russh::server::Session, + ) -> Result<(), Self::Error> { + reply + .reject(russh::ChannelOpenFailure::Other { + code: russh::ChannelOpenFailure::AdministrativelyProhibited.code(), + reason: "port forwarding is disabled".to_string(), + }) + .await; + Ok(()) + } +} + +async fn spawn_forwarding_denying_jump_server() -> std::io::Result { + let socket = TcpListener::bind(("127.0.0.1", 0)).await?; + let address = socket.local_addr()?; + let ed25519 = PrivateKey::random(&mut rand::rng(), Algorithm::Ed25519).map_err(|error| { + std::io::Error::other(format!("failed to generate test host key: {error}")) + })?; + let server_config = Arc::new(russh::server::Config { + auth_rejection_time: Duration::ZERO, + auth_rejection_time_initial: Some(Duration::ZERO), + keys: vec![ed25519], + ..Default::default() + }); + tokio::spawn(async move { + let mut server = ForwardingDenyingJumpServer; + server.run_on_socket(server_config, &socket).await + }); + Ok(address) +} + +#[tokio::test] +async fn sftp_jump_direct_tcpip_rejection_surfaces_hint_and_server_description() { + let jump_address = spawn_forwarding_denying_jump_server() + .await + .expect("test server should bind"); + + let config = SshConnectConfig { + host: "10.255.255.1".to_owned(), + port: 22, + username: "tester".to_owned(), + auth: SshAuth::Password("password".to_owned()), + timeout: Some(Duration::from_secs(10)), + keepalive_interval: None, + keepalive_max: None, + jump_server: Some(JumpServerConnectConfig { + host: jump_address.ip().to_string(), + port: jump_address.port(), + username: "jump".to_owned(), + auth: SshAuth::Password("password".to_owned()), + mode: JumpMode::default(), + bastion_asset: String::new(), + bastion_account: String::new(), + bastion_user_format: BastionUserFormat::default(), + }), + proxy: None, + keyboard_interactive_responder: None, + host_key_verifier: HostKeyVerifier::insecure(), + x11_forwarding: false, + allow_legacy_algorithms: false, + forward_agent: false, + agent_identities: Vec::new(), + }; + + let result = RusshSftpClient::connect(config).await; + + let Err(error) = result else { + panic!("a jump server rejecting direct-tcpip must fail the SFTP connection"); + }; + assert!( + error.downcast_ref::().is_some(), + "rejection should be wrapped as JumpChannelRejected, got: {error:#}" + ); + assert!(format!("{error:#}").contains("Failed to open channel")); + assert!( + format!("{error:#}").contains("port forwarding is disabled"), + "server description should be surfaced, got: {error:#}" + ); +} diff --git a/crates/sftp_transfer/src/lib.rs b/crates/sftp_transfer/src/lib.rs index 00e120f80..ca3a42598 100644 --- a/crates/sftp_transfer/src/lib.rs +++ b/crates/sftp_transfer/src/lib.rs @@ -25,8 +25,8 @@ pub use model::{ pub use provider::{RusshSftpTransferProvider, SftpTransferProvider}; pub use scheduler::MAX_CONCURRENT_TRANSFERS_PER_CONNECTION; pub use ssh_config::{ - ResolvedSshTarget, resolve_ssh_target, sftp_initial_directory, sftp_initial_directory_of, - ssh_auth, ssh_config_for, + ResolvedSshTarget, jump_connect_config, proxy_connect_config, resolve_ssh_target, + sftp_initial_directory, sftp_initial_directory_of, ssh_auth, ssh_config_for, }; #[cfg(test)] diff --git a/crates/sftp_transfer/src/ssh_config.rs b/crates/sftp_transfer/src/ssh_config.rs index 16f36a63b..fe4a057c1 100644 --- a/crates/sftp_transfer/src/ssh_config.rs +++ b/crates/sftp_transfer/src/ssh_config.rs @@ -12,11 +12,13 @@ use std::time::Duration; use anyhow::{Context as _, Result}; use one_core::storage::models::{ + BastionUserFormat as StorageBastionUserFormat, JumpMode as StorageJumpMode, + JumpServerConfig as StorageJumpServerConfig, ProxyConfig as StorageProxyConfig, ProxyType as StorageProxyType, SshAuthMethod, SshParams, StoredConnection, }; use ssh::{ - AgentIdentity, HostKeyVerifier, JumpServerConnectConfig, ProxyConnectConfig, ProxyType, - SshAuth, SshConnectConfig, + AgentIdentity, BastionUserFormat, HostKeyVerifier, JumpMode, JumpServerConnectConfig, + ProxyConnectConfig, ProxyType, SshAuth, SshConnectConfig, }; /// 已保存连接解析出的 SSH 目标。 @@ -63,22 +65,8 @@ pub fn resolve_ssh_target(connection: &StoredConnection) -> Result ProxyType::Socks5, - StorageProxyType::Http => ProxyType::Http, - }, - host: proxy.host, - port: proxy.port, - username: proxy.username, - password: proxy.password, - }), + jump_server: params.jump_server.as_ref().map(jump_connect_config), + proxy: params.proxy.as_ref().map(proxy_connect_config), keyboard_interactive_responder: None, host_key_verifier: HostKeyVerifier::default(), x11_forwarding: false, @@ -142,6 +130,55 @@ pub fn ssh_auth(method: SshAuthMethod) -> SshAuth { } } +/// 存储的跳板机配置 → 连接层跳板机配置(统一映射入口)。 +/// +/// 历史上 terminal / runtime_sftp / port_forwarding / ssh_form 各自维护一份 +/// 等价映射,bastion 字段加入后必须五处同步;统一到本函数后新增字段只需 +/// 改这里,各构造点显式传入 MFA 响应器即可。 +pub fn jump_connect_config(jump: &StorageJumpServerConfig) -> JumpServerConnectConfig { + JumpServerConnectConfig { + host: jump.host.clone(), + port: jump.port, + username: jump.username.clone(), + auth: ssh_auth(jump.auth_method.clone()), + mode: match jump.mode { + StorageJumpMode::ProxyJump => JumpMode::ProxyJump, + StorageJumpMode::BastionDirect => JumpMode::BastionDirect, + }, + bastion_asset: jump + .bastion + .as_ref() + .map(|target| target.asset.clone()) + .unwrap_or_default(), + bastion_account: jump + .bastion + .as_ref() + .map(|target| target.account.clone()) + .unwrap_or_default(), + bastion_user_format: jump + .bastion + .as_ref() + .map(|target| match target.user_format { + StorageBastionUserFormat::JumpServer => BastionUserFormat::JumpServer, + }) + .unwrap_or_default(), + } +} + +/// 存储的代理配置 → 连接层代理配置。 +pub fn proxy_connect_config(proxy: &StorageProxyConfig) -> ProxyConnectConfig { + ProxyConnectConfig { + proxy_type: match proxy.proxy_type { + StorageProxyType::Socks5 => ProxyType::Socks5, + StorageProxyType::Http => ProxyType::Http, + }, + host: proxy.host.clone(), + port: proxy.port, + username: proxy.username.clone(), + password: proxy.password.clone(), + } +} + /// 从存储 SSH 认证方式推导要加入本地 ssh-agent 的私钥身份。 /// /// 仅当连接开启了 ForwardAgent 时才会被加载进 agent 并转发给远端。 diff --git a/crates/sftp_transfer/src/tests.rs b/crates/sftp_transfer/src/tests.rs index 1c69908ae..aa515e460 100644 --- a/crates/sftp_transfer/src/tests.rs +++ b/crates/sftp_transfer/src/tests.rs @@ -5,6 +5,7 @@ use super::{SftpConnectionIdentity, SftpTransferState, scheduler::ConnectionLane mod delete_remote_tests; mod download_tests; +mod jump_config_mapping_tests; mod lifecycle_tests; mod support; mod upload_retry_tests; diff --git a/crates/sftp_transfer/src/tests/jump_config_mapping_tests.rs b/crates/sftp_transfer/src/tests/jump_config_mapping_tests.rs new file mode 100644 index 000000000..d46640bdd --- /dev/null +++ b/crates/sftp_transfer/src/tests/jump_config_mapping_tests.rs @@ -0,0 +1,82 @@ +//! 统一跳板机/代理映射的单测。 +//! +//! 五个历史构造点(terminal / sftp_transfer / runtime_sftp / port_forwarding / +//! ssh_form)各自维护一份「存储 JumpServerConfig → 连接层 +//! JumpServerConnectConfig」的映射,bastion 字段加入后重复度进一步扩大。 +//! 本模块锁定统一入口 [`crate::ssh_config::jump_connect_config`] 与 +//! [`crate::ssh_config::proxy_connect_config`] 的行为,供各构造点共用。 + +use one_core::storage::models::{ + BastionUserFormat as StorageBastionUserFormat, JumpMode as StorageJumpMode, + JumpServerConfig, ProxyConfig as StorageProxyConfig, ProxyType as StorageProxyType, + SshAuthMethod, +}; +use ssh::{BastionUserFormat, JumpMode, ProxyType, SshAuth}; + +use crate::ssh_config::{jump_connect_config, proxy_connect_config}; + +fn storage_jump(mode: StorageJumpMode) -> JumpServerConfig { + JumpServerConfig { + host: "jump.example.com".to_string(), + port: 2222, + username: "hufei".to_string(), + auth_method: SshAuthMethod::Password { + password: "secret".to_string(), + }, + credential_reference: None, + mode, + bastion: None, + } +} + +#[test] +fn jump_connect_config_maps_proxy_jump_defaults() { + let jump = storage_jump(StorageJumpMode::ProxyJump); + let config = jump_connect_config(&jump); + assert_eq!(config.host, "jump.example.com"); + assert_eq!(config.port, 2222); + assert_eq!(config.username, "hufei"); + assert_eq!(config.auth, SshAuth::Password("secret".to_string())); + assert_eq!(config.mode, JumpMode::ProxyJump); + assert_eq!(config.bastion_asset, ""); + assert_eq!(config.bastion_account, ""); + assert_eq!(config.bastion_user_format, BastionUserFormat::JumpServer); +} + +#[test] +fn jump_connect_config_maps_bastion_direct_target() { + let mut jump = storage_jump(StorageJumpMode::BastionDirect); + jump.bastion = Some(one_core::storage::models::BastionTarget { + asset: "0e85eca7-422a-4cdb-8e4c-8e3ff68eee39".to_string(), + account: "root".to_string(), + user_format: StorageBastionUserFormat::JumpServer, + }); + let config = jump_connect_config(&jump); + assert_eq!(config.mode, JumpMode::BastionDirect); + assert_eq!(config.bastion_asset, "0e85eca7-422a-4cdb-8e4c-8e3ff68eee39"); + assert_eq!(config.bastion_account, "root"); + assert_eq!(config.bastion_user_format, BastionUserFormat::JumpServer); + // 渲染出的登录用户名是堡垒机直连的核心语义。 + assert_eq!( + config.bastion_login_username().as_deref(), + Some("hufei#root#0e85eca7-422a-4cdb-8e4c-8e3ff68eee39") + ); +} + +#[test] +fn proxy_connect_config_maps_types_and_credentials() { + let proxy = StorageProxyConfig { + proxy_type: StorageProxyType::Socks5, + host: "proxy.example.com".to_string(), + port: 1080, + username: Some("pu".to_string()), + password: Some("pp".to_string()), + credential_reference: None, + }; + let config = proxy_connect_config(&proxy); + assert_eq!(config.proxy_type, ProxyType::Socks5); + assert_eq!(config.host, "proxy.example.com"); + assert_eq!(config.port, 1080); + assert_eq!(config.username.as_deref(), Some("pu")); + assert_eq!(config.password.as_deref(), Some("pp")); +} diff --git a/crates/sftp_view/src/lib.rs b/crates/sftp_view/src/lib.rs index 842823ba7..aebb11ccb 100644 --- a/crates/sftp_view/src/lib.rs +++ b/crates/sftp_view/src/lib.rs @@ -1102,8 +1102,12 @@ fn is_valid_entry_name(name: &str) -> bool { sftp::is_valid_remote_entry_name(name) } +/// 远程条目名拼成本地下载路径。 +/// +/// 落盘要用本机校验:Windows 上 `join("c:")` 会解析成盘符相对路径, +/// 而同一份名字在 Linux 上完全合法,所以列表阶段不能拒绝它。 fn safe_local_download_path(local_root: &std::path::Path, remote_name: &str) -> Option { - is_valid_entry_name(remote_name).then(|| local_root.join(remote_name)) + sftp::is_valid_local_file_name(remote_name).then(|| local_root.join(remote_name)) } fn breadcrumb_item_min_width(label: &str) -> f32 { @@ -9638,6 +9642,11 @@ mod tests { assert_eq!(None, safe_local_download_path(root, "../outside.txt")); assert_eq!(None, safe_local_download_path(root, "/tmp/outside.txt")); assert_eq!(None, safe_local_download_path(root, "..\\outside.txt")); + // 盘符形态的名字在 Linux 上可以安全落盘;Windows 由本机校验拦下。 + #[cfg(not(windows))] + assert_eq!(Some(root.join("c:")), safe_local_download_path(root, "c:")); + #[cfg(windows)] + assert_eq!(None, safe_local_download_path(root, "c:")); } #[test] diff --git a/crates/shell_domain/src/lib.rs b/crates/shell_domain/src/lib.rs index f70f1fd55..5c63bc71a 100644 --- a/crates/shell_domain/src/lib.rs +++ b/crates/shell_domain/src/lib.rs @@ -8,6 +8,9 @@ rust_i18n::i18n!("locales", fallback = "en"); mod connection_forms; mod connection_openers; mod lifecycle; + +/// 应用级 SSH 会话共享服务获取口(见 [`lifecycle`])。 +pub use lifecycle::ssh_session_service; #[cfg(feature = "nsh-host")] mod native_terminal; mod recording; diff --git a/crates/shell_domain/src/lifecycle.rs b/crates/shell_domain/src/lifecycle.rs index d50bdc0e5..680beb0d1 100644 --- a/crates/shell_domain/src/lifecycle.rs +++ b/crates/shell_domain/src/lifecycle.rs @@ -27,6 +27,15 @@ impl GlobalSshSessionService { } } +/// 获取应用级 SSH 会话服务;未安装(测试环境/领域未初始化)时返回 `None`。 +/// +/// Terminal 在连接尝试时经此入口获取共享传输服务;拿不到时回退到 +/// 本地 `SshSessionManager`,保证非装配环境行为不变。 +pub fn ssh_session_service(cx: &App) -> Option { + cx.try_global::() + .map(|global| global.service()) +} + /// 安装 SSH 会话服务,并注册平台退出路径的兜底关停回调。 pub(crate) fn init(cx: &mut App) { assert!( @@ -38,6 +47,9 @@ pub(crate) fn init(cx: &mut App) { let fallback_service = global.service(); cx.set_global(global); + // 把共享服务同步注入 Terminal 侧的获取桥,供连接尝试时 acquire 共享租约。 + terminal::terminal::install_ssh_session_service(fallback_service.clone(), cx); + // 正常退出路径会先 await 关停再退出;这里只是平台强制退出的幂等兜底。 // GPUI 给退出回调的时间很短,因此它不能承担主要关停职责。 cx.on_app_quit(move |cx| { @@ -179,4 +191,33 @@ mod tests { let ssh = body.find("spawn_ssh_session_shutdown").expect("ssh spawn"); assert!(rdp < ssh); } + + /// `init` 必须把同一个服务同时装进两个全局:领域自身的 + /// `GlobalSshSessionService`(关停路径用)与 Terminal 侧的获取桥 + /// (连接尝试 acquire 共享租约用),保证两条路径拿到同一实例。 + #[test] + fn init_installs_shared_service_into_both_globals() { + let source = include_str!("lifecycle.rs").replace("\r\n", "\n"); + let init_start = source.find("pub(crate) fn init").expect("init fn"); + let init_end = source[init_start..] + .find("\n}\n\n") + .map(|offset| init_start + offset) + .expect("init fn end"); + let init = &source[init_start..init_end]; + + let set_global = init + .find("cx.set_global(global)") + .expect("domain global install"); + let bridge = init + .find("terminal::terminal::install_ssh_session_service(") + .expect("terminal bridge install"); + assert!( + set_global < bridge, + "先装领域全局,再注入 Terminal 获取桥(桥注入依赖全局已就位)" + ); + assert!( + init.contains("fallback_service"), + "两条注入路径必须共享同一个服务实例" + ); + } } diff --git a/crates/ssh/locales/ssh.yml b/crates/ssh/locales/ssh.yml index 8cec1ce29..a3df6e2c7 100644 --- a/crates/ssh/locales/ssh.yml +++ b/crates/ssh/locales/ssh.yml @@ -85,3 +85,11 @@ Ssh: en: The server may only support legacy SSH algorithms, for example a DSA host key, SHA-1 key exchange, or SHA-1 MAC. Edit this connection and enable “Allow Legacy SSH Algorithms” under “Advanced Settings”, then try again. zh-CN: 服务器可能仅支持旧版 SSH 算法,例如 DSA 主机密钥、SHA-1 密钥交换或 SHA-1 MAC。请编辑此连接,在“高级设置”中开启“允许旧版 SSH 算法”后重试。 zh-HK: 伺服器可能僅支援舊版 SSH 演算法,例如 DSA 主機金鑰、SHA-1 金鑰交換或 SHA-1 MAC。請編輯此連線,在「進階設定」中開啟「允許舊版 SSH 演算法」後重試。 + jump_channel_rejected_hint: + en: "The jump server refused to open a forwarded channel to the target host (reason code %{reason}). Many bastion hosts (such as JumpServer) disable SSH port forwarding by policy, so ProxyJump-style jump connections cannot work. Edit this connection, disable “Jump Server”, and connect to the bastion directly (or ask the administrator to allow port forwarding)." + zh-CN: "跳板机拒绝了到目标主机的转发通道(原因码 %{reason})。很多堡垒机(如 JumpServer)默认禁用 SSH 端口转发,ProxyJump 式跳板连接无法工作。请编辑此连接,关闭「跳板机」并直连堡垒机(或联系管理员开放端口转发)。" + zh-HK: "跳板機拒絕了到目標主機的轉發通道(原因碼 %{reason})。很多堡壘機(如 JumpServer)預設停用 SSH 連接埠轉發,ProxyJump 式跳板連線無法工作。請編輯此連線,關閉「跳板機」並直連堡壘機(或聯絡管理員開放連接埠轉發)。" + server_reason: + en: "Server message: %{reason}" + zh-CN: "服务器返回: %{reason}" + zh-HK: "伺服器返回: %{reason}" diff --git a/crates/ssh/src/connection_error.rs b/crates/ssh/src/connection_error.rs index 226e79454..98da12500 100644 --- a/crates/ssh/src/connection_error.rs +++ b/crates/ssh/src/connection_error.rs @@ -33,6 +33,25 @@ impl fmt::Display for PrivateKeyLoadFailed { impl StdError for PrivateKeyLoadFailed {} +/// 跳板机 direct-tcpip 通道被远端拒绝(含服务器回传的原因码与描述)。 +/// +/// 典型场景是 JumpServer 这类堡垒机默认禁用端口转发:客户端能登录跳板机, +/// 但 `channel_open_direct_tcpip` 被以 `AdministrativelyProhibited` 拒绝, +/// 界面上只剩 `Failed to open channel (AdministrativelyProhibited)` 一个枚举名, +/// 用户无从知道该关掉「跳板机」直连资产。 +#[derive(Debug)] +pub struct JumpChannelRejected { + message: String, +} + +impl fmt::Display for JumpChannelRejected { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(&self.message) + } +} + +impl StdError for JumpChannelRejected {} + /// Wrap private-key loading failures so the terminal does not reduce a wrong /// passphrase or malformed key to russh's opaque `SshKey: cryptographic error`. pub(crate) fn add_private_key_load_hint(error: Error) -> Error { @@ -58,6 +77,39 @@ pub fn add_legacy_algorithm_hint(error: Error, allow_legacy_algorithms: bool) -> }) } +/// 给「跳板机 direct-tcpip 通道被拒」的错误追加可执行的处理建议。 +/// +/// `description` 是服务器在 CHANNEL_OPEN_FAILURE 里回传的描述文本(可能为空)。 +/// 仅当错误链里确实是 `russh::Error::ChannelOpenFailure` 时才包装,其余错误原样返回。 +pub fn add_jump_channel_rejected_hint(error: Error, description: &str) -> Error { + let Some(reason) = error + .chain() + .find_map(|cause| cause.downcast_ref::()) + .and_then(|error| match error { + russh::Error::ChannelOpenFailure(reason) => Some(reason.clone()), + _ => None, + }) + else { + return error; + }; + + let reason_code = reason.code(); + + let mut message = format!( + "{error:#}\n\n{}", + t!("Ssh.jump_channel_rejected_hint", reason = reason_code) + ); + let trimmed = description.trim(); + if !trimmed.is_empty() { + message.push_str(&format!( + "\n\n{}", + t!("Ssh.server_reason", reason = trimmed) + )); + } + + Error::new(JumpChannelRejected { message }) +} + fn is_no_common_algorithm_with_legacy_remedy(error: &Error) -> bool { error.chain().any(|cause| { cause @@ -84,7 +136,9 @@ fn matches_kind(kind: &russh::AlgorithmKind, theirs: &[String]) -> bool { #[cfg(test)] mod tests { - use super::{LegacyAlgorithmRequired, add_legacy_algorithm_hint}; + use super::{ + LegacyAlgorithmRequired, add_jump_channel_rejected_hint, add_legacy_algorithm_hint, + }; fn no_common_algorithm(kind: russh::AlgorithmKind) -> anyhow::Error { no_common_algorithm_with_theirs(kind, vec!["theirs".to_owned()]) @@ -187,4 +241,53 @@ mod tests { assert_eq!(error.to_string(), message); } } + + fn administratively_prohibited() -> anyhow::Error { + russh::Error::ChannelOpenFailure(russh::ChannelOpenFailure::AdministrativelyProhibited) + .into() + } + + fn connect_failed() -> anyhow::Error { + russh::Error::ChannelOpenFailure(russh::ChannelOpenFailure::ConnectFailed).into() + } + + #[test] + fn jump_channel_rejection_includes_hint_and_server_description() { + let error = add_jump_channel_rejected_hint( + administratively_prohibited(), + "port forwarding is disabled", + ); + + assert!(error.downcast_ref::().is_some()); + assert!(error.to_string().contains("Failed to open channel")); + assert!(error.to_string().contains("jump server")); + assert!(error.to_string().contains("port forwarding is disabled")); + } + + #[test] + fn jump_channel_rejection_without_description_keeps_hint() { + let error = add_jump_channel_rejected_hint(administratively_prohibited(), " "); + + assert!(error.downcast_ref::().is_some()); + assert!(error.to_string().contains("jump server")); + } + + #[test] + fn jump_channel_hint_covers_connect_failed_rejections() { + let error = add_jump_channel_rejected_hint(connect_failed(), ""); + + assert!(error.downcast_ref::().is_some()); + assert!(error.to_string().contains("Failed to open channel")); + } + + #[test] + fn unrelated_errors_are_not_wrapped_as_jump_channel_rejections() { + let error = add_jump_channel_rejected_hint( + anyhow::anyhow!("Password authentication failed"), + "ignored", + ); + + assert!(error.downcast_ref::().is_none()); + assert_eq!(error.to_string(), "Password authentication failed"); + } } diff --git a/crates/ssh/src/connection_key.rs b/crates/ssh/src/connection_key.rs index c51206170..778da0e05 100644 --- a/crates/ssh/src/connection_key.rs +++ b/crates/ssh/src/connection_key.rs @@ -475,8 +475,9 @@ mod tests { CredentialScope, }; use crate::{ - HostKeyPolicy, HostKeyVerifier, JumpServerConnectConfig, KeyboardInteractiveRequest, - KeyboardInteractiveResponder, ProxyConnectConfig, ProxyType, SshAuth, SshConnectConfig, + BastionUserFormat, HostKeyPolicy, HostKeyVerifier, JumpMode, JumpServerConnectConfig, + KeyboardInteractiveRequest, KeyboardInteractiveResponder, ProxyConnectConfig, ProxyType, + SshAuth, SshConnectConfig, }; use anyhow::Result; use async_trait::async_trait; @@ -582,6 +583,10 @@ mod tests { port: 22, username: "jumper".to_owned(), auth: SshAuth::Password("jump-password".to_owned()), + mode: JumpMode::default(), + bastion_asset: String::new(), + bastion_account: String::new(), + bastion_user_format: BastionUserFormat::default(), }); baseline.proxy = Some(ProxyConnectConfig { proxy_type: ProxyType::Socks5, @@ -721,6 +726,10 @@ mod tests { port: 22, username: "jumper".to_owned(), auth: SshAuth::Agent, + mode: JumpMode::default(), + bastion_asset: String::new(), + bastion_account: String::new(), + bastion_user_format: BastionUserFormat::default(), }); assert_eq!( ConnectionKey::from_config(&jump_config, target_credentials()), @@ -762,6 +771,10 @@ mod tests { port: 22, username: "jumper".to_owned(), auth: SshAuth::Password("JUMP-PASSWORD-SECRET".to_owned()), + mode: JumpMode::default(), + bastion_asset: String::new(), + bastion_account: String::new(), + bastion_user_format: BastionUserFormat::default(), }); config.proxy = Some(ProxyConnectConfig { proxy_type: ProxyType::Http, diff --git a/crates/ssh/src/lib.rs b/crates/ssh/src/lib.rs index 55e474f7f..03db2ab6e 100644 --- a/crates/ssh/src/lib.rs +++ b/crates/ssh/src/lib.rs @@ -12,7 +12,10 @@ mod session_registry; mod socks5; mod ssh; -pub use connection_error::{LegacyAlgorithmRequired, add_legacy_algorithm_hint}; +pub use connection_error::{ + JumpChannelRejected, LegacyAlgorithmRequired, add_jump_channel_rejected_hint, + add_legacy_algorithm_hint, +}; pub use connection_key::{ ConnectionCredentialRevisions, ConnectionKey, ConnectionKeyError, CredentialRevision, CredentialScope, @@ -35,14 +38,14 @@ pub use session_registry::{ SshSessionServiceState, SshSessionShutdownReport, }; pub use ssh::{ - AgentIdentity, AuthFailureMessages, ChannelEvent, JumpServerConnectConfig, - KeyboardInteractivePrompt, KeyboardInteractiveRequest, KeyboardInteractiveResponder, - KeyboardInteractiveTarget, LocalPortForwardActivity, LocalPortForwardConfig, - LocalPortForwardTunnel, ProxyConnectConfig, ProxyType, PtyConfig, RusshChannel, RusshClient, - SshAuth, SshChannel, SshClient, SshConnectConfig, authenticate_session, - authenticate_session_with_fallbacks, authenticate_with_strategy, - build_client_preferred_algorithms, build_client_preferred_algorithms_with_legacy, - connect_via_proxy, defaults, expand_auto_publickey_auth, start_local_port_forward, - start_local_port_forward_with_config, + AgentIdentity, AuthFailureMessages, BastionUserFormat, ChannelEvent, JumpMode, + JumpServerConnectConfig, KeyboardInteractivePrompt, KeyboardInteractiveRequest, + KeyboardInteractiveResponder, KeyboardInteractiveTarget, LocalPortForwardActivity, + LocalPortForwardConfig, LocalPortForwardTunnel, ProxyConnectConfig, ProxyType, PtyConfig, + RusshChannel, RusshClient, SshAuth, SshChannel, SshClient, SshConnectConfig, + authenticate_session, authenticate_session_with_fallbacks, authenticate_with_strategy, + authenticate_with_strategy_for_target, build_client_preferred_algorithms, + build_client_preferred_algorithms_with_legacy, connect_via_proxy, defaults, + expand_auto_publickey_auth, start_local_port_forward, start_local_port_forward_with_config, }; pub use x11_forwarding::{ForwardRequest, X11Proxy}; diff --git a/crates/ssh/src/ssh.rs b/crates/ssh/src/ssh.rs index 763225b5e..b881fe606 100644 --- a/crates/ssh/src/ssh.rs +++ b/crates/ssh/src/ssh.rs @@ -1,7 +1,7 @@ use std::borrow::Cow; use std::net::SocketAddr; use std::path::PathBuf; -use std::sync::{Arc, RwLock}; +use std::sync::{Arc, Mutex as StdMutex, RwLock}; use std::time::Duration; use anyhow::{Context, Result}; @@ -14,7 +14,7 @@ use tokio::net::{TcpListener, TcpStream}; use tokio::sync::{Mutex, oneshot}; use x11_forwarding::{ForwardRequest, X11Proxy, X11ProxyHandle}; -use crate::connection_error::add_private_key_load_hint; +use crate::connection_error::{add_jump_channel_rejected_hint, add_private_key_load_hint}; use crate::remote_forwarding::RemoteForwardTarget; use crate::{ HostKeyAcceptance, HostKeyDetails, HostKeyIdentity, HostKeyProxyType, HostKeyRoute, @@ -261,6 +261,25 @@ fn host_key_proxy_type(proxy_type: ProxyType) -> HostKeyProxyType { } } +/// 跳板机工作模式 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum JumpMode { + /// 现有语义:在跳板机上开 direct-tcpip 通道连目标(ProxyJump 式)。 + #[default] + ProxyJump, + /// 直连型堡垒机:目标会话就是堡垒机会话,用户名按预设格式渲染 + /// (JumpServer 的 `{user}#{account}#{asset}`),不开端口转发通道。 + BastionDirect, +} + +/// 堡垒机用户名格式预设 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum BastionUserFormat { + /// JumpServer:`{user}#{account}#{asset}` + #[default] + JumpServer, +} + /// 跳板机连接配置 #[derive(Clone)] pub struct JumpServerConnectConfig { @@ -268,10 +287,34 @@ pub struct JumpServerConnectConfig { pub port: u16, pub username: String, pub auth: SshAuth, + /// 工作模式。缺省 ProxyJump,保持既有调用点语义不变。 + pub mode: JumpMode, + /// 堡垒机直连目标资产(IP / 名称 / UUID)。仅 BastionDirect 时有意义。 + pub bastion_asset: String, + /// 堡垒机直连目标账号(如 root)。仅 BastionDirect 时有意义。 + pub bastion_account: String, + /// 堡垒机登录用户名格式预设。仅 BastionDirect 时有意义。 + pub bastion_user_format: BastionUserFormat, +} + +impl JumpServerConnectConfig { + /// 渲染堡垒机直连登录用户名;ProxyJump 模式返回 `None`(沿用普通用户名)。 + #[must_use] + pub fn bastion_login_username(&self) -> Option { + if self.mode != JumpMode::BastionDirect { + return None; + } + match self.bastion_user_format { + BastionUserFormat::JumpServer => Some(format!( + "{}#{}#{}", + self.username, self.bastion_account, self.bastion_asset + )), + } + } } /// 代理类型 -#[derive(Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ProxyType { Socks5, Http, @@ -287,7 +330,7 @@ pub struct ProxyConnectConfig { pub password: Option, } -#[derive(Clone)] +#[derive(Clone, Debug, PartialEq)] pub enum SshAuth { Password(String), PrivateKey { @@ -508,6 +551,9 @@ struct RusshHandler { remote_forward_target: Arc>>, /// 是否把收到的 `auth-agent@openssh.com` 回连通道桥接到本地 ssh-agent。 forward_agent: bool, + /// 最近一次 CHANNEL_OPEN_FAILURE 的服务器侧描述,供连接流程把被丢弃的 + /// 描述文本(russh 只回传原因码枚举)补回给用户。 + last_open_failure: Option>>>, } impl RusshHandler { @@ -524,8 +570,18 @@ impl RusshHandler { host_key_verifier, remote_forward_target, forward_agent, + last_open_failure: None, } } + + /// 附带一个共享槽位,用于捕获服务器拒绝通道时回传的描述文本。 + fn with_open_failure_capture( + mut self, + slot: Arc>>, + ) -> Self { + self.last_open_failure = Some(slot); + self + } } impl client::Handler for RusshHandler { @@ -613,6 +669,36 @@ impl client::Handler for RusshHandler { } } + /// 服务器拒绝通道打开请求时的回调。 + /// + /// russh 的 `wait_channel_confirmation` 只把原因码枚举透传给调用方 + /// (`Error::ChannelOpenFailure(ChannelOpenFailure)`),服务器附带的描述文本 + /// (如 JumpServer 的 "port forwarding is disabled")在默认路径上被丢弃。 + /// 这里记录到共享槽位并打 warn,供连接流程在失败时把描述补回错误链。 + async fn channel_open_failure( + &mut self, + channel: russh::ChannelId, + reason: russh::ChannelOpenFailure, + description: &str, + _language: &str, + _session: &mut client::Session, + ) -> Result<(), Self::Error> { + tracing::warn!( + target: "ssh.channel", + identity = %self.identity, + channel = ?channel, + reason = ?reason, + description = %description, + "SSH 服务器拒绝打开通道" + ); + if let Some(slot) = &self.last_open_failure { + if let Ok(mut guard) = slot.lock() { + *guard = Some((reason, description.to_string())); + } + } + Ok(()) + } + /// sshd 为远端 X client 回连的 `x11` 通道:按 fake cookie 找到注册会话, /// 改写为本机 real cookie 后桥接到本机 X server。 async fn server_channel_open_x11( @@ -858,6 +944,12 @@ pub struct RusshClient { /// 启用后,终端在 pty 之后、shell 之前会发送 agent 转发请求, /// 使远端(如跳板机)能通过 `auth-agent@openssh.com` 通道使用本地 ssh-agent。 forward_agent: bool, + /// 是否以「堡垒机直连」方式建立(会话即堡垒机,没有 direct-tcpip)。 + /// + /// 关闭 SSH 连接前的会话共享方(如文件面板复用终端连接)据此判断目标 + /// 是不是堡垒机本身:JumpServer 会把这类会话的 SFTP 限制在资产配置的 + /// 「文件管理根目录」里,路径不存在时要给出不同解释。 + bastion_direct: bool, } pub struct LocalPortForwardTunnel { @@ -1477,7 +1569,7 @@ where .await } -async fn authenticate_with_strategy_for_target( +pub async fn authenticate_with_strategy_for_target( session: &mut client::Handle, username: &str, auth: &SshAuth, @@ -2618,6 +2710,12 @@ impl SshClient for RusshClient { let x11_handle = x11_proxy.as_ref().map(|proxy| proxy.handle()); let host_key_verifier = config.host_key_verifier.clone(); let remote_forward_target = Arc::new(RwLock::new(None)); + // 堡垒机直连:会话本身就是堡垒机(用户名按 user#account#asset 渲染), + // 不建立 direct-tcpip。共享这条连接的 SFTP 需要据此解释路径错误。 + let bastion_direct = config + .jump_server + .as_ref() + .is_some_and(|jump| jump.bastion_login_username().is_some()); let connect = async { // 情况1: 使用跳板机连接 @@ -2629,6 +2727,62 @@ impl SshClient for RusshClient { let jump_russh_config = jump_russh_config .clone() .expect("jump config must exist when jump server is configured"); + // 捕获跳板机在 CHANNEL_OPEN_FAILURE 里回传的描述文本, + // russh 错误链只保留原因码枚举,描述需要经 Handler 钩子找回。 + let open_failure_slot = Arc::new(StdMutex::new(None)); + + // 堡垒机直连(BastionDirect):目标会话就是堡垒机会话本身, + // 用户名按预设格式渲染(如 JumpServer 的 user#account#asset), + // 不开 direct-tcpip 通道——直连型堡垒机按策略禁用端口转发。 + if let Some(bastion_username) = jump.bastion_login_username() { + tracing::info!( + "堡垒机直连模式:以渲染用户名登录 {}:{}", + jump.host, + jump.port + ); + let handler = RusshHandler::new( + jump_identity, + host_key_verifier.clone(), + x11_handle.clone(), + Arc::new(RwLock::new(None)), + config.forward_agent, + ) + .with_open_failure_capture(Arc::clone(&open_failure_slot)); + let mut session = if let Some(ref proxy) = config.proxy { + let stream = connect_via_proxy(proxy, &jump.host, jump.port).await?; + client::connect_stream(jump_russh_config, stream, handler) + .await + .map_err(|error| { + add_legacy_algorithm_hint(error, config.allow_legacy_algorithms) + })? + } else { + client::connect(jump_russh_config, (jump.host.as_str(), jump.port), handler) + .await + .map_err(|error| { + add_legacy_algorithm_hint(error, config.allow_legacy_algorithms) + })? + }; + + // 认证堡垒机(会话即目标:PTY/exec/SFTP 都跑在这条会话上) + authenticate_with_strategy_for_target( + &mut session, + &bastion_username, + &jump.auth, + default_auth_failure_messages(), + KeyboardInteractiveTarget::JumpServer, + config.keyboard_interactive_responder.clone(), + ) + .await?; + + return Ok(Self { + session, + _jump_session: None, + x11_proxy: x11_proxy.clone(), + remote_forward_target: Arc::clone(&remote_forward_target), + forward_agent: config.forward_agent, + bastion_direct, + }); + } // 先连接到跳板机(可能通过代理) let jump_session = if let Some(ref proxy) = config.proxy { @@ -2640,7 +2794,8 @@ impl SshClient for RusshClient { None, Arc::new(RwLock::new(None)), config.forward_agent, - ); + ) + .with_open_failure_capture(Arc::clone(&open_failure_slot)); client::connect_stream(jump_russh_config, stream, handler) .await .map_err(|error| { @@ -2654,7 +2809,8 @@ impl SshClient for RusshClient { None, Arc::new(RwLock::new(None)), config.forward_agent, - ); + ) + .with_open_failure_capture(Arc::clone(&open_failure_slot)); client::connect(jump_russh_config, addrs, handler) .await .map_err(|error| { @@ -2678,7 +2834,16 @@ impl SshClient for RusshClient { tracing::info!("通过跳板机转发到目标服务器 {}:{}", config.host, config.port); let forwarded_channel = jump_session .channel_open_direct_tcpip(&config.host, config.port as u32, "127.0.0.1", 0) - .await?; + .await + .map_err(|error| { + let description = open_failure_slot + .lock() + .ok() + .and_then(|guard| guard.clone()) + .map(|(_, description)| description) + .unwrap_or_default(); + add_jump_channel_rejected_hint(anyhow::Error::new(error), &description) + })?; // 使用转发通道创建SSH会话 let handler = RusshHandler::new( @@ -2715,6 +2880,7 @@ impl SshClient for RusshClient { x11_proxy: x11_proxy.clone(), remote_forward_target: Arc::clone(&remote_forward_target), forward_agent: config.forward_agent, + bastion_direct, }) } // 情况2: 仅使用代理连接 @@ -2756,6 +2922,7 @@ impl SshClient for RusshClient { x11_proxy: x11_proxy.clone(), remote_forward_target: Arc::clone(&remote_forward_target), forward_agent: config.forward_agent, + bastion_direct, }) } // 情况3: 直接连接 @@ -2790,6 +2957,7 @@ impl SshClient for RusshClient { x11_proxy: x11_proxy.clone(), remote_forward_target: Arc::clone(&remote_forward_target), forward_agent: config.forward_agent, + bastion_direct, }) } }; @@ -2843,6 +3011,11 @@ impl RusshClient { pub async fn open_raw_channel(&mut self) -> Result> { Ok(self.session.channel_open_session().await?) } + + /// 这条连接是否以「堡垒机直连」方式建立(会话即堡垒机)。 + pub fn is_bastion_direct(&self) -> bool { + self.bastion_direct + } } /// 解析本机 X server 环境,失败仅告警并返回 None(X11 转发静默停用)。 @@ -2901,14 +3074,15 @@ mod port_forward_tests { use tempfile::TempDir; use tokio::net::TcpListener; - use crate::{HostKeyPolicy, LegacyAlgorithmRequired}; + use crate::{HostKeyPolicy, JumpChannelRejected, LegacyAlgorithmRequired}; use super::{ - Algorithm, EcdsaCurve, HostKeyDetails, HostKeyIdentity, HostKeyProxyType, HostKeyRoute, - HostKeyVerifier, JumpServerConnectConfig, Preferred, PrivateKey, ProxyConnectConfig, - ProxyType, RusshClient, SshAuth, SshClient, SshConnectConfig, - build_client_preferred_algorithms_with_legacy, build_local_forward_bind_addr, - build_russh_client_config, legacy_gex_params, normalize_disconnect_result, + Algorithm, BastionUserFormat, EcdsaCurve, HostKeyDetails, HostKeyIdentity, + HostKeyProxyType, HostKeyRoute, HostKeyVerifier, JumpMode, JumpServerConnectConfig, + Preferred, PrivateKey, ProxyConnectConfig, ProxyType, RusshClient, SshAuth, SshClient, + SshConnectConfig, build_client_preferred_algorithms_with_legacy, + build_local_forward_bind_addr, build_russh_client_config, legacy_gex_params, + normalize_disconnect_result, }; #[derive(Clone)] @@ -3031,6 +3205,10 @@ mod port_forward_tests { port: 2222, username: "jumper".to_owned(), auth: SshAuth::Agent, + mode: JumpMode::default(), + bastion_asset: String::new(), + bastion_account: String::new(), + bastion_user_format: BastionUserFormat::default(), }); config.proxy = Some(ProxyConnectConfig { proxy_type: ProxyType::Http, @@ -3077,6 +3255,10 @@ mod port_forward_tests { port: 22, username: "jumper".to_owned(), auth: SshAuth::Agent, + mode: super::JumpMode::default(), + bastion_asset: String::new(), + bastion_account: String::new(), + bastion_user_format: super::BastionUserFormat::default(), }); assert_eq!( @@ -3261,6 +3443,10 @@ mod port_forward_tests { port: 22, username: "jumper".to_owned(), auth: SshAuth::Agent, + mode: super::JumpMode::default(), + bastion_asset: String::new(), + bastion_account: String::new(), + bastion_user_format: super::BastionUserFormat::default(), }); config.allow_legacy_algorithms = true; let target_identity = config.target_host_key_identity(); @@ -3979,6 +4165,123 @@ zsXyAAAAAAE= assert!(result.is_err()); } + + /// 跳板机测试服务器:接受登录,但像 JumpServer Koko 一样拒绝所有 direct-tcpip 通道。 + #[derive(Clone)] + struct ForwardingDenyingJumpServer; + + impl russh::server::Server for ForwardingDenyingJumpServer { + type Handler = Self; + + fn new_client(&mut self, _: Option) -> Self::Handler { + self.clone() + } + } + + impl russh::server::Handler for ForwardingDenyingJumpServer { + type Error = anyhow::Error; + + async fn auth_password(&mut self, _: &str, _: &str) -> Result { + Ok(Auth::Accept) + } + + async fn channel_open_direct_tcpip( + &mut self, + _channel: russh::Channel, + _host_to_connect: &str, + _port_to_connect: u32, + _originator_address: &str, + _originator_port: u32, + reply: russh::server::ChannelOpenHandle, + _session: &mut russh::server::Session, + ) -> Result<(), Self::Error> { + // 仿真 JumpServer:管理性拒绝端口转发,并附上服务器侧描述文本。 + reply + .reject(russh::ChannelOpenFailure::Other { + code: russh::ChannelOpenFailure::AdministrativelyProhibited.code(), + reason: "port forwarding is disabled".to_string(), + }) + .await; + Ok(()) + } + } + + async fn spawn_forwarding_denying_jump_server() -> ( + std::net::SocketAddr, + tokio::task::JoinHandle>, + ) { + let socket = TcpListener::bind(("127.0.0.1", 0)) + .await + .expect("forwarding-denying jump server should bind"); + let address = socket + .local_addr() + .expect("forwarding-denying jump server should have an address"); + let ed25519 = PrivateKey::random(&mut rand_010::rng(), Algorithm::Ed25519) + .expect("Ed25519 host key should be generated"); + let server_config = Arc::new(russh::server::Config { + auth_rejection_time: Duration::ZERO, + auth_rejection_time_initial: Some(Duration::ZERO), + keys: vec![ed25519], + ..Default::default() + }); + let server_task = tokio::spawn(async move { + let mut server = ForwardingDenyingJumpServer; + server.run_on_socket(server_config, &socket).await + }); + (address, server_task) + } + + fn jump_denied_test_config(jump_address: std::net::SocketAddr) -> SshConnectConfig { + SshConnectConfig { + host: "10.255.255.1".to_owned(), + port: 22, + username: "tester".to_owned(), + auth: SshAuth::Password("password".to_owned()), + timeout: Some(Duration::from_secs(10)), + keepalive_interval: None, + keepalive_max: None, + jump_server: Some(JumpServerConnectConfig { + host: jump_address.ip().to_string(), + port: jump_address.port(), + username: "jump".to_owned(), + auth: SshAuth::Password("password".to_owned()), + mode: JumpMode::default(), + bastion_asset: String::new(), + bastion_account: String::new(), + bastion_user_format: BastionUserFormat::default(), + }), + proxy: None, + keyboard_interactive_responder: None, + host_key_verifier: HostKeyVerifier::insecure(), + x11_forwarding: false, + allow_legacy_algorithms: false, + forward_agent: false, + agent_identities: Vec::new(), + } + } + + #[tokio::test] + async fn jump_direct_tcpip_rejection_surfaces_hint_and_server_description() { + let (jump_address, server_task) = spawn_forwarding_denying_jump_server().await; + + let result = RusshClient::connect(jump_denied_test_config(jump_address)).await; + server_task.abort(); + + let Err(error) = result else { + panic!("a jump server rejecting direct-tcpip must fail the connection"); + }; + assert!( + error.downcast_ref::().is_some(), + "rejection should be wrapped as JumpChannelRejected, got: {error:#}" + ); + assert!(error.to_string().contains("Failed to open channel")); + // 服务器描述必须透传,否则用户只会看到枚举名。 + assert!( + error.to_string().contains("port forwarding is disabled"), + "server description should be surfaced, got: {error:#}" + ); + assert!(error.to_string().contains("jump")); + } } pub struct RusshChannel { diff --git a/crates/ssh/tests/bastion_direct_test.rs b/crates/ssh/tests/bastion_direct_test.rs new file mode 100644 index 000000000..fc8c827ce --- /dev/null +++ b/crates/ssh/tests/bastion_direct_test.rs @@ -0,0 +1,117 @@ +use std::sync::Arc; +use std::sync::Mutex as StdMutex; +use std::time::Duration; + +use russh::keys::{Algorithm, PrivateKey}; +use russh::server::{Auth, Server as _}; +use tokio::net::TcpListener; + +use ssh::{ + BastionUserFormat, JumpMode, JumpServerConnectConfig, RusshClient, SshAuth, SshClient, + SshConnectConfig, +}; + +/// 直连型堡垒机测试服务器:记录登录用户名,接受密码认证, +/// 像真实堡垒机一样提供 shell 会话(会话即目标)。 +#[derive(Clone)] +struct BastionLikeServer { + seen_usernames: Arc>>, +} + +impl russh::server::Server for BastionLikeServer { + type Handler = Self; + + fn new_client(&mut self, _: Option) -> Self::Handler { + self.clone() + } +} + +impl russh::server::Handler for BastionLikeServer { + type Error = anyhow::Error; + + async fn auth_password(&mut self, user: &str, _: &str) -> Result { + self.seen_usernames + .lock() + .expect("username log mutex") + .push(user.to_owned()); + Ok(Auth::Accept) + } + + async fn channel_open_session( + &mut self, + _channel: russh::Channel, + _reply: russh::server::ChannelOpenHandle, + _session: &mut russh::server::Session, + ) -> Result<(), Self::Error> { + Ok(()) + } +} + +async fn spawn_bastion_like_server() +-> std::io::Result<(std::net::SocketAddr, Arc>>)> { + let socket = TcpListener::bind(("127.0.0.1", 0)).await?; + let address = socket.local_addr()?; + let seen = Arc::new(StdMutex::new(Vec::new())); + let mut server = BastionLikeServer { + seen_usernames: seen.clone(), + }; + let ed25519 = PrivateKey::random(&mut rand_010::rng(), Algorithm::Ed25519) + .map_err(std::io::Error::other)?; + let server_config = Arc::new(russh::server::Config { + auth_rejection_time: Duration::ZERO, + auth_rejection_time_initial: Some(Duration::ZERO), + keys: vec![ed25519], + ..Default::default() + }); + tokio::spawn(async move { server.run_on_socket(server_config, &socket).await }); + Ok((address, seen)) +} + +#[tokio::test] +async fn bastion_direct_connects_without_direct_tcpip_channel() { + let (bastion_address, seen_usernames) = spawn_bastion_like_server() + .await + .expect("server should bind"); + + let config = SshConnectConfig { + host: bastion_address.ip().to_string(), + port: bastion_address.port(), + username: "ignored-target-user".to_owned(), + auth: SshAuth::Password("password".to_owned()), + timeout: Some(Duration::from_secs(10)), + keepalive_interval: None, + keepalive_max: None, + jump_server: Some(JumpServerConnectConfig { + host: bastion_address.ip().to_string(), + port: bastion_address.port(), + username: "hufei".to_owned(), + auth: SshAuth::Password("password".to_owned()), + mode: JumpMode::BastionDirect, + bastion_asset: "0e85eca7-422a-4cdb-8e4c-8e3ff68eee39".to_owned(), + bastion_account: "root".to_owned(), + bastion_user_format: BastionUserFormat::JumpServer, + }), + proxy: None, + keyboard_interactive_responder: None, + host_key_verifier: ssh::HostKeyVerifier::insecure(), + x11_forwarding: false, + allow_legacy_algorithms: false, + forward_agent: false, + agent_identities: Vec::new(), + }; + + let mut client = RusshClient::connect(config) + .await + .expect("bastion direct connect must succeed without direct-tcpip"); + + // 登录用户名必须渲染为 {user}#{account}#{asset},而不是表单里的目标用户名。 + let usernames = seen_usernames.lock().expect("username log").clone(); + assert_eq!( + usernames, + vec!["hufei#root#0e85eca7-422a-4cdb-8e4c-8e3ff68eee39".to_owned()], + "bastion login username must follow the JumpServer format" + ); + + // 会话即堡垒机:断开会话即断开堡垒机连接。 + client.disconnect().await.expect("disconnect"); +} diff --git a/crates/ssh/tests/huawei_vrp_legacy.rs b/crates/ssh/tests/huawei_vrp_legacy.rs index 7bbbe1d5d..8d31f42d0 100644 --- a/crates/ssh/tests/huawei_vrp_legacy.rs +++ b/crates/ssh/tests/huawei_vrp_legacy.rs @@ -34,7 +34,11 @@ impl russh::server::Server for HuaweiVrpServer { impl russh::server::Handler for HuaweiVrpServer { type Error = anyhow::Error; - async fn auth_password(&mut self, _: &str, _: &str) -> Result { + async fn auth_password( + &mut self, + _: &str, + _: &str, + ) -> Result { Ok(russh::server::Auth::Accept) } } @@ -84,10 +88,7 @@ async fn spawn_huawei_vrp_server() -> ( russh::kex::DH_G1_SHA1, ]), key: Cow::Owned(vec![Algorithm::Rsa { hash: None }]), - cipher: Cow::Owned(vec![ - russh::cipher::AES_256_CTR, - russh::cipher::AES_128_CTR, - ]), + cipher: Cow::Owned(vec![russh::cipher::AES_256_CTR, russh::cipher::AES_128_CTR]), mac: Cow::Owned(vec![russh::mac::HMAC_SHA256, russh::mac::HMAC_SHA1]), compression: Cow::Owned(vec![russh::compression::NONE]), ..russh::Preferred::default() @@ -105,11 +106,7 @@ async fn spawn_huawei_vrp_server() -> ( #[tokio::test] async fn client_connects_to_huawei_vrp_profile_with_legacy_algorithms() { let (address, server_task) = spawn_huawei_vrp_server().await; - let config = client_config( - address.ip().to_string(), - address.port(), - true, - ); + let config = client_config(address.ip().to_string(), address.port(), true); let result = RusshClient::connect(config).await; server_task.abort(); diff --git a/crates/ssh_form/Cargo.toml b/crates/ssh_form/Cargo.toml index 848002900..c515f7778 100644 --- a/crates/ssh_form/Cargo.toml +++ b/crates/ssh_form/Cargo.toml @@ -13,6 +13,7 @@ gpui-component = { workspace = true } image = { workspace = true } one-assets = { workspace = true } one-core = { workspace = true } +sftp_transfer = { workspace = true } otp = { workspace = true } rqrr = "0.9" rust-i18n = { workspace = true } diff --git a/crates/ssh_form/locales/ssh_form.yml b/crates/ssh_form/locales/ssh_form.yml index e3dd28688..b3bfa4c56 100644 --- a/crates/ssh_form/locales/ssh_form.yml +++ b/crates/ssh_form/locales/ssh_form.yml @@ -498,11 +498,64 @@ SSH: en: Other zh-CN: 其他设置 zh-HK: 其他設定 + # 连接方式(基础信息) + connection_mode: + en: Connection Mode + zh-CN: 连接方式 + zh-HK: 連接方式 + connection_mode_direct: + en: Direct + zh-CN: 直连 + zh-HK: 直連 + connection_mode_jump: + en: Jump Server + zh-CN: 跳板机 + zh-HK: 跳板機 + connection_mode_bastion: + en: Bastion Direct + zh-CN: 堡垒机直连 + zh-HK: 堡壘機直連 + bastion_direct_hint: + en: The address, port, username and credentials above are the bastion login. The bastion proxies the session to the asset below; the login name is rendered as user#account#asset. + zh-CN: 上方地址、端口、用户名与认证即堡垒机登录信息,由堡垒机把会话代理到下方填写的资产;登录名按 用户名#账号#资产 渲染。 + zh-HK: 上方地址、端口、用戶名與認證即堡壘機登錄信息,由堡壘機把會話代理到下方填寫的資產;登錄名按 用戶名#賬號#資產 渲染。 + bastion_host: + en: Bastion Host + zh-CN: 堡垒机地址 + zh-HK: 堡壘機地址 + bastion_port: + en: Bastion Port + zh-CN: 堡垒机端口 + zh-HK: 堡壘機端口 # 跳板机相关 - enable_jump_server: - en: Enable Jump Server - zh-CN: 启用跳板机 - zh-HK: 啟用跳板機 + jump_tab_enabled_hint: + en: Traffic is forwarded through the jump server (ProxyJump). Fill in the jump server below. + zh-CN: 当前连接方式为「跳板机」,流量经下方跳板机转发(ProxyJump)。 + zh-HK: 當前連接方式為「跳板機」,流量經下方跳板機轉發(ProxyJump)。 + jump_tab_bastion_hint: + en: Connection mode is Bastion Direct. The bastion login is configured in Basic Info, so the jump server settings below do not take effect. + zh-CN: 当前连接方式为「堡垒机直连」,堡垒机登录信息在「基本信息」中配置,下方跳板机设置不生效。 + zh-HK: 當前連接方式為「堡壘機直連」,堡壘機登錄信息在「基本信息」中配置,下方跳板機設定不生效。 + jump_tab_disabled_hint: + en: Connection mode is Direct. Choose "Jump Server" in Basic Info to enable the forwarding below. Filled settings are kept for later. + zh-CN: 当前连接方式为「直连」。如需经跳板机转发,请先在「基本信息」中选择「跳板机」;已填内容会保留备用。 + zh-HK: 當前連接方式為「直連」。如需經跳板機轉發,請先在「基本信息」中選擇「跳板機」;已填內容會保留備用。 + bastion_asset: + en: Bastion Asset ID + zh-CN: 堡垒机资产 ID + zh-HK: 堡壘機資產 ID + bastion_asset_placeholder: + en: Asset ID on the bastion host, e.g. 0e85eca7-... + zh-CN: 堡垒机上的资产 ID,如 0e85eca7-... + zh-HK: 堡壘機上的資產 ID,如 0e85eca7-... + bastion_account: + en: Bastion Asset Account + zh-CN: 资产登录账号 + zh-HK: 資產登錄賬號 + bastion_account_placeholder: + en: Login account on the asset, e.g. root + zh-CN: 资产上的登录账号,如 root + zh-HK: 資產上的登錄賬號,如 root jump_host: en: Jump Host zh-CN: 跳板机地址 diff --git a/crates/ssh_form/src/ssh_form_window.rs b/crates/ssh_form/src/ssh_form_window.rs index 4279776cb..32aa325c6 100644 --- a/crates/ssh_form/src/ssh_form_window.rs +++ b/crates/ssh_form/src/ssh_form_window.rs @@ -35,17 +35,20 @@ use one_core::connection_notifier::{ConnectionDataEvent, get_notifier}; use one_core::gpui_tokio::Tokio; use one_core::storage::traits::Repository; use one_core::storage::{ - FtpParams, JumpServerConfig, PreferredOpenMode, ProxyConfig, ProxyType as StorageProxyType, - RemoteFileParams, RemoteFileProtocol as StoredRemoteFileProtocol, SSH_ICON_IDS, SftpAccount, - SshAccountExpect, SshAgentForwardKey, SshAuthMethod, SshElevationExpect, SshParams, - StoredConnection, StoredTerminalEncoding, StoredTerminalType, Workspace, ssh_os_icon, + BastionTarget, FtpParams, + JumpMode as StorageJumpMode, JumpServerConfig, PreferredOpenMode, ProxyConfig, + ProxyType as StorageProxyType, RemoteFileParams, + RemoteFileProtocol as StoredRemoteFileProtocol, SSH_ICON_IDS, SftpAccount, SshAccountExpect, + SshAgentForwardKey, SshAuthMethod, SshElevationExpect, SshParams, StoredConnection, + StoredTerminalEncoding, StoredTerminalType, Workspace, ssh_os_icon, }; use otp::OtpSecret; use rust_i18n::t; +use sftp_transfer::{jump_connect_config, proxy_connect_config, ssh_auth}; use ssh::{ AgentIdentity, ChannelEvent, HostKeyDetails, HostKeyIdentity, HostKeyRejection, - HostKeyVerifier, JumpServerConnectConfig, ProxyConnectConfig, ProxyType, RusshClient, SshAuth, - SshChannel, SshClient, SshConnectConfig, SshSessionManager, + HostKeyVerifier, RusshClient, SshAuth, SshChannel, SshClient, SshConnectConfig, + SshSessionManager, }; use std::net::IpAddr; use std::sync::Arc; @@ -228,6 +231,38 @@ impl SelectItem for AuthMethodSelectItem { } } +/// 认证方式下拉的全部选项:目标主机与跳板机共用同一套顺序。 +fn auth_method_items() -> Vec { + [ + AuthMethodSelection::Password, + AuthMethodSelection::PrivateKey, + AuthMethodSelection::PasswordAndPrivateKey, + AuthMethodSelection::PrivateKeyContent, + AuthMethodSelection::Agent, + AuthMethodSelection::Pageant, + AuthMethodSelection::AutoPublicKey, + AuthMethodSelection::None, + ] + .into_iter() + .map(|method| AuthMethodSelectItem { method }) + .collect() +} + +/// 基础信息里的连接方式单选:决定这条连接走哪条链路。 +/// +/// 三者互斥: +/// - `Direct`:直接连目标主机; +/// - `Jump`:经跳板机转发(ProxyJump 语义,跳板机设置见「跳板机」页); +/// - `BastionDirect`:基础信息里的地址/端口/用户名/认证即堡垒机登录信息, +/// 由堡垒机把会话代理到资产(登录名渲染为 `用户#账号#资产`)。 +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +enum ConnectionMode { + #[default] + Direct, + Jump, + BastionDirect, +} + pub struct SshFormWindow { focus_handle: FocusHandle, is_editing: bool, @@ -273,9 +308,15 @@ pub struct SshFormWindow { workspace_select: Entity>>, team_select: Entity>>, - // 跳板机设置 - enable_jump_server: bool, + // 连接方式:直连 / 跳板机 / 堡垒机直连(基础信息里单选决定) + connection_mode: ConnectionMode, jump_auth_method: AuthMethodSelection, + /// 跳板机认证方式下拉框;与目标主机认证方式共用同一套选项,避免一整排单选把表单撑宽。 + jump_auth_method_select: Entity>>, + /// 堡垒机直连模式下的目标资产 ID(如 JumpServer 的资产 UUID)。 + bastion_asset_input: Entity, + /// 堡垒机直连模式下的资产登录账号(如 root)。 + bastion_account_input: Entity, jump_host_input: Entity, jump_port_input: Entity, jump_username_input: Entity, @@ -641,8 +682,10 @@ fn preferred_open_mode_from_form(open_dual_pane_by_default: bool) -> Option, + bastion_account_input: &Entity, jump_credential_reference: &mut Option, - enabled: &mut bool, jump_host_input: &Entity, jump_port_input: &Entity, jump_username_input: &Entity, @@ -654,7 +697,14 @@ fn load_jump_server_into_form( cx: &mut App, ) { *jump_credential_reference = jump.credential_reference.clone(); - *enabled = true; + *connection_mode = match jump.mode { + StorageJumpMode::BastionDirect => ConnectionMode::BastionDirect, + StorageJumpMode::ProxyJump => ConnectionMode::Jump, + }; + if let Some(ref bastion) = jump.bastion { + bastion_asset_input.update(cx, |s, cx| s.set_value(&bastion.asset, window, cx)); + bastion_account_input.update(cx, |s, cx| s.set_value(&bastion.account, window, cx)); + } jump_host_input.update(cx, |s, cx| s.set_value(&jump.host, window, cx)); jump_port_input.update(cx, |s, cx| s.set_value(&jump.port.to_string(), window, cx)); jump_username_input.update(cx, |s, cx| s.set_value(&jump.username, window, cx)); @@ -800,32 +850,6 @@ fn combined_auth_fields(auth: &SshAuthMethod) -> (String, String, String, String } /// 存储层认证方式 → 运行时认证方式(组合认证递归展开)。 -fn runtime_ssh_auth(auth: &SshAuthMethod) -> SshAuth { - match auth { - SshAuthMethod::Password { password } => SshAuth::Password(password.clone()), - SshAuthMethod::PrivateKey { - key_path, - passphrase, - } => SshAuth::PrivateKey { - key_path: key_path.clone(), - passphrase: passphrase.clone(), - certificate_path: None, - }, - SshAuthMethod::PrivateKeyContent { - private_key, - passphrase, - } => SshAuth::PrivateKeyContent { - private_key: private_key.clone(), - passphrase: passphrase.clone(), - certificate_path: None, - }, - SshAuthMethod::Agent => SshAuth::Agent, - SshAuthMethod::Pageant => SshAuth::Pageant, - SshAuthMethod::AutoPublicKey => SshAuth::AutoPublicKey, - SshAuthMethod::None => SshAuth::None, - SshAuthMethod::Chain(steps) => SshAuth::Chain(steps.iter().map(runtime_ssh_auth).collect()), - } -} #[derive(Clone, Copy, PartialEq, Eq, Default)] pub enum ProxyTypeSelection { @@ -897,6 +921,11 @@ impl SshFormWindow { state.set_value("22", window, cx); state }); + let bastion_asset_input = cx + .new(|cx| InputState::new(window, cx).placeholder(t!("SSH.bastion_asset_placeholder"))); + let bastion_account_input = cx.new(|cx| { + InputState::new(window, cx).placeholder(t!("SSH.bastion_account_placeholder")) + }); let jump_username_input = cx.new(|cx| InputState::new(window, cx).placeholder(t!("SSH.username_placeholder"))); let jump_password_input = cx.new(|cx| { @@ -1048,13 +1077,13 @@ impl SshFormWindow { let mut otp_secret: Option = None; let mut sudo_password_auto_fill: Option = None; let mut jump_auth_method = AuthMethodSelection::Password; + let mut connection_mode = ConnectionMode::Direct; // 新建连接向导指定了目标分组时预选该分组(编辑 / 复制连接走下面的回填逻辑)。 let mut workspace_id: Option = if is_editing || config.initial_connection.is_some() { None } else { config.initial_workspace_id }; - let mut enable_jump_server = false; let mut enable_proxy = false; let mut proxy_type = ProxyTypeSelection::default(); let mut sync_enabled = true; // 默认启用云同步 @@ -1202,8 +1231,10 @@ impl SshFormWindow { load_jump_server_into_form( jump, &mut jump_auth_method, + &mut connection_mode, + &bastion_asset_input, + &bastion_account_input, &mut jump_credential_reference, - &mut enable_jump_server, &jump_host_input, &jump_port_input, &jump_username_input, @@ -1216,12 +1247,15 @@ impl SshFormWindow { ); } if let Some(ref jump) = params.disabled_jump_server { - let mut enabled = false; + // 停用保留的配置只回填输入框,不改变连接方式(保持直连)。 + let mut ignored_mode = ConnectionMode::Direct; load_jump_server_into_form( jump, &mut jump_auth_method, + &mut ignored_mode, + &bastion_asset_input, + &bastion_account_input, &mut jump_credential_reference, - &mut enabled, &jump_host_input, &jump_port_input, &jump_username_input, @@ -1310,25 +1344,17 @@ impl SshFormWindow { // 认证方式用下拉框呈现:一整排单选按钮在窄窗口 / 多语言长标签下会换行撑宽表单, // 而它本质上只是一个单选项。默认停在「密码」,与 `SshAuthOption::default()` 一致。 - let auth_method_items = [ - AuthMethodSelection::Password, - AuthMethodSelection::PrivateKey, - AuthMethodSelection::PasswordAndPrivateKey, - AuthMethodSelection::PrivateKeyContent, - AuthMethodSelection::Agent, - AuthMethodSelection::Pageant, - AuthMethodSelection::AutoPublicKey, - AuthMethodSelection::None, - ] - .iter() - .copied() - .map(|method| AuthMethodSelectItem { method }) - .collect::>(); let auth_method_select = cx.new(|cx| { - let mut state = SelectState::new(auth_method_items, None, window, cx); + let mut state = SelectState::new(auth_method_items(), None, window, cx); state.set_selected_value(&auth_method, window, cx); state }); + // 跳板机认证方式与目标主机同构,也用下拉框,省掉一整排单选按钮。 + let jump_auth_method_select = cx.new(|cx| { + let mut state = SelectState::new(auth_method_items(), None, window, cx); + state.set_selected_value(&jump_auth_method, window, cx); + state + }); let credential_picker = create_credential_picker( CredentialPickerConfig::new( @@ -1395,6 +1421,15 @@ impl SshFormWindow { } }, ), + cx.subscribe_in( + &jump_auth_method_select, + window, + |this, _, event: &SelectEvent>, window, cx| { + if let SelectEvent::Confirm(Some(method)) = event { + this.set_jump_auth_method(*method, window, cx); + } + }, + ), ]; // 验证码按时间窗口滚动,配置了密钥时每秒刷新一次,让预览里的验证码与剩余秒数保持准确。 cx.spawn(async move |this, cx| { @@ -1433,6 +1468,7 @@ impl SshFormWindow { credential_picker, auth_method_select, auth_method, + jump_auth_method_select, save_username, save_password, keyboard_interactive, @@ -1445,8 +1481,10 @@ impl SshFormWindow { terminal_type_select, workspace_select, team_select, - enable_jump_server, + connection_mode, jump_auth_method, + bastion_asset_input, + bastion_account_input, jump_host_input, jump_port_input, jump_username_input, @@ -1536,6 +1574,18 @@ impl SshFormWindow { cx.notify(); } + /// 切换连接方式:离开「跳板机」时清掉该页的 MFA 状态,避免带着上一次的交互残留。 + fn set_connection_mode(&mut self, mode: ConnectionMode, cx: &mut Context) { + if self.connection_mode == mode { + return; + } + self.connection_mode = mode; + if mode != ConnectionMode::Jump { + self.clear_jump_mfa_fields(); + } + cx.notify(); + } + fn set_jump_auth_method( &mut self, auth_method: AuthMethodSelection, @@ -1543,6 +1593,9 @@ impl SshFormWindow { cx: &mut Context, ) { self.jump_auth_method = auth_method; + self.jump_auth_method_select.update(cx, |select, cx| { + select.set_selected_value(&auth_method, window, cx); + }); self.jump_credential_picker.update(cx, |picker, cx| { picker.set_capabilities(credential_capabilities_for_auth(auth_method), window, cx); }); @@ -1588,6 +1641,56 @@ impl SshFormWindow { jump_private_key, jump_passphrase, ), + mode: StorageJumpMode::ProxyJump, + bastion: None, + }) + } + + /// 堡垒机直连的资产账号;两栏任一为空都返回 `None`(保存时会被校验拦住)。 + fn collect_bastion_target(&self, cx: &App) -> Option { + let asset = self + .bastion_asset_input + .read(cx) + .text() + .to_string() + .trim() + .to_string(); + let account = self + .bastion_account_input + .read(cx) + .text() + .to_string() + .trim() + .to_string(); + if asset.is_empty() || account.is_empty() { + return None; + } + Some(BastionTarget { + asset, + account, + user_format: Default::default(), + }) + } + + /// 堡垒机直连模式下的「跳板机配置」:地址/端口/用户名/认证直接取基础信息, + /// 只额外挂上资产与账号。登录名在连接时渲染为 `用户#账号#资产`。 + fn build_bastion_direct_jump_config( + &self, + cx: &App, + host: String, + port: u16, + username: String, + credential_reference: Option, + auth_method: SshAuthMethod, + ) -> Option { + Some(JumpServerConfig { + host, + port, + username, + credential_reference, + auth_method, + mode: StorageJumpMode::BastionDirect, + bastion: self.collect_bastion_target(cx), }) } @@ -1610,6 +1713,12 @@ impl SshFormWindow { if host.is_empty() || (username.is_empty() && self.save_username && !keychain_selected) { return None; } + // 堡垒机直连没有资产或账号就渲染不出「用户#账号#资产」登录名,拦住半成品配置。 + if self.connection_mode == ConnectionMode::BastionDirect + && self.collect_bastion_target(cx).is_none() + { + return None; + } let auth_method = match self.auth_method { AuthMethodSelection::None => SshAuthMethod::None, @@ -1694,12 +1803,24 @@ impl SshFormWindow { .to_string(); if s.is_empty() { None } else { Some(s) } }; - // 跳板机配置:启用时读取表单并生效;停用时保留已填信息以便下次恢复 - let jump_config = self.collect_jump_server_config(cx); - let (jump_server, disabled_jump_server) = if self.enable_jump_server { - (jump_config, None) - } else { - (None, jump_config) + // 连接方式决定 jump_server 的来源: + // - 跳板机:读「跳板机」页的表单; + // - 堡垒机直连:基础信息即堡垒机登录信息,资产/账号来自专用两栏; + // - 直连:不生效,但把「跳板机」页已填内容留在 disabled_jump_server 里以便下次恢复。 + let (jump_server, disabled_jump_server) = match self.connection_mode { + ConnectionMode::Jump => (self.collect_jump_server_config(cx), None), + ConnectionMode::Direct => (None, self.collect_jump_server_config(cx)), + ConnectionMode::BastionDirect => ( + self.build_bastion_direct_jump_config( + cx, + host.clone(), + port, + username.clone(), + credential_reference.clone(), + auth_method.clone(), + ), + None, + ), }; // 代理配置 @@ -1911,33 +2032,12 @@ impl SshFormWindow { } fn build_ssh_connect_config(&self, params: &SshParams) -> SshConnectConfig { - let auth = runtime_ssh_auth(¶ms.auth_method); - - // 构建跳板机配置 - let jump_server = params.jump_server.as_ref().map(|jump| { - let jump_auth = runtime_ssh_auth(&jump.auth_method); - JumpServerConnectConfig { - host: jump.host.clone(), - port: jump.port, - username: jump.username.clone(), - auth: jump_auth, - } - }); + let auth = ssh_auth(params.auth_method.clone()); + // 构建跳板机配置(统一映射入口,与终端/端口转发/SFTP 工具一致) + let jump_server = params.jump_server.as_ref().map(jump_connect_config); // 构建代理配置 - let proxy = params.proxy.as_ref().map(|p| { - let proxy_type = match p.proxy_type { - StorageProxyType::Socks5 => ProxyType::Socks5, - StorageProxyType::Http => ProxyType::Http, - }; - ProxyConnectConfig { - proxy_type, - host: p.host.clone(), - port: p.port, - username: p.username.clone(), - password: p.password.clone(), - } - }); + let proxy = params.proxy.as_ref().map(proxy_connect_config); SshConnectConfig { host: params.host.clone(), @@ -2953,19 +3053,79 @@ impl SshFormWindow { /// 渲染基本信息标签页 fn render_basic_tab(&self, cx: &mut Context) -> impl IntoElement { let auth_method = self.auth_method; + let connection_mode = self.connection_mode; let credential_is_manual = self .credential_picker .read(cx) .selected_reference() .is_none(); + // 堡垒机直连时,基础信息的地址/端口/用户名/认证就是堡垒机登录信息。 + let host_label = match connection_mode { + ConnectionMode::BastionDirect => t!("SSH.bastion_host"), + _ => t!("SSH.host"), + }; + let port_label = match connection_mode { + ConnectionMode::BastionDirect => t!("SSH.bastion_port"), + _ => t!("SSH.port"), + }; v_flex() .w_full() .gap_2() .child(self.render_form_row(&t!("SSH.name"), self.render_form_input(&self.name_input))) .child(self.render_form_row(&t!("SSH.icon"), self.render_icon_picker(cx))) - .child(self.render_form_row(&t!("SSH.host"), self.render_form_input(&self.host_input))) - .child(self.render_form_row(&t!("SSH.port"), self.render_form_input(&self.port_input))) + .child( + self.render_form_row( + &t!("SSH.connection_mode"), + h_flex() + .gap_4() + .flex_wrap() + .child( + Radio::new("connection-mode-direct") + .label(t!("SSH.connection_mode_direct").to_string()) + .checked(connection_mode == ConnectionMode::Direct) + .on_click(cx.listener(|this, _, _, cx| { + this.set_connection_mode(ConnectionMode::Direct, cx); + })), + ) + .child( + Radio::new("connection-mode-jump") + .label(t!("SSH.connection_mode_jump").to_string()) + .checked(connection_mode == ConnectionMode::Jump) + .on_click(cx.listener(|this, _, _, cx| { + this.set_connection_mode(ConnectionMode::Jump, cx); + })), + ) + .child( + Radio::new("connection-mode-bastion") + .label(t!("SSH.connection_mode_bastion").to_string()) + .checked(connection_mode == ConnectionMode::BastionDirect) + .on_click(cx.listener(|this, _, _, cx| { + this.set_connection_mode(ConnectionMode::BastionDirect, cx); + })), + ), + ), + ) + .child(self.render_form_row(&host_label, self.render_form_input(&self.host_input))) + .child(self.render_form_row(&port_label, self.render_form_input(&self.port_input))) + .when(connection_mode == ConnectionMode::BastionDirect, |this| { + this.child( + h_flex().justify_center().child( + div() + .text_sm() + .text_color(cx.theme().muted_foreground) + .child(t!("SSH.bastion_direct_hint").to_string()), + ), + ) + .child(self.render_form_row( + &t!("SSH.bastion_asset"), + self.render_form_input(&self.bastion_asset_input), + )) + .child(self.render_form_row( + &t!("SSH.bastion_account"), + self.render_form_input(&self.bastion_account_input), + )) + }) .child(self.render_form_row(&t!("SSH.keychain"), self.credential_picker.clone())) .when(credential_is_manual, |form| { form.child(self.render_form_row( @@ -3254,8 +3414,13 @@ impl SshFormWindow { /// 渲染跳板机标签页 fn render_jump_server_tab(&self, cx: &mut Context) -> impl IntoElement { - let enable_jump = self.enable_jump_server; + let connection_mode = self.connection_mode; let jump_auth_method = self.jump_auth_method; + let jump_tab_hint = match connection_mode { + ConnectionMode::Jump => t!("SSH.jump_tab_enabled_hint").to_string(), + ConnectionMode::BastionDirect => t!("SSH.jump_tab_bastion_hint").to_string(), + ConnectionMode::Direct => t!("SSH.jump_tab_disabled_hint").to_string(), + }; let jump_credential_is_manual = self .jump_credential_picker .read(cx) @@ -3266,20 +3431,14 @@ impl SshFormWindow { .w_full() .gap_2() .child( - self.render_form_row( - &t!("SSH.enable_jump_server"), - Checkbox::new("enable-jump") - .checked(enable_jump) - .on_click(cx.listener(|this, _, _, cx| { - this.enable_jump_server = !this.enable_jump_server; - if !this.enable_jump_server { - this.clear_jump_mfa_fields(); - } - cx.notify(); - })), + h_flex().justify_center().child( + div() + .text_sm() + .text_color(cx.theme().muted_foreground) + .child(jump_tab_hint), ), ) - .when(enable_jump, |this| { + .when(connection_mode == ConnectionMode::Jump, |this| { this.child(self.render_form_row( &t!("SSH.jump_host"), self.render_form_input(&self.jump_host_input), @@ -3300,110 +3459,7 @@ impl SshFormWindow { .child( self.render_form_row( &t!("SSH.jump_auth_method"), - h_flex() - .gap_4() - .flex_wrap() - .child( - Radio::new("jump-no-auth") - .label(t!("SSH.none_auth").to_string()) - .checked(jump_auth_method == AuthMethodSelection::None) - .on_click(cx.listener(|this, _, window, cx| { - this.set_jump_auth_method( - AuthMethodSelection::None, - window, - cx, - ); - })), - ) - .child( - Radio::new("jump-password") - .label(t!("SSH.password").to_string()) - .checked(jump_auth_method == AuthMethodSelection::Password) - .on_click(cx.listener(|this, _, window, cx| { - this.set_jump_auth_method( - AuthMethodSelection::Password, - window, - cx, - ); - })), - ) - .child( - Radio::new("jump-password-and-private-key") - .label(t!("SSH.password_and_private_key").to_string()) - .checked( - jump_auth_method - == AuthMethodSelection::PasswordAndPrivateKey, - ) - .on_click(cx.listener(|this, _, window, cx| { - this.set_jump_auth_method( - AuthMethodSelection::PasswordAndPrivateKey, - window, - cx, - ); - })), - ) - .child( - Radio::new("jump-private-key") - .label(t!("SSH.private_key").to_string()) - .checked(jump_auth_method == AuthMethodSelection::PrivateKey) - .on_click(cx.listener(|this, _, window, cx| { - this.set_jump_auth_method( - AuthMethodSelection::PrivateKey, - window, - cx, - ); - })), - ) - .child( - Radio::new("jump-private-key-content") - .label(t!("SSH.private_key_content").to_string()) - .checked( - jump_auth_method == AuthMethodSelection::PrivateKeyContent, - ) - .on_click(cx.listener(|this, _, window, cx| { - this.set_jump_auth_method( - AuthMethodSelection::PrivateKeyContent, - window, - cx, - ); - })), - ) - .child( - Radio::new("jump-agent") - .label(t!("SSH.agent").to_string()) - .checked(jump_auth_method == AuthMethodSelection::Agent) - .on_click(cx.listener(|this, _, window, cx| { - this.set_jump_auth_method( - AuthMethodSelection::Agent, - window, - cx, - ); - })), - ) - .child( - Radio::new("jump-pageant") - .label(t!("SSH.pageant").to_string()) - .checked(jump_auth_method == AuthMethodSelection::Pageant) - .on_click(cx.listener(|this, _, window, cx| { - this.set_jump_auth_method( - AuthMethodSelection::Pageant, - window, - cx, - ); - })), - ) - .child( - Radio::new("jump-auto-publickey") - .label(t!("SSH.auto_publickey").to_string()) - .checked(jump_auth_method == AuthMethodSelection::AutoPublicKey) - .on_click(cx.listener(|this, _, window, cx| { - this.set_jump_auth_method( - AuthMethodSelection::AutoPublicKey, - window, - cx, - ); - })), - ), + Select::new(&self.jump_auth_method_select).w_full(), ), ) .when( @@ -4308,7 +4364,8 @@ mod tests { use gpui::{Modifiers, TestAppContext, VisualTestContext}; use one_core::settings::AppSettings; use one_core::storage::{ - ConnectionType, CredentialReference, FtpParams, JumpServerConfig, PreferredOpenMode, + BastionTarget, BastionUserFormat, ConnectionType, CredentialReference, FtpParams, + JumpMode as StorageJumpMode, JumpServerConfig, PreferredOpenMode, RemoteFileParams, RemoteFileProtocol as StoredRemoteFileProtocol, SftpAccount, SshAuthMethod, SshElevationExpect, SshParams, StoredConnection, StoredTerminalEncoding, StoredTerminalType, @@ -5113,6 +5170,8 @@ mod tests { auth_method: SshAuthMethod::Password { password: "jump-secret".to_string(), }, + mode: Default::default(), + bastion: None, }); let initial_connection = StoredConnection::new_ssh("disabled-jump".to_string(), params, None); @@ -5132,7 +5191,11 @@ mod tests { }); form.read_with(cx, |form, _| { - assert!(!form.enable_jump_server, "停用的跳板机不应自动启用"); + assert_eq!( + form.connection_mode, + super::ConnectionMode::Direct, + "停用的跳板机不应自动启用" + ); }); form.read_with(cx, |form, cx| { assert_eq!(form.jump_host_input.read(cx).text(), "jump.example.com"); @@ -5156,7 +5219,7 @@ mod tests { // 重新启用保存:同一份数据切换到生效的 jump_server form.update(cx, |form, cx| { - form.enable_jump_server = true; + form.connection_mode = super::ConnectionMode::Jump; cx.notify(); }); let enabled = form @@ -5964,4 +6027,131 @@ mod tests { let conn = StoredConnection::new_ssh("same-record".to_string(), built, None); assert_eq!(conn.connection_type, ConnectionType::SshSftp); } + + /// 堡垒机直连:基础信息就是堡垒机登录信息,保存时由它派生 jump_server。 + #[gpui::test] + fn ssh_form_bastion_direct_derives_jump_config_from_basic_info( + cx: &mut TestAppContext, + ) { + cx.update(|cx| { + cx.set_global(AppSettings::default()); + gpui_component::init(cx); + }); + let mut params = sample_params(); + params.host = "10.2.5.220".to_string(); + params.port = 2222; + params.username = "hufei".to_string(); + params.auth_method = SshAuthMethod::Password { + password: "bastion-secret".to_string(), + }; + params.jump_server = Some(JumpServerConfig { + host: "10.2.5.220".to_string(), + port: 2222, + username: "hufei".to_string(), + credential_reference: None, + auth_method: SshAuthMethod::Password { + password: "bastion-secret".to_string(), + }, + mode: StorageJumpMode::BastionDirect, + bastion: Some(BastionTarget { + asset: "0e85eca7-422a-4cdb-8e4c-8e3ff68eee39".to_string(), + account: "root".to_string(), + user_format: BastionUserFormat::JumpServer, + }), + }); + let initial_connection = + StoredConnection::new_ssh("bastion-direct".to_string(), params, None); + let (form, cx) = cx.add_window_view(|window, cx| { + super::SshFormWindow::new( + super::SshFormWindowConfig { + initial_workspace_id: None, + editing_connection: None, + initial_connection: Some(initial_connection), + on_saved: None, + workspaces: Vec::new(), + teams: Vec::new(), + }, + window, + cx, + ) + }); + + form.read_with(cx, |form, _| { + assert_eq!( + form.connection_mode, + super::ConnectionMode::BastionDirect, + "已保存的堡垒机直连应在基础信息里回显为对应单选" + ); + }); + + let built = form + .read_with(cx, |form, cx| form.build_ssh_params(cx)) + .expect("堡垒机直连表单应能构建参数"); + assert_eq!(built.host, "10.2.5.220"); + assert_eq!(built.port, 2222); + assert_eq!(built.username, "hufei"); + let jump = built + .jump_server + .expect("堡垒机直连应把基础信息写成 jump_server"); + assert_eq!(jump.mode, StorageJumpMode::BastionDirect); + assert_eq!(jump.host, "10.2.5.220"); + assert_eq!(jump.port, 2222); + assert_eq!( + jump.bastion_login_username().as_deref(), + Some("hufei#root#0e85eca7-422a-4cdb-8e4c-8e3ff68eee39") + ); + assert!( + built.disabled_jump_server.is_none(), + "堡垒机直连是生效模式,不应落到停用暂存里" + ); + } + + /// 堡垒机直连缺资产或账号时渲染不出登录名,保存必须被拦住。 + #[gpui::test] + fn ssh_form_bastion_direct_requires_asset_and_account(cx: &mut TestAppContext) { + cx.update(|cx| { + cx.set_global(AppSettings::default()); + gpui_component::init(cx); + }); + let mut params = sample_params(); + params.host = "10.2.5.220".to_string(); + params.port = 2222; + params.username = "hufei".to_string(); + params.auth_method = SshAuthMethod::Password { + password: "bastion-secret".to_string(), + }; + params.jump_server = Some(JumpServerConfig { + host: "10.2.5.220".to_string(), + port: 2222, + username: "hufei".to_string(), + credential_reference: None, + auth_method: SshAuthMethod::Password { + password: "bastion-secret".to_string(), + }, + mode: StorageJumpMode::BastionDirect, + bastion: None, + }); + let initial_connection = + StoredConnection::new_ssh("bastion-incomplete".to_string(), params, None); + let (form, cx) = cx.add_window_view(|window, cx| { + super::SshFormWindow::new( + super::SshFormWindowConfig { + initial_workspace_id: None, + editing_connection: None, + initial_connection: Some(initial_connection), + on_saved: None, + workspaces: Vec::new(), + teams: Vec::new(), + }, + window, + cx, + ) + }); + + assert!( + form.read_with(cx, |form, cx| form.build_ssh_params(cx)) + .is_none(), + "缺资产/账号的堡垒机直连不应通过保存校验" + ); + } } diff --git a/crates/terminal/Cargo.toml b/crates/terminal/Cargo.toml index dba092c56..ee6d22c2e 100644 --- a/crates/terminal/Cargo.toml +++ b/crates/terminal/Cargo.toml @@ -12,6 +12,7 @@ futures = { workspace = true } anyhow = { workspace = true } async-trait = { workspace = true } one-core = { workspace = true } +sftp_transfer = { workspace = true } gpui = { workspace = true } ssh = { workspace = true } process-util = { workspace = true } diff --git a/crates/terminal/src/ssh_session_identity.rs b/crates/terminal/src/ssh_session_identity.rs index 1be90b7d7..f30390519 100644 --- a/crates/terminal/src/ssh_session_identity.rs +++ b/crates/terminal/src/ssh_session_identity.rs @@ -13,6 +13,7 @@ use std::fmt; use one_core::storage::models::{ConnectionType, StoredConnection}; + use ssh::{ ConnectionCredentialRevisions, ConnectionKey, ConnectionKeyError, CredentialRevision, SshConnectConfig, @@ -58,6 +59,30 @@ impl PersistedSshSessionIdentity { } let generation = PersistedCredentialGeneration::from_connection(connection)?; + Self::derive_with_generation(generation, config) + } + + /// 由连接 id 与凭据修订号直接派生(跳过 StoredConnection 装配)。 + /// + /// 校验与槽位派生和 [`PersistedSshSessionIdentity::derive`] 完全一致; + /// 供已抓取好元数据的连接尝试路径使用。类型校验由调用方保证 + /// (仅 SSH 连接应走到这里)。 + pub fn derive_from_metadata( + connection_id: i64, + credential_revision: i64, + config: &SshConnectConfig, + ) -> Result { + let generation = PersistedCredentialGeneration::from_metadata( + connection_id, + credential_revision, + )?; + Self::derive_with_generation(generation, config) + } + + fn derive_with_generation( + generation: PersistedCredentialGeneration, + config: &SshConnectConfig, + ) -> Result { let mut credentials = ConnectionCredentialRevisions::new(generation.for_scope(CredentialSlotScope::Target)?); @@ -192,33 +217,36 @@ struct PersistedCredentialGeneration { } impl PersistedCredentialGeneration { - fn from_connection( - connection: &StoredConnection, + /// 与 [`PersistedCredentialGeneration::from_connection`] 相同的校验, + /// 但直接接收已抓取好的连接 id 与凭据修订号。 + fn from_metadata( + connection_id: i64, + revision: i64, ) -> Result { - let connection_id = connection - .id - .ok_or(PersistedSshSessionIdentityError::MissingConnectionId)?; let connection_id = u64::try_from(connection_id) .ok() .filter(|id| *id > 0) .ok_or(PersistedSshSessionIdentityError::InvalidConnectionId)?; - - let revision = connection - .credential_revision - .ok_or(PersistedSshSessionIdentityError::MissingCredentialRevision)?; let revision = u64::try_from(revision) .ok() .filter(|revision| *revision > 0) .ok_or(PersistedSshSessionIdentityError::InvalidCredentialRevision)?; - let slot_base = connection_id .checked_mul(PERSISTED_CREDENTIAL_SCOPE_COUNT) .ok_or(PersistedSshSessionIdentityError::CredentialSlotOverflow)?; + Ok(Self { slot_base, revision }) + } - Ok(Self { - slot_base, - revision, - }) + fn from_connection( + connection: &StoredConnection, + ) -> Result { + let connection_id = connection + .id + .ok_or(PersistedSshSessionIdentityError::MissingConnectionId)?; + let revision = connection + .credential_revision + .ok_or(PersistedSshSessionIdentityError::MissingCredentialRevision)?; + Self::from_metadata(connection_id, revision) } fn for_scope( @@ -245,9 +273,11 @@ mod tests { use anyhow::Result; use async_trait::async_trait; use one_core::storage::models::{ConnectionType, SshAuthMethod, SshParams, StoredConnection}; - use ssh::{ - HostKeyVerifier, JumpServerConnectConfig, KeyboardInteractiveRequest, - KeyboardInteractiveResponder, ProxyConnectConfig, ProxyType, SshAuth, SshConnectConfig, + + use ssh::{ + BastionUserFormat, HostKeyVerifier, JumpMode, JumpServerConnectConfig, + KeyboardInteractiveRequest, KeyboardInteractiveResponder, ProxyConnectConfig, ProxyType, + SshAuth, SshConnectConfig, }; use super::{ @@ -344,6 +374,10 @@ mod tests { port: 2222, username: "jumper".to_string(), auth: SshAuth::Password(JUMP_PASSWORD.to_string()), + mode: JumpMode::default(), + bastion_asset: String::new(), + bastion_account: String::new(), + bastion_user_format: BastionUserFormat::default(), }); config.proxy = Some(ProxyConnectConfig { proxy_type: ProxyType::Socks5, @@ -355,6 +389,35 @@ mod tests { config } + #[test] + fn derive_from_metadata_matches_derived_identity() { + let connection = stored_connection(Some(7), Some(12)); + let config = terminal_config(); + + let identity = PersistedSshSessionIdentity::derive_from_metadata(7, 12, &config) + .expect("携带合法元数据时应当能派生共享租约身份"); + + let direct = PersistedSshSessionIdentity::derive(&connection, &config) + .expect("直接从 StoredConnection 派生也应当成功"); + assert_eq!( + identity, direct, + "derive_from_metadata 必须与 derive 保持完全一致的语义" + ); + } + + #[test] + fn derive_from_metadata_fails_closed_without_credential_revision() { + let error = PersistedSshSessionIdentity::derive_from_metadata(7, 0, &terminal_config()) + .expect_err("revision 无效时必须 fail-closed"); + assert!( + matches!( + error, + PersistedSshSessionIdentityError::InvalidCredentialRevision + ), + "revision 无效的错误应当是 InvalidCredentialRevision,实际是 {error:?}" + ); + } + #[test] fn ordinary_reconnect_reuses_the_same_lease_identity() { let connection = stored_connection(Some(42), Some(7)); diff --git a/crates/terminal/src/terminal.rs b/crates/terminal/src/terminal.rs index 73e7d9158..c0ea142b8 100644 --- a/crates/terminal/src/terminal.rs +++ b/crates/terminal/src/terminal.rs @@ -22,8 +22,8 @@ use one_core::app_dirs; use one_core::gpui_tokio::Tokio; use one_core::settings::AppSettings; use one_core::storage::models::{ - ActiveConnections, ProxyType as StorageProxyType, SerialParams, SshAccountExpect, - SshAgentForwardKey, SshAuthMethod, StoredConnection, TelnetParams, + ActiveConnections, SerialParams, SshAccountExpect, SshAgentForwardKey, + SshAuthMethod, StoredConnection, TelnetParams, }; use one_core::storage::{ GlobalStorageState, TerminalCommandHistoryRepository, TerminalCommandHistorySort, @@ -86,8 +86,8 @@ use crate::{ TerminalTransferCancelHandle, }; pub use ssh::{ - AgentIdentity, JumpServerConnectConfig, ProxyConnectConfig, ProxyType, PtyConfig, SshAuth, - SshConnectConfig, + AgentIdentity, BastionUserFormat as SshBastionUserFormat, JumpMode as SshJumpMode, + JumpServerConnectConfig, ProxyConnectConfig, ProxyType, PtyConfig, SshAuth, SshConnectConfig, }; use ssh::{ ChannelEvent, HostKeyDetails, HostKeyIdentity, HostKeyRejection, HostKeyVerifier, @@ -354,6 +354,8 @@ struct ResolvedSshConnection { init_commands: Option, connection_id: Option, connection_name: String, + /// 仓库凭据修订号;临时连接为 `None`,用于派生共享租约身份。 + credential_revision: Option, } struct SshConnectTask { @@ -370,35 +372,6 @@ struct SshConnectTask { generation: u64, } -fn ssh_auth_from_storage(auth: SshAuthMethod) -> SshAuth { - match auth { - SshAuthMethod::Password { password } => SshAuth::Password(password), - SshAuthMethod::PrivateKey { - key_path, - passphrase, - } => SshAuth::PrivateKey { - key_path, - passphrase, - certificate_path: None, - }, - SshAuthMethod::PrivateKeyContent { - private_key, - passphrase, - } => SshAuth::PrivateKeyContent { - private_key, - passphrase, - certificate_path: None, - }, - SshAuthMethod::Agent => SshAuth::Agent, - SshAuthMethod::Pageant => SshAuth::Pageant, - SshAuthMethod::AutoPublicKey => SshAuth::AutoPublicKey, - SshAuthMethod::None => SshAuth::None, - SshAuthMethod::Chain(steps) => { - SshAuth::Chain(steps.into_iter().map(ssh_auth_from_storage).collect()) - } - } -} - fn password_from_ssh_auth(auth: &SshAuth) -> Option { match auth { SshAuth::Password(password) => Some(password.clone()), @@ -733,26 +706,12 @@ fn resolve_ssh_connection( host: params.host, port: params.port, username: params.username, - auth: ssh_auth_from_storage(params.auth_method), + auth: sftp_transfer::ssh_auth(params.auth_method), timeout: params.connect_timeout.map(Duration::from_secs), keepalive_interval: params.keepalive_interval.map(Duration::from_secs), keepalive_max: params.keepalive_max, - jump_server: params.jump_server.map(|jump| JumpServerConnectConfig { - host: jump.host, - port: jump.port, - username: jump.username, - auth: ssh_auth_from_storage(jump.auth_method), - }), - proxy: params.proxy.map(|proxy| ProxyConnectConfig { - proxy_type: match proxy.proxy_type { - StorageProxyType::Socks5 => ProxyType::Socks5, - StorageProxyType::Http => ProxyType::Http, - }, - host: proxy.host, - port: proxy.port, - username: proxy.username, - password: proxy.password, - }), + jump_server: params.jump_server.as_ref().map(sftp_transfer::jump_connect_config), + proxy: params.proxy.as_ref().map(sftp_transfer::proxy_connect_config), keyboard_interactive_responder: None, host_key_verifier: HostKeyVerifier::default(), x11_forwarding: params.x11_forwarding.unwrap_or(false), @@ -775,6 +734,7 @@ fn resolve_ssh_connection( init_commands, connection_id: update.connection.id, connection_name: update.connection.name, + credential_revision: update.connection.credential_revision, }) } @@ -855,6 +815,37 @@ fn ssh_config_with_runtime_credentials( .as_ref() .and_then(|jump| password_from_ssh_auth(&jump.auth)); let target_password = password_from_ssh_auth(&config.ssh_config.auth); + + // 堡垒机直连(BastionDirect)模式下目标认证被跳过,实际认证的是堡垒机会话: + // 运行时输入的密码必须同时注入 jump.auth,否则「连接时输入密码」在该模式下 + // 永远拿到空密码。 + if let (Some(password), Some(jump)) = ( + credentials.password.as_deref(), + config.ssh_config.jump_server.as_mut(), + ) { + if jump.bastion_login_username().is_some() { + match &mut jump.auth { + SshAuth::Password(configured) => { + if configured.is_empty() { + *configured = password.to_string(); + } + } + // 组合认证里的密码因素同样补齐(与目标侧语义一致)。 + SshAuth::Chain(steps) => { + if let Some(configured) = steps.iter_mut().find_map(|step| match step { + SshAuth::Password(configured) => Some(configured), + _ => None, + }) { + if configured.is_empty() { + *configured = password.to_string(); + } + } + } + _ => {} + } + } + } + let responder = TerminalMfaResponder::new(event_tx, jump_password, target_password) .with_otp(base_config.otp.clone()); config.ssh_config.keyboard_interactive_responder = keyboard_interactive_enabled @@ -1457,6 +1448,13 @@ pub struct Terminal { ssh_base_config: Option, /// SSH 会话管理器(同一 SSH tab 共享底层连接) ssh_session_manager: Option>, + /// 应用级共享租约(经 `SshSessionService` 获取)。 + /// + /// `None` 表示当前 manager 是本地回退(不进 registry 记账), + /// 断开语义见 `take_ssh_session_manager`。 + ssh_session_lease: Option, + /// 仓库凭据修订号快照(来自最近一次 resolve),用于派生共享租约身份。 + ssh_credential_revision: Option, /// 当前连接的临时凭据策略。 ssh_credential_prompt_policy: SshCredentialPromptPolicy, /// 等待用户输入的临时 SSH 用户名/密码。 @@ -1955,6 +1953,8 @@ impl Terminal { ssh_config: None, ssh_base_config: None, ssh_session_manager: None, + ssh_session_lease: None, + ssh_credential_revision: None, ssh_credential_prompt_policy: SshCredentialPromptPolicy::default(), ssh_credential_request: None, ssh_keyboard_interactive_enabled: false, @@ -2078,6 +2078,8 @@ impl Terminal { ssh_config: None, ssh_base_config: None, ssh_session_manager: None, + ssh_session_lease: None, + ssh_credential_revision: None, ssh_credential_prompt_policy: SshCredentialPromptPolicy::default(), ssh_credential_request: None, ssh_keyboard_interactive_enabled: false, @@ -2412,6 +2414,8 @@ impl Terminal { ssh_config: Some(base_config.clone()), ssh_base_config: Some(base_config.clone()), ssh_session_manager: None, + ssh_session_lease: None, + ssh_credential_revision: resolved.credential_revision, ssh_credential_prompt_policy: resolved.credential_prompt_policy, ssh_credential_request: None, ssh_keyboard_interactive_enabled: resolved.keyboard_interactive_enabled, @@ -2549,6 +2553,8 @@ impl Terminal { ssh_config: None, ssh_base_config: None, ssh_session_manager: None, + ssh_session_lease: None, + ssh_credential_revision: None, ssh_credential_prompt_policy: SshCredentialPromptPolicy::default(), ssh_credential_request: None, ssh_keyboard_interactive_enabled: false, @@ -2672,6 +2678,8 @@ impl Terminal { ssh_config: None, ssh_base_config: None, ssh_session_manager: None, + ssh_session_lease: None, + ssh_credential_revision: None, ssh_credential_prompt_policy: SshCredentialPromptPolicy::default(), ssh_credential_request: None, ssh_keyboard_interactive_enabled: false, @@ -2819,6 +2827,8 @@ impl Terminal { ssh_config: None, ssh_base_config: None, ssh_session_manager: None, + ssh_session_lease: None, + ssh_credential_revision: None, ssh_credential_prompt_policy: SshCredentialPromptPolicy::default(), ssh_credential_request: None, ssh_keyboard_interactive_enabled: false, @@ -2855,6 +2865,50 @@ impl Terminal { ) } + /// 取走当前 SSH 会话管理器并按持有方式收尾。 + /// + /// - 本地 manager(未进 registry):异步 disconnect,保持旧行为; + /// - 共享租约:只 release 本次租约,registry 的空闲回收(60s)接管, + /// 绝不 disconnect 其他标签页可能仍在共享的传输。 + fn take_ssh_session_manager(&mut self, cx: &mut Context) { + let lease = self.ssh_session_lease.take(); + let Some(session_manager) = self.ssh_session_manager.take() else { + return; + }; + match lease { + Some(lease) => lease.release(), + None => { + cx.spawn(async move |_, _| { + let _ = session_manager.disconnect().await; + }) + .detach(); + } + } + } + + /// 获取装配层注入的应用级 SSH 会话服务;未注入时返回 `None`(本地回退)。 + fn ssh_session_service(cx: &App) -> Option { + cx.try_global::() + .map(|handle| handle.service.clone()) + } + + /// 派生共享租约身份:连接 id、凭据修订号、传输配置三者齐备才可能成功。 + /// + /// 身份派生是纯函数(无 I/O);失败仅意味着本次回退本地 manager。 + fn derive_shared_session_identity( + &self, + config: &SshTerminalConfig, + ) -> Option { + let connection_id = self.connection_id?; + let revision = self.ssh_credential_revision?; + crate::ssh_session_identity::PersistedSshSessionIdentity::derive_from_metadata( + connection_id, + revision, + &config.ssh_config, + ) + .ok() + } + fn history_repository(cx: &mut Context) -> Option> { cx.try_global::() .and_then(|state| state.storage.get::()) @@ -3239,18 +3293,74 @@ impl Terminal { return false; }; - let session_manager = Arc::new(SshSessionManager::new(config.ssh_config.clone())); - let (disconnect_tx, disconnect_rx) = tokio::sync::oneshot::channel::>(); - Self::spawn_ssh_disconnect_handler(disconnect_rx, generation, cx); + // 共享租约身份派生:需要连接 id + 凭据修订号 + 传输配置三者齐备; + // 任一缺失(临时连接、旧数据、非装配环境)都回退到本地 manager, + // 行为与改造前完全一致。 + let service = Self::ssh_session_service(cx); + let shared_identity = service + .as_ref() + .and_then(|_| self.derive_shared_session_identity(&config)); // `spawn_ssh_connect` 会拿走 `config`,门禁必须在移动之前先算好。 let load_remote_history = remote_shell_history_allowed(config.disable_shell_integration); self.ssh_config = Some(config.clone()); - self.ssh_session_manager = Some(session_manager.clone()); self.ssh_mfa_responder = Some(responder); let credential_request_cleared = self.ssh_credential_request.take().is_some(); + if let (Some(service), Some(identity)) = (service, shared_identity) { + // 共享路径:连接任务等共享租约到位后再启动,保证首个连接就走 + // registry 的共享传输(本地路径先起跑再换 manager 无法真正共享)。 + Self::spawn_shared_lease_then_connect( + service, + identity, + config, + event_tx, + event_proxy, + zmodem_responder, + load_remote_history, + generation, + cx, + ); + } else { + let session_manager = Arc::new(SshSessionManager::new(config.ssh_config.clone())); + self.launch_ssh_connect( + session_manager, + None, + config, + event_tx, + event_proxy, + zmodem_responder, + load_remote_history, + generation, + cx, + ); + } + + if credential_request_cleared { + cx.emit(TerminalModelEvent::SshCredentialChanged); + } + cx.emit(TerminalModelEvent::Wakeup); + true + } + + /// 用给定 manager 启动 SSH 连接任务(同步路径与共享租约路径共用)。 + fn launch_ssh_connect( + &mut self, + session_manager: Arc, + lease: Option, + config: SshTerminalConfig, + event_tx: UnboundedSender, + event_proxy: GpuiEventProxy, + zmodem_responder: ZmodemResponder, + load_remote_history: bool, + generation: u64, + cx: &mut Context, + ) { + let (disconnect_tx, disconnect_rx) = tokio::sync::oneshot::channel::>(); + Self::spawn_ssh_disconnect_handler(disconnect_rx, generation, cx); + self.ssh_session_manager = Some(session_manager.clone()); + self.ssh_session_lease = lease; Self::spawn_ssh_connect( SshConnectTask { session_manager: session_manager.clone(), @@ -3270,12 +3380,73 @@ impl Terminal { if load_remote_history { Self::spawn_ssh_history_loader(session_manager, cx); } + } - if credential_request_cleared { - cx.emit(TerminalModelEvent::SshCredentialChanged); + /// 异步获取共享租约,到位后(generation 仍有效)再启动连接任务。 + /// + /// acquire 失败或 generation 过期时回退本地 manager / 放弃启动, + /// 行为与未装配共享服务时一致。 + fn spawn_shared_lease_then_connect( + service: ssh::SshSessionService, + identity: crate::ssh_session_identity::PersistedSshSessionIdentity, + config: SshTerminalConfig, + event_tx: UnboundedSender, + event_proxy: GpuiEventProxy, + zmodem_responder: ZmodemResponder, + load_remote_history: bool, + generation: u64, + cx: &mut Context, + ) { + /// 租约获取结果:共享租约或本地回退。 + enum ManagerSource { + Shared(ssh::SshSessionLease), + Local, } - cx.emit(TerminalModelEvent::Wakeup); - true + + let key = identity.connection_key().clone(); + let acquire_connect_config = config.ssh_config.clone(); + cx.spawn(async move |this, cx| { + // acquire 内部会 tokio::spawn(reaper/创建飞行),必须在 Tokio runtime + // 上下文里调用;GPUI executor 上没有 reactor,直接 await 会 panic。 + let acquire_task = Tokio::spawn(cx, async move { + service + .acquire(&key, acquire_connect_config) + .await + }); + let source = match acquire_task.await { + Ok(Ok(lease)) => ManagerSource::Shared(lease), + Ok(Err(_)) | Err(_) => ManagerSource::Local, // acquire 失败:本地 manager 兜底 + }; + let _ = this.update(cx, |terminal, cx| { + if !terminal.is_current_connection_generation(generation) { + // 过期:不启动连接任务;共享租约随 drop 释放。 + return; + } + let (session_manager, lease) = match source { + ManagerSource::Shared(lease) => { + let manager = Arc::new(lease.manager().clone()); + (manager, Some(lease)) + } + ManagerSource::Local => ( + Arc::new(SshSessionManager::new(config.ssh_config.clone())), + None, + ), + }; + terminal.launch_ssh_connect( + session_manager, + lease, + config, + event_tx, + event_proxy, + zmodem_responder, + load_remote_history, + generation, + cx, + ); + cx.emit(TerminalModelEvent::Wakeup); + }); + }) + .detach(); } /// keyboard-interactive 的生效开关。 @@ -3334,12 +3505,7 @@ impl Terminal { if let Some(backend) = self.backend.take() { backend.shutdown(); } - if let Some(session_manager) = self.ssh_session_manager.take() { - cx.spawn(async move |_, _| { - let _ = session_manager.disconnect().await; - }) - .detach(); - } + self.take_ssh_session_manager(cx); self.prepare_surface_for_reconnect(); self.connection_state = ConnectionState::Connecting; self.set_connection_active(false, cx); @@ -3976,6 +4142,7 @@ impl Terminal { } self.connection_id = resolved.connection_id; self.connection_name = Some(resolved.connection_name); + self.ssh_credential_revision = resolved.credential_revision; self.init_commands = resolved.init_commands; self.history_scope = resolved.connection_id.map(TerminalHistoryScope::ssh); Ok(()) @@ -4696,12 +4863,7 @@ impl Terminal { self.ssh_credential_request = None; self.ssh_config = Some(base_config.clone()); - if let Some(session_manager) = self.ssh_session_manager.take() { - cx.spawn(async move |_, _| { - let _ = session_manager.disconnect().await; - }) - .detach(); - } + self.take_ssh_session_manager(cx); if self.ssh_credential_prompt_policy.requires_credentials() { self.queue_ssh_credential_request(generation, cx); @@ -4816,12 +4978,7 @@ impl Terminal { if let Some(backend) = self.backend.take() { backend.shutdown(); } - if let Some(session_manager) = self.ssh_session_manager.take() { - cx.spawn(async move |_, _| { - let _ = session_manager.disconnect().await; - }) - .detach(); - } + self.take_ssh_session_manager(cx); self.connection_state = ConnectionState::Disconnected { error: None }; self.set_connection_active(false, cx); cx.emit(TerminalModelEvent::Wakeup); @@ -4912,12 +5069,7 @@ impl Terminal { self.ssh_mfa_responder = None; self.ssh_credential_request = None; - if let Some(session_manager) = self.ssh_session_manager.take() { - cx.spawn(async move |_, _| { - let _ = session_manager.disconnect().await; - }) - .detach(); - } + self.take_ssh_session_manager(cx); if !self.start_ssh_connection_attempt(retry_config, responder, generation, cx) { self.connection_state = ConnectionState::Disconnected { @@ -5172,6 +5324,28 @@ async fn receive_terminal_event_for_gpui( Some(event) } +/// 注入应用级 SSH 会话服务(由装配层在启动时调用一次)。 +/// +/// 重复注入是编程错误:全局句柄应当只由领域装配建立一次。 +pub fn install_ssh_session_service(service: ssh::SshSessionService, cx: &mut App) { + assert!( + cx.try_global::().is_none(), + "Terminal SSH session service handle must be installed exactly once" + ); + cx.set_global(GlobalSshSessionServiceHandle { service }); +} + +/// 装配层注入的应用级 SSH 会话服务句柄。 +/// +/// `terminal` crate 不依赖任何领域装配 crate;`shell_domain::init` 负责在 +/// 启动时 `cx.set_global` 本句柄,Terminal 连接尝试经它拿共享服务。 +#[derive(Clone)] +pub(crate) struct GlobalSshSessionServiceHandle { + pub(crate) service: ssh::SshSessionService, +} + +impl gpui::Global for GlobalSshSessionServiceHandle {} + #[cfg(test)] mod tests { #[cfg(target_os = "macos")] @@ -5362,6 +5536,8 @@ mod tests { ssh_config: None, ssh_base_config: None, ssh_session_manager: None, + ssh_session_lease: None, + ssh_credential_revision: None, ssh_credential_prompt_policy: SshCredentialPromptPolicy::default(), ssh_credential_request: None, ssh_keyboard_interactive_enabled: false, @@ -7726,6 +7902,8 @@ mod tests { ssh_config: None, ssh_base_config: None, ssh_session_manager: None, + ssh_session_lease: None, + ssh_credential_revision: None, ssh_credential_prompt_policy: SshCredentialPromptPolicy::default(), ssh_credential_request: None, ssh_keyboard_interactive_enabled: false, @@ -8069,6 +8247,8 @@ mod tests { ssh_config: None, ssh_base_config: None, ssh_session_manager: None, + ssh_session_lease: None, + ssh_credential_revision: None, ssh_credential_prompt_policy: SshCredentialPromptPolicy::default(), ssh_credential_request: None, ssh_keyboard_interactive_enabled: false, diff --git a/crates/terminal_view/locales/terminal_view.yml b/crates/terminal_view/locales/terminal_view.yml index 8be3944dd..723d48a29 100644 --- a/crates/terminal_view/locales/terminal_view.yml +++ b/crates/terminal_view/locales/terminal_view.yml @@ -2210,6 +2210,10 @@ FileManager: en: "Failed to read directory: %{error}. Returned to your working directory." zh-CN: "读取目录失败:%{error}。已返回你的工作目录。" zh-HK: "讀取目錄失敗:%{error}。已返回你的工作目錄。" + follow_suspended_restricted_root: + en: "Stopped following the terminal directory: this session exposes only a restricted file root (such as a bastion host's file management root), so the terminal's paths do not exist remotely. The panel went back to the root directory; browse it manually, or turn following back on from the toolbar." + zh-CN: "已停止跟随终端目录:当前会话只开放了受限的文件根目录(如堡垒机的「文件管理根目录」),终端里的路径在远端并不存在。面板已回到根目录,可手动浏览;需要时可在工具栏重新打开跟随。" + zh-HK: "已停止跟隨終端目錄:目前工作階段只開放受限的檔案根目錄(如堡壘機的「檔案管理根目錄」),終端中的路徑在遠端並不存在。面板已回到根目錄,可手動瀏覽;需要時可在工具列重新開啟跟隨。" foreign_host_notice: en: "Terminal is now on %{host}; the file panel is still connected to %{connection}." zh-CN: "终端已进入 %{host},文件面板仍连接 %{connection}。" diff --git a/crates/terminal_view/src/public_mcp.rs b/crates/terminal_view/src/public_mcp.rs index cf0883852..68a666505 100644 --- a/crates/terminal_view/src/public_mcp.rs +++ b/crates/terminal_view/src/public_mcp.rs @@ -134,6 +134,23 @@ impl TerminalPublicMcpRegistration { terminal.external_control_handle(), terminal.external_input_handle(), ); + self.ensure_remote_ops_registered(terminal); + } + + /// manager 就绪后补注册 remote_ops。 + /// + /// 需要运行时凭据的连接在视图构造时 manager 尚为 `None`; + /// `SshCredentialChanged`/`Wakeup` 事件驱动的 refresh 是天然补注册窗口。 + /// registry 的注册是覆盖语义,重复调用幂等。 + fn ensure_remote_ops_registered(&self, terminal: &Terminal) { + if let Some(session_manager) = terminal.ssh_session_manager() { + let remote_ops = crate::public_mcp_remote_ops::SshRemoteOpsHandle::with_shared_state( + session_manager.clone(), + self.state.clone(), + self.registry.command_store().clone(), + ); + self.registry.register_remote_ops(remote_ops); + } } fn refresh_parts( diff --git a/crates/terminal_view/src/sidebar/file_manager_panel.rs b/crates/terminal_view/src/sidebar/file_manager_panel.rs index 65fc828ce..cc31d62a4 100644 --- a/crates/terminal_view/src/sidebar/file_manager_panel.rs +++ b/crates/terminal_view/src/sidebar/file_manager_panel.rs @@ -1050,6 +1050,14 @@ fn should_apply_directory_result(current_path: &str, listed_path: &str) -> bool current_path == listed_path } +/// 一次读目录失败是否该归因于「跟随终端目录」。 +/// +/// 条件是这个目录本来就是终端上报、面板才去切过去的:只有这种失败才值得 +/// 停用跟随;用户自己点进去的目录失败仍走原来的回退逻辑。 +fn should_suspend_follow(current_path: &str, follow_target: Option<&str>) -> bool { + follow_target.is_some_and(|target| target == current_path) +} + fn is_current_generation(current: u64, expected: u64) -> bool { current == expected } @@ -1287,7 +1295,8 @@ fn download_targets_for_selection( .filter_map(|filtered_ix| { let real_ix = *filtered_indices.get(filtered_ix)?; let item = items.get(real_ix)?; - if !sftp::is_valid_remote_entry_name(&item.name) { + // 下载目标要拼成本地路径:用本机校验拦掉 Windows 盘符形态。 + if !sftp::is_valid_local_file_name(&item.name) { return None; } Some(DownloadTarget { @@ -1473,6 +1482,13 @@ pub struct FileManagerPanel { loading: bool, /// 读目录失败后的自动回退额度 navigation_recovery: NavigationRecovery, + + /// 最近一次由「跟随终端目录」发起的导航目标。 + /// + /// 终端里的路径属于远端真实文件系统,而受限会话(堡垒机文件管理根目录) + /// 只暴露一小块,两者经常对不上。记住是谁发起的导航,失败时才能判断 + /// 该不该自动停用跟随,而不是每 cd 一次弹一次错误。 + follow_navigation_target: Option, /// 读目录失败通知的节流(同一条错误短时间内只弹一次) navigation_failure_notice: NotificationThrottle, /// 文件复制/剪切缓冲区 @@ -1639,6 +1655,7 @@ impl FileManagerPanel { focus_handle, loading: false, navigation_recovery: NavigationRecovery::default(), + follow_navigation_target: None, navigation_failure_notice: NotificationThrottle::new(NAVIGATION_FAILURE_NOTICE_WINDOW), file_clipboard: None, favorite_paths, @@ -1849,6 +1866,12 @@ impl FileManagerPanel { fn recover_from_navigation_error(&mut self, message: String, cx: &mut Context) { self.loading = false; + let follow_target = self.follow_navigation_target.take(); + if should_suspend_follow(&self.current_path, follow_target.as_deref()) { + self.suspend_follow_after_restricted_root(cx); + return; + } + let fallback_path = self.navigation_recovery.next_fallback( &self.current_path, self.working_dir_hint.as_deref(), @@ -1885,6 +1908,42 @@ impl FileManagerPanel { self.refresh_dir(cx); } + /// 跟随终端目录失败后停用跟随,退到根目录,并只提示一次。 + /// + /// 受限会话(堡垒机直连常见)只开放一个文件根目录,终端里的 cwd 在远端 + /// 不存在。此时继续跟随只会每 `cd` 一次报一次错,所以直接停掉跟随、回到 + /// 根目录让用户手动浏览;开关状态通过事件交回宿主持久化。 + fn suspend_follow_after_restricted_root(&mut self, cx: &mut Context) { + tracing::info!( + path = %self.current_path, + "跟随终端目录失败,已停用跟随并回到根目录" + ); + if self.follow_terminal_cwd { + self.follow_terminal_cwd = false; + cx.emit(FileManagerPanelEvent::ToggleFollowTerminalCwd); + } + + let notice = t!("FileManager.follow_suspended_restricted_root").to_string(); + if self.navigation_failure_notice.should_show(¬ice) { + if let Some(window) = cx.active_window() { + let notification = Notification::error(notice).autohide(true); + let _ = window.update(cx, |_, window, cx| { + window.push_notification(notification, cx); + }); + } + } + + self.connection_state = ConnectionState::Connected; + let root = "/".to_string(); + if self.current_path != root { + let failed_path = self.current_path.clone(); + self.current_path = root.clone(); + self.repair_history_after_navigation_failure(&failed_path, &root); + } + self.navigation_recovery.reset(); + self.refresh_dir(cx); + } + /// 推送「已返回上一级」提示,同一文案在时间窗内只弹一次。 fn push_navigation_failure_notice(&mut self, message: String, cx: &mut Context) { let notice = t!("FileManager.read_dir_failed_recovered", error = message).to_string(); @@ -1992,6 +2051,7 @@ impl FileManagerPanel { if path == self.current_path { return; } + self.follow_navigation_target = Some(path.clone()); self.navigate_to(path, cx); } @@ -2472,6 +2532,7 @@ impl FileManagerPanel { match result { Ok(Ok(entries)) => { this.navigation_recovery.reset(); + this.follow_navigation_target = None; this.items = entries .into_iter() .filter(|e| e.name != "." && e.name != "..") @@ -4278,7 +4339,9 @@ impl FileManagerPanel { .next() .unwrap_or(&remote_path) .to_string(); - if !sftp::is_valid_remote_entry_name(&remote_name) { + // 远程名随后会 join 到用户选的本地目录,必须用本机落盘校验。 + // 远程名随后会 join 到用户选的本地目录,必须用本机落盘校验。 + if !sftp::is_valid_local_file_name(&remote_name) { window.push_notification(Notification::error(t!("FileManager.invalid_name")), cx); return; } @@ -6503,6 +6566,23 @@ impl Render for FileManagerPanel { } } +#[cfg(test)] +mod follow_suspension_tests { + use super::should_suspend_follow; + + #[test] + fn follow_failure_is_attributed_to_following_only_for_the_same_path() { + assert!(should_suspend_follow("/home/u", Some("/home/u"))); + } + + #[test] + fn failure_of_a_path_the_user_opened_is_not_blamed_on_following() { + // 用户自己点进去的目录:即使刚刚跟随失败过,也不该因此停用跟随。 + assert!(!should_suspend_follow("/home/u", None)); + assert!(!should_suspend_follow("/var/log", Some("/home/u"))); + } +} + #[cfg(test)] mod tests { use super::{ diff --git a/crates/terminal_view/src/sidebar/mod.rs b/crates/terminal_view/src/sidebar/mod.rs index 1f4059216..467a2e65d 100644 --- a/crates/terminal_view/src/sidebar/mod.rs +++ b/crates/terminal_view/src/sidebar/mod.rs @@ -729,12 +729,6 @@ impl TerminalToolDockState { pub enum TerminalSidebarEvent { /// 面板切换 PanelChanged(Option), - /// 搜索模式变化 - SearchPatternChanged(String), - /// 搜索前一个 - SearchPrevious, - /// 搜索下一个 - SearchNext, /// 字体大小变更 FontSizeChanged(f32), /// 字体变更 @@ -1283,15 +1277,6 @@ impl TerminalSidebar { settings_panel::SettingsPanelEvent::Close => { this.close_tool(SidebarPanel::Settings, cx); } - settings_panel::SettingsPanelEvent::SearchPatternChanged(pattern) => { - cx.emit(TerminalSidebarEvent::SearchPatternChanged(pattern.clone())); - } - settings_panel::SettingsPanelEvent::SearchPrevious => { - cx.emit(TerminalSidebarEvent::SearchPrevious); - } - settings_panel::SettingsPanelEvent::SearchNext => { - cx.emit(TerminalSidebarEvent::SearchNext); - } settings_panel::SettingsPanelEvent::FontSizeChanged(size) => { cx.emit(TerminalSidebarEvent::FontSizeChanged(*size)); } @@ -2118,18 +2103,6 @@ impl TerminalSidebar { }); } - /// 更新搜索输入框的值 - pub fn set_search_value(&self, value: &str, window: &mut Window, cx: &mut Context) { - self.settings_panel.update(cx, |panel, cx| { - panel.set_search_value(value, window, cx); - }); - } - - /// 获取搜索输入框的值 - pub fn search_value(&self, cx: &App) -> String { - self.settings_panel.read(cx).search_value(cx) - } - /// 询问 AI pub fn ask_ai(&mut self, message: String, cx: &mut Context) { self.open_tool_internal(SidebarPanel::AiChat, cx); diff --git a/crates/terminal_view/src/sidebar/server_monitor_panel.rs b/crates/terminal_view/src/sidebar/server_monitor_panel.rs index 496f4a6b1..74d75b43b 100644 --- a/crates/terminal_view/src/sidebar/server_monitor_panel.rs +++ b/crates/terminal_view/src/sidebar/server_monitor_panel.rs @@ -2278,8 +2278,12 @@ async fn collect_remote_stats( /// 首页等非终端场景看到的一份远端资源占用快照。 #[derive(Clone, Debug, PartialEq)] pub struct HostResourceUsage { + pub os_name: Option, + pub cpu_cores: Option, pub cpu_percent: Option, + pub memory_total_kib: Option, pub memory_percent: Option, + pub disk_total_kib: Option, pub disk_percent: Option, } @@ -2311,15 +2315,76 @@ pub async fn probe_host_resource_usage( let session_id = format!("host-metrics-{}", Utc::now().timestamp_millis()); let payload = collect_remote_stats(session_manager.clone(), &session_id).await; let parsed = payload.and_then(|payload| parse_server_stats(&payload)); - session_manager.disconnect().await.ok(); let stats = parsed?; + tokio::time::sleep(Duration::from_millis(250)).await; + let next_cpu_snapshot = collect_cpu_snapshot(session_manager.clone()) + .await + .ok() + .unwrap_or_default(); + session_manager.disconnect().await.ok(); + let cpu_percent = (stats.cpu_snapshots.iter().any(|item| item.name == "cpu") + && next_cpu_snapshot.iter().any(|item| item.name == "cpu")) + .then(|| sample_cpu_usage(&stats.cpu_snapshots, &next_cpu_snapshot).total_percent); + let disk_total_kib = stats + .disks + .iter() + .find(|disk| disk.mount == "/") + .map(|disk| disk.size) + .or_else(|| stats.disks.iter().map(|disk| disk.size).max()); Ok(HostResourceUsage { - cpu_percent: stats.cpu_usage.as_ref().map(|sample| sample.total_percent), + os_name: stats.os.as_ref().map(|os| os.pretty_name.clone()), + cpu_cores: stats + .cpu_usage + .as_ref() + .map(|sample| sample.cores.len()) + .filter(|cores| *cores > 0) + .or_else(|| { + let cores = stats + .cpu_snapshots + .iter() + .filter(|snapshot| { + snapshot.name != "cpu" + && snapshot + .name + .strip_prefix("cpu") + .is_some_and(|suffix| !suffix.is_empty()) + }) + .count(); + (cores > 0).then_some(cores) + }), + cpu_percent, + memory_total_kib: stats.memory.as_ref().map(|memory| memory.total), memory_percent: stats.memory.as_ref().map(|memory| memory.used_percent()), + disk_total_kib, disk_percent: stats.disks.iter().map(|disk| disk.percent).reduce(f64::max), }) } +async fn collect_cpu_snapshot(session_manager: Arc) -> Result> { + let output = exec_capture( + &session_manager, + "awk '/^cpu[0-9]* / { total = $2 + $3 + $4 + $5 + $6 + $7 + $8 + $9 + $10 + $11; print $1, $2, $4, $5, total }' /proc/stat", + ) + .await?; + Ok(parse_cpu_snapshot_output(&output)) +} + +fn parse_cpu_snapshot_output(output: &str) -> Vec { + output + .lines() + .filter_map(|line| { + let mut fields = line.split_whitespace(); + Some(CpuSnapshot { + name: fields.next()?.to_string(), + load_user: fields.next()?.parse().ok()?, + load_system: fields.next()?.parse().ok()?, + load_idle: fields.next()?.parse().ok()?, + load_total: fields.next()?.parse().ok()?, + }) + }) + .collect() +} + /// 执行简单远端命令(不推送脚本),用于 legacy 清理等 best-effort 场景。 async fn exec_capture(session_manager: &Arc, command: &str) -> Result { let mut channel = session_manager.open_channel().await?; @@ -2444,16 +2509,21 @@ mod tests { use super::{ AcceleratorVendor, CpuSnapshot, HistoryLimit, HostResourceUsage, MemoryStats, NetworkTotals, ProcessEntry, REMOTE_MONITOR_SCRIPT, build_collect_command, - build_legacy_cleanup_command, history_points, history_tick_margin, parse_server_stats, - push_history_point, sample_cpu_usage, sample_network_rates, split_sections, + build_legacy_cleanup_command, history_points, history_tick_margin, + parse_cpu_snapshot_output, parse_server_stats, push_history_point, sample_cpu_usage, + sample_network_rates, split_sections, }; #[test] fn host_resource_usage_summary_skips_missing_metrics() { assert_eq!( HostResourceUsage { + os_name: None, + cpu_cores: None, cpu_percent: Some(12.4), + memory_total_kib: None, memory_percent: None, + disk_total_kib: None, disk_percent: Some(51.6), } .summary() @@ -2462,8 +2532,12 @@ mod tests { ); assert_eq!( HostResourceUsage { + os_name: None, + cpu_cores: None, cpu_percent: None, + memory_total_kib: None, memory_percent: None, + disk_total_kib: None, disk_percent: None, } .summary(), @@ -2471,6 +2545,20 @@ mod tests { ); } + #[test] + fn host_metrics_cpu_snapshot_parser_reads_total_and_cores() { + let snapshots = parse_cpu_snapshot_output( + "cpu 100 40 860 1000\ncpu0 50 20 430 500\ncpu1 50 20 430 500\n", + ); + + assert_eq!(snapshots.len(), 3); + assert_eq!(snapshots[0].name, "cpu"); + assert_eq!(snapshots[0].load_user, 100); + assert_eq!(snapshots[0].load_system, 40); + assert_eq!(snapshots[0].load_idle, 860); + assert_eq!(snapshots[0].load_total, 1000); + } + #[test] fn split_sections_parses_nested_monitor_document() { let sections = split_sections( diff --git a/crates/terminal_view/src/sidebar/settings_panel.rs b/crates/terminal_view/src/sidebar/settings_panel.rs index 19d44d4d4..182349208 100644 --- a/crates/terminal_view/src/sidebar/settings_panel.rs +++ b/crates/terminal_view/src/sidebar/settings_panel.rs @@ -1,6 +1,6 @@ //! 终端设置面板 //! -//! 提供搜索、字体设置和主题切换功能 +//! 提供字体设置和主题切换功能 use gpui::FontWeight; use gpui::prelude::FluentBuilder; @@ -123,12 +123,6 @@ fn terminal_font_options( pub enum SettingsPanelEvent { /// 关闭面板 Close, - /// 搜索模式变化 - SearchPatternChanged(String), - /// 搜索前一个 - SearchPrevious, - /// 搜索下一个 - SearchNext, /// 字体大小变更 FontSizeChanged(f32), /// 字体变更 @@ -175,8 +169,6 @@ pub enum SettingsPanelEvent { /// 设置面板组件 pub struct SettingsPanel { - /// 搜索输入框状态 - search_input_state: Entity, /// 字体大小输入框状态 font_size_input_state: Entity, /// 滚屏历史行数输入框状态 @@ -256,9 +248,6 @@ impl SettingsPanel { window: &mut Window, cx: &mut Context, ) -> Self { - let search_input_state = - cx.new(|cx| InputState::new(window, cx).placeholder(t!("Settings.search_placeholder"))); - // 字体大小输入框 let font_size = f32::from(initial_font_size); let font_size_input_state = cx.new(|cx| InputState::new(window, cx).placeholder("13")); @@ -312,27 +301,6 @@ impl SettingsPanel { let mut subscriptions = Vec::new(); - // 订阅搜索输入事件 - let input_entity = search_input_state.clone(); - subscriptions.push(cx.subscribe_in( - &search_input_state, - window, - move |_this, _state, event, _window, cx| match event { - InputEvent::Change => { - let value = input_entity.read(cx).value().to_string(); - cx.emit(SettingsPanelEvent::SearchPatternChanged(value)); - } - InputEvent::PressEnter { secondary, .. } => { - if *secondary { - cx.emit(SettingsPanelEvent::SearchPrevious); - } else { - cx.emit(SettingsPanelEvent::SearchNext); - } - } - _ => {} - }, - )); - // 订阅字体大小输入事件 let font_size_entity = font_size_input_state.clone(); subscriptions.push(cx.subscribe_in( @@ -450,7 +418,6 @@ impl SettingsPanel { )); Self { - search_input_state, font_size_input_state, scrollback_lines_input_state, font_select_state, @@ -895,19 +862,6 @@ impl SettingsPanel { }); } - /// 获取搜索值 - pub fn search_value(&self, cx: &App) -> String { - self.search_input_state.read(cx).value().to_string() - } - - /// 设置搜索值 - pub fn set_search_value(&self, value: &str, window: &mut Window, cx: &mut Context) { - let value = value.to_string(); - self.search_input_state.update(cx, |state, cx| { - state.set_value(&value, window, cx); - }); - } - /// 设置主题(用户点击主题时调用) fn set_theme(&mut self, theme: TerminalTheme, cx: &mut Context) { self.current_theme = theme.clone(); @@ -919,53 +873,6 @@ impl SettingsPanel { self.current_theme.colors() } - /// 渲染搜索区域 - fn render_search_section(&self, cx: &mut Context) -> impl IntoElement { - let colors = self.colors(); - let muted_fg = colors.muted_foreground; - - v_flex().gap_3().p_3().child( - v_flex() - .gap_2() - .child( - div() - .text_xs() - .font_weight(FontWeight::MEDIUM) - .text_color(muted_fg) - .child(t!("Settings.search").to_uppercase()), - ) - .child( - h_flex() - .gap_2() - .child(Input::new(&self.search_input_state).small().w_full()) - .child( - Button::new("search-prev") - .icon(IconName::ChevronUp) - .ghost() - .small() - .on_click(cx.listener(|_this, _, _window, cx| { - cx.emit(SettingsPanelEvent::SearchPrevious); - })), - ) - .child( - Button::new("search-next") - .icon(IconName::ChevronDown) - .ghost() - .small() - .on_click(cx.listener(|_this, _, _window, cx| { - cx.emit(SettingsPanelEvent::SearchNext); - })), - ), - ) - .child( - div() - .text_xs() - .text_color(muted_fg) - .child(t!("Settings.search_shortcuts_hint")), - ), - ) - } - /// 渲染主题项 fn render_theme_item(&self, theme: TerminalTheme, cx: &mut Context) -> AnyElement { let is_current = self.current_theme.name == theme.name; @@ -2059,7 +1966,6 @@ impl Render for SettingsPanel { v_flex() .flex_shrink_0() .pb_4() - .child(self.render_search_section(cx)) .child(self.render_font_section(cx)) .child(self.render_scrollback_section(cx)) .child(self.render_cursor_section(cx)) diff --git a/crates/terminal_view/src/view.rs b/crates/terminal_view/src/view.rs index 63b17c7cf..8cd6b11c7 100644 --- a/crates/terminal_view/src/view.rs +++ b/crates/terminal_view/src/view.rs @@ -8,6 +8,7 @@ use gpui::prelude::FluentBuilder; use gpui::*; use gpui_component::button::{Button, ButtonVariants}; use gpui_component::dialog::{DialogButtonProps, DialogFooter}; +use gpui_component::input::{Input, InputEvent, InputState}; use gpui_component::menu::{ContextMenuExt, PopupMenu, PopupMenuItem}; use gpui_component::notification::Notification; use gpui_component::scroll::{Scrollbar, ScrollbarHandle, ScrollbarMode}; @@ -174,6 +175,7 @@ mod render_surface; mod resize_event_handler; mod scroll; mod scroll_keys; +mod search_bar; mod selection_autoscroll; mod selection_search; mod session_log_config; @@ -197,8 +199,9 @@ use helpers::*; use init_config::TerminalViewInit; use keybindings::{ TERMINAL_CLEAR_SCREEN_SHORTCUT, TERMINAL_CONTEXT, TERMINAL_COPY_SHORTCUT, - TERMINAL_PASTE_SHORTCUT, TERMINAL_SELECT_ALL_SHORTCUT, TERMINAL_TOGGLE_VI_MODE_SHORTCUT, - is_terminal_action_shortcut, terminal_paste_defaults, terminal_shortcut_label, + TERMINAL_PASTE_SHORTCUT, TERMINAL_SEARCH_CONTEXT, TERMINAL_SELECT_ALL_SHORTCUT, + TERMINAL_TOGGLE_VI_MODE_SHORTCUT, is_terminal_action_shortcut, terminal_paste_defaults, + terminal_shortcut_label, }; pub use keybindings::{init, refresh_keybindings}; pub use recording_playback_config::RecordingPlaybackViewConfig; @@ -266,6 +269,9 @@ pub struct TerminalView { pending_render_cache_reset: bool, block_selection: Option, addon_manager: AddonManager, + /// 独立于设置侧栏的终端搜索浮层。 + search_input: Entity, + search_open: bool, _subscriptions: Vec, diff --git a/crates/terminal_view/src/view/actions.rs b/crates/terminal_view/src/view/actions.rs index 3246d2836..dc00dabc2 100644 --- a/crates/terminal_view/src/view/actions.rs +++ b/crates/terminal_view/src/view/actions.rs @@ -12,6 +12,7 @@ actions!( ClearScreen, SearchForward, SearchBackward, + CloseTerminalSearch, ToggleViMode, ViModeStartSelection, IncreaseFont, diff --git a/crates/terminal_view/src/view/clipboard_image.rs b/crates/terminal_view/src/view/clipboard_image.rs index eb995c047..28e8cd799 100644 --- a/crates/terminal_view/src/view/clipboard_image.rs +++ b/crates/terminal_view/src/view/clipboard_image.rs @@ -51,12 +51,14 @@ impl TerminalView { if !self.is_live_ssh_terminal(cx) { return; } - let remote_path = remote_clipboard_image_path(image.format, current_timestamp_millis()); - let bytes = image.bytes; let window_handle = window.window_handle(); let task = Tokio::spawn(cx, async move { + // macOS 剪贴板图片是 TIFF,远端 CLI 通常读不了;先统一转成 PNG + // 再决定远端文件名,保证扩展名与实际字节一致。 + let image = remote_image_preview::normalize_clipboard_image(image); + let remote_path = remote_clipboard_image_path(image.format, current_timestamp_millis()); let mut client = RusshSftpClient::connect(ssh_config).await?; - client.write_file(&remote_path, &bytes).await?; + client.write_file(&remote_path, &image.bytes).await?; Ok::<_, anyhow::Error>(remote_path) }); diff --git a/crates/terminal_view/src/view/helpers.rs b/crates/terminal_view/src/view/helpers.rs index 450af90dc..dbe47b602 100644 --- a/crates/terminal_view/src/view/helpers.rs +++ b/crates/terminal_view/src/view/helpers.rs @@ -2,7 +2,7 @@ use super::*; use alacritty_terminal::sync::FairMutex; pub(super) const REMOTE_CLIPBOARD_IMAGE_DIR: &str = "/tmp"; -pub(super) const REMOTE_CLIPBOARD_IMAGE_PREFIX: &str = "onetcli-paste"; +pub(super) const REMOTE_CLIPBOARD_IMAGE_PREFIX: &str = "navop-paste"; #[derive(Clone, Debug, PartialEq, Eq)] pub(super) struct WrappedLineSegment { diff --git a/crates/terminal_view/src/view/initialization.rs b/crates/terminal_view/src/view/initialization.rs index e87905b98..042e6bf0f 100644 --- a/crates/terminal_view/src/view/initialization.rs +++ b/crates/terminal_view/src/view/initialization.rs @@ -27,6 +27,8 @@ impl TerminalView { .step(0.001) .default_value(0.0) }); + let search_input = + cx.new(|cx| InputState::new(window, cx).placeholder(t!("Settings.search_placeholder"))); // 获取初始颜色 let colors = terminal.read(cx).term().lock().colors().clone(); @@ -178,6 +180,26 @@ impl TerminalView { let terminal_subscription = cx.subscribe_in(&terminal, window, Self::handle_terminal_event); let command_bar_subscription = cx.subscribe_in(&command_bar, window, Self::handle_command_bar_event); + let search_input_for_events = search_input.clone(); + let search_subscription = cx.subscribe_in( + &search_input, + window, + move |this, _state, event: &InputEvent, _window, cx| match event { + InputEvent::Change => { + let pattern = search_input_for_events.read(cx).value().to_string(); + let _ = this.set_search_pattern(&pattern); + cx.notify(); + } + InputEvent::PressEnter { secondary, .. } => { + if *secondary { + this.search_backward_internal(cx); + } else { + this.search_forward_internal(cx); + } + } + _ => {} + }, + ); let recording_playback_slider_subscription = cx.subscribe_in( &recording_playback_slider, window, @@ -216,6 +238,7 @@ impl TerminalView { subscriptions.push(sidebar_subscription); subscriptions.push(terminal_subscription); subscriptions.push(command_bar_subscription); + subscriptions.push(search_subscription); subscriptions.push(recording_playback_slider_subscription); if let Some(subscription) = workspace_editor_subscription { subscriptions.push(subscription); @@ -293,6 +316,8 @@ impl TerminalView { pending_render_cache_reset: false, block_selection: None, addon_manager: Self::create_addon_manager(), + search_input, + search_open: false, _subscriptions: subscriptions, mouse_position: None, render_cache: RenderCache::new(DEFAULT_ROWS, DEFAULT_COLS, colors), diff --git a/crates/terminal_view/src/view/keybindings.rs b/crates/terminal_view/src/view/keybindings.rs index 7e84ca3c3..2c4d04be5 100644 --- a/crates/terminal_view/src/view/keybindings.rs +++ b/crates/terminal_view/src/view/keybindings.rs @@ -1,6 +1,7 @@ use super::*; pub(super) const TERMINAL_CONTEXT: &str = "TerminalView"; +pub(super) const TERMINAL_SEARCH_CONTEXT: &str = "TerminalSearch"; #[cfg(target_os = "macos")] pub(super) const TERMINAL_COPY_SHORTCUT: &str = "cmd-c"; @@ -63,6 +64,7 @@ pub fn refresh_keybindings(cx: &mut App) { pub(super) fn init_keybindings(cx: &App) -> Vec { let mut keybindings = Vec::new(); keybindings.extend(crate::sidebar::file_manager_panel::init_keybindings()); + keybindings.push(terminal_search_close_keybinding()); keybindings.extend( shortcuts_for(cx, action_id::TERMINAL_SEND_TAB, &["tab"]) .into_iter() @@ -206,6 +208,7 @@ pub(super) fn init_keybindings(cx: &App) -> Vec { pub(super) fn refreshable_keybindings(cx: &App) -> Vec { let mut keybindings = Vec::new(); keybindings.extend(crate::sidebar::file_manager_panel::init_keybindings()); + keybindings.push(terminal_search_close_keybinding()); keybindings.extend(rebind_keybindings( cx, action_id::TERMINAL_SEND_TAB, @@ -328,6 +331,10 @@ pub(super) fn refreshable_keybindings(cx: &App) -> Vec { keybindings } +fn terminal_search_close_keybinding() -> KeyBinding { + KeyBinding::new("escape", CloseTerminalSearch, Some(TERMINAL_SEARCH_CONTEXT)) +} + pub(super) fn terminal_paste_defaults() -> Vec<&'static str> { if cfg!(target_os = "macos") { vec![TERMINAL_PASTE_SHORTCUT] diff --git a/crates/terminal_view/src/view/render_surface.rs b/crates/terminal_view/src/view/render_surface.rs index 3c7be4059..aeee6a723 100644 --- a/crates/terminal_view/src/view/render_surface.rs +++ b/crates/terminal_view/src/view/render_surface.rs @@ -46,6 +46,9 @@ impl TerminalView { .flex_col() .overflow_hidden() .child(self.render_terminal_core(state, cx)) + .when(self.search_open, |this| { + this.child(self.render_terminal_search_bar(cx)) + }) .when(show_scrollbar, |this| { this.child(self.render_terminal_scrollbar()) }) diff --git a/crates/terminal_view/src/view/search_bar.rs b/crates/terminal_view/src/view/search_bar.rs new file mode 100644 index 000000000..280f3dde9 --- /dev/null +++ b/crates/terminal_view/src/view/search_bar.rs @@ -0,0 +1,61 @@ +use super::*; + +impl TerminalView { + pub(super) fn render_terminal_search_bar(&mut self, cx: &mut Context) -> AnyElement { + let colors = self.current_theme.colors(); + h_flex() + .id("terminal-search-bar") + .key_context(TERMINAL_SEARCH_CONTEXT) + .absolute() + .top(px(20.0)) + .right(px(20.0)) + .occlude() + .w(px(340.0)) + .max_w(px(420.0)) + .gap_1() + .p_2() + .rounded_md() + .border_1() + .border_color(colors.border) + .bg(colors.background) + .shadow_lg() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_action(cx.listener(Self::close_terminal_search)) + .on_action(cx.listener(Self::search_forward)) + .on_action(cx.listener(Self::search_backward)) + .child( + Input::new(&self.search_input) + .small() + .w_full() + .prefix(Icon::new(IconName::Search).xsmall()), + ) + .child( + Button::new("terminal-search-prev") + .icon(IconName::ChevronUp) + .ghost() + .small() + .on_click(cx.listener(|this, _, _window, cx| { + this.search_backward_internal(cx); + })), + ) + .child( + Button::new("terminal-search-next") + .icon(IconName::ChevronDown) + .ghost() + .small() + .on_click(cx.listener(|this, _, _window, cx| { + this.search_forward_internal(cx); + })), + ) + .child( + Button::new("terminal-search-close") + .icon(IconName::Close) + .ghost() + .small() + .on_click(cx.listener(|this, _, window, cx| { + this.close_search(window, cx); + })), + ) + .into_any_element() + } +} diff --git a/crates/terminal_view/src/view/selection_search.rs b/crates/terminal_view/src/view/selection_search.rs index 496c5018a..d828d39bd 100644 --- a/crates/terminal_view/src/view/selection_search.rs +++ b/crates/terminal_view/src/view/selection_search.rs @@ -60,14 +60,6 @@ impl TerminalView { self.sidebar.update(cx, |sidebar, cx| { sidebar.set_active_panel(None, cx); }); - // 清除搜索 - self.sidebar.update(cx, |sidebar, cx| { - sidebar.set_search_value("", window, cx); - }); - if let Some(search) = self.addon_manager.get_as_mut::("search") { - search.clear(); - } - self.invalidate_terminal_searches(); cx.notify(); return; } @@ -88,39 +80,61 @@ impl TerminalView { ); } + fn open_search(&mut self, window: &mut Window, cx: &mut Context) { + self.search_open = true; + let focus_handle = self.search_input.read(cx).focus_handle(cx); + focus_handle.focus(window, cx); + cx.notify(); + } + + pub(super) fn close_terminal_search( + &mut self, + _: &CloseTerminalSearch, + window: &mut Window, + cx: &mut Context, + ) { + self.close_search(window, cx); + } + + pub(super) fn close_search(&mut self, window: &mut Window, cx: &mut Context) { + if !self.search_open { + return; + } + self.search_open = false; + let search_input = self.search_input.clone(); + search_input.update(cx, |input, cx| input.set_value("", window, cx)); + if let Some(search) = self.addon_manager.get_as_mut::("search") { + search.clear(); + } + self.invalidate_terminal_searches(); + // 浮层卸载前把焦点还给终端,避免后续快捷键和终端输入丢失。 + self.focus_terminal(window, cx); + cx.notify(); + } + pub(super) fn search_forward( &mut self, _: &SearchForward, - _window: &mut Window, + window: &mut Window, cx: &mut Context, ) { - // 如果侧边栏设置面板未激活,则激活它 - if self.sidebar.read(cx).active_panel() != Some(SidebarPanel::Settings) { - self.sidebar.update(cx, |sidebar, cx| { - sidebar.set_active_panel(Some(SidebarPanel::Settings), cx); - }); - cx.notify(); + if !self.search_open { + self.open_search(window, cx); return; } - // 执行向前搜索 self.search_forward_internal(cx); } pub(super) fn search_backward( &mut self, _: &SearchBackward, - _window: &mut Window, + window: &mut Window, cx: &mut Context, ) { - // 如果侧边栏设置面板未激活,则激活它 - if self.sidebar.read(cx).active_panel() != Some(SidebarPanel::Settings) { - self.sidebar.update(cx, |sidebar, cx| { - sidebar.set_active_panel(Some(SidebarPanel::Settings), cx); - }); - cx.notify(); + if !self.search_open { + self.open_search(window, cx); return; } - // 执行向后搜索 self.search_backward_internal(cx); } diff --git a/crates/terminal_view/src/view/sidebar_events.rs b/crates/terminal_view/src/view/sidebar_events.rs index 98c1c650c..bea628bb5 100644 --- a/crates/terminal_view/src/view/sidebar_events.rs +++ b/crates/terminal_view/src/view/sidebar_events.rs @@ -207,16 +207,6 @@ impl TerminalView { cx.emit(TabContentEvent::StateChanged); cx.notify(); } - TerminalSidebarEvent::SearchPatternChanged(pattern) => { - let _ = self.set_search_pattern(pattern); - cx.notify(); - } - TerminalSidebarEvent::SearchPrevious => { - self.search_backward_internal(cx); - } - TerminalSidebarEvent::SearchNext => { - self.search_forward_internal(cx); - } TerminalSidebarEvent::FontSizeChanged(size) => { self.set_font_size(*size, cx); } diff --git a/crates/terminal_view/src/view/tests/capabilities.rs b/crates/terminal_view/src/view/tests/capabilities.rs index 831905dc8..e0dfd118c 100644 --- a/crates/terminal_view/src/view/tests/capabilities.rs +++ b/crates/terminal_view/src/view/tests/capabilities.rs @@ -659,6 +659,53 @@ fn terminal_key_and_selection_actions_never_wait_for_the_parser() { assert!(hot_actions.contains("PendingTerminalAction::ResolveClearSelection")); } +#[test] +fn terminal_search_uses_an_independent_overlay_without_opening_settings() { + let selection = include_str!("../selection_search.rs"); + for action in [ + "pub(super) fn search_forward", + "pub(super) fn search_backward", + ] { + let region = function_region(selection, action, "\n pub "); + assert!( + region.contains("self.open_search(window, cx)"), + "搜索快捷键必须打开独立搜索浮层" + ); + assert!( + !region.contains("SidebarPanel::Settings"), + "搜索快捷键不得展开设置侧栏" + ); + } + + let close = function_region(selection, "pub(super) fn close_search", "\n pub "); + assert!( + close.contains("self.search_open = false") + && close.contains("input.set_value(\"\", window, cx)") + && close.contains("search.clear()") + && close.contains("self.invalidate_terminal_searches()") + && close.contains("self.focus_terminal(window, cx)"), + "关闭搜索必须清理匹配、取消旧任务并恢复终端焦点" + ); + + let surface = include_str!("../render_surface.rs"); + assert!( + surface.contains(".when(self.search_open") + && surface.contains("render_terminal_search_bar"), + "搜索浮层应挂在终端视口内" + ); + let search_bar = include_str!("../search_bar.rs"); + assert!( + search_bar.contains(".absolute()") && search_bar.contains(".occlude()"), + "搜索框必须是覆盖层,不能挤动终端画布" + ); + + let settings = include_str!("../../sidebar/settings_panel.rs"); + assert!( + !settings.contains("render_search_section") && !settings.contains("search_input_state"), + "设置面板不得保留另一套不同步的搜索框" + ); +} + #[test] fn terminal_search_never_waits_for_the_parser_on_the_gpui_thread() { let source = include_str!("../sidebar_events.rs"); diff --git a/crates/terminal_view/src/view/tests/core.rs b/crates/terminal_view/src/view/tests/core.rs index 2a2d96415..9512b38b2 100644 --- a/crates/terminal_view/src/view/tests/core.rs +++ b/crates/terminal_view/src/view/tests/core.rs @@ -434,14 +434,14 @@ fn recording_playback_tab_title_is_visibly_read_only_playback() { fn remote_clipboard_image_path_uses_tmp_prefix_and_format_extension() { let path = remote_clipboard_image_path(ImageFormat::Png, 1_720_000_000_123); - assert_eq!("/tmp/onetcli-paste-1720000000123.png", path); + assert_eq!("/tmp/navop-paste-1720000000123.png", path); } #[test] fn remote_clipboard_image_path_uses_jpg_for_jpeg_images() { let path = remote_clipboard_image_path(ImageFormat::Jpeg, 42); - assert_eq!("/tmp/onetcli-paste-42.jpg", path); + assert_eq!("/tmp/navop-paste-42.jpg", path); } #[test] diff --git a/docs/design/ssh-jump-server-optimization.md b/docs/design/ssh-jump-server-optimization.md new file mode 100644 index 000000000..6d7a58ec8 --- /dev/null +++ b/docs/design/ssh-jump-server-optimization.md @@ -0,0 +1,241 @@ +# 跳板机连接体系优化(ProxyJump 统一与堡垒机直连) + +> 文档状态:Proposed Design +> +> 目标读者:维护 `crates/ssh` / `crates/sftp` / `crates/terminal` / `crates/ssh_form` / +> `crates/connection_tunnel` 的开发 Agent +> +> 编写日期:2026-11-19 + +--- + +## 1. 问题 + +用户以 JumpServer(Koko)作跳板机连接资产时,得到的是一句无法行动的报错 +`Failed to open channel (AdministrativelyProhibited)`。顺着这条报错把整个跳板机链路勘察一遍后, +发现它是**体系性问题**的一个切面,共七项: + +1. **错误黑盒**:跳板拒绝 `direct-tcpip` 通道时,russh 在 + `client/encrypted.rs:558-585` 已解出服务端的 `description`(如 JumpServer 的 + `port forwarding is disabled`),但只把原因码枚举下发,description 被丢弃。 + Navop 下游只能靠字符串匹配兜底(`crates/terminal/src/ssh_backend.rs:153-230`), + 没有任何一条提示「堡垒机策略禁用端口转发」这一最常见成因。 +2. **SFTP 跳板是一套重复且退化的实现**:`crates/sftp/src/russh_impl.rs:2357-2440` + 重复了 `crates/ssh/src/ssh.rs:2623-2723` 约 80 行跳板连接逻辑;且认证用的是 + `authenticate_with_strategy`(`crates/ssh/src/ssh.rs:1460-1478`,内部转发为 + `KeyboardInteractiveTarget::TargetServer` + responder 恒 None)→ + **SFTP 走跳板时无 MFA/OTP 能力**,与终端路径行为不一致。 +3. **五处独立的 `JumpServerConnectConfig` 映射**: + `crates/sftp_transfer/src/ssh_config.rs:66`、`crates/terminal/src/terminal.rs:740`、 + `crates/runtime_sftp/src/sftp_tools.rs:330`、`crates/port_forwarding/src/runtime.rs:250`、 + `crates/ssh_form/src/ssh_form_window.rs:1919`。 + 键盘交互 responder 只有 ssh_form(测试连接)和 terminal 两条路传入,其余全是 None。 +4. **跨子系统零会话复用**:终端每个连接独立建 `SshSessionManager` + (`crates/terminal/src/terminal.rs:3242`,仅同连接多 tab 共享);SFTP 工具、 + 端口转发(`crates/ssh/src/ssh.rs:2481`)、SOCKS、DB 隧道每次调用都新建完整 + TCP+认证链(含跳板 MFA 重答)。而仓库里**已建好未接线**的应用级共享层: + `crates/ssh/src/session_registry.rs`(`SshSessionService`,ConnectionKey→单飞 manager、 + 租约、60s idle 回收,由 `crates/shell_domain/src/lifecycle.rs:12` 挂进 GPUI global) + 与 `crates/terminal/src/ssh_session_identity.rs`(`PersistedSshSessionIdentity::derive`) + 全库无任何 acquire 调用者;`crates/ssh/src/connection_key.rs` 的 `JumpKey` + 本就是为跨连接共享跳板传输设计的。 +5. **堡垒机(直连型)形态不支持**:JumpServer/Koko 默认拒绝 direct-tcpip, + 只支持「用户名指定资产」的直连格式(`user#asset#account@堡垒机:2222`, + 终端走 proxyAssetCommand、SFTP 走 DirectConnectSftpMode;2026-11-19 已在 + 10.2.5.220:2222 实测验证)。Navop 的跳板机只有 ProxyJump 语义,且 UI 没有模式区分, + 用户只能靠手填 `user#asset#account` 用户名绕过。 +6. **引用 SSH 连接的隧道丢失跳板**:`crates/core/src/storage/models.rs` + `apply_referenced_ssh_tunnel` 三份重复实现(:1056/:1155/:1280,Redis/MongoDB/Db) + 只回填 host/port/username/auth/timeout,jump_server 与 proxy 全部丢弃; + `crates/redis-runtime/src/builtin.rs:469`、mongodb builtin 更是 `jump_server: None` 硬编码。 +7. **模型能力上限**:`JumpServerConfig`(`crates/core/src/storage/models.rs:812-819`) + 是单跳模型:无链式多跳、无每跳独立 proxy/超时/MFA;`SshConnectConfig` 里 + proxy 与 MFA responder 是全局的(跳板和目标两段共用)。 + +### 现状地图 + +| 连接路径 | 跳板实现 | 跳板 MFA | 会话复用 | +| --- | --- | --- | --- | +| 终端(`ssh.rs::connect` 跳板分支) | ssh.rs:2623-2723 | ✅ TerminalMfaResponder | 单连接内(SessionPool) | +| 表单「测试连接」 | 同上 | ✅ JumpServerMfaResponder | 无 | +| SFTP 客户端(`russh_impl.rs`) | :2357-2440 重复实现 | ❌ | 无 | +| SFTP 工具(`runtime_sftp`) | jump_config :330 | ❌ | 无 | +| 端口转发(`port_forwarding`) | runtime.rs:250 | ❌ | 无 | +| 本地转发 / SOCKS(ssh.rs:2481、dynamic_socks) | 每次 connect 重建 | ❌ | 无 | +| DB / Redis / Mongo 隧道 | 引用 SSH 连接但丢 jump | — | 无 | + +## 2. 目标与非目标 + +**目标** + +- G1 错误可读可行动:direct-tcpip 被拒时透出服务端 description,并给出 + 「该堡垒机禁用端口转发,建议改用堡垒机直连模式」的专门提示。 +- G2 SFTP 走跳板支持 MFA,与终端路径行为一致。 +- G3 跳板连接构造与实现收敛到唯一入口,五处映射、两套实现合一。 +- G4 堡垒机(直连型)成为一等公民连接模式:资产/账号字段化,终端/SFTP/ + exec 全部可用,不再依赖手拼 `user#asset#account`。 +- G5 引用 SSH 连接的隧道继承完整上游语义(jump/proxy/MFA)。 +- G6 跳板传输跨连接复用(接线现有 SshSessionService / ConnectionKey 体系)。 + +**非目标** + +- 本期不做链式多跳(数据模型预留字段即可)。 +- 不改 russh 公共 API 语义;fork 只做增量(新增携带信息,不改已有签名含义)。 + +## 3. 设计 + +### 3.1 错误链修复(F1):把 description 送达 UI + +两步走,先零 fork 改动,后 fork 收尾: + +- **方案 B(Navop 侧,先行)**:russh 的 Handler trait 已有钩子 + `channel_open_failure(channel, reason, description, language, session)` + (fork `client/mod.rs:2903`,默认 no-op)。给 Navop 的 client Handler 增加 + `last_open_failures: Arc>>`, + 在钩子里记录;`channel_open_direct_tcpip` 返回 + `Err(Error::ChannelOpenFailure(reason))` 后(ssh.rs:2680、russh_impl.rs:2405、 + ssh.rs:2422 三个调用点)按 channel id 查记录,把 description 拼进 anyhow context。 +- **方案 C(fork 增量,后续)**:`Error::ChannelOpenFailure` 增加 + `description: Option`(或新增变体),`wait_channel_confirmation` + 从 handler 缓存补齐。落地后退回 Navop 的 slot 方案。 +- **分类提示**:`crates/terminal/src/ssh_backend.rs` 的 + `add_connect_error_context` / `is_channel_open_failure` 增加 + AdministrativelyProhibited + 跳板场景分支:提示「跳板机/堡垒机拒绝了端口转发通道 + ({description})。JumpServer 等堡垒机默认禁用 direct-tcpip,请在连接设置的 + 跳板机页改用『堡垒机直连』模式,或联系管理员」。ssh_form 的 + `format_connection_error`(:527)同步受益。 + +### 3.2 统一跳板传输(U1/U2):一个入口、一套实现 + +从 `RusshClient::connect` 里抽出可复用的跳板传输层: + +```rust +// crates/ssh(终端/SFTP/端口转发共用) +pub struct JumpConnectOptions<'a> { + pub jump: &'a JumpServerConnectConfig, + pub proxy: Option<&'a ProxyConfig>, + pub mfa: Option<&'a dyn KeyboardInteractiveResponder>, // 作用于跳板段 + pub timeouts: ConnectTimeouts, +} + +/// 一条已认证的跳板传输(含路由身份,供将来的跨连接复用) +pub struct JumpTransport { /* session handle + JumpRoute */ } + +impl JumpTransport { + /// 对目标 host:port 开 direct-tcpip 通道(每目标一条) + pub async fn open_channel_to(&self, host: &str, port: u16) -> Result>; +} + +pub async fn open_jump_transport(opts: JumpConnectOptions<'_>) -> Result; +``` + +- `ssh.rs::connect` 跳板分支改为 `open_jump_transport` + `open_channel_to` + + 在通道上 `connect_stream` 建目标 SSH; +- `crates/sftp/src/russh_impl.rs:2357-2440` 删除重复实现,改调同一入口; +- MFA:认证统一走 `authenticate_with_strategy_for_target(..., + KeyboardInteractiveTarget::JumpServer, opts.mfa)`;`ssh.rs:1460` 的无 target + 变体收敛(改签名带 target 或直接删掉,编译期逼出所有调用点); +- 五处 `JumpServerConnectConfig` 映射收敛为一个 builder(放 `crates/ssh`, + 输入 core 的 `JumpServerConfig` + 可选 responder/proxy),SFTP 工具、 + 端口转发、终端、表单测试全部改走它——MFA 从「散落的 None」变成显式参数。 + +### 3.3 堡垒机直连模式(B1):解决 JumpServer 形态 + +数据模型(core): + +```rust +pub enum JumpMode { + /// 现有语义:跳板上开 direct-tcpip 通道连目标(默认,向后兼容) + ProxyJump, + /// 直连型堡垒机:目标会话就是堡垒机会话,用户名按模板渲染 + BastionDirect, +} + +pub struct JumpServerConfig { + pub host: String, + pub port: u16, + pub username: String, + pub auth_method: SshAuthMethod, + pub credential_reference: Option, + pub mode: JumpMode, // 新增,缺省 ProxyJump(旧数据无感) + pub bastion: Option, // BastionDirect 时生效 +} + +pub struct BastionTarget { + pub asset: String, // 资产 IP / 名称 / UUID + pub account: String, // 资产账号(如 root) + pub user_format: BastionUserFormat, // 预设:JumpServer 的 user#account#asset 等 +} +``` + +连接流(BastionDirect): + +- **不开 direct-tcpip**;目标会话 = 堡垒机 SSH 会话本身; +- username 按 `user_format` 渲染(JumpServer:`{user}#{account}#{asset}`); +- host key 沿用 `jump_host_key_identity`(HostKeyRoute::Jump); +- 终端(PTY)、exec 通道、SFTP 子系统直接跑在堡垒机会话上—— + Koko 对直连格式会代理到资产(exec 走 proxyAssetCommand,SFTP 走 + DirectConnectSftpMode,2026-11-19 已实测),三层全部可用; +- `RusshClient` 需要区分「会话即堡垒机」与「会话在通道上」两种形态 + (`_jump_session` 在 BastionDirect 下为 None,断线重连、保活逻辑走同一会话)。 + +UI(ssh_form 跳板机 tab): + +- 模式单选:「SSH 跳板(ProxyJump)」/「堡垒机直连(JumpServer 等)」; +- BastionDirect 下显示资产/账号/用户名格式字段,隐藏「目标主机经跳板转发」相关说明; +- 存量行为不变:未选模式 = ProxyJump,`disabled_jump_server` 保留逻辑照旧。 + +检测辅助(可选,P2):连跳板成功但 direct-tcpip 被拒、且 banner 含 +`SSH-2.0-JumpServer`(或 description 含 `port forwarding is disabled`)时, +在错误提示里给出「一键切换为堡垒机直连模式」。 + +### 3.4 会话复用接线(R1):让已建好的共享层生效 + +- 终端建连:`crates/terminal/src/terminal.rs:3242` 从 + `Arc::new(SshSessionManager::new(...))` 改为经 + `GlobalSshSessionService` 以 `PersistedSshSessionIdentity::derive(connection, config)` + acquire(租约即生命周期,`transition_to` 的 ReuseLease/ReplaceLease 分支生效); +- 跳板传输复用:`JumpTransport` 按 `ConnectionKey::JumpKey` 缓存进 + `SshSessionRegistry`——同一跳板 host+凭据修订 下,多个目标连接共享一条 + 跳板传输(每目标仍各开 direct-tcpip 通道),跳板 MFA 只答一次; +- 端口转发/DB 隧道按需接入(先观察终端接线稳定性)。 + +### 3.5 隧道继承(T1):引用 SSH 连接不再丢语义 + +- `crates/connection_tunnel` 的 `SshTunnelConfig` 增加 `jump`/`proxy` 字段 + (或改为直接持有 `connection_id`,运行时经 `resolve_runtime_connection` 取全量); +- `apply_referenced_ssh_tunnel` 三份重复实现合并为一个共享函数,回填 jump/proxy; +- redis/mongodb builtin 去掉 `jump_server: None` 硬编码,跟随引用连接。 + +## 4. 分阶段实施 + +| 阶段 | 内容 | 主要改动点 | 规模/风险 | +| --- | --- | --- | --- | +| **P0 快赢** | F1 错误透传 + 跳板拒绝专用提示;F2 SFTP 跳板 MFA(改用 `_for_target` + responder 传通) | russh Handler 钩子实现、ssh.rs 三个 direct-tcpip 调用点、ssh_backend.rs 分类、russh_impl.rs 认证行 | 小;行为只增不改,风险低 | +| **P1 堡垒机直连** | B1 模型 + 连接流 + 表单模式 | models.rs、ssh.rs(会话形态分支)、ssh_form(tab + i18n 三语)、迁移(mode 缺省) | 中;新路径,老路径不动 | +| **P2 统一收敛** | U1/U2 `JumpTransport` 唯一入口、五处映射合一、删 SFTP 重复实现 | ssh.rs、russh_impl.rs、五个构造点 | 中;纯重构,靠测试兜底 | +| **P3 复用接线** | R1 registry acquire + 跳板传输共享;T1 隧道继承 | terminal.rs、session_registry/identity、connection_tunnel、models.rs | 中大;生命周期交互需小心 | +| **P4 长尾** | fork 方案 C(Error 携带 description)、堡垒机检测一键切换、链式多跳预留、ssh_exec 空结果 UX | russh fork、模型预留 | 按需 | + +依赖关系:P0 独立可做;P1 依赖 P0 的错误提示(切换建议文案);P2 与 P1 可并行; +P3 依赖 P2(`JumpTransport` 稳定后才能按 JumpKey 缓存)。 + +## 5. 验证 + +- 每阶段:`cargo test -p ssh -p sftp -p terminal -p ssh_form` + + `cargo clippy -- --deny warnings`(按 AGENTS.md,TDD:先补 Red 测试再实现); +- F1:单测覆盖 Handler slot 记录与错误上下文拼接(AdministrativelyProhibited + + description 透传);利用 `ssh_backend.rs:2555` 附近 MockClient 测试模式补 + 分类提示断言; +- F2:单测断言 SFTP 跳板认证收到 `KeyboardInteractiveTarget::JumpServer` 与 + 非 None responder; +- B1:以 10.2.5.220:2222 实测(用户名 `hufei#root#{asset-uuid}`,JumpServer + 账号密码),验证终端、SFTP 浏览/传输、`ssh_exec` 三层; +- R1:多终端连接同一跳板下多个资产,观察跳板认证次数与 idle 回收后重连。 + +## 6. 开放问题 + +- BastionDirect 的用户名格式预设集(JumpServer `user#account#asset` 之外, + Teleport `user@asset`、齐治等)先只做 JumpServer,格式字段留扩展位; +- 跳板传输共享时,JumpServer 会话并发 direct-tcpip 上限(MaxSessions)与 + 通道排队策略需要在 P3 实测定参。 diff --git a/installer/windows/navop.wxs b/installer/windows/navop.wxs index 58f4d4ab6..f6e2ddefb 100644 --- a/installer/windows/navop.wxs +++ b/installer/windows/navop.wxs @@ -91,6 +91,26 @@ + + + + + + + + + + + + + + CFBundleURLTypes + + + CFBundleURLName + com.onetcli.app.jms + CFBundleTypeRole + Viewer + CFBundleURLSchemes + jms + + + CFBundleURLName + com.onetcli.app.ssh + CFBundleTypeRole + Viewer + CFBundleURLSchemes + ssh + + + CFBundleURLName + com.onetcli.app.sftp + CFBundleTypeRole + Viewer + CFBundleURLSchemes + sftp + + LSApplicationCategoryType public.app-category.developer-tools diff --git a/script/test-bundle-macos.sh b/script/test-bundle-macos.sh index 09ba8c96b..4a77f1527 100755 --- a/script/test-bundle-macos.sh +++ b/script/test-bundle-macos.sh @@ -59,9 +59,17 @@ bundle_product() { grep -q 'Viewer' "${app_dir}/Contents/Info.plist" grep -q 'org.asciinema.cast' "${app_dir}/Contents/Info.plist" grep -q 'application/x-asciicast' "${app_dir}/Contents/Info.plist" + # 深链接:全量产品声明 jms://;ssh:// 与 sftp:// 只是候选声明, + # 真正是否接管由设置开关决定(默认关闭)。 + grep -q 'CFBundleURLTypes' "${app_dir}/Contents/Info.plist" + grep -A2 'CFBundleURLSchemes' "${app_dir}/Contents/Info.plist" \ + | grep -q 'jms' + grep -q 'ssh' "${app_dir}/Contents/Info.plist" + grep -q 'sftp' "${app_dir}/Contents/Info.plist" else ! grep -q 'CFBundleDocumentTypes' "${app_dir}/Contents/Info.plist" ! grep -q 'UTImportedTypeDeclarations' "${app_dir}/Contents/Info.plist" + ! grep -q 'CFBundleURLTypes' "${app_dir}/Contents/Info.plist" fi } diff --git a/script/test-release-packaging.mjs b/script/test-release-packaging.mjs index db0ee9809..4d3a5fcc1 100644 --- a/script/test-release-packaging.mjs +++ b/script/test-release-packaging.mjs @@ -51,7 +51,7 @@ test("release packaging uses the navop executable on every platform", () => { assert.doesNotMatch(bundle, /generate-macos-icon\.sh/); assert.match(bundle, /Error: Icon file not found/); assert.match(plist, /CFBundleExecutable<\/key>\s*navop<\/string>/); - assert.match(desktop, /^Exec=navop %F$/m); + assert.match(desktop, /^Exec=navop %U$/m); assert.match(desktop, /^Icon=navop$/m); assert.match(desktop, /^StartupWMClass=navop$/m); }); @@ -127,6 +127,38 @@ test("installers register database, Markdown, and terminal recording file associ assert.match(release, /update-desktop-database \/usr\/share\/applications/); }); +test("installers register the jms:// JumpServer deep link", () => { + const plist = read("resources/macos/Info.plist"); + const desktop = read("resources/linux/navop.desktop"); + const wix = read("installer/windows/navop.wxs"); + + assert.match(plist, /CFBundleURLTypes<\/key>/); + assert.match( + plist, + /CFBundleURLSchemes<\/key>\s*jms<\/string><\/array>/, + ); + // 通用连接 scheme 只是「声明候选」,是否接管由设置开关决定(默认关闭)。 + assert.match(plist, /com\.onetcli\.app\.ssh<\/string>/); + assert.match(plist, /com\.onetcli\.app\.sftp<\/string>/); + assert.match(plist, /ssh<\/string><\/array>/); + assert.match(plist, /sftp<\/string><\/array>/); + assert.match(plist, /CFBundleTypeRole<\/key>\s*Viewer<\/string>/); + + assert.match(desktop, /^Exec=navop %U$/m); + assert.match(desktop, /^MimeType=.*x-scheme-handler\/jms;/m); + + assert.match(wix, //); + assert.match(wix, //); + assert.match( + wix, + /Value=""\[INSTALLFOLDER\]navop\.exe" "%1""/, + ); + + // 独立产品(shell/data)不接管 jms://,避免抢占全量产品的深链接。 + assert.doesNotMatch(read("resources/linux/navop-shell.desktop"), /jms/); + assert.doesNotMatch(read("resources/linux/navop-data.desktop"), /jms/); +}); + test("renamed Linux packages replace legacy onetcli installations", () => { const release = read(".github/workflows/release.yml");