Files
Netcatty/components/KeychainManager.tsx
T
陈大猫andClaude Opus 4.7 7272f2564d fix(ssh): per-host skipEcdsaHostKey toggle + advanced algorithm overrides (#1027) (#1116)
* fix(ssh): per-host skipEcdsaHostKey toggle + advanced algorithm overrides (#1027)

#1027 reported an old Huawei S7706 (SSH banner `SSH-2.0--`, empty
software-version field) where the legacy-algorithms toggle still
couldn't get a connection through. The debug log shows the handshake
makes it through every negotiation step, picks `ecdsa-sha2-nistp521`
for the host key, then dies at:

  Handshake failed: signature verification failed

i.e. ssh2's strict RFC verifier rejects the ECDSA signature the
switch produces. OpenSSH on the same machine connects because its
known_hosts is already pinned to an RSA fingerprint, so it never
advertises ECDSA in the first place.

This adds two layers of escape hatch:

A. `host.skipEcdsaHostKey` (one-click) — drops every `ecdsa-sha2-*`
   from the offered host-key list. Forces the fallback to
   ssh-rsa / ssh-dss / ssh-ed25519 that those old stacks implement
   correctly. Wired through ssh / sftp / port-forwarding bridges,
   inheritable from the group default.

B. `host.algorithms` (advanced) — per-category override lists
   (`kex`, `cipher`, `hmac`, `serverHostKey`, `compress`). When a
   category's array is non-empty, it fully replaces the negotiated
   list for that category. Exposed in a collapsible "Advanced
   algorithm overrides" panel on both host and group settings,
   inspired by Tabby's per-profile algorithm UI. Empty arrays
   normalize to "use default" so picking zero algorithms in a
   category doesn't bench the connection with
   "no matching algorithm".

Overrides apply BEFORE `skipEcdsaHostKey` so the latter stays an
unconditional kill switch even if the user explicitly puts
`ecdsa-*` back into the host-key list.

Behavior with default values (neither toggle set, no override list)
is identical to before — zero change for hosts that aren't opted in.

Tests cover the new options on both `buildAlgorithms` and
`buildSftpAlgorithms`, plus group→host inheritance for both fields.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ssh): address Codex review on #1116 — proper seed + jump-host carry + missing call sites

Four review findings from the Codex pass on #1116, all real:

1. AlgorithmOverridesPanel was seeding the first customization in a
   category from `SUPPORTED_ALGORITHMS_BY_CATEGORY`, which contains
   legacy algorithms (CBC, arcfour, MD5, ssh-dss, group1-sha1...).
   Unchecking a single modern algorithm in a host that had legacy mode
   *off* would silently start offering those legacy algorithms. Now
   seeds from `effectiveDefaultAlgorithms(legacyEnabled)`, mirroring
   what `buildAlgorithms` actually emits at connect time.

   - New `effectiveDefaultAlgorithms` pure helper in
     `domain/sshAlgorithmList.ts` with its own test suite (also asserts
     the modern subset contains no SHA-1 KEX / CBC / arcfour / MD5)
   - `AlgorithmOverridesPanel` takes a `legacyEnabled` prop
   - `isChecked` now reflects the effective-default state for an
     untouched category, so unchecked rows visually represent
     algorithms the connection wouldn't currently advertise

2. The chain-mode jump-host loop in `sshBridge.cjs` was applying the
   target host's `skipEcdsaHostKey` / `algorithmOverrides` to every
   bastion hop, which is wrong when the bastion has its own settings.
   This was actually a pre-existing issue with `legacyAlgorithms` too
   — `NetcattyJumpHost` simply didn't carry any of these fields.

   - `NetcattyJumpHost` gains `legacyAlgorithms`, `skipEcdsaHostKey`,
     `algorithmOverrides`
   - `createTerminalSessionStarters` populates them from each jump
     host's own configuration
   - The jump-host bridge call now reads `jump.* ?? options.*` so a
     hop with its own setting wins, but unset hops still fall back to
     the target's settings (preserves historic chain-wide behavior
     when nothing is overridden)

3. `infrastructure/services/portForwardingService.ts` only forwarded
   `legacyAlgorithms` to the port-forwarding bridge, so a host that
   needed the ECDSA skip or advanced overrides could connect through
   the terminal but its auto-start tunnels would still hit the
   original handshake failure.

   - Forward `skipEcdsaHostKey` and `algorithmOverrides` at the target
     call site and at the jump-host map.

4. `application/state/sftp/useSftpHostCredentials.ts` built
   `NetcattySSHOptions` for `openSftp` without any of the algorithm
   fields — and on inspection it didn't even forward `legacyAlgorithms`
   to begin with, so SFTP panes for legacy-mode hosts were silently
   negotiating with the modern default list. Same gap at the jump-host
   map.

   - Forward all three fields at both the target and the jump-host map.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* polish(hosts): make the advanced-algorithm collapsible trigger a real button

The first cut used a plain underlined caption for the
"Advanced algorithm overrides" collapsible trigger. That blends into
the surrounding helper text and doesn't read as an interactive
control — users couldn't tell that the per-category checkbox editor
was reachable at all.

Match the project's existing collapsible-trigger pattern (see
`SerialConnectModal`): full-width ghost Button, label on the left,
ChevronDown / ChevronUp on the right that flips with open state,
controlled via `useState`. Applied in both `HostDetailsPanel` and
`GroupDetailsPanel`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* polish(hosts): rename Legacy Algorithms card to SSH Algorithms; split Backspace into its own section

The card now carries three algorithm controls (Allow Legacy / Skip
ECDSA / Advanced overrides) plus a Backspace Behavior dropdown that
doesn't belong with the rest. Two cleanups:

1. Rename the card from "Legacy Algorithms" to "SSH Algorithms".
   The original title only described the first toggle; the section
   now covers the whole algorithm-negotiation surface, including the
   ECDSA host-key skip and the per-category override editor.
   - i18n key renamed `hostDetails.section.legacyAlgorithms`
     -> `hostDetails.section.sshAlgorithms` in zh-CN / en / ru
   - `HostDetailsPanel` references the new key

2. Move the Backspace Behavior control out of the algorithm card.
   - `HostDetailsPanel`: new dedicated "Terminal Behavior" card
     (TerminalSquare icon) placed between SSH Algorithms and
     Keepalive. New i18n key `hostDetails.section.terminalBehavior`.
   - `GroupDetailsPanel`: no separate Card scaffolding for group
     defaults — moved Backspace to the bottom of the SSH section
     (after Mosh) so it visually separates from the algorithm block
     above without introducing a new card heading.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(sftp): per-hop algorithm settings in SFTP chain (Codex review on #1116)

`sshBridge.cjs`'s jump loop already reads `jump.* ?? options.*` for
the three algorithm fields, but `sftpBridge.cjs#connectThroughChainForSftp`
was missed in that change and still applied the target host's
`options.legacyAlgorithms` / `skipEcdsaHostKey` / `algorithmOverrides`
to every bastion. A bastion that needed the ECDSA skip or a custom
algorithm list while the target didn't would still fail the SFTP
handshake before reaching the target.

Mirror the sshBridge fix: read each setting from the jump host first,
falling back to the target options when the hop didn't override.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ssh): keychain SSH exec + advanced editor seed honor inherited algorithm settings

Two findings from a local Codex review pass on the branch:

1. The keychain "export public key to host" flow opens its own one-off
   SSH connection through `sshBridge#execCommand`, but the connectOpts
   built there didn't include any `algorithms`. ssh2 then negotiated
   with its built-in modern defaults regardless of what the host had
   set, so a host that needs the ECDSA skip (or legacy mode) would
   connect in the terminal but the keychain export would fail with
   the original signature-verification error.

   - `sshBridge.cjs#execCommand` now sets `algorithms` from
     `payload.legacyAlgorithms` / `skipEcdsaHostKey` /
     `algorithmOverrides`, mirroring `startSSHSession`.
   - `useKeychainBackend`'s `execCommand` typing gets the three new
     optional fields.
   - `KeychainManager` forwards the host's `legacyAlgorithms`,
     `skipEcdsaHostKey`, and `algorithms` when invoking the export.

2. The Advanced Algorithm Overrides editor seeded its first
   customization from `form.legacyAlgorithms`, which is the host's
   own field — it doesn't reflect a value the host *inherits* from
   its group's default. A user in a group with `legacyAlgorithms=true`
   editing a host that hadn't explicitly set the flag would see the
   editor seed in modern-only mode, and saving could silently drop
   the legacy algorithms the host actually needed.

   - `HostDetailsPanel` passes `form.legacyAlgorithms ?? groupDefaults?.legacyAlgorithms`.
   - `GroupDetailsPanel` adds an `inheritedLegacyAlgorithms` memo
     resolved from the parent group chain via `resolveGroupDefaults`,
     and the editor uses `form.legacyAlgorithms ?? inheritedLegacyAlgorithms`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(keychain): export-public-key honors group-inherited algorithm settings

Second-pass Codex review on PR #1116 flagged that the keychain
"export public key to host" flow now carries the three algorithm
fields end-to-end, but only reads them from `exportHost.*` directly —
which doesn't reflect values the host inherits from its group's
defaults. A host that left `legacyAlgorithms` / `skipEcdsaHostKey` /
`algorithms` unset but sat inside a group that turned them on would
work fine in the terminal (the terminal starter applies group
defaults before sending the IPC payload) but its keychain export
would silently fall back to ssh2's modern defaults and hit the
original signature-verification failure.

Resolve the effective host with `applyGroupDefaults` +
`resolveGroupDefaults` before the `execCommand` call, then read the
algorithm fields off the effective host. Requires plumbing
`groupConfigs` into `KeychainManager` (added as an optional prop,
forwarded by `VaultView`).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(host-details): algorithm-overrides editor reads currently selected group's defaults

Third-pass Codex review caught that the editor seed was reading from
the `groupDefaults` prop, which is whatever group the host belonged
to when the panel opened. If a user switched the host into a different
group inside the panel and then opened the Advanced Algorithm
Overrides collapsible before saving, the editor would seed from the
old group's `legacyAlgorithms` flag and could save the wrong list.

The panel already memoizes `effectiveGroupDefaults` from
`form.group`/`defaultGroup`/`groupConfigs` for exactly this kind of
re-resolution (used by theme/font effective lookups). Read the
inherited flag from there instead of the stale prop.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(algorithms): trim UI cipher list to algorithms ssh2 actually supports

Fourth-pass Codex review flagged that `SUPPORTED_CIPHER_ALGORITHMS`
included `blowfish-cbc`, `cast128-cbc`, and the `arcfour*` family,
but OpenSSL 3 disabled those primitives, so ssh2's `canUseCipher`
filter drops them from `SUPPORTED_CIPHER` at startup. Selecting any
of them in the Advanced Algorithm Overrides editor would make
`ssh2.Client.connect()` throw `Unsupported algorithm` synchronously,
turning the override into a "host now unreachable" footgun instead
of a narrowing knob.

Realigned each `SUPPORTED_*_ALGORITHMS` list to ssh2's actual
`SUPPORTED_*` constants:

- `SUPPORTED_CIPHER_ALGORITHMS`: dropped blowfish / cast128 / arcfour;
  added the no-suffix `aes128-gcm` / `aes256-gcm` variants ssh2 also
  accepts.
- `SUPPORTED_KEX_ALGORITHMS`: added `diffie-hellman-group15-sha512`
  and `diffie-hellman-group17-sha512` (present in ssh2 but missing
  from the UI list); reordered to ssh2's canonical order.
- `SUPPORTED_HMAC_ALGORITHMS`: reordered so the ETM/SHA-2 grouping
  matches ssh2's `DEFAULT_MAC` and lookups are predictable.

Locked the invariant in `sshAlgorithmList.test.ts` with a new test
that asserts every UI-offered algorithm is a member of ssh2's
`SUPPORTED_*` for its category. A future ssh2 bump that drops an
algorithm we still expose will fail this test instead of silently
becoming a connect-time error for users.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(algorithms): run KEX override through the runtime fixed-DH filter

Codex round-N flagged a gap in `applyAlgorithmOverrides`: when the
user supplies a custom KEX list via the advanced editor, the previous
implementation copied it verbatim into the negotiated `algorithms.kex`
field. The default builder already passes its KEX list through
`filterSupportedFixedDhKex` to drop fixed-DH groups the runtime
doesn't support (notably `diffie-hellman-group1-sha1` on
Electron/BoringSSL, which lacks modp2), but the override path
bypassed that filter — so an Electron user enabling legacy mode and
saving any KEX checkbox state would re-advertise group1-sha1 and the
handshake would crash with "Unknown DH group" instead of failing fast.

Apply the same `filterSupportedFixedDhKex` to the override list. New
test in `sshAlgorithms.test.cjs` exercises a simulated BoringSSL
runtime that lacks modp2 and asserts the override-filtered KEX no
longer includes group1-sha1, while group14-sha1 / group-exchange-sha1
remain.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(algorithms): run HMAC override through the FIPS MD5 filter

Codex flagged the same runtime-bypass pattern Round-N-1 fixed for KEX,
now in HMAC: `applyLegacyHmacAlgorithms` gates `hmac-md5` behind
`md5Supported()` so FIPS Node builds don't get it, but the UI's
`effectiveDefaultAlgorithms(true)` seed adds `hmac-md5` /
`hmac-md5-96` unconditionally. A user with legacy mode on who saves
any HMAC checkbox change would push those MD5 entries through
`applyAlgorithmOverrides`, which previously copied the override
verbatim — bypassing the FIPS gate and making ssh2 throw
"Unsupported algorithm" before negotiation.

New `filterRuntimeUnsupportedHmac` helper applies the same
`md5Supported()` gate to a user override. `applyAlgorithmOverrides`
routes the HMAC override through it (mirrors how the same function
already routes KEX overrides through `filterSupportedFixedDhKex`).
New test simulates a FIPS-disabled MD5 runtime and asserts MD5
variants drop from the final HMAC list while SHA-1 / SHA-2 entries
remain.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ssh): jump-host overrides no longer inherit the leaf's algorithm overrides

Codex flagged that the jump-loop fallback I added for chain
convenience applied the target's per-host \`algorithmOverrides\` to
every bastion whose own override wasn't set, which is wrong: a target
restricted to e.g. \`serverHostKey: [\"ssh-rsa\"]\` would lock the hop
to ssh-rsa too and break negotiation against an Ed25519-only bastion.

The fallback IS still correct for \`legacyAlgorithms\` and
\`skipEcdsaHostKey\` — those are append/safety toggles that widen the
offered list, so propagating them to a bastion is safe and matches
the historic chain-wide behavior of \`options.legacyAlgorithms\`
(single-toggle convenience for a chain with one old leaf).

Treat \`algorithmOverrides\` strictly per-host instead. Same change in
both \`sshBridge.cjs\` and \`sftpBridge.cjs\` jump loops, with a
comment block explaining the asymmetry so a future refactor doesn't
"clean up" the distinction.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* ui(host-details): surface inherited algorithm overrides in the advanced editor

Codex flagged a real gap in the inheritance model: when a parent
group has set algorithm overrides (e.g. \`algorithms.kex: [...]\`),
a host or child group under it can't simply Reset a category back to
NetCatty's defaults — \`applyGroupDefaults\` treats an unset host
field as "inherit", so the local Reset falls back to the group's
list rather than to ssh2's defaults. Cleanly distinguishing "reset
to NetCatty defaults" from "inherit from group" needs a new schema
field or sentinel, which is a non-trivial design change well beyond
the scope of this PR.

For now, surface the situation in the UI so the user understands
why Reset doesn't behave the way they might expect and where to go
to actually clear the restriction:

- \`AlgorithmOverridesPanel\` accepts an optional \`inheritedFromGroup\`
  prop and, when populated, renders a blue inline notice listing the
  inherited categories and directing the user to the group's
  algorithm settings if they need to opt out.
- \`HostDetailsPanel\` passes \`effectiveGroupDefaults?.algorithms\`.
- \`GroupDetailsPanel\` adds a new \`inheritedAlgorithmOverrides\`
  memo that resolves the same way the existing
  \`inheritedLegacyAlgorithms\` does, and forwards it.
- i18n strings added in zh-CN / en / ru.

Follow-up (out of scope for this PR): if real users do hit this,
introduce a \`host.algorithms = null\` (or explicit
\`algorithmsOverride: boolean\`) sentinel and a Reset-to-defaults
button that uses it.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ssh): jump-host skipEcdsaHostKey is per-host; panel seeds from inherited overrides

Three findings from the latest Codex pass:

1 & 2. `skipEcdsaHostKey` on the leaf was still falling back onto
   jump hosts in both `sshBridge.cjs` and `sftpBridge.cjs`. I had
   classified it with `legacyAlgorithms` as a "safety widening" knob,
   but Codex is right that it actually *narrows* the offered host-key
   list by dropping every `ecdsa-sha2-*`. An ECDSA-only bastion (or
   one where the operator pinned ECDSA via known_hosts) would still
   negotiate when ECDSA is offered, but fails when the leaf's skip is
   propagated to it. Same fix as `algorithmOverrides` last round:
   strictly per-host. Only `legacyAlgorithms` keeps the chain-wide
   fallback (append-only — it widens the offer, can never break a
   hop that wasn't already failing).

3. `AlgorithmOverridesPanel` was seeding the first customization of a
   category from the NetCatty/legacy effective default, ignoring any
   list the host inherits from its group for OTHER categories.
   Because `applyGroupDefaults` treats `host.algorithms` as an
   all-or-nothing inherit boundary, the moment the user saved any
   host-local override `{ cipher: [...] }`, the group's
   `{ serverHostKey: ["ssh-rsa"] }` restriction silently dropped from
   the effective host. Now:
   - `toggleAlgorithm`'s first-click seed reads
     `inheritedFromGroup?.[category] ?? effectiveDefault[category]`,
     so customizing one category preserves the group's narrowing on
     the others.
   - `updateCategory` initializes `next` from
     `{ ...inheritedFromGroup, ...value }` so saved overrides carry
     the inherited categories alongside the host's own edits.
   - `isChecked` reflects the inherited list when there's no local
     value, so the visible checkbox state matches what would actually
     be advertised.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(host-details): Reset preserves the inherited list instead of silently widening

Codex caught a follow-on bug from the previous "carry inheritance"
fix: pressing Reset on a category that's inherited from the group
deleted that category from \`host.algorithms\` while other host-local
or carried-inherited categories remained. Because
\`applyGroupDefaults\` treats \`host.algorithms\` as all-or-nothing,
the moment any host-local entry exists the group's \`algorithms\`
object stops being inherited as a whole — so the freshly-deleted
category fell back to NetCatty defaults rather than the group's
narrower list. Effective result: Reset on an inherited category
*widened* the offer instead of restoring it.

Reset now persists the inherited list verbatim onto the host when
the group has an override for that category, so "Reset" means "use
what this host would otherwise inherit" in all cases.

Also tightened \`isCustomized\` to suppress the "customized" badge
(and the per-category Reset button) when the host's stored list is
identical to the inherited list — those rows haven't really been
customized by the user.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* ui(host-details): gate the inherited-notice / checkbox baseline on no host override

Codex caught the asymmetry between the read and write sides of the
panel. The write side (`updateCategory`, `toggleAlgorithm`, Reset)
intentionally carries `inheritedFromGroup` onto the host on the first
edit so the runtime's all-or-nothing inherit boundary in
`applyGroupDefaults` doesn't silently widen the offer. But the read
side (the inherited-notice banner and the `isChecked` baseline for
unfilled categories) was applying inherited values *unconditionally*
— including when the host already had any local `algorithms` object,
which makes `applyGroupDefaults` stop inheriting from the group as a
whole. Net effect on a host that only locally overrode `cipher`: the
UI claimed the group's `serverHostKey` restriction was still in
effect, while the runtime would actually use NetCatty's modern
defaults for that category.

Introduce `inheritedForDisplay`, defined as `value === undefined ?
inheritedFromGroup : undefined`, and route the notice + the
`isChecked` baseline through it. The write side keeps consulting the
unconditional `inheritedFromGroup` so the carry-over still happens on
first edit — that part is what makes the runtime behavior match what
the UI used to advertise.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* ui(host-details): legacy/skipEcdsa toggles reflect group-inherited value

Codex caught that the Skip ECDSA toggle in both the host and group
panels read `form.skipEcdsaHostKey` directly, so a host whose group
turned the flag on (and `applyGroupDefaults` therefore applied it to
the runtime SSH negotiation) still saw the toggle rendered as off.
Worse, clicking it computed `!form.skipEcdsaHostKey` — which is `!undefined`
= `true` — so the first click could not actually disable the
inherited setting on a per-host basis; it would just store `true`
explicitly, the same effective state.

The Allow Legacy Algorithms toggle had the same pre-existing issue.
Fix both at once: each toggle now derives its enabled state from
`form.<field> ?? <inherited>` and the onToggle handler flips that same
effective value, so the toggle accurately represents what the runtime
would do and a single click off correctly stores `false`
(which `applyGroupDefaults` then leaves alone, breaking inheritance
for this host).

- `HostDetailsPanel` reads from `effectiveGroupDefaults`.
- `GroupDetailsPanel` adds an `inheritedSkipEcdsaHostKey` memo
  alongside the existing `inheritedLegacyAlgorithms` and uses both.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-27 15:12:42 +08:00

1369 lines
49 KiB
TypeScript

import {
BadgeCheck,
ChevronDown,
ChevronRight,
Edit2,
Eye,
EyeOff,
FileKey,
Info,
Key,
LayoutGrid,
List as ListIcon,
MoreHorizontal,
Plus,
Search,
Shield,
Trash2,
Upload,
UserPlus,
} from "lucide-react";
import React, { useCallback, useMemo, useState } from "react";
import { useI18n } from "../application/i18n/I18nProvider";
import { useStoredViewMode } from "../application/state/useStoredViewMode";
import { sanitizeCredentialValue } from "../domain/credentials";
import { applyGroupDefaults, resolveGroupDefaults } from "../domain/groupConfig";
import type { GroupConfig } from "../domain/models";
import { resolveBridgeKeyAuth, resolveHostAuth } from "../domain/sshAuth";
import { STORAGE_KEY_VAULT_KEYS_VIEW_MODE } from "../infrastructure/config/storageKeys";
import { logger } from "../lib/logger";
import { cn } from "../lib/utils";
import { Host, Identity, KeyType, ProxyProfile, SSHKey } from "../types";
import { ManagedSource } from "../domain/models";
import { useKeychainBackend } from "../application/state/useKeychainBackend";
import SelectHostPanel from "./SelectHostPanel";
import {
AsideActionMenu,
AsideActionMenuItem,
AsidePanel,
AsidePanelContent,
} from "./ui/aside-panel";
import { Button } from "./ui/button";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "./ui/collapsible";
import {
ContextMenu,
ContextMenuContent,
ContextMenuItem,
ContextMenuSeparator,
ContextMenuTrigger,
} from "./ui/context-menu";
import { Dropdown, DropdownContent, DropdownTrigger } from "./ui/dropdown";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Textarea } from "./ui/textarea";
import { toast } from "./ui/toast";
import { Tooltip, TooltipContent, TooltipTrigger } from "./ui/tooltip";
// Import utilities and components from keychain module
import {
type FilterTab,
GenerateStandardPanel,
IdentityCard,
IdentityPanel,
ImportKeyPanel,
isMacOS,
KeyCard,
type PanelMode,
ViewKeyPanel,
} from "./keychain";
interface KeychainManagerProps {
keys: SSHKey[];
identities?: Identity[];
hosts?: Host[];
proxyProfiles?: ProxyProfile[];
customGroups?: string[];
/**
* Group default configurations. Needed by the "export public key to
* host" flow so per-host SSH algorithm settings (legacy / skipEcdsa /
* overrides) that the host inherits from its group are honored when
* the export opens its one-off SSH connection.
*/
groupConfigs?: GroupConfig[];
managedSources?: ManagedSource[];
onSave: (key: SSHKey) => void;
onUpdate: (key: SSHKey) => void;
onDelete: (id: string) => void;
onSaveIdentity?: (identity: Identity) => void;
onDeleteIdentity?: (id: string) => void;
onNewHost?: () => void;
onSaveHost?: (host: Host) => void;
onCreateGroup?: (groupPath: string) => void;
}
const KeychainManager: React.FC<KeychainManagerProps> = ({
keys,
identities = [],
hosts = [],
proxyProfiles = [],
customGroups = [],
groupConfigs = [],
managedSources = [],
onSave,
onUpdate,
onDelete,
onSaveIdentity,
onDeleteIdentity,
onNewHost: _onNewHost,
onSaveHost,
onCreateGroup,
}) => {
const { t } = useI18n();
const { generateKeyPair, execCommand } = useKeychainBackend();
const [activeFilter, setActiveFilter] = useState<FilterTab>("key");
const [search, setSearch] = useState("");
const [viewMode, setViewMode] = useStoredViewMode(
STORAGE_KEY_VAULT_KEYS_VIEW_MODE,
"grid",
);
// Panel stack for navigation (supports back navigation)
const [panelStack, setPanelStack] = useState<PanelMode[]>([]);
const panel = useMemo(
() =>
panelStack.length > 0
? panelStack[panelStack.length - 1]
: ({ type: "closed" } as PanelMode),
[panelStack],
);
const panelTitle = useMemo(() => {
switch (panel.type) {
case "generate":
return t("keychain.panel.generateKey");
case "import":
return t("keychain.panel.newKey");
case "view":
return t("keychain.panel.keyDetails");
case "edit":
return t("keychain.panel.editKey");
case "identity":
return panel.identity
? t("keychain.panel.editIdentity")
: t("keychain.panel.newIdentity");
case "export":
return t("keychain.panel.keyExport");
default:
return "";
}
}, [panel, t]);
const [showHostSelector, setShowHostSelector] = useState(false);
const [isExporting, setIsExporting] = useState(false);
// Export panel state
const [exportLocation, setExportLocation] = useState(".ssh");
const [exportFilename, setExportFilename] = useState("authorized_keys");
const [exportHost, setExportHost] = useState<Host | null>(null);
const [exportAdvancedOpen, setExportAdvancedOpen] = useState(false);
const [exportScript, setExportScript] = useState(`DIR="$HOME/$1"
FILE="$DIR/$2"
if [ ! -d "$DIR" ]; then
mkdir -p "$DIR"
chmod 700 "$DIR"
fi
if [ ! -f "$FILE" ]; then
touch "$FILE"
chmod 600 "$FILE"
fi
echo $3 >> "$FILE"`);
// Draft state for forms
const [draftKey, setDraftKey] = useState<Partial<SSHKey>>({});
const [draftIdentity, setDraftIdentity] = useState<Partial<Identity>>({});
const [showPassphrase, setShowPassphrase] = useState(false);
const [isGenerating, setIsGenerating] = useState(false);
const showError = useCallback((message: string, title = t("common.error")) => {
toast.error(message, title);
}, [t]);
// Filter keys based on active tab and search
const filteredKeys = useMemo(() => {
let result = keys;
// Filter by tab
switch (activeFilter) {
case "key":
result = result.filter(
(k) => k.source === "generated" || k.source === "imported" || k.source === "reference",
);
break;
case "certificate":
result = result.filter(
(k) => k.category === "certificate" || k.certificate,
);
break;
}
// Filter by search
if (search.trim()) {
const s = search.toLowerCase();
result = result.filter(
(k) =>
k.label.toLowerCase().includes(s) ||
k.type.toLowerCase().includes(s) ||
k.publicKey?.toLowerCase().includes(s),
);
}
return result;
}, [keys, activeFilter, search]);
// Filter identities based on search
const filteredIdentities = useMemo(() => {
if (!search.trim()) return identities;
const s = search.toLowerCase();
return identities.filter(
(i) =>
i.label.toLowerCase().includes(s) ||
i.username.toLowerCase().includes(s),
);
}, [identities, search]);
// Push a new panel onto the stack
const pushPanel = useCallback((newPanel: PanelMode) => {
setPanelStack((prev) => [...prev, newPanel]);
}, []);
// Pop the top panel from the stack (go back)
const popPanel = useCallback(() => {
setPanelStack((prev) => {
if (prev.length <= 1) {
// Last panel, close everything
setDraftKey({});
setDraftIdentity({});
setShowPassphrase(false);
setExportHost(null);
setExportAdvancedOpen(false);
return [];
}
return prev.slice(0, -1);
});
}, []);
// Close all panels
const closePanel = useCallback(() => {
setPanelStack([]);
setDraftKey({});
setDraftIdentity({});
setShowPassphrase(false);
setExportHost(null);
setExportAdvancedOpen(false);
}, []);
// Open panel for viewing key (replaces stack with single panel)
const openKeyView = useCallback((key: SSHKey) => {
setPanelStack([{ type: "view", key }]);
setDraftKey({ ...key });
}, []);
// Open panel for exporting key (pushes onto stack)
const openKeyExport = useCallback(
(key: SSHKey) => {
pushPanel({ type: "export", key });
setExportHost(null);
setExportLocation(".ssh");
setExportFilename("authorized_keys");
},
[pushPanel],
);
// Open panel for editing key (replaces stack)
const openKeyEdit = useCallback((key: SSHKey) => {
setPanelStack([{ type: "edit", key }]);
setDraftKey({ ...key });
}, []);
// Copy public key to clipboard
const copyPublicKey = useCallback(async (key: SSHKey) => {
if (key.publicKey) {
try {
await navigator.clipboard.writeText(key.publicKey);
// Could add toast notification here
} catch (err) {
logger.error("Failed to copy public key:", err);
}
}
}, []);
// Open panel for new identity
const openNewIdentity = useCallback(() => {
setPanelStack([{ type: "identity" }]);
setDraftIdentity({
id: "",
label: "",
username: "",
authMethod: "password",
created: Date.now(),
});
}, []);
// Open generate panel
const openGenerate = useCallback(() => {
const defaultType: KeyType = "ED25519";
setPanelStack([{ type: "generate", keyType: "standard" }]);
setDraftKey({
id: "",
label: "",
type: defaultType,
keySize: undefined,
privateKey: "",
publicKey: "",
source: "generated",
category: "key",
created: Date.now(),
});
}, []);
// Open import panel
const openImport = useCallback(() => {
setPanelStack([{ type: "import" }]);
setDraftKey({
id: "",
label: "",
type: "ED25519",
privateKey: "",
publicKey: "",
source: "imported",
category: "key",
created: Date.now(),
});
}, []);
// Handle standard key generation
const handleGenerateStandard = useCallback(async () => {
if (!draftKey.label?.trim()) {
showError(t("keychain.validation.labelRequired"), t("common.validation"));
return;
}
setIsGenerating(true);
try {
const keyType = (draftKey.type as KeyType) || "ED25519";
const keySize = draftKey.keySize;
// Use real key generation via Electron backend
const result = await generateKeyPair({
type: keyType,
bits: keySize,
comment: `${draftKey.label.trim()}@netcatty`,
});
if (!result) {
throw new Error(
t("keychain.error.generationUnavailable"),
);
}
if (!result.success || !result.privateKey || !result.publicKey) {
throw new Error(result.error || t("keychain.error.generateKeyPairFailed"));
}
const newKey: SSHKey = {
id: crypto.randomUUID(),
label: draftKey.label.trim(),
type: keyType,
keySize: keyType !== "ED25519" ? keySize : undefined,
privateKey: result.privateKey,
publicKey: result.publicKey,
passphrase: draftKey.passphrase,
savePassphrase: draftKey.savePassphrase,
source: "generated",
category: "key",
created: Date.now(),
};
onSave(newKey);
closePanel();
} catch (err) {
showError(
err instanceof Error ? err.message : t("keychain.error.generateKeyFailed"),
t("keychain.error.keyGenerationTitle"),
);
} finally {
setIsGenerating(false);
}
}, [draftKey, onSave, closePanel, generateKeyPair, showError, t]);
// Handle key import
const handleImport = useCallback(() => {
if (!draftKey.label?.trim() || !draftKey.privateKey?.trim()) {
showError(t("keychain.validation.labelAndPrivateKeyRequired"), t("common.validation"));
return;
}
// Detect key type from private key content
let detectedType: KeyType = "ED25519";
const pk = draftKey.privateKey.toLowerCase();
if (pk.includes("rsa")) detectedType = "RSA";
else if (pk.includes("ecdsa") || pk.includes("ec ")) detectedType = "ECDSA";
else if (pk.includes("ed25519")) detectedType = "ED25519";
const newKey: SSHKey = {
id: crypto.randomUUID(),
label: draftKey.label.trim(),
type: (draftKey.type as KeyType) || detectedType,
privateKey: draftKey.privateKey.trim(),
publicKey: draftKey.publicKey?.trim() || undefined,
certificate: draftKey.certificate?.trim() || undefined,
passphrase: draftKey.passphrase,
savePassphrase: draftKey.savePassphrase,
source: "imported",
category: draftKey.certificate ? "certificate" : "key",
created: Date.now(),
};
onSave(newKey);
closePanel();
}, [draftKey, onSave, closePanel, showError, t]);
// Handle save identity
const handleSaveIdentity = useCallback(() => {
if (!draftIdentity.label?.trim() || !draftIdentity.username?.trim()) {
showError(t("keychain.validation.labelAndUsernameRequired"), t("common.validation"));
return;
}
if (!onSaveIdentity) return;
const newIdentity: Identity = {
id: draftIdentity.id || crypto.randomUUID(),
label: draftIdentity.label.trim(),
username: draftIdentity.username.trim(),
authMethod: draftIdentity.authMethod || "password",
password: draftIdentity.password,
keyId: draftIdentity.keyId,
created: draftIdentity.created || Date.now(),
};
onSaveIdentity(newIdentity);
closePanel();
}, [draftIdentity, onSaveIdentity, closePanel, showError, t]);
// Handle delete
const handleDelete = useCallback(
async (id: string) => {
onDelete(id);
if (panel.type === "view" && panel.key.id === id) {
closePanel();
}
},
[onDelete, panel, closePanel],
);
// Handle delete identity
const _handleDeleteIdentity = useCallback(
(id: string) => {
onDeleteIdentity?.(id);
if (panel.type === "identity" && panel.identity?.id === id) {
closePanel();
}
},
[onDeleteIdentity, panel, closePanel],
);
// Get icon for key source
const getKeyIcon = (key: SSHKey) => {
if (key.certificate) return <BadgeCheck size={16} />;
return <Key size={16} />;
};
// Get key type display
const getKeyTypeDisplay = (key: SSHKey) => {
return key.type;
};
// File input ref for import
const fileInputRef = React.useRef<HTMLInputElement>(null);
// Handle file import
const handleFileImport = useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
const content = e.target?.result as string;
if (content) {
// Try to detect key type from content
let detectedType: KeyType = "ED25519";
const lc = content.toLowerCase();
if (lc.includes("rsa")) detectedType = "RSA";
else if (lc.includes("ecdsa") || lc.includes("ec private"))
detectedType = "ECDSA";
else if (lc.includes("ed25519")) detectedType = "ED25519";
// Extract label from filename (remove extension)
const label = file.name.replace(/\.(pem|key|pub|ppk)$/i, "");
setDraftKey((prev) => ({
...prev,
privateKey: content,
label: prev.label || label,
type: detectedType,
}));
}
};
reader.readAsText(file);
// Reset input so same file can be selected again
event.target.value = "";
},
[],
);
return (
<div className="h-full flex relative">
{/* Hidden file input */}
<input
ref={fileInputRef}
type="file"
accept=".pem,.key,.pub,.ppk,*"
className="hidden"
onChange={handleFileImport}
/>
{/* Main Content */}
<div
className={cn(
"flex-1 flex flex-col min-h-0 transition-all duration-200",
panel.type !== "closed" && "mr-[380px]",
)}
>
{/* Toolbar */}
<div className="h-14 px-4 py-2 flex items-center gap-3 bg-secondary/80 supports-[backdrop-filter]:backdrop-blur-sm border-b border-border/50 shrink-0">
{/* Filter Tabs */}
<div className="flex items-center gap-1">
{/* KEY button with split interaction: left=switch view, right=dropdown */}
<Dropdown>
<div
className={cn(
"flex items-center rounded-md transition-colors",
activeFilter === "key"
? "bg-foreground/10 text-foreground hover:bg-foreground/15"
: "bg-foreground/5 text-foreground hover:bg-foreground/10",
)}
>
<Button
size="sm"
variant="ghost"
className="h-10 px-3 gap-2 rounded-r-none hover:bg-transparent text-inherit"
onClick={() => setActiveFilter("key")}
>
<Key size={14} />
{t("keychain.filter.key")}
</Button>
<DropdownTrigger asChild>
<Button
size="sm"
variant="ghost"
className="h-10 px-1.5 rounded-l-none hover:bg-transparent text-inherit"
>
<ChevronDown size={12} />
</Button>
</DropdownTrigger>
</div>
<DropdownContent className="w-44" align="start" alignToParent>
<Button
variant="ghost"
className="w-full justify-start gap-2"
onClick={openGenerate}
>
<Plus size={14} /> {t("keychain.action.generateKey")}
</Button>
<Button
variant="ghost"
className="w-full justify-start gap-2"
onClick={openImport}
>
<Upload size={14} /> {t("keychain.action.importKey")}
</Button>
{onSaveIdentity && (
<Button
variant="ghost"
className="w-full justify-start gap-2"
onClick={openNewIdentity}
>
<UserPlus size={14} /> {t("keychain.action.newIdentity")}
</Button>
)}
</DropdownContent>
</Dropdown>
{/* CERTIFICATE button with split interaction */}
<Dropdown>
<div
className={cn(
"flex items-center rounded-md transition-colors",
activeFilter === "certificate"
? "bg-foreground/10 text-foreground hover:bg-foreground/15"
: "bg-foreground/5 text-foreground hover:bg-foreground/10",
)}
>
<Button
size="sm"
variant="ghost"
className="h-10 px-3 gap-2 rounded-r-none hover:bg-transparent text-inherit"
onClick={() => setActiveFilter("certificate")}
>
<BadgeCheck size={14} />
{t("keychain.filter.certificate")}
</Button>
<DropdownTrigger asChild>
<Button
size="sm"
variant="ghost"
className="h-10 px-1.5 rounded-l-none hover:bg-transparent text-inherit"
>
<ChevronDown size={12} />
</Button>
</DropdownTrigger>
</div>
<DropdownContent className="w-48" align="start" alignToParent>
<Button
variant="ghost"
className="w-full justify-start gap-2"
onClick={openImport}
>
<Upload size={14} /> {t("keychain.action.importCertificate")}
</Button>
</DropdownContent>
</Dropdown>
</div>
{/* Search and View Mode - hide search when panel is open */}
<div className="ml-auto flex items-center gap-2 min-w-0 flex-shrink">
{panel.type === "closed" && (
<div className="relative flex-shrink min-w-[100px]">
<Search
size={14}
className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"
/>
<Input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder={t("common.searchPlaceholder")}
className="h-10 pl-9 w-full bg-secondary border-border/60 text-sm"
/>
</div>
)}
<Dropdown>
<DropdownTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-10 w-10 flex-shrink-0"
>
{viewMode === "grid" ? (
<LayoutGrid size={16} />
) : (
<ListIcon size={16} />
)}
<ChevronDown size={10} className="ml-0.5" />
</Button>
</DropdownTrigger>
<DropdownContent className="w-32" align="end">
<Button
variant={viewMode === "grid" ? "secondary" : "ghost"}
className="w-full justify-start gap-2 h-9"
onClick={() => setViewMode("grid")}
>
<LayoutGrid size={14} /> {t("keychain.view.grid")}
</Button>
<Button
variant={viewMode === "list" ? "secondary" : "ghost"}
className="w-full justify-start gap-2 h-9"
onClick={() => setViewMode("list")}
>
<ListIcon size={14} /> {t("keychain.view.list")}
</Button>
</DropdownContent>
</Dropdown>
</div>
</div>
{/* Scrollable Content */}
<div className="flex-1 overflow-y-auto">
{/* Keys Section */}
<div className="space-y-3 p-3">
<div className="flex items-center justify-between">
<h2 className="text-base font-semibold text-muted-foreground">
{t("keychain.section.keys")}
</h2>
<span className="text-xs text-muted-foreground">
{t("keychain.count.items", { count: filteredKeys.length })}
</span>
</div>
{filteredKeys.length === 0 ? (
<div className="flex flex-col items-center justify-center h-64 text-muted-foreground">
<div className="h-16 w-16 rounded-2xl bg-secondary/80 flex items-center justify-center mb-4">
<Shield size={32} className="opacity-60" />
</div>
<h3 className="text-lg font-semibold text-foreground mb-2">
{t("keychain.empty.title")}
</h3>
<p className="text-sm text-center max-w-sm mb-4">
{t("keychain.empty.desc")}
</p>
{(activeFilter === "key" || activeFilter === "certificate") && (
<div className="flex gap-2">
<Button variant="secondary" onClick={openImport}>
<Upload size={14} className="mr-2" />
{t("common.import")}
</Button>
<Button onClick={openGenerate}>
<Plus size={14} className="mr-2" />
{t("common.generate")}
</Button>
</div>
)}
</div>
) : (
<div
className={
viewMode === "grid"
? "grid gap-3 grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"
: "flex flex-col gap-0"
}
>
{filteredKeys.map((key) => (
<KeyCard
key={key.id}
keyItem={key}
viewMode={viewMode}
isSelected={
(panel.type === "view" && panel.key.id === key.id) ||
(panel.type === "export" && panel.key.id === key.id)
}
isMac={isMacOS()}
onClick={() => openKeyView(key)}
onEdit={() => openKeyEdit(key)}
onExport={() => openKeyExport(key)}
onCopyPublicKey={() => copyPublicKey(key)}
onDelete={() => handleDelete(key.id)}
/>
))}
</div>
)}
</div>
{/* Identities Section */}
{activeFilter === "key" && filteredIdentities.length > 0 && (
<div className="space-y-3 px-3 pb-3">
<div className="flex items-center justify-between">
<h2 className="text-base font-semibold text-muted-foreground">
{t("keychain.section.identities")}
</h2>
<span className="text-xs text-muted-foreground">
{t("keychain.count.items", { count: filteredIdentities.length })}
</span>
</div>
<div
className={
viewMode === "grid"
? "grid gap-3 grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"
: "flex flex-col gap-0"
}
>
{filteredIdentities.map((identity) => (
<ContextMenu key={identity.id}>
<ContextMenuTrigger>
<IdentityCard
identity={identity}
viewMode={viewMode}
isSelected={
panel.type === "identity" &&
panel.identity?.id === identity.id
}
onClick={() => {
setPanelStack([{ type: "identity", identity }]);
setDraftIdentity({ ...identity });
}}
/>
</ContextMenuTrigger>
<ContextMenuContent>
<ContextMenuItem
onClick={() => {
setPanelStack([{ type: "identity", identity }]);
setDraftIdentity({ ...identity });
}}
>
<Edit2 className="mr-2 h-4 w-4" /> {t("action.edit")}
</ContextMenuItem>
{onDeleteIdentity && (
<>
<ContextMenuSeparator />
<ContextMenuItem
className="text-destructive"
onClick={() => {
const ok = window.confirm(
t("confirm.deleteIdentity", {
name: identity.label || "",
}),
);
if (!ok) return;
_handleDeleteIdentity(identity.id);
}}
>
<Trash2 className="mr-2 h-4 w-4" />{" "}
{t("action.delete")}
</ContextMenuItem>
</>
)}
</ContextMenuContent>
</ContextMenu>
))}
</div>
</div>
)}
</div>
</div>
{/* Slide-out Panel */}
{panel.type !== "closed" && (
<AsidePanel
open={true}
onClose={closePanel}
title={panelTitle}
showBackButton={panelStack.length > 1}
onBack={popPanel}
actions={
panel.type === "identity" && panel.identity && onDeleteIdentity ? (
<AsideActionMenu>
<AsideActionMenuItem
variant="destructive"
icon={<Trash2 size={14} />}
onClick={() => {
const ok = window.confirm(
t("confirm.deleteIdentity", {
name: panel.identity?.label || "",
}),
);
if (!ok || !panel.identity) return;
_handleDeleteIdentity(panel.identity.id);
}}
>
{t("common.delete")}
</AsideActionMenuItem>
</AsideActionMenu>
) : panel.type === "view" ? (
<Button variant="ghost" size="icon" className="h-8 w-8">
<MoreHorizontal size={16} />
</Button>
) : undefined
}
>
<AsidePanelContent>
{/* Generate Standard Key */}
{panel.type === "generate" && panel.keyType === "standard" && (
<GenerateStandardPanel
draftKey={draftKey}
setDraftKey={setDraftKey}
showPassphrase={showPassphrase}
setShowPassphrase={setShowPassphrase}
isGenerating={isGenerating}
onGenerate={handleGenerateStandard}
/>
)}
{/* Import Key */}
{panel.type === "import" && (
<ImportKeyPanel
draftKey={draftKey}
setDraftKey={setDraftKey}
showPassphrase={showPassphrase}
setShowPassphrase={setShowPassphrase}
onImport={handleImport}
/>
)}
{/* View Key */}
{panel.type === "view" && (
<ViewKeyPanel
keyItem={panel.key}
onExport={() => openKeyExport(panel.key)}
/>
)}
{/* Identity Panel */}
{panel.type === "identity" && (
<IdentityPanel
draftIdentity={draftIdentity}
setDraftIdentity={setDraftIdentity}
keys={keys}
showPassphrase={showPassphrase}
setShowPassphrase={setShowPassphrase}
isNew={!panel.identity}
onSave={handleSaveIdentity}
/>
)}
{/* Key Export Panel */}
{panel.type === "export" && !showHostSelector && (
<>
{/* Key info card */}
<div className="flex items-center gap-3 p-3 bg-card border border-border/80 rounded-lg">
<div
className={cn(
"h-10 w-10 rounded-md flex items-center justify-center",
panel.key.certificate
? "bg-emerald-500/15 text-emerald-500"
: "bg-primary/15 text-primary",
)}
>
{getKeyIcon(panel.key)}
</div>
<div className="min-w-0 flex-1">
<p className="text-sm font-semibold truncate">
{panel.key.label}
</p>
<p className="text-xs text-muted-foreground">
{t("auth.keyType", { type: getKeyTypeDisplay(panel.key) })}
</p>
</div>
</div>
{/* Export to field */}
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-muted-foreground">
{t("keychain.export.exportTo")}
</Label>
<Button
variant="link"
className="h-auto p-0 text-primary text-sm"
onClick={() => setShowHostSelector(true)}
>
{t("keychain.export.selectHost")}
</Button>
</div>
<Input
value={exportHost?.label || ""}
readOnly
placeholder={t("common.selectAHostPlaceholder")}
className="bg-muted/50 cursor-pointer"
onClick={() => setShowHostSelector(true)}
/>
</div>
{/* Location field */}
<div className="space-y-2">
<Label className="text-muted-foreground">
{t("keychain.export.location")}
</Label>
<Input
value={exportLocation}
onChange={(e) => setExportLocation(e.target.value)}
placeholder=".ssh"
/>
</div>
{/* Filename field */}
<div className="space-y-2">
<Label className="text-muted-foreground">
{t("keychain.export.filename")}
</Label>
<Input
value={exportFilename}
onChange={(e) => setExportFilename(e.target.value)}
placeholder="authorized_keys"
/>
</div>
{/* Info note */}
<div className="flex items-start gap-2 p-3 bg-muted/50 border border-border/60 rounded-lg">
<Info
size={14}
className="mt-0.5 text-muted-foreground shrink-0"
/>
<p className="text-xs text-muted-foreground">
{t("keychain.export.note", {
unix: "UNIX",
advanced: t("common.advanced"),
})}
</p>
</div>
{/* Advanced collapsible */}
<Collapsible
open={exportAdvancedOpen}
onOpenChange={setExportAdvancedOpen}
>
<CollapsibleTrigger asChild>
<Button
variant="ghost"
className="w-full justify-between px-0 h-10 hover:bg-transparent hover:text-current"
>
<span className="font-medium">{t("common.advanced")}</span>
<ChevronRight
size={16}
className={cn(
"transition-transform",
exportAdvancedOpen && "rotate-90",
)}
/>
</Button>
</CollapsibleTrigger>
<CollapsibleContent className="space-y-2 pt-2">
<Label className="text-muted-foreground">
{t("keychain.export.script")}
</Label>
<Textarea
value={exportScript}
onChange={(e) => setExportScript(e.target.value)}
className="min-h-[180px] font-mono text-xs"
placeholder={t("keychain.export.scriptPlaceholder")}
/>
</CollapsibleContent>
</Collapsible>
{/* Export button */}
<Button
className="w-full h-11"
disabled={
!exportHost ||
!exportLocation ||
!exportFilename ||
isExporting
}
onClick={async () => {
if (!exportHost || !panel.key.publicKey) return;
setIsExporting(true);
try {
const exportAuth = resolveHostAuth({
host: exportHost,
keys,
identities,
});
const exportKeyAuth = resolveBridgeKeyAuth({
key: exportAuth.key,
fallbackIdentityFilePaths: exportAuth.authMethod === "password" || exportAuth.keyId
? undefined
: exportHost.identityFilePaths,
passphrase: exportAuth.passphrase,
});
const exportPassword = sanitizeCredentialValue(exportAuth.password);
// Need either password or a usable key to run remote command.
if (
!exportPassword &&
!exportKeyAuth.privateKey &&
!exportKeyAuth.identityFilePaths?.length
) {
throw new Error(
t("keychain.export.missingCredentials"),
);
}
// Escape the public key for shell (single quotes, escape existing quotes)
const escapedPublicKey = panel.key.publicKey.replace(
/'/g,
"'\\''",
);
// Build the command by replacing $1, $2, $3
const scriptWithVars = exportScript
.replace(/\$1/g, exportLocation)
.replace(/\$2/g, exportFilename)
.replace(/\$3/g, `'${escapedPublicKey}'`);
// Execute the script directly - SSH exec handles multiline commands
const command = scriptWithVars;
// Resolve the effective host (applying group
// defaults), so algorithm settings inherited from
// the group reach the bridge — the host object on
// its own only carries explicitly set fields.
const effectiveExportHost = exportHost.group
? applyGroupDefaults(
exportHost,
resolveGroupDefaults(exportHost.group, groupConfigs),
)
: applyGroupDefaults(exportHost, {});
// Execute via SSH
const result = await execCommand({
hostname: effectiveExportHost.hostname,
username: exportAuth.username,
port: effectiveExportHost.port || 22,
password: exportPassword,
privateKey: exportKeyAuth.privateKey,
certificate: exportAuth.key?.certificate,
publicKey: exportAuth.key?.publicKey,
keyId: exportAuth.keyId,
keySource: exportAuth.key?.source,
passphrase: exportKeyAuth.passphrase,
identityFilePaths: exportKeyAuth.identityFilePaths,
// Carry the effective host's algorithm settings
// (host value falling back to its group default)
// so the one-off SSH exec honors them just like
// the interactive terminal does.
legacyAlgorithms: effectiveExportHost.legacyAlgorithms,
skipEcdsaHostKey: effectiveExportHost.skipEcdsaHostKey,
algorithmOverrides: effectiveExportHost.algorithms,
command,
timeout: 30000,
enableKeyboardInteractive: true,
sessionId: `export-key:${effectiveExportHost.id}:${panel.key.id}`,
});
// Check result - code 0, null, or undefined with no stderr is success
const exitCode = result?.code;
const hasError = result?.stderr?.trim();
if (exitCode === 0 || (exitCode == null && !hasError)) {
// Update identity (preferred) or host to use this key for authentication
if (exportHost.identityId && onSaveIdentity) {
const existing = identities.find(
(i) => i.id === exportHost.identityId,
);
if (existing) {
onSaveIdentity({
...existing,
authMethod: "key",
keyId: panel.key.id,
});
}
} else if (onSaveHost) {
onSaveHost({
...exportHost,
identityFileId: panel.key.id,
authMethod: "key",
});
}
toast.success(
t("keychain.export.successMessage", {
host: exportHost.label,
}),
t("keychain.export.successTitle"),
);
closePanel();
} else {
const errorMsg =
hasError ||
result?.stdout?.trim() ||
t("keychain.export.exitCode", { code: exitCode });
toast.error(
t("keychain.export.failedMessage", { error: errorMsg }),
t("keychain.export.failedTitle"),
);
}
} catch (err) {
const message =
err instanceof Error ? err.message : String(err);
toast.error(
t("keychain.export.failedPrefix", { error: message }),
t("keychain.export.failedTitle"),
);
} finally {
setIsExporting(false);
}
}}
>
{isExporting
? t("keychain.export.exporting")
: t("keychain.export.exportAndAttach")}
</Button>
</>
)}
{/* Edit Key Panel */}
{panel.type === "edit" && (
<>
<div className="space-y-2">
<Label>{t("keychain.edit.labelRequired")}</Label>
<Input
value={draftKey.label || ""}
onChange={(e) =>
setDraftKey({ ...draftKey, label: e.target.value })
}
placeholder={t("keychain.edit.keyLabelPlaceholder")}
/>
</div>
{/* Reference key: show file path read-only */}
{draftKey.source === 'reference' && draftKey.filePath && (
<div className="space-y-2">
<Label className="text-muted-foreground">
{t("keychain.edit.filePath")}
</Label>
<div className="flex items-center gap-2 p-2 rounded-md bg-secondary/50 border border-border/60">
<FileKey size={14} className="text-primary shrink-0" />
<Tooltip>
<TooltipTrigger asChild>
<span className="text-xs font-mono truncate cursor-default">
{draftKey.filePath}
</span>
</TooltipTrigger>
<TooltipContent>{draftKey.filePath}</TooltipContent>
</Tooltip>
</div>
</div>
)}
{/* Managed key: show private key editor */}
{draftKey.source !== 'reference' && (
<div className="space-y-2">
<Label className="text-destructive">
{t("keychain.edit.privateKeyRequired")}
</Label>
<Textarea
value={draftKey.privateKey || ""}
onChange={(e) =>
setDraftKey({ ...draftKey, privateKey: e.target.value })
}
placeholder="-----BEGIN OPENSSH PRIVATE KEY-----"
className="min-h-[180px] font-mono text-xs"
/>
</div>
)}
{draftKey.source !== 'reference' && (
<div className="space-y-2">
<Label className="text-muted-foreground">
{t("keychain.edit.publicKey")}
</Label>
<Textarea
value={draftKey.publicKey || ""}
onChange={(e) =>
setDraftKey({ ...draftKey, publicKey: e.target.value })
}
placeholder="ssh-ed25519 AAAA..."
className="min-h-[80px] font-mono text-xs"
/>
</div>
)}
{draftKey.source !== 'reference' && (
<div className="space-y-2">
<Label className="text-muted-foreground">
{t("keychain.edit.certificate")}
</Label>
<Textarea
value={draftKey.certificate || ""}
onChange={(e) =>
setDraftKey({ ...draftKey, certificate: e.target.value })
}
placeholder={t("keychain.edit.certificatePlaceholder")}
className="min-h-[60px] font-mono text-xs"
/>
</div>
)}
{/* Passphrase section */}
<div className="space-y-2">
<Label>{t('terminal.auth.passphrase')}</Label>
<div className="relative">
<Input
type={showPassphrase ? 'text' : 'password'}
value={draftKey.passphrase || ''}
onChange={(e) =>
setDraftKey({ ...draftKey, passphrase: e.target.value })
}
placeholder={t('keychain.generate.passphrasePlaceholder')}
className="pr-10"
/>
<Button
variant="ghost"
size="icon"
className="absolute right-1 top-1/2 -translate-y-1/2 h-8 w-8"
onClick={() => setShowPassphrase(!showPassphrase)}
>
{showPassphrase ? <EyeOff size={14} /> : <Eye size={14} />}
</Button>
</div>
<div className="flex items-center gap-2">
<input
type="checkbox"
id="editSavePassphrase"
checked={draftKey.savePassphrase || false}
onChange={(e) =>
setDraftKey({ ...draftKey, savePassphrase: e.target.checked })
}
className="h-4 w-4 rounded border-border"
/>
<Label htmlFor="editSavePassphrase" className="text-sm font-normal cursor-pointer">
{t('keychain.generate.savePassphrase')}
</Label>
</div>
</div>
{/* Key Export section - only for managed keys */}
{draftKey.source !== 'reference' && (
<div className="pt-4 mt-4 border-t border-border/60">
<div className="flex items-center gap-2 mb-3">
<span className="text-sm font-medium">
{t("keychain.edit.keyExport")}
</span>
<div className="h-4 w-4 rounded-full bg-muted flex items-center justify-center">
<Info size={10} className="text-muted-foreground" />
</div>
</div>
<Button
className="w-full h-11"
onClick={() => openKeyExport(panel.key)}
>
{t("keychain.edit.exportToHost")}
</Button>
</div>
)}
{/* Save button */}
<Button
className="w-full h-11 mt-4"
disabled={
!draftKey.label?.trim() ||
(draftKey.source !== 'reference' && !draftKey.privateKey?.trim())
}
onClick={() => {
if (draftKey.id) {
onUpdate({
...panel.key,
...(draftKey as SSHKey),
});
closePanel();
}
}}
>
{t("common.saveChanges")}
</Button>
</>
)}
</AsidePanelContent>
{/* Host Selector Overlay for Export */}
{showHostSelector && panel.type === "export" && (
<SelectHostPanel
hosts={hosts}
customGroups={customGroups}
selectedHostIds={exportHost?.id ? [exportHost.id] : []}
multiSelect={false}
onSelect={(host) => {
setExportHost(host);
setShowHostSelector(false);
}}
onBack={() => setShowHostSelector(false)}
onContinue={() => setShowHostSelector(false)}
availableKeys={keys}
proxyProfiles={proxyProfiles}
managedSources={managedSources}
onSaveHost={onSaveHost}
onCreateGroup={onCreateGroup}
/>
)}
</AsidePanel>
)}
</div>
);
};
export default KeychainManager;