diff --git a/crates/ide-host/src/ops/vcs/commands.rs b/crates/ide-host/src/ops/vcs/commands.rs index 65007a656..8914eca02 100644 --- a/crates/ide-host/src/ops/vcs/commands.rs +++ b/crates/ide-host/src/ops/vcs/commands.rs @@ -2095,6 +2095,22 @@ pub async fn vcs_gpg_signing_keys( result } +/// Lists SSH public keys from ssh-agent and `~/.ssh` for SSH commit signing. +#[command(trust = trusted)] +pub async fn vcs_ssh_signing_keys( + host: &Host, + window: &str, + repo: PathBuf, + request: RequestId, +) -> IdeResult> { + host.require_trust(window)?; + let project = host.project(window)?; + let cancel = host.begin_project_request(window, request); + let result = blocking(move || project.with_repo_at(Some(&repo), |repo| repo.ssh_signing_keys(&cancel))).await; + host.end_request(request); + result +} + /// Git LFS files of the repository still checked out as pointer files, and whether git-lfs runs. #[command(trust = trusted)] pub async fn vcs_lfs_status(host: &Host, window: &str, repo: PathBuf, request: RequestId) -> IdeResult { @@ -3309,6 +3325,7 @@ ide_command::domain!( vcs_signing_config, vcs_lfs_status, vcs_gpg_signing_keys, + vcs_ssh_signing_keys, vcs_edit_signing, vcs_watch_commit_messages, vcs_set_user_identity, diff --git a/crates/ide-vcs/src/lib.rs b/crates/ide-vcs/src/lib.rs index b586bc614..558405ea7 100644 --- a/crates/ide-vcs/src/lib.rs +++ b/crates/ide-vcs/src/lib.rs @@ -1048,7 +1048,7 @@ pub use rebase_editor::{ }; pub use remotes::{FetchReport, Remote}; pub use roots::{ProjectUpdateTarget, Repos}; -pub use signing::{GitSigningConfig, GitSigningEdit, GpgSigningKey}; +pub use signing::{GitSigningConfig, GitSigningEdit, GpgSigningKey, SshSigningKey}; pub use staged_text::{StagedText, StagedTextEdit, StagingLineHunk, StagingLineHunks}; fn clone_args(url: &str, dest: &str, depth: Option, recurse_submodules: bool) -> IdeResult> { diff --git a/crates/ide-vcs/src/signing.rs b/crates/ide-vcs/src/signing.rs index b2e7a0328..bd140e3a9 100644 --- a/crates/ide-vcs/src/signing.rs +++ b/crates/ide-vcs/src/signing.rs @@ -27,6 +27,18 @@ pub struct GpgSigningKey { pub struct GitSigningEdit { pub enabled: Option, pub key: Option, + /// `openpgp` or `ssh`. + pub format: Option, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct SshSigningKey { + /// The `user.signingkey` value: a public key file path, or `key::` and the key itself. + pub key: String, + pub comment: Option, + /// ssh-agent holds this key, so signing with it needs no passphrase prompt. + pub in_agent: bool, } impl Repo { @@ -40,7 +52,7 @@ impl Repo { pub fn gpg_signing_keys(&self, cancel: &CancellationToken) -> IdeResult> { let _scope = self.execution_scope(); - self.require_openpgp()?; + self.require_editable()?; let program = gpg_program(self.root(), cancel)?; let mut cmd = Command::new(&program); cmd.current_dir(self.root()).args(["--batch", "--no-tty", "--with-colons", "--list-secret-keys"]); @@ -56,14 +68,52 @@ impl Repo { Ok(parse_keys(&out.stdout_str())) } + /// Keys ssh-agent holds, then the public key files in `~/.ssh`. + pub fn ssh_signing_keys(&self, cancel: &CancellationToken) -> IdeResult> { + let _scope = self.execution_scope(); + self.require_editable()?; + let mut cmd = Command::new("ssh-add"); + cmd.current_dir(self.root()).arg("-L"); + ide_core::process::prepare(&mut cmd); + // ssh-add exits 1 without identities and 2 without an agent; both just mean no agent keys. + let agent = cli::capture_command(cmd, None, cancel, 1 << 20, "ssh-add") + .ok() + .filter(|out| out.code == Some(0)) + .map(|out| out.stdout_str()) + .unwrap_or_default(); + let mut files = Vec::new(); + if let Some(dir) = gix::path::env::home_dir().map(|home| home.join(".ssh")) + && let Ok(entries) = std::fs::read_dir(dir) + { + for path in entries.flatten().map(|entry| entry.path()) { + if path.extension().is_some_and(|ext| ext == "pub") + && let (Some(path), Ok(text)) = (path.to_str(), std::fs::read_to_string(&path)) + { + files.push((path.to_owned(), text)); + } + } + } + files.sort(); + Ok(ssh_keys(&agent, &files)) + } + pub fn edit_signing(&self, edit: GitSigningEdit) -> IdeResult<()> { let _scope = self.execution_scope(); - self.require_openpgp()?; - if edit.enabled.is_none() && edit.key.is_none() { + let current = self.require_editable()?; + if edit.enabled.is_none() && edit.key.is_none() && edit.format.is_none() { return Ok(()); } - if edit.key.as_deref().is_some_and(|key| !valid_fingerprint(key)) { - return Err(IdeError::invalid("invalid OpenPGP fingerprint")); + let format = edit.format.as_deref().unwrap_or(¤t); + if !matches!(format, "openpgp" | "ssh") { + return Err(IdeError::invalid("unsupported signing format")); + } + if let Some(key) = edit.key.as_deref() { + if format == "openpgp" && !valid_fingerprint(key) { + return Err(IdeError::invalid("invalid OpenPGP fingerprint")); + } + if format == "ssh" && (key.trim().is_empty() || key.chars().any(char::is_control)) { + return Err(IdeError::invalid("invalid SSH signing key")); + } } let config = self.metadata_dirs()?[1].join("config"); let mut lock = lock::File::acquire(&config, Fail::Immediately, None, 0, Some(&lock::acquire::resolve_symlink)) @@ -74,7 +124,11 @@ impl Repo { let mut staged = tempfile::NamedTempFile::new_in(config.parent().expect("repository config directory"))?; io::copy(&mut original, &mut staged)?; let enabled = edit.enabled.map(|enabled| if enabled { "true" } else { "false" }); - for (name, value) in [("commit.gpgsign", enabled), ("user.signingkey", edit.key.as_deref())] { + for (name, value) in [ + ("gpg.format", edit.format.as_deref()), + ("commit.gpgsign", enabled), + ("user.signingkey", edit.key.as_deref()), + ] { if let Some(value) = value { cli::run( self.root(), @@ -91,6 +145,16 @@ impl Repo { )?; } } + // A new format without a new key: the old key belongs to the other format. + if edit.format.as_deref().is_some_and(|format| format != current) && edit.key.is_none() { + let path = staged.path().to_str().ok_or_else(|| IdeError::invalid("non-UTF-8 Git config path"))?; + let args = ["config", "--file", path, "--unset-all", "user.signingkey"]; + let out = cli::run_cancellable_raw(self.root(), &args, &CancellationToken::default())?; + // 5: the key was not set in this file. + if !matches!(out.code, Some(0 | 5)) { + return Err(cli::failure(&args, &out.stderr, &out.stdout, out.code)); + } + } // Git's config writer replaces the staging file, so reopen its final path. let mut updated = std::fs::File::open(staged.path())?; lock.with_mut(|file| { @@ -102,14 +166,16 @@ impl Repo { Ok(()) } - fn require_openpgp(&self) -> IdeResult<()> { + /// The repository's signing format, when the IDE can edit it (OpenPGP or SSH). + fn require_editable(&self) -> IdeResult { if !execution_allowed() { return Err(IdeError::unavailable("Git signing configuration requires a trusted project")); } - if self.config_get("gpg.format")?.is_some_and(|format| format != "openpgp") { - return Err(IdeError::invalid("the repository uses a signing format other than OpenPGP")); + let format = self.config_get("gpg.format")?.unwrap_or_else(|| "openpgp".into()); + if !matches!(format.as_str(), "openpgp" | "ssh") { + return Err(IdeError::invalid("the repository uses a signing format other than OpenPGP or SSH")); } - Ok(()) + Ok(format) } } @@ -142,6 +208,37 @@ fn gpg_program(root: &Path, cancel: &CancellationToken) -> IdeResult { Ok(if program.is_relative() && program.components().count() > 1 { root.join(program) } else { program }) } +/// `agent` is `ssh-add -L` output; `files` are `(path, contents)` of public key files. +/// A file whose key the agent holds replaces that agent entry. +fn ssh_keys(agent: &str, files: &[(String, String)]) -> Vec { + // " [comment]": the first two fields identify the key. + let split = |line: &str| { + let mut parts = line.trim().splitn(3, ' '); + let id = parts.next().zip(parts.next()).map(|(kind, blob)| format!("{kind} {blob}")); + id.map(|id| (id, parts.next().map(str::trim).filter(|c| !c.is_empty()).map(str::to_owned))) + }; + let agent: Vec<_> = agent.lines().filter_map(split).collect(); + let files: Vec<_> = files + .iter() + .filter_map(|(path, text)| { + let (id, comment) = text.lines().find(|line| !line.trim().is_empty()).and_then(split)?; + Some((id, SshSigningKey { key: path.clone(), comment, in_agent: false })) + }) + .collect(); + let mut keys: Vec<_> = agent + .iter() + .filter(|(id, _)| !files.iter().any(|(file, _)| file == id)) + .map(|(id, comment)| SshSigningKey { key: format!("key::{id}"), comment: comment.clone(), in_agent: true }) + .collect(); + for (id, mut key) in files { + key.in_agent = agent.iter().any(|(held, _)| *held == id); + keys.push(key); + } + // Keys the agent holds first: they sign without a passphrase prompt. + keys.sort_by_key(|key| !key.in_agent); + keys +} + fn valid_fingerprint(value: &str) -> bool { matches!(value.len(), 40 | 64) && value.bytes().all(|byte| byte.is_ascii_hexdigit()) } @@ -239,7 +336,7 @@ mod tests { git(&["config", "--local", "user.email", "test@example.com"]); let repo = Repo::discover(dir.path()).unwrap().unwrap(); - let enable = || GitSigningEdit { enabled: Some(true), key: Some(FINGERPRINT.into()) }; + let enable = || GitSigningEdit { enabled: Some(true), key: Some(FINGERPRINT.into()), format: None }; assert!(repo.edit_signing(enable()).is_err()); assert!(repo.gpg_signing_keys(&CancellationToken::default()).is_err()); repo.set_execution_allowed(true); @@ -254,13 +351,54 @@ mod tests { assert_eq!(git(&["config", "--local", "--get", "user.email"]).trim(), "test@example.com"); assert!(repo.signing_config().unwrap().enabled); - repo.edit_signing(GitSigningEdit { enabled: Some(false), key: None }).unwrap(); + repo.edit_signing(GitSigningEdit { enabled: Some(false), key: None, format: None }).unwrap(); assert!(!repo.signing_config().unwrap().enabled); assert_eq!(git(&["config", "--local", "--get", "user.signingkey"]).trim(), FINGERPRINT); - git(&["config", "--local", "gpg.format", "ssh"]); + let ssh = GitSigningEdit { + enabled: Some(true), + key: Some("key::ssh-ed25519 AAAA".into()), + format: Some("ssh".into()), + }; + repo.edit_signing(ssh).unwrap(); + let config = repo.signing_config().unwrap(); + assert_eq!((config.format.as_str(), config.enabled), ("ssh", true)); + assert_eq!(config.key.as_deref(), Some("key::ssh-ed25519 AAAA")); + let bad = GitSigningEdit { enabled: None, key: Some("a\nb".into()), format: None }; + assert!(repo.edit_signing(bad).is_err()); + + // Switching the format with signing off must not leave the other format's key behind. + repo.edit_signing(GitSigningEdit { enabled: Some(false), key: None, format: Some("openpgp".into()) }).unwrap(); + repo.edit_signing(GitSigningEdit { enabled: Some(false), key: Some(FINGERPRINT.into()), format: None }) + .unwrap(); + repo.edit_signing(GitSigningEdit { enabled: None, key: None, format: Some("ssh".into()) }).unwrap(); + assert_eq!(repo.signing_config().unwrap().key, None); + + git(&["config", "--local", "gpg.format", "x509"]); assert!(repo.edit_signing(enable()).is_err()); - assert_eq!(repo.signing_config().unwrap().format, "ssh"); - assert!(!repo.signing_config().unwrap().enabled); + assert_eq!(repo.signing_config().unwrap().format, "x509"); + } + + #[test] + fn lists_agent_keys_first_and_prefers_files_for_held_keys() { + let agent = "ssh-ed25519 AAAA held@host\nssh-rsa BBBB agent only\n"; + let files = [ + ("/h/.ssh/a.pub".to_owned(), "ssh-ed25519 CCCC other\n".to_owned()), + ("/h/.ssh/b.pub".to_owned(), "\nssh-ed25519 AAAA held@host\n".to_owned()), + ("/h/.ssh/bad.pub".to_owned(), "garbage".to_owned()), + ]; + let key = |key: &str, comment: &str, in_agent| SshSigningKey { + key: key.into(), + comment: Some(comment.into()), + in_agent, + }; + assert_eq!( + ssh_keys(agent, &files), + vec![ + key("key::ssh-rsa BBBB", "agent only", true), + key("/h/.ssh/b.pub", "held@host", true), + key("/h/.ssh/a.pub", "other", false), + ] + ); } } diff --git a/docs/en/guide/vcs.mdx b/docs/en/guide/vcs.mdx index 863e670a1..13be44c97 100644 --- a/docs/en/guide/vcs.mdx +++ b/docs/en/guide/vcs.mdx @@ -102,9 +102,11 @@ In the Commit tool window, choose a run configuration and turn on **Run Tests** Before committing, OpenIDEA also warns about committing in detached HEAD or during a rebase, file names that cause problems on other systems, files larger than 50 MB, and CRLF line endings. A warning stops the commit once; click **Commit Anyway** to go ahead. -### Sign commits with GPG +### Sign commits with GPG or SSH -Open **Settings › Version Control › Git › Configure GPG Signature** in a trusted project. Choose the repository, enable **Sign commits with GPG**, and select an OpenPGP signing key. OpenIDEA saves the settings to that repository's Git config. Subsequent commits use the repository's configured signer. +Open **Settings › Version Control › Git › Configure GPG Signature** in a trusted project. Choose the repository and a **Signing format**, enable signing, and select a key. OpenIDEA saves the settings to that repository's Git config (`gpg.format`, `commit.gpgsign`, `user.signingkey`). Subsequent commits use the repository's configured signer. + +For SSH, the list shows the keys ssh-agent holds, then the public keys in `~/.ssh`. A key with a passphrase must be in ssh-agent (`ssh-add`), since a commit from the IDE cannot ask for it. SSH signing needs Git 2.34 or later. To see your SSH-signed commits as verified in the log, list your key in the file that `gpg.ssh.allowedSignersFile` names, as on the command line. ### Modal commit diff --git a/docs/zh/guide/vcs.mdx b/docs/zh/guide/vcs.mdx index 44ecde10b..4a4d82817 100644 --- a/docs/zh/guide/vcs.mdx +++ b/docs/zh/guide/vcs.mdx @@ -100,9 +100,11 @@ OpenIDEA 会找到包含项目的仓库,以及向下最多四层的嵌套仓 提交前,OpenIDEA 还会对以下情况发出警告:在分离 HEAD 或变基过程中提交、文件名在其他系统上可能有问题、文件大于 50 MB、CRLF 换行符。出现警告时第一次提交会被拦下,点击 **仍然提交** 继续。 -### 使用 GPG 为提交签名 +### 使用 GPG 或 SSH 为提交签名 -在受信任的项目中打开 **设置 › 版本控制 › Git › 配置 GPG 签名**。选择仓库,开启 **使用 GPG 为提交签名**,然后选择 OpenPGP 签名密钥。OpenIDEA 将设置保存到所选仓库的 Git 配置,后续提交使用该仓库配置的签名程序。 +在受信任的项目中打开 **设置 › 版本控制 › Git › 配置 GPG 签名**。选择仓库和 **签名格式**,开启签名,然后选择密钥。OpenIDEA 将设置保存到所选仓库的 Git 配置(`gpg.format`、`commit.gpgsign`、`user.signingkey`),后续提交使用该仓库配置的签名程序。 + +选择 SSH 时,列表先显示 ssh-agent 中的密钥,再显示 `~/.ssh` 中的公钥。设置了密码的密钥需要先加入 ssh-agent(`ssh-add`),因为在 IDE 中提交时无法输入密码。SSH 签名需要 Git 2.34 或更高版本。要让日志把你用 SSH 签名的提交显示为已验证,需要和命令行一样,把密钥写入 `gpg.ssh.allowedSignersFile` 指定的文件。 ### 模态提交 diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 5687874cb..d33fafa95 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -846,6 +846,7 @@ vcs_shelf_rename trusted project_host bin vcs_shelve trusted project_host bindings async vcs_shelves always project_host bindings async vcs_signing_config always project_host bindings async +vcs_ssh_signing_keys trusted project_host bindings async vcs_stage trusted project_host bindings async vcs_stage_formatted_text trusted project_host bindings async vcs_stage_hunks trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index ea11dc6c0..763d06403 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -2390,6 +2390,8 @@ export const commands = { vcsShelves: () => typedError(__TAURI_INVOKE("vcs_shelves")), /** The effective signing settings for one registered Git repository. */ vcsSigningConfig: (repo: string) => typedError(__TAURI_INVOKE("vcs_signing_config", { repo })), + /** Lists SSH public keys from ssh-agent and `~/.ssh` for SSH commit signing. */ + vcsSshSigningKeys: (repo: string, request: RequestId) => typedError(__TAURI_INVOKE("vcs_ssh_signing_keys", { repo, request })), vcsStage: (paths: string[]) => typedError(__TAURI_INVOKE("vcs_stage", { paths })), vcsStageFormattedText: (path: string, before: string, after: string) => typedError(__TAURI_INVOKE("vcs_stage_formatted_text", { path, before, after })), /** @@ -8205,6 +8207,8 @@ export type GitSigningConfig = { export type GitSigningEdit = { enabled: boolean | null, key: string | null, + /** `openpgp` or `ssh`. */ + format: string | null, }; /** Settings › Version Control › GitHub (`vcs.github`). */ @@ -14120,6 +14124,14 @@ export type SshSettings = { configs?: SshConfiguration[], }; +export type SshSigningKey = { + /** The `user.signingkey` value: a public key file path, or `key::` and the key itself. */ + key: string, + comment: string | null, + /** ssh-agent holds this key, so signing with it needs no passphrase prompt. */ + inAgent: boolean, +}; + export type StackFrame = { id: number, name: string, diff --git a/src/features/settings/__tests__/gitSigning.test.tsx b/src/features/settings/__tests__/gitSigning.test.tsx new file mode 100644 index 000000000..34a9219df --- /dev/null +++ b/src/features/settings/__tests__/gitSigning.test.tsx @@ -0,0 +1,69 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { act, fireEvent, render, screen } from "@testing-library/react"; +import type { GitSigningConfig } from "@/platform/ipc"; + +const FPR = "1234567890123456789012345678901234567890"; +const SSH_KEY = "key::ssh-ed25519 AAAA"; +let config: GitSigningConfig; +const editSigning = vi.fn(async (..._args: unknown[]) => ({ status: "ok", data: null })); + +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + isTauri: () => true, + commands: { + ...real.commands, + vcsRoots: vi.fn(async () => ({ status: "ok", data: [{ root: "/project" }] })), + vcsSigningConfig: vi.fn(async () => ({ status: "ok", data: config })), + vcsGpgSigningKeys: vi.fn(async () => ({ status: "ok", data: [{ fingerprint: FPR, userId: "Me" }] })), + vcsSshSigningKeys: vi.fn(async () => ({ + status: "ok", + data: [{ key: SSH_KEY, comment: "me@example.com", inAgent: true }], + })), + vcsEditSigning: (...args: unknown[]) => editSigning(...args), + cancelRequest: vi.fn(async () => ({ status: "ok", data: null })), + }, + }; +}); + +import { useProject } from "@/platform/project"; +import { GitSigningRow } from "../pages/GitSigningRow"; + +async function openDialog() { + render(); + await act(async () => fireEvent.click(screen.getByRole("button", { name: "Configure GPG Signature…" }))); + await screen.findByText("Signing format"); +} + +async function choose(current: string, option: string) { + await act(async () => fireEvent.click(screen.getByLabelText(new RegExp(current)))); + await act(async () => fireEvent.click(await screen.findByRole("option", { name: new RegExp(option) }))); +} + +beforeEach(() => { + editSigning.mockClear(); + useProject.setState({ project: { name: "demo", root: "/project", trusted: true } as never }); +}); + +afterEach(() => useProject.setState({ project: null })); + +describe("Configure GPG Signature", () => { + it("saves the SSH format with the chosen SSH key", async () => { + config = { format: "openpgp", enabled: true, key: FPR }; + await openDialog(); + await choose("Signing format", "SSH"); + await screen.findByText("Sign commits with SSH"); + await choose("Signing key", "me@example.com"); + await act(async () => fireEvent.click(screen.getByRole("button", { name: "OK" }))); + expect(editSigning).toHaveBeenCalledWith("/project", { enabled: null, key: SSH_KEY, format: "ssh" }); + }); + + it("drops the OpenPGP key when the format changes with signing off", async () => { + config = { format: "openpgp", enabled: false, key: FPR }; + await openDialog(); + await choose("Signing format", "SSH"); + await act(async () => fireEvent.click(screen.getByRole("button", { name: "OK" }))); + expect(editSigning).toHaveBeenCalledWith("/project", { enabled: null, key: null, format: "ssh" }); + }); +}); diff --git a/src/features/settings/pages/GitSigningRow.tsx b/src/features/settings/pages/GitSigningRow.tsx index 4fd2105c3..d3a399fcf 100644 --- a/src/features/settings/pages/GitSigningRow.tsx +++ b/src/features/settings/pages/GitSigningRow.tsx @@ -7,6 +7,7 @@ import { nextRequestId, type GitSigningConfig, type GpgSigningKey, + type SshSigningKey, type VcsRoot, } from "@/platform/ipc"; import { basename, useProject } from "@/platform/project"; @@ -96,55 +97,92 @@ function RepositorySigning({ }) { const rootId = useId(); const keyId = useId(); + const formatId = useId(); const [initial, setInitial] = useState(); + const [format, setFormat] = useState(); const [enabled, setEnabled] = useState(false); const [key, setKey] = useState(null); - const [keys, setKeys] = useState(); - const [keysError, setKeysError] = useState(); + const [keys, setKeys] = useState<{ + format: string; + gpg?: GpgSigningKey[]; + ssh?: SshSigningKey[]; + error?: string; + }>(); const [error, setError] = useState(); const [saving, setSaving] = useState(false); useEffect(() => { let live = true; - let request: ReturnType | undefined; void call(commands.vcsSigningConfig(repo)).then( (config) => { if (!live) return; setInitial(config); + setFormat(config.format); setEnabled(config.enabled); setKey(config.key); - if (config.format !== "openpgp") return; - request = nextRequestId(); - void call(commands.vcsGpgSigningKeys(repo, request)) - .then( - (keys) => live && setKeys(keys), - (error: unknown) => live && setKeysError(message(error)), - ) - .finally(() => { - request = undefined; - }); }, (error: unknown) => live && setError(message(error)), ); return () => { live = false; - if (request !== undefined) void commands.cancelRequest(request).catch(() => undefined); }; }, [repo]); - const supported = initial?.format === "openpgp"; + const supported = initial?.format === "openpgp" || initial?.format === "ssh"; + useEffect(() => { + if (!supported || !format) return; + let live = true; + let request: ReturnType | undefined = nextRequestId(); + const loaded = + format === "ssh" + ? call(commands.vcsSshSigningKeys(repo, request)).then((ssh) => ({ format, ssh })) + : call(commands.vcsGpgSigningKeys(repo, request)).then((gpg) => ({ format, gpg })); + void loaded + .then( + (keys) => live && setKeys(keys), + (error: unknown) => live && setKeys({ format, error: message(error) }), + ) + .finally(() => { + request = undefined; + }); + return () => { + live = false; + if (request !== undefined) void commands.cancelRequest(request).catch(() => undefined); + }; + }, [repo, format, supported]); + + const ssh = format === "ssh"; + const changedFormat = initial && format !== initial.format; const changedEnabled = initial && enabled !== initial.enabled; - const changedKey = enabled && key !== initial?.key; - const dirty = changedEnabled || changedKey; - const options: SelectOption[] = (keys ?? []).map((key) => ({ - value: key.fingerprint, - label: key.userId || key.fingerprint, - verbatim: true, - detail: key.userId ? key.fingerprint : undefined, - verbatimDetail: true, - })); - if (initial?.key && !options.some((option) => option.value === initial.key)) { - options.unshift({ value: initial.key, label: initial.key, verbatim: true }); + const changedKey = enabled && (key !== initial?.key || changedFormat); + const dirty = changedFormat || changedEnabled || changedKey; + const shown = keys?.format === format ? keys : undefined; + const keysError = shown?.error; + const options: SelectOption[] = ssh + ? (shown?.ssh ?? []).map((key) => ({ + value: key.key, + label: key.comment || key.key, + verbatim: true, + detail: [key.key.startsWith("key::") ? undefined : key.key, key.inAgent ? "ssh-agent" : undefined] + .filter(Boolean) + .join(" · "), + verbatimDetail: true, + })) + : (shown?.gpg ?? []).map((key) => ({ + value: key.fingerprint, + label: key.userId || key.fingerprint, + verbatim: true, + detail: key.userId ? key.fingerprint : undefined, + verbatimDetail: true, + })); + if (key && !options.some((option) => option.value === key)) { + options.unshift({ value: key, label: key, verbatim: true }); + } + const outsideAgent = ssh && !!key && !!shown?.ssh && !shown.ssh.some((k) => k.key === key && k.inAgent); + + function chooseFormat(next: string) { + setFormat(next); + setKey(next === initial?.format ? (initial?.key ?? null) : null); } async function save() { @@ -153,7 +191,11 @@ function RepositorySigning({ setError(undefined); try { await call( - commands.vcsEditSigning(repo, { enabled: changedEnabled ? enabled : null, key: changedKey ? key : null }), + commands.vcsEditSigning(repo, { + enabled: changedEnabled ? enabled : null, + key: changedKey ? key : null, + format: changedFormat ? (format ?? null) : null, + }), ); onClose(); } catch (error) { @@ -208,7 +250,25 @@ function RepositorySigning({ {initial ? ( supported ? ( <> - + +